feat(datasource): implement data source management functionality
- Added a new API for managing data sources, including CRUD operations and connection validation. - Introduced UI components for data source settings, sync logs, and editor dialog, enhancing user experience in managing external data sources. - Updated localization files to support new data source features in multiple languages. - Implemented cron expression humanization for better scheduling visibility. - Enhanced knowledge base editor to include data source management options.
This commit is contained in:
@@ -0,0 +1,235 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// DataSourceRepository provides data access for data sources
|
||||
type DataSourceRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewDataSourceRepository creates a new data source repository
|
||||
func NewDataSourceRepository(db *gorm.DB) interfaces.DataSourceRepository {
|
||||
return &DataSourceRepository{db: db}
|
||||
}
|
||||
|
||||
// Create inserts a new data source record
|
||||
func (r *DataSourceRepository) Create(ctx context.Context, ds *types.DataSource) error {
|
||||
if ds == nil {
|
||||
return errors.New("data source is nil")
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Create(ds).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FindByID retrieves a data source by ID
|
||||
func (r *DataSourceRepository) FindByID(ctx context.Context, id string) (*types.DataSource, error) {
|
||||
if id == "" {
|
||||
return nil, errors.New("id is empty")
|
||||
}
|
||||
var ds types.DataSource
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("id = ?", id).
|
||||
Where("deleted_at IS NULL").
|
||||
First(&ds).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("data source not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &ds, nil
|
||||
}
|
||||
|
||||
// FindByKnowledgeBase lists all data sources for a knowledge base
|
||||
func (r *DataSourceRepository) FindByKnowledgeBase(ctx context.Context, kbID string) ([]*types.DataSource, error) {
|
||||
if kbID == "" {
|
||||
return nil, errors.New("knowledge base id is empty")
|
||||
}
|
||||
var dataSources []*types.DataSource
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("knowledge_base_id = ?", kbID).
|
||||
Where("deleted_at IS NULL").
|
||||
Order("created_at DESC").
|
||||
Find(&dataSources).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dataSources, nil
|
||||
}
|
||||
|
||||
// Update updates an existing data source
|
||||
func (r *DataSourceRepository) Update(ctx context.Context, ds *types.DataSource) error {
|
||||
if ds == nil {
|
||||
return errors.New("data source is nil")
|
||||
}
|
||||
if ds.ID == "" {
|
||||
return errors.New("data source id is empty")
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(ds).
|
||||
Updates(ds).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete performs a soft delete
|
||||
func (r *DataSourceRepository) Delete(ctx context.Context, id string) error {
|
||||
if id == "" {
|
||||
return errors.New("id is empty")
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&types.DataSource{}).
|
||||
Where("id = ?", id).
|
||||
Update("deleted_at", gorm.Expr("NOW()")).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FindActive retrieves all active data sources (used for scheduling)
|
||||
func (r *DataSourceRepository) FindActive(ctx context.Context) ([]*types.DataSource, error) {
|
||||
var dataSources []*types.DataSource
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("status = ?", types.DataSourceStatusActive).
|
||||
Where("deleted_at IS NULL").
|
||||
Where("sync_schedule != ''").
|
||||
Order("created_at DESC").
|
||||
Find(&dataSources).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dataSources, nil
|
||||
}
|
||||
|
||||
// SyncLogRepository provides data access for sync logs
|
||||
type SyncLogRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewSyncLogRepository creates a new sync log repository
|
||||
func NewSyncLogRepository(db *gorm.DB) interfaces.SyncLogRepository {
|
||||
return &SyncLogRepository{db: db}
|
||||
}
|
||||
|
||||
// Create inserts a new sync log entry
|
||||
func (r *SyncLogRepository) Create(ctx context.Context, log *types.SyncLog) error {
|
||||
if log == nil {
|
||||
return errors.New("sync log is nil")
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Create(log).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FindByID retrieves a sync log by ID
|
||||
func (r *SyncLogRepository) FindByID(ctx context.Context, id string) (*types.SyncLog, error) {
|
||||
if id == "" {
|
||||
return nil, errors.New("id is empty")
|
||||
}
|
||||
var log types.SyncLog
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("id = ?", id).
|
||||
First(&log).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("sync log not found")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &log, nil
|
||||
}
|
||||
|
||||
// FindByDataSource lists sync logs for a data source with pagination
|
||||
func (r *SyncLogRepository) FindByDataSource(ctx context.Context, dsID string, limit int, offset int) ([]*types.SyncLog, error) {
|
||||
if dsID == "" {
|
||||
return nil, errors.New("data source id is empty")
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 10
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
var logs []*types.SyncLog
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("data_source_id = ?", dsID).
|
||||
Order("started_at DESC").
|
||||
Limit(limit).
|
||||
Offset(offset).
|
||||
Find(&logs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return logs, nil
|
||||
}
|
||||
|
||||
// FindLatest retrieves the most recent sync log for a data source
|
||||
func (r *SyncLogRepository) FindLatest(ctx context.Context, dsID string) (*types.SyncLog, error) {
|
||||
if dsID == "" {
|
||||
return nil, errors.New("data source id is empty")
|
||||
}
|
||||
var log types.SyncLog
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("data_source_id = ?", dsID).
|
||||
Order("started_at DESC").
|
||||
Limit(1).
|
||||
First(&log).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &log, nil
|
||||
}
|
||||
|
||||
// HasRunningSync checks if a data source has any sync currently in "running" status.
|
||||
func (r *SyncLogRepository) HasRunningSync(ctx context.Context, dsID string) (bool, error) {
|
||||
if dsID == "" {
|
||||
return false, errors.New("data source id is empty")
|
||||
}
|
||||
var count int64
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&types.SyncLog{}).
|
||||
Where("data_source_id = ?", dsID).
|
||||
Where("status = ?", types.SyncLogStatusRunning).
|
||||
Count(&count).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
// Update updates an existing sync log entry
|
||||
func (r *SyncLogRepository) Update(ctx context.Context, log *types.SyncLog) error {
|
||||
if log == nil {
|
||||
return errors.New("sync log is nil")
|
||||
}
|
||||
if log.ID == "" {
|
||||
return errors.New("sync log id is empty")
|
||||
}
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(log).
|
||||
Updates(log).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CleanupOldLogs deletes sync logs older than the retention period
|
||||
func (r *SyncLogRepository) CleanupOldLogs(ctx context.Context, retentionDays int) error {
|
||||
if retentionDays <= 0 {
|
||||
retentionDays = 30
|
||||
}
|
||||
// Delete logs older than the retention period
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("started_at < NOW() - INTERVAL ? DAY", retentionDays).
|
||||
Delete(&types.SyncLog{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -168,7 +168,7 @@ func (r *messageRepository) SearchMessagesByKeyword(
|
||||
Joins("INNER JOIN sessions ON sessions.id = messages.session_id AND sessions.deleted_at IS NULL").
|
||||
Where("sessions.tenant_id = ?", tenantID).
|
||||
Where("messages.deleted_at IS NULL").
|
||||
Where("messages.content ILIKE ?", "%"+keyword+"%")
|
||||
Where("messages.content ILIKE ?", "%"+escapeLikeKeyword(keyword)+"%")
|
||||
|
||||
if len(sessionIDs) > 0 {
|
||||
query = query.Where("messages.session_id IN ?", sessionIDs)
|
||||
|
||||
@@ -107,7 +107,8 @@ func (r *knowledgeTagRepository) ListByKB(
|
||||
baseQuery := r.db.WithContext(ctx).Model(&types.KnowledgeTag{}).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID)
|
||||
if keyword != "" {
|
||||
baseQuery = baseQuery.Where("name LIKE ?", "%"+keyword+"%")
|
||||
escaped := escapeLikeKeyword(keyword)
|
||||
baseQuery = baseQuery.Where("name LIKE ?", "%"+escaped+"%")
|
||||
}
|
||||
|
||||
if err := baseQuery.Count(&total).Error; err != nil {
|
||||
@@ -117,7 +118,8 @@ func (r *knowledgeTagRepository) ListByKB(
|
||||
dataQuery := r.db.WithContext(ctx).
|
||||
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID)
|
||||
if keyword != "" {
|
||||
dataQuery = dataQuery.Where("name LIKE ?", "%"+keyword+"%")
|
||||
escaped := escapeLikeKeyword(keyword)
|
||||
dataQuery = dataQuery.Where("name LIKE ?", "%"+escaped+"%")
|
||||
}
|
||||
|
||||
var tags []*types.KnowledgeTag
|
||||
|
||||
@@ -63,14 +63,13 @@ func (r *tenantRepository) SearchTenants(ctx context.Context, keyword string, te
|
||||
|
||||
// Build search conditions
|
||||
if tenantID > 0 && keyword != "" {
|
||||
// When both tenantID and keyword are provided, use OR to match either
|
||||
query = query.Where("id = ? OR name LIKE ? OR description LIKE ?", tenantID, "%"+keyword+"%", "%"+keyword+"%")
|
||||
escaped := escapeLikeKeyword(keyword)
|
||||
query = query.Where("id = ? OR name LIKE ? OR description LIKE ?", tenantID, "%"+escaped+"%", "%"+escaped+"%")
|
||||
} else if tenantID > 0 {
|
||||
// Filter by tenant ID only
|
||||
query = query.Where("id = ?", tenantID)
|
||||
} else if keyword != "" {
|
||||
// Filter by keyword only (search in name and description)
|
||||
query = query.Where("name LIKE ? OR description LIKE ?", "%"+keyword+"%", "%"+keyword+"%")
|
||||
escaped := escapeLikeKeyword(keyword)
|
||||
query = query.Where("name LIKE ? OR description LIKE ?", "%"+escaped+"%", "%"+escaped+"%")
|
||||
}
|
||||
|
||||
// Count total
|
||||
|
||||
@@ -0,0 +1,713 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"mime/multipart"
|
||||
"net/textproto"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/datasource"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/hibiken/asynq"
|
||||
)
|
||||
|
||||
// DataSourceService implements the DataSourceService interface
|
||||
type DataSourceService struct {
|
||||
dsRepo interfaces.DataSourceRepository
|
||||
syncLogRepo interfaces.SyncLogRepository
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
kbService interfaces.KnowledgeBaseService
|
||||
taskEnqueuer interfaces.TaskEnqueuer
|
||||
connectorRegistry *datasource.ConnectorRegistry
|
||||
scheduler *datasource.Scheduler
|
||||
tenantRepo interfaces.TenantRepository
|
||||
tagService interfaces.KnowledgeTagService
|
||||
}
|
||||
|
||||
// NewDataSourceService creates a new data source service
|
||||
func NewDataSourceService(
|
||||
dsRepo interfaces.DataSourceRepository,
|
||||
syncLogRepo interfaces.SyncLogRepository,
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
taskEnqueuer interfaces.TaskEnqueuer,
|
||||
connectorRegistry *datasource.ConnectorRegistry,
|
||||
scheduler *datasource.Scheduler,
|
||||
tenantRepo interfaces.TenantRepository,
|
||||
tagService interfaces.KnowledgeTagService,
|
||||
) interfaces.DataSourceService {
|
||||
return &DataSourceService{
|
||||
dsRepo: dsRepo,
|
||||
syncLogRepo: syncLogRepo,
|
||||
knowledgeService: knowledgeService,
|
||||
kbService: kbService,
|
||||
taskEnqueuer: taskEnqueuer,
|
||||
connectorRegistry: connectorRegistry,
|
||||
scheduler: scheduler,
|
||||
tenantRepo: tenantRepo,
|
||||
tagService: tagService,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateDataSource creates a new data source configuration
|
||||
func (s *DataSourceService) CreateDataSource(ctx context.Context, ds *types.DataSource) (*types.DataSource, error) {
|
||||
if ds == nil {
|
||||
return nil, datasource.ErrDataSourceInvalid
|
||||
}
|
||||
|
||||
// Validate knowledge base exists
|
||||
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, ds.KnowledgeBaseID)
|
||||
if err != nil || kb == nil {
|
||||
return nil, datasource.ErrKnowledgeBaseNotFound
|
||||
}
|
||||
|
||||
// Validate connector type
|
||||
_, err = s.connectorRegistry.Get(ds.Type)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Validate configuration
|
||||
if err := s.validateDataSourceConfig(ctx, ds); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Create in database
|
||||
if err := s.dsRepo.Create(ctx, ds); err != nil {
|
||||
logger.Errorf(ctx, "failed to create data source: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Register cron schedule if configured
|
||||
if ds.SyncSchedule != "" && ds.Status == types.DataSourceStatusActive {
|
||||
if err := s.scheduler.AddOrUpdate(ds); err != nil {
|
||||
logger.Warnf(ctx, "failed to register cron for ds=%s: %v", ds.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "data source created: id=%s type=%s kb=%s", ds.ID, ds.Type, ds.KnowledgeBaseID)
|
||||
return ds, nil
|
||||
}
|
||||
|
||||
// GetDataSource retrieves a data source by ID
|
||||
func (s *DataSourceService) GetDataSource(ctx context.Context, id string) (*types.DataSource, error) {
|
||||
ds, err := s.dsRepo.FindByID(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ds, nil
|
||||
}
|
||||
|
||||
// ListDataSources lists all data sources for a knowledge base
|
||||
func (s *DataSourceService) ListDataSources(ctx context.Context, kbID string) ([]*types.DataSource, error) {
|
||||
dataSources, err := s.dsRepo.FindByKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "failed to list data sources: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Attach latest sync log to each data source
|
||||
for _, ds := range dataSources {
|
||||
log, _ := s.syncLogRepo.FindLatest(ctx, ds.ID)
|
||||
if log != nil {
|
||||
ds.LatestSyncLog = log
|
||||
}
|
||||
}
|
||||
|
||||
return dataSources, nil
|
||||
}
|
||||
|
||||
// UpdateDataSource updates an existing data source
|
||||
func (s *DataSourceService) UpdateDataSource(ctx context.Context, ds *types.DataSource) (*types.DataSource, error) {
|
||||
if ds == nil || ds.ID == "" {
|
||||
return nil, datasource.ErrDataSourceInvalid
|
||||
}
|
||||
|
||||
// Verify data source exists
|
||||
existing, err := s.dsRepo.FindByID(ctx, ds.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Validate new configuration if changed
|
||||
if ds.Type != existing.Type || string(ds.Config) != string(existing.Config) {
|
||||
if err := s.validateDataSourceConfig(ctx, ds); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.dsRepo.Update(ctx, ds); err != nil {
|
||||
logger.Errorf(ctx, "failed to update data source: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Update cron schedule
|
||||
if err := s.scheduler.AddOrUpdate(ds); err != nil {
|
||||
logger.Warnf(ctx, "failed to update cron for ds=%s: %v", ds.ID, err)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "data source updated: id=%s", ds.ID)
|
||||
return ds, nil
|
||||
}
|
||||
|
||||
// DeleteDataSource deletes a data source (soft delete)
|
||||
func (s *DataSourceService) DeleteDataSource(ctx context.Context, id string) error {
|
||||
// Verify data source exists
|
||||
_, err := s.dsRepo.FindByID(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.dsRepo.Delete(ctx, id); err != nil {
|
||||
logger.Errorf(ctx, "failed to delete data source: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Remove cron schedule
|
||||
s.scheduler.Remove(id)
|
||||
|
||||
logger.Infof(ctx, "data source deleted: id=%s", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateConnection tests the connection to an external data source
|
||||
func (s *DataSourceService) ValidateConnection(ctx context.Context, dsID string) error {
|
||||
ds, err := s.GetDataSource(ctx, dsID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Get connector
|
||||
connector, err := s.connectorRegistry.Get(ds.Type)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Parse configuration
|
||||
config, err := ds.ParseConfig()
|
||||
if err != nil {
|
||||
return datasource.ErrInvalidConfig
|
||||
}
|
||||
|
||||
// Validate connection
|
||||
if err := connector.Validate(ctx, config); err != nil {
|
||||
// Update data source with error
|
||||
ds.Status = types.DataSourceStatusError
|
||||
ds.ErrorMessage = err.Error()
|
||||
_ = s.dsRepo.Update(ctx, ds)
|
||||
return err
|
||||
}
|
||||
|
||||
// Clear error if it was previously in error state
|
||||
if ds.Status == types.DataSourceStatusError {
|
||||
ds.Status = types.DataSourceStatusActive
|
||||
ds.ErrorMessage = ""
|
||||
_ = s.dsRepo.Update(ctx, ds)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListAvailableResources lists resources available for sync in the external system
|
||||
func (s *DataSourceService) ListAvailableResources(ctx context.Context, dsID string) ([]types.Resource, error) {
|
||||
ds, err := s.GetDataSource(ctx, dsID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Get connector
|
||||
connector, err := s.connectorRegistry.Get(ds.Type)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Parse configuration
|
||||
config, err := ds.ParseConfig()
|
||||
if err != nil {
|
||||
return nil, datasource.ErrInvalidConfig
|
||||
}
|
||||
|
||||
// List resources
|
||||
resources, err := connector.ListResources(ctx, config)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "failed to list resources: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resources, nil
|
||||
}
|
||||
|
||||
// ManualSync triggers an immediate sync for a data source
|
||||
func (s *DataSourceService) ManualSync(ctx context.Context, dsID string) (*types.SyncLog, error) {
|
||||
ds, err := s.GetDataSource(ctx, dsID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if ds.Status != types.DataSourceStatusActive && ds.Status != types.DataSourceStatusError {
|
||||
return nil, datasource.ErrDataSourceNotActive
|
||||
}
|
||||
|
||||
// Create sync log
|
||||
syncLog := &types.SyncLog{
|
||||
DataSourceID: dsID,
|
||||
TenantID: ds.TenantID,
|
||||
Status: types.SyncLogStatusRunning,
|
||||
StartedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
if err := s.syncLogRepo.Create(ctx, syncLog); err != nil {
|
||||
logger.Errorf(ctx, "failed to create sync log: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Enqueue sync task
|
||||
payload := &types.DataSourceSyncPayload{
|
||||
DataSourceID: dsID,
|
||||
TenantID: ds.TenantID,
|
||||
SyncLogID: syncLog.ID,
|
||||
ForceFull: false,
|
||||
}
|
||||
|
||||
payloadJSON, _ := json.Marshal(payload)
|
||||
task := asynq.NewTask(types.TypeDataSourceSync, payloadJSON)
|
||||
|
||||
_, err = s.taskEnqueuer.Enqueue(task, asynq.Queue("default"))
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "failed to enqueue sync task: %v", err)
|
||||
// Update sync log as failed
|
||||
syncLog.Status = types.SyncLogStatusFailed
|
||||
syncLog.FinishedAt = timePtr(time.Now())
|
||||
syncLog.ErrorMessage = err.Error()
|
||||
_ = s.syncLogRepo.Update(ctx, syncLog)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "sync task enqueued: ds=%s syncLog=%s", dsID, syncLog.ID)
|
||||
return syncLog, nil
|
||||
}
|
||||
|
||||
// PauseDataSource pauses a data source's scheduled syncs
|
||||
func (s *DataSourceService) PauseDataSource(ctx context.Context, id string) error {
|
||||
ds, err := s.GetDataSource(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ds.Status = types.DataSourceStatusPaused
|
||||
if err := s.dsRepo.Update(ctx, ds); err != nil {
|
||||
logger.Errorf(ctx, "failed to pause data source: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Remove cron schedule
|
||||
s.scheduler.Remove(id)
|
||||
|
||||
logger.Infof(ctx, "data source paused: id=%s", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResumeDataSource resumes a paused data source
|
||||
func (s *DataSourceService) ResumeDataSource(ctx context.Context, id string) error {
|
||||
ds, err := s.GetDataSource(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ds.Status = types.DataSourceStatusActive
|
||||
if err := s.dsRepo.Update(ctx, ds); err != nil {
|
||||
logger.Errorf(ctx, "failed to resume data source: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Re-register cron schedule
|
||||
if err := s.scheduler.AddOrUpdate(ds); err != nil {
|
||||
logger.Warnf(ctx, "failed to re-register cron for ds=%s: %v", ds.ID, err)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "data source resumed: id=%s", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSyncLogs retrieves sync history for a data source
|
||||
func (s *DataSourceService) GetSyncLogs(ctx context.Context, dsID string, limit int, offset int) ([]*types.SyncLog, error) {
|
||||
logs, err := s.syncLogRepo.FindByDataSource(ctx, dsID, limit, offset)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "failed to get sync logs: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
return logs, nil
|
||||
}
|
||||
|
||||
// GetSyncLog retrieves a specific sync log entry
|
||||
func (s *DataSourceService) GetSyncLog(ctx context.Context, syncLogID string) (*types.SyncLog, error) {
|
||||
log, err := s.syncLogRepo.FindByID(ctx, syncLogID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return log, nil
|
||||
}
|
||||
|
||||
// ProcessSync handles the actual sync operation (called by asynq task)
|
||||
func (s *DataSourceService) ProcessSync(ctx context.Context, task *asynq.Task) error {
|
||||
var payload types.DataSourceSyncPayload
|
||||
if err := json.Unmarshal(task.Payload(), &payload); err != nil {
|
||||
logger.Errorf(ctx, "failed to unmarshal sync payload: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "processing data source sync: ds=%s syncLog=%s", payload.DataSourceID, payload.SyncLogID)
|
||||
|
||||
// Get data source
|
||||
ds, err := s.GetDataSource(ctx, payload.DataSourceID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "failed to get data source: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Get sync log
|
||||
syncLog, err := s.syncLogRepo.FindByID(ctx, payload.SyncLogID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "failed to get sync log: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Get connector
|
||||
connector, err := s.connectorRegistry.Get(ds.Type)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "connector not found: type=%s", ds.Type)
|
||||
syncLog.Status = types.SyncLogStatusFailed
|
||||
syncLog.FinishedAt = timePtr(time.Now())
|
||||
syncLog.ErrorMessage = fmt.Sprintf("Connector not found: %s", ds.Type)
|
||||
_ = s.syncLogRepo.Update(ctx, syncLog)
|
||||
return err
|
||||
}
|
||||
|
||||
// Parse configuration
|
||||
config, err := ds.ParseConfig()
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "failed to parse config: %v", err)
|
||||
syncLog.Status = types.SyncLogStatusFailed
|
||||
syncLog.FinishedAt = timePtr(time.Now())
|
||||
syncLog.ErrorMessage = fmt.Sprintf("Invalid configuration: %v", err)
|
||||
_ = s.syncLogRepo.Update(ctx, syncLog)
|
||||
return err
|
||||
}
|
||||
|
||||
// Fetch items based on sync mode
|
||||
var items []types.FetchedItem
|
||||
var nextCursor *types.SyncCursor
|
||||
var fetchErr error
|
||||
|
||||
if payload.ForceFull || ds.SyncMode == types.SyncModeFull {
|
||||
// Full sync
|
||||
items, fetchErr = connector.FetchAll(ctx, config, config.ResourceIDs)
|
||||
logger.Infof(ctx, "full sync fetched %d items", len(items))
|
||||
} else {
|
||||
// Incremental sync
|
||||
cursor, _ := ds.ParseSyncCursor()
|
||||
items, nextCursor, fetchErr = connector.FetchIncremental(ctx, config, cursor)
|
||||
logger.Infof(ctx, "incremental sync fetched %d items", len(items))
|
||||
}
|
||||
|
||||
if fetchErr != nil {
|
||||
logger.Errorf(ctx, "fetch operation failed: %v", fetchErr)
|
||||
syncLog.Status = types.SyncLogStatusFailed
|
||||
syncLog.FinishedAt = timePtr(time.Now())
|
||||
syncLog.ErrorMessage = fmt.Sprintf("Fetch failed: %v", fetchErr)
|
||||
_ = s.syncLogRepo.Update(ctx, syncLog)
|
||||
return fetchErr
|
||||
}
|
||||
|
||||
// Process fetched items and write to knowledge base
|
||||
var result = &types.SyncResult{
|
||||
Total: len(items),
|
||||
}
|
||||
|
||||
// Set tenant context so KnowledgeService can resolve tenant info correctly
|
||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, ds.TenantID)
|
||||
|
||||
tenant, err := s.tenantRepo.GetTenantByID(ctx, ds.TenantID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "failed to get tenant info: %v", err)
|
||||
syncLog.Status = types.SyncLogStatusFailed
|
||||
syncLog.FinishedAt = timePtr(time.Now())
|
||||
syncLog.ErrorMessage = fmt.Sprintf("Failed to get tenant info: %v", err)
|
||||
_ = s.syncLogRepo.Update(ctx, syncLog)
|
||||
return err
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenant)
|
||||
|
||||
// Auto-tag: find or create a tag for this data source so synced items are easily identifiable
|
||||
autoTagID := ""
|
||||
autoTagName := connectorDisplayLabel(ds.Type) + "·" + ds.Name
|
||||
if autoTag, tagErr := s.tagService.FindOrCreateTagByName(ctx, ds.KnowledgeBaseID, autoTagName); tagErr != nil {
|
||||
logger.Warnf(ctx, "failed to find/create auto-tag %q: %v (proceeding without tag)", autoTagName, tagErr)
|
||||
} else if autoTag != nil {
|
||||
autoTagID = autoTag.ID
|
||||
logger.Infof(ctx, "using auto-tag %q (id=%s) for data source sync", autoTagName, autoTagID)
|
||||
}
|
||||
|
||||
for _, item := range items {
|
||||
if item.IsDeleted {
|
||||
if ds.SyncDeletions {
|
||||
result.Deleted++
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if len(item.Content) == 0 && item.URL == "" {
|
||||
// Check if this is an error item from the connector (failed to fetch content)
|
||||
if errMsg, hasErr := item.Metadata["error"]; hasErr {
|
||||
logger.Warnf(ctx, "item %q (external_id=%s) fetch failed: %s", item.Title, item.ExternalID, errMsg)
|
||||
result.Failed++
|
||||
result.Errors = append(result.Errors, fmt.Sprintf("%s: %s", item.Title, errMsg))
|
||||
} else {
|
||||
logger.Infof(ctx, "skipping item %q (external_id=%s): no content or URL", item.Title, item.ExternalID)
|
||||
result.Skipped++
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
isUpdate, err := s.ingestItem(ctx, ds, &item, autoTagID)
|
||||
if err != nil {
|
||||
// Duplicate file/URL is not a failure — count as skipped
|
||||
var dupErr *types.DuplicateKnowledgeError
|
||||
if errors.As(err, &dupErr) {
|
||||
logger.Infof(ctx, "item %q (external_id=%s) already exists, skipping", item.Title, item.ExternalID)
|
||||
result.Skipped++
|
||||
} else {
|
||||
logger.Warnf(ctx, "failed to ingest item %q (external_id=%s): %v", item.Title, item.ExternalID, err)
|
||||
result.Failed++
|
||||
result.Errors = append(result.Errors, fmt.Sprintf("%s: %v", item.Title, err))
|
||||
}
|
||||
} else if isUpdate {
|
||||
result.Updated++
|
||||
} else {
|
||||
result.Created++
|
||||
}
|
||||
}
|
||||
|
||||
// Update sync log with results
|
||||
syncLog.ItemsTotal = result.Total
|
||||
syncLog.ItemsCreated = result.Created
|
||||
syncLog.ItemsUpdated = result.Updated
|
||||
syncLog.ItemsDeleted = result.Deleted
|
||||
syncLog.ItemsSkipped = result.Skipped
|
||||
syncLog.ItemsFailed = result.Failed
|
||||
syncLog.Status = types.SyncLogStatusSuccess
|
||||
syncLog.FinishedAt = timePtr(time.Now())
|
||||
|
||||
// Update cursor for next incremental sync
|
||||
if nextCursor != nil {
|
||||
cursorJSON, _ := nextCursor.ToJSON()
|
||||
ds.LastSyncCursor = cursorJSON
|
||||
}
|
||||
|
||||
ds.LastSyncAt = timePtr(time.Now())
|
||||
ds.Status = types.DataSourceStatusActive
|
||||
ds.ErrorMessage = ""
|
||||
|
||||
// Store result
|
||||
resultJSON, _ := result.ToJSON()
|
||||
ds.LastSyncResult = resultJSON
|
||||
syncLog.Result = resultJSON
|
||||
|
||||
// Update database
|
||||
if err := s.dsRepo.Update(ctx, ds); err != nil {
|
||||
logger.Errorf(ctx, "failed to update data source: %v", err)
|
||||
}
|
||||
if err := s.syncLogRepo.Update(ctx, syncLog); err != nil {
|
||||
logger.Errorf(ctx, "failed to update sync log: %v", err)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "data source sync completed: ds=%s created=%d updated=%d deleted=%d",
|
||||
payload.DataSourceID, syncLog.ItemsCreated, syncLog.ItemsUpdated, syncLog.ItemsDeleted)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateCredentials tests connectivity using raw credentials without persisting anything.
|
||||
func (s *DataSourceService) ValidateCredentials(ctx context.Context, connectorType string, credentials map[string]interface{}) error {
|
||||
connector, err := s.connectorRegistry.Get(connectorType)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
config := &types.DataSourceConfig{
|
||||
Type: connectorType,
|
||||
Credentials: credentials,
|
||||
}
|
||||
|
||||
if err := connector.Validate(ctx, config); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
|
||||
func (s *DataSourceService) validateDataSourceConfig(ctx context.Context, ds *types.DataSource) error {
|
||||
connector, err := s.connectorRegistry.Get(ds.Type)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
config, err := ds.ParseConfig()
|
||||
if err != nil {
|
||||
return datasource.ErrInvalidConfig
|
||||
}
|
||||
|
||||
return connector.Validate(ctx, config)
|
||||
}
|
||||
|
||||
// ingestItem writes a single FetchedItem into the knowledge base.
|
||||
// If a knowledge item with the same external_id already exists, it is deleted first (update = delete + re-create).
|
||||
//
|
||||
// Routing logic:
|
||||
// - Has Content bytes → CreateKnowledgeFromFile (走完整的文档解析 pipeline)
|
||||
// - Has URL only → CreateKnowledgeFromURL (让 WeKnora 下载并解析)
|
||||
//
|
||||
// Returns (isUpdate, error) — isUpdate is true when an existing item was replaced.
|
||||
func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource, item *types.FetchedItem, tagID string) (bool, error) {
|
||||
channel := ds.Type // e.g. "feishu", "notion"
|
||||
|
||||
metadata := map[string]string{
|
||||
"external_id": item.ExternalID,
|
||||
"source_resource_id": item.SourceResourceID,
|
||||
"datasource_id": ds.ID,
|
||||
}
|
||||
for k, v := range item.Metadata {
|
||||
metadata[k] = v
|
||||
}
|
||||
|
||||
// Check if a knowledge item with this external_id already exists → delete it first (update)
|
||||
isUpdate := false
|
||||
if item.ExternalID != "" {
|
||||
repo := s.knowledgeService.GetRepository()
|
||||
existing, err := repo.FindByMetadataKey(ctx, ds.TenantID, ds.KnowledgeBaseID, "external_id", item.ExternalID)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "failed to check existing knowledge for external_id=%s: %v", item.ExternalID, err)
|
||||
// Non-fatal: proceed with creation (may produce duplicate)
|
||||
} else if existing != nil {
|
||||
logger.Infof(ctx, "found existing knowledge %s for external_id=%s, deleting for update", existing.ID, item.ExternalID)
|
||||
if err := s.knowledgeService.DeleteKnowledge(ctx, existing.ID); err != nil {
|
||||
logger.Warnf(ctx, "failed to delete existing knowledge %s: %v", existing.ID, err)
|
||||
} else {
|
||||
isUpdate = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Case 1: content already fetched → build a FileHeader from bytes and call CreateKnowledgeFromFile
|
||||
if len(item.Content) > 0 {
|
||||
fh, err := bytesToFileHeader(item.Content, item.FileName)
|
||||
if err != nil {
|
||||
return isUpdate, fmt.Errorf("build file header: %w", err)
|
||||
}
|
||||
_, err = s.knowledgeService.CreateKnowledgeFromFile(
|
||||
ctx,
|
||||
ds.KnowledgeBaseID,
|
||||
fh,
|
||||
metadata,
|
||||
nil, // use KB default for multimodal
|
||||
item.FileName, // customFileName — must include extension for file-type validation
|
||||
tagID, // auto-tag from data source
|
||||
channel,
|
||||
)
|
||||
return isUpdate, err
|
||||
}
|
||||
|
||||
// Case 2: only a remote URL — let WeKnora handle downloading and parsing
|
||||
if item.URL != "" {
|
||||
_, err := s.knowledgeService.CreateKnowledgeFromURL(
|
||||
ctx,
|
||||
ds.KnowledgeBaseID,
|
||||
item.URL,
|
||||
item.FileName,
|
||||
"", // auto-detect file type
|
||||
nil, // use KB default for multimodal
|
||||
item.Title,
|
||||
tagID, // auto-tag from data source
|
||||
channel,
|
||||
)
|
||||
return isUpdate, err
|
||||
}
|
||||
|
||||
return isUpdate, fmt.Errorf("item has neither content nor URL")
|
||||
}
|
||||
|
||||
// bytesToFileHeader wraps a []byte into a *multipart.FileHeader so it can be
|
||||
// consumed by KnowledgeService.CreateKnowledgeFromFile.
|
||||
func bytesToFileHeader(data []byte, filename string) (*multipart.FileHeader, error) {
|
||||
var buf bytes.Buffer
|
||||
writer := multipart.NewWriter(&buf)
|
||||
|
||||
// Create a form file part
|
||||
partHeader := make(textproto.MIMEHeader)
|
||||
partHeader.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, filename))
|
||||
partHeader.Set("Content-Type", "application/octet-stream")
|
||||
|
||||
part, err := writer.CreatePart(partHeader)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create multipart part: %w", err)
|
||||
}
|
||||
|
||||
if _, err := part.Write(data); err != nil {
|
||||
return nil, fmt.Errorf("write data to part: %w", err)
|
||||
}
|
||||
|
||||
if err := writer.Close(); err != nil {
|
||||
return nil, fmt.Errorf("close multipart writer: %w", err)
|
||||
}
|
||||
|
||||
// Parse the multipart data to get a FileHeader
|
||||
reader := multipart.NewReader(&buf, writer.Boundary())
|
||||
form, err := reader.ReadForm(int64(len(data)) + 1024)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read multipart form: %w", err)
|
||||
}
|
||||
|
||||
files := form.File["file"]
|
||||
if len(files) == 0 {
|
||||
return nil, fmt.Errorf("no file in multipart form")
|
||||
}
|
||||
|
||||
return files[0], nil
|
||||
}
|
||||
|
||||
func timePtr(t time.Time) *time.Time {
|
||||
utc := t.UTC()
|
||||
return &utc
|
||||
}
|
||||
|
||||
// connectorDisplayLabel returns a human-readable label for a connector type.
|
||||
// Used to generate auto-tag names like "飞书·我的知识库".
|
||||
func connectorDisplayLabel(connectorType string) string {
|
||||
labels := map[string]string{
|
||||
"feishu": "飞书",
|
||||
"notion": "Notion",
|
||||
"confluence": "Confluence",
|
||||
"yuque": "语雀",
|
||||
"github": "GitHub",
|
||||
"google_drive": "Google Drive",
|
||||
"onedrive": "OneDrive",
|
||||
"dingtalk": "钉钉",
|
||||
"wecom_doc": "企微文档",
|
||||
"web_crawler": "网页爬虫",
|
||||
"slack": "Slack",
|
||||
"imap": "邮件",
|
||||
"rss": "RSS",
|
||||
}
|
||||
if l, ok := labels[connectorType]; ok {
|
||||
return l
|
||||
}
|
||||
return connectorType
|
||||
}
|
||||
Reference in New Issue
Block a user