refactor: Update tenant ID handling across the application

This commit is contained in:
wizardchen
2025-11-25 16:30:54 +08:00
parent 9f6f5f5773
commit 64c44c9e27
78 changed files with 437 additions and 601 deletions
+12 -12
View File
@@ -29,7 +29,7 @@ func (r *chunkRepository) CreateChunks(ctx context.Context, chunks []*types.Chun
}
// GetChunkByID retrieves a chunk by its ID and tenant ID
func (r *chunkRepository) GetChunkByID(ctx context.Context, tenantID uint, id string) (*types.Chunk, error) {
func (r *chunkRepository) GetChunkByID(ctx context.Context, tenantID uint64, id string) (*types.Chunk, error) {
var chunk types.Chunk
if err := r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).First(&chunk).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -42,7 +42,7 @@ func (r *chunkRepository) GetChunkByID(ctx context.Context, tenantID uint, id st
// ListChunksByID retrieves multiple chunks by their IDs
func (r *chunkRepository) ListChunksByID(
ctx context.Context, tenantID uint, ids []string,
ctx context.Context, tenantID uint64, ids []string,
) ([]*types.Chunk, error) {
var chunks []*types.Chunk
if err := r.db.Debug().WithContext(ctx).
@@ -55,7 +55,7 @@ func (r *chunkRepository) ListChunksByID(
// ListChunksByKnowledgeID lists all chunks for a knowledge ID
func (r *chunkRepository) ListChunksByKnowledgeID(
ctx context.Context, tenantID uint, knowledgeID string,
ctx context.Context, tenantID uint64, knowledgeID string,
) ([]*types.Chunk, error) {
var chunks []*types.Chunk
if err := r.db.WithContext(ctx).
@@ -71,7 +71,7 @@ func (r *chunkRepository) ListChunksByKnowledgeID(
// ListPagedChunksByKnowledgeID lists chunks for a knowledge ID with pagination
func (r *chunkRepository) ListPagedChunksByKnowledgeID(
ctx context.Context,
tenantID uint,
tenantID uint64,
knowledgeID string,
page *types.Pagination,
chunkType []types.ChunkType,
@@ -112,7 +112,7 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(
return chunks, total, nil
}
func (r *chunkRepository) ListChunkByParentID(ctx context.Context, tenantID uint, parentID string) ([]*types.Chunk, error) {
func (r *chunkRepository) ListChunkByParentID(ctx context.Context, tenantID uint64, parentID string) ([]*types.Chunk, error) {
var chunks []*types.Chunk
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND parent_chunk_id = ?", tenantID, parentID).
@@ -139,12 +139,12 @@ func (r *chunkRepository) UpdateChunks(ctx context.Context, chunks []*types.Chun
}
// DeleteChunk deletes a chunk by its ID
func (r *chunkRepository) DeleteChunk(ctx context.Context, tenantID uint, id string) error {
func (r *chunkRepository) DeleteChunk(ctx context.Context, tenantID uint64, id string) error {
return r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).Delete(&types.Chunk{}).Error
}
// DeleteChunks deletes chunks by IDs in batch
func (r *chunkRepository) DeleteChunks(ctx context.Context, tenantID uint, ids []string) error {
func (r *chunkRepository) DeleteChunks(ctx context.Context, tenantID uint64, ids []string) error {
if len(ids) == 0 {
return nil
}
@@ -152,21 +152,21 @@ func (r *chunkRepository) DeleteChunks(ctx context.Context, tenantID uint, ids [
}
// DeleteChunksByKnowledgeID deletes all chunks for a knowledge ID
func (r *chunkRepository) DeleteChunksByKnowledgeID(ctx context.Context, tenantID uint, knowledgeID string) error {
func (r *chunkRepository) DeleteChunksByKnowledgeID(ctx context.Context, tenantID uint64, knowledgeID string) error {
return r.db.WithContext(ctx).Where(
"tenant_id = ? AND knowledge_id = ?", tenantID, knowledgeID,
).Delete(&types.Chunk{}).Error
}
// DeleteByKnowledgeList deletes all chunks for a knowledge list
func (r *chunkRepository) DeleteByKnowledgeList(ctx context.Context, tenantID uint, knowledgeIDs []string) error {
func (r *chunkRepository) DeleteByKnowledgeList(ctx context.Context, tenantID uint64, knowledgeIDs []string) error {
return r.db.WithContext(ctx).Where(
"tenant_id = ? AND knowledge_id in ?", tenantID, knowledgeIDs,
).Delete(&types.Chunk{}).Error
}
// CountChunksByKnowledgeBaseID counts the number of chunks in a knowledge base
func (r *chunkRepository) CountChunksByKnowledgeBaseID(ctx context.Context, tenantID uint, kbID string) (int64, error) {
func (r *chunkRepository) CountChunksByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) (int64, error) {
var count int64
err := r.db.WithContext(ctx).Model(&types.Chunk{}).
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID).
@@ -175,7 +175,7 @@ func (r *chunkRepository) CountChunksByKnowledgeBaseID(ctx context.Context, tena
}
// DeleteUnindexedChunks by knowledge id and chunk index range
func (r *chunkRepository) DeleteUnindexedChunks(ctx context.Context, tenantID uint, knowledgeID string) ([]*types.Chunk, error) {
func (r *chunkRepository) DeleteUnindexedChunks(ctx context.Context, tenantID uint64, knowledgeID string) ([]*types.Chunk, error) {
var chunks []*types.Chunk
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND knowledge_id = ? AND status = ?", tenantID, knowledgeID, types.ChunkStatusStored).
@@ -194,7 +194,7 @@ func (r *chunkRepository) DeleteUnindexedChunks(ctx context.Context, tenantID ui
// ListAllFAQChunksByKnowledgeID lists all FAQ chunks for a knowledge ID (only essential fields for efficiency)
// Uses batch query to handle large datasets
func (r *chunkRepository) ListAllFAQChunksByKnowledgeID(ctx context.Context, tenantID uint, knowledgeID string) ([]*types.Chunk, error) {
func (r *chunkRepository) ListAllFAQChunksByKnowledgeID(ctx context.Context, tenantID uint64, knowledgeID string) ([]*types.Chunk, error) {
const batchSize = 1000 // 每批查询1000条
var allChunks []*types.Chunk
offset := 0
+11 -11
View File
@@ -28,7 +28,7 @@ func (r *knowledgeRepository) CreateKnowledge(ctx context.Context, knowledge *ty
}
// GetKnowledgeByID gets knowledge
func (r *knowledgeRepository) GetKnowledgeByID(ctx context.Context, tenantID uint, id string) (*types.Knowledge, error) {
func (r *knowledgeRepository) GetKnowledgeByID(ctx context.Context, tenantID uint64, id string) (*types.Knowledge, error) {
var knowledge types.Knowledge
if err := r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).First(&knowledge).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -41,7 +41,7 @@ func (r *knowledgeRepository) GetKnowledgeByID(ctx context.Context, tenantID uin
// ListKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base
func (r *knowledgeRepository) ListKnowledgeByKnowledgeBaseID(
ctx context.Context, tenantID uint, kbID string,
ctx context.Context, tenantID uint64, kbID string,
) ([]*types.Knowledge, error) {
var knowledges []*types.Knowledge
if err := r.db.WithContext(ctx).Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID).
@@ -54,7 +54,7 @@ func (r *knowledgeRepository) ListKnowledgeByKnowledgeBaseID(
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge in a knowledge base with pagination
func (r *knowledgeRepository) ListPagedKnowledgeByKnowledgeBaseID(
ctx context.Context,
tenantID uint,
tenantID uint64,
kbID string,
page *types.Pagination,
tagID string,
@@ -106,18 +106,18 @@ func (r *knowledgeRepository) UpdateKnowledgeBatch(ctx context.Context, knowledg
}
// DeleteKnowledge deletes knowledge
func (r *knowledgeRepository) DeleteKnowledge(ctx context.Context, tenantID uint, id string) error {
func (r *knowledgeRepository) DeleteKnowledge(ctx context.Context, tenantID uint64, id string) error {
return r.db.WithContext(ctx).Where("tenant_id = ? AND id = ?", tenantID, id).Delete(&types.Knowledge{}).Error
}
// DeleteKnowledge deletes knowledge
func (r *knowledgeRepository) DeleteKnowledgeList(ctx context.Context, tenantID uint, ids []string) error {
func (r *knowledgeRepository) DeleteKnowledgeList(ctx context.Context, tenantID uint64, ids []string) error {
return r.db.WithContext(ctx).Where("tenant_id = ? AND id in ?", tenantID, ids).Delete(&types.Knowledge{}).Error
}
// GetKnowledgeBatch gets knowledge in batch
func (r *knowledgeRepository) GetKnowledgeBatch(
ctx context.Context, tenantID uint, ids []string,
ctx context.Context, tenantID uint64, ids []string,
) ([]*types.Knowledge, error) {
var knowledge []*types.Knowledge
if err := r.db.WithContext(ctx).Debug().
@@ -131,7 +131,7 @@ func (r *knowledgeRepository) GetKnowledgeBatch(
// CheckKnowledgeExists checks if knowledge already exists
func (r *knowledgeRepository) CheckKnowledgeExists(
ctx context.Context,
tenantID uint,
tenantID uint64,
kbID string,
params *types.KnowledgeCheckParams,
) (bool, *types.Knowledge, error) {
@@ -199,8 +199,8 @@ func (r *knowledgeRepository) CheckKnowledgeExists(
func (r *knowledgeRepository) AminusB(
ctx context.Context,
Atenant uint, A string,
Btenant uint, B string,
Atenant uint64, A string,
Btenant uint64, B string,
) ([]string, error) {
knowledgeIDs := []string{}
subQuery := r.db.Model(&types.Knowledge{}).
@@ -222,7 +222,7 @@ func (r *knowledgeRepository) UpdateKnowledgeColumn(ctx context.Context, id stri
}
// CountKnowledgeByKnowledgeBaseID counts the number of knowledge items in a knowledge base
func (r *knowledgeRepository) CountKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint, kbID string) (int64, error) {
func (r *knowledgeRepository) CountKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) (int64, error) {
var count int64
err := r.db.WithContext(ctx).Model(&types.Knowledge{}).
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID).
@@ -233,7 +233,7 @@ func (r *knowledgeRepository) CountKnowledgeByKnowledgeBaseID(ctx context.Contex
// CountKnowledgeByStatus counts the number of knowledge items with the specified parse status
func (r *knowledgeRepository) CountKnowledgeByStatus(
ctx context.Context,
tenantID uint,
tenantID uint64,
kbID string,
parseStatuses []string,
) (int64, error) {
@@ -49,7 +49,7 @@ func (r *knowledgeBaseRepository) ListKnowledgeBases(ctx context.Context) ([]*ty
// ListKnowledgeBasesByTenantID lists all knowledge bases by tenant id
func (r *knowledgeBaseRepository) ListKnowledgeBasesByTenantID(
ctx context.Context, tenantID uint,
ctx context.Context, tenantID uint64,
) ([]*types.KnowledgeBase, error) {
var kbs []*types.KnowledgeBase
if err := r.db.WithContext(ctx).Where("tenant_id = ? AND is_temporary = ?", tenantID, false).
@@ -25,7 +25,7 @@ func (r *mcpServiceRepository) Create(ctx context.Context, service *types.MCPSer
}
// GetByID retrieves an MCP service by ID and tenant ID
func (r *mcpServiceRepository) GetByID(ctx context.Context, tenantID uint, id string) (*types.MCPService, error) {
func (r *mcpServiceRepository) GetByID(ctx context.Context, tenantID uint64, id string) (*types.MCPService, error) {
var service types.MCPService
err := r.db.WithContext(ctx).
Where("id = ? AND tenant_id = ?", id, tenantID).
@@ -42,7 +42,7 @@ func (r *mcpServiceRepository) GetByID(ctx context.Context, tenantID uint, id st
}
// List retrieves all MCP services for a tenant
func (r *mcpServiceRepository) List(ctx context.Context, tenantID uint) ([]*types.MCPService, error) {
func (r *mcpServiceRepository) List(ctx context.Context, tenantID uint64) ([]*types.MCPService, error) {
var services []*types.MCPService
err := r.db.WithContext(ctx).
Where("tenant_id = ?", tenantID).
@@ -57,7 +57,7 @@ func (r *mcpServiceRepository) List(ctx context.Context, tenantID uint) ([]*type
}
// ListEnabled retrieves all enabled MCP services for a tenant
func (r *mcpServiceRepository) ListEnabled(ctx context.Context, tenantID uint) ([]*types.MCPService, error) {
func (r *mcpServiceRepository) ListEnabled(ctx context.Context, tenantID uint64) ([]*types.MCPService, error) {
var services []*types.MCPService
err := r.db.WithContext(ctx).
Where("tenant_id = ? AND enabled = ?", tenantID, true).
@@ -72,7 +72,7 @@ func (r *mcpServiceRepository) ListEnabled(ctx context.Context, tenantID uint) (
}
// ListByIDs retrieves MCP services by multiple IDs for a tenant
func (r *mcpServiceRepository) ListByIDs(ctx context.Context, tenantID uint, ids []string) ([]*types.MCPService, error) {
func (r *mcpServiceRepository) ListByIDs(ctx context.Context, tenantID uint64, ids []string) ([]*types.MCPService, error) {
if len(ids) == 0 {
return []*types.MCPService{}, nil
}
@@ -134,7 +134,7 @@ func (r *mcpServiceRepository) Update(ctx context.Context, service *types.MCPSer
}
// Delete deletes an MCP service (soft delete)
func (r *mcpServiceRepository) Delete(ctx context.Context, tenantID uint, id string) error {
func (r *mcpServiceRepository) Delete(ctx context.Context, tenantID uint64, id string) error {
return r.db.WithContext(ctx).
Where("id = ? AND tenant_id = ?", id, tenantID).
Delete(&types.MCPService{}).Error
+3 -3
View File
@@ -25,7 +25,7 @@ func (r *modelRepository) Create(ctx context.Context, m *types.Model) error {
}
// GetByID retrieves a model by ID
func (r *modelRepository) GetByID(ctx context.Context, tenantID uint, id string) (*types.Model, error) {
func (r *modelRepository) GetByID(ctx context.Context, tenantID uint64, id string) (*types.Model, error) {
var m types.Model
if err := r.db.WithContext(ctx).Where("id = ?", id).Where(
"tenant_id = ? OR is_builtin = true", tenantID,
@@ -40,7 +40,7 @@ func (r *modelRepository) GetByID(ctx context.Context, tenantID uint, id string)
// List lists models with optional filtering
func (r *modelRepository) List(
ctx context.Context, tenantID uint, modelType types.ModelType, source types.ModelSource,
ctx context.Context, tenantID uint64, modelType types.ModelType, source types.ModelSource,
) ([]*types.Model, error) {
var models []*types.Model
query := r.db.WithContext(ctx).Where(
@@ -71,7 +71,7 @@ func (r *modelRepository) Update(ctx context.Context, m *types.Model) error {
}
// Delete deletes a model
func (r *modelRepository) Delete(ctx context.Context, tenantID uint, id string) error {
func (r *modelRepository) Delete(ctx context.Context, tenantID uint64, id string) error {
return r.db.WithContext(ctx).Where(
"id = ? AND tenant_id = ?", id, tenantID,
).Delete(&types.Model{}).Error
+4 -4
View File
@@ -31,7 +31,7 @@ func (r *sessionRepository) Create(ctx context.Context, session *types.Session)
}
// Get retrieves a session by ID
func (r *sessionRepository) Get(ctx context.Context, tenantID uint, id string) (*types.Session, error) {
func (r *sessionRepository) Get(ctx context.Context, tenantID uint64, id string) (*types.Session, error) {
var session types.Session
err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).First(&session, "id = ?", id).Error
if err != nil {
@@ -41,7 +41,7 @@ func (r *sessionRepository) Get(ctx context.Context, tenantID uint, id string) (
}
// GetByTenantID retrieves all sessions for a tenant
func (r *sessionRepository) GetByTenantID(ctx context.Context, tenantID uint) ([]*types.Session, error) {
func (r *sessionRepository) GetByTenantID(ctx context.Context, tenantID uint64) ([]*types.Session, error) {
var sessions []*types.Session
err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Order("created_at DESC").Find(&sessions).Error
if err != nil {
@@ -52,7 +52,7 @@ func (r *sessionRepository) GetByTenantID(ctx context.Context, tenantID uint) ([
// GetPagedByTenantID retrieves sessions for a tenant with pagination
func (r *sessionRepository) GetPagedByTenantID(
ctx context.Context, tenantID uint, page *types.Pagination,
ctx context.Context, tenantID uint64, page *types.Pagination,
) ([]*types.Session, int64, error) {
var sessions []*types.Session
var total int64
@@ -84,6 +84,6 @@ func (r *sessionRepository) Update(ctx context.Context, session *types.Session)
}
// Delete deletes a session
func (r *sessionRepository) Delete(ctx context.Context, tenantID uint, id string) error {
func (r *sessionRepository) Delete(ctx context.Context, tenantID uint64, id string) error {
return r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Delete(&types.Session{}, "id = ?", id).Error
}
+4 -4
View File
@@ -25,7 +25,7 @@ func (r *knowledgeTagRepository) Update(ctx context.Context, tag *types.Knowledg
return r.db.WithContext(ctx).Save(tag).Error
}
func (r *knowledgeTagRepository) GetByID(ctx context.Context, tenantID uint, id string) (*types.KnowledgeTag, error) {
func (r *knowledgeTagRepository) GetByID(ctx context.Context, tenantID uint64, id string) (*types.KnowledgeTag, error) {
var tag types.KnowledgeTag
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND id = ?", tenantID, id).
@@ -35,7 +35,7 @@ func (r *knowledgeTagRepository) GetByID(ctx context.Context, tenantID uint, id
return &tag, nil
}
func (r *knowledgeTagRepository) ListByKB(ctx context.Context, tenantID uint, kbID string) ([]*types.KnowledgeTag, error) {
func (r *knowledgeTagRepository) ListByKB(ctx context.Context, tenantID uint64, kbID string) ([]*types.KnowledgeTag, error) {
var tags []*types.KnowledgeTag
if err := r.db.WithContext(ctx).
Where("tenant_id = ? AND knowledge_base_id = ?", tenantID, kbID).
@@ -46,7 +46,7 @@ func (r *knowledgeTagRepository) ListByKB(ctx context.Context, tenantID uint, kb
return tags, nil
}
func (r *knowledgeTagRepository) Delete(ctx context.Context, tenantID uint, id string) error {
func (r *knowledgeTagRepository) Delete(ctx context.Context, tenantID uint64, id string) error {
return r.db.WithContext(ctx).
Where("tenant_id = ? AND id = ?", tenantID, id).
Delete(&types.KnowledgeTag{}).Error
@@ -55,7 +55,7 @@ func (r *knowledgeTagRepository) Delete(ctx context.Context, tenantID uint, id s
// CountReferences returns how many knowledges and chunks reference this tag.
func (r *knowledgeTagRepository) CountReferences(
ctx context.Context,
tenantID uint,
tenantID uint64,
kbID string,
tagID string,
) (knowledgeCount int64, chunkCount int64, err error) {
+3 -3
View File
@@ -32,7 +32,7 @@ func (r *tenantRepository) CreateTenant(ctx context.Context, tenant *types.Tenan
}
// GetTenantByID gets tenant by ID
func (r *tenantRepository) GetTenantByID(ctx context.Context, id uint) (*types.Tenant, error) {
func (r *tenantRepository) GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error) {
var tenant types.Tenant
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&tenant).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -58,11 +58,11 @@ func (r *tenantRepository) UpdateTenant(ctx context.Context, tenant *types.Tenan
}
// DeleteTenant deletes tenant
func (r *tenantRepository) DeleteTenant(ctx context.Context, id uint) error {
func (r *tenantRepository) DeleteTenant(ctx context.Context, id uint64) error {
return r.db.WithContext(ctx).Where("id = ?", id).Delete(&types.Tenant{}).Error
}
func (r *tenantRepository) AdjustStorageUsed(ctx context.Context, tenantID uint, delta int64) error {
func (r *tenantRepository) AdjustStorageUsed(ctx context.Context, tenantID uint64, delta int64) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var tenant types.Tenant
// 使用悲观锁确保并发安全
+6 -8
View File
@@ -4,16 +4,15 @@ import (
"context"
"errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
var (
ErrUserNotFound = errors.New("user not found")
ErrUserNotFound = errors.New("user not found")
ErrUserAlreadyExists = errors.New("user already exists")
ErrTokenNotFound = errors.New("token not found")
ErrTokenNotFound = errors.New("token not found")
)
// userRepository implements user repository interface
@@ -28,7 +27,6 @@ func NewUserRepository(db *gorm.DB) interfaces.UserRepository {
// CreateUser creates a user
func (r *userRepository) CreateUser(ctx context.Context, user *types.User) error {
logger.Infof(ctx, "Creating user in database: %s", user.Email)
return r.db.WithContext(ctx).Create(user).Error
}
@@ -82,15 +80,15 @@ func (r *userRepository) DeleteUser(ctx context.Context, id string) error {
func (r *userRepository) ListUsers(ctx context.Context, offset, limit int) ([]*types.User, error) {
var users []*types.User
query := r.db.WithContext(ctx).Order("created_at DESC")
if limit > 0 {
query = query.Limit(limit)
}
if offset > 0 {
query = query.Offset(offset)
}
if err := query.Find(&users).Error; err != nil {
return nil, err
}
@@ -151,4 +149,4 @@ func (r *authTokenRepository) DeleteExpiredTokens(ctx context.Context) error {
// RevokeTokensByUserID revokes all tokens for a user
func (r *authTokenRepository) RevokeTokensByUserID(ctx context.Context, userID string) error {
return r.db.WithContext(ctx).Model(&types.AuthToken{}).Where("user_id = ?", userID).Update("is_revoked", true).Error
}
}
@@ -95,8 +95,8 @@ func (s *agentService) CreateAgentEngine(
}
// Register MCP tools from enabled services for this tenant
tenantID := uint(0)
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint); ok {
tenantID := uint64(0)
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
tenantID = tid
}
if tenantID > 0 && s.mcpServiceService != nil && s.mcpManager != nil {
@@ -108,7 +108,7 @@ func (s *agentService) CreateAgentEngine(
// Filter enabled services
enabledServices := make([]*types.MCPService, 0)
for _, svc := range mcpServices {
if svc.Enabled {
if svc != nil && svc.Enabled {
enabledServices = append(enabledServices, svc)
}
}
@@ -179,8 +179,8 @@ func (s *agentService) registerTools(
}
// Get tenant ID from context
tenantID := uint(0)
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint); ok {
tenantID := uint64(0)
if tid, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok {
tenantID = tid
}
logger.Infof(ctx, "Registering tools: %v, tenant ID: %d, webSearchEnabled: %v", allowedTools, tenantID, config.WebSearchEnabled)
@@ -217,7 +217,7 @@ func (p *PluginMerge) populateFAQAnswers(ctx context.Context, chatManage *types.
return results
}
tenantID, _ := ctx.Value(types.TenantIDContextKey).(uint)
tenantID, _ := ctx.Value(types.TenantIDContextKey).(uint64)
if tenantID == 0 && chatManage != nil {
tenantID = chatManage.TenantID
}
@@ -342,7 +342,7 @@ func (p *PluginMerge) expandShortContextWithNeighbors(ctx context.Context, chatM
return results
}
tenantID, _ := ctx.Value(types.TenantIDContextKey).(uint)
tenantID, _ := ctx.Value(types.TenantIDContextKey).(uint64)
if tenantID == 0 && chatManage != nil {
tenantID = chatManage.TenantID
}
@@ -626,7 +626,7 @@ func containsID(ids []string, target string) bool {
return false
}
func (p *PluginMerge) fetchChunksIfMissing(ctx context.Context, tenantID uint, chunkMap map[string]*types.Chunk, chunkIDs ...string) {
func (p *PluginMerge) fetchChunksIfMissing(ctx context.Context, tenantID uint64, chunkMap map[string]*types.Chunk, chunkIDs ...string) {
missing := make([]string, 0, len(chunkIDs))
for _, id := range chunkIDs {
if id == "" {
@@ -100,7 +100,7 @@ func (p *PluginSearchEntity) OnEvent(ctx context.Context,
logger.Infof(ctx, "No new chunk found")
return next()
}
chunks, err := p.chunkRepo.ListChunksByID(ctx, ctx.Value(types.TenantIDContextKey).(uint), chunkIDs)
chunks, err := p.chunkRepo.ListChunksByID(ctx, ctx.Value(types.TenantIDContextKey).(uint64), chunkIDs)
if err != nil {
logger.Errorf(ctx, "Failed to list chunks, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
@@ -109,7 +109,7 @@ func (p *PluginSearchEntity) OnEvent(ctx context.Context,
for _, chunk := range chunks {
knowledgeIDs = append(knowledgeIDs, chunk.KnowledgeID)
}
knowledges, err := p.knowledgeRepo.GetKnowledgeBatch(ctx, ctx.Value(types.TenantIDContextKey).(uint), knowledgeIDs)
knowledges, err := p.knowledgeRepo.GetKnowledgeBatch(ctx, ctx.Value(types.TenantIDContextKey).(uint64), knowledgeIDs)
if err != nil {
logger.Errorf(ctx, "Failed to list knowledge, session_id: %s, error: %v", chatManage.SessionID, err)
return next()
+8 -8
View File
@@ -82,7 +82,7 @@ func (s *chunkService) CreateChunks(ctx context.Context, chunks []*types.Chunk)
// - *types.Chunk: Retrieved chunk if found
// - error: Any error encountered during retrieval
func (s *chunkService) GetChunkByID(ctx context.Context, id string) (*types.Chunk, error) {
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Getting chunk by ID, ID: %s, tenant ID: %d", id, tenantID)
chunk, err := s.chunkRepository.GetChunkByID(ctx, tenantID, id)
if err != nil {
@@ -110,7 +110,7 @@ func (s *chunkService) ListChunksByKnowledgeID(ctx context.Context, knowledgeID
logger.Info(ctx, "Start listing chunks by knowledge ID")
logger.Infof(ctx, "Knowledge ID: %s", knowledgeID)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
chunks, err := s.chunkRepository.ListChunksByKnowledgeID(ctx, tenantID, knowledgeID)
@@ -142,7 +142,7 @@ func (s *chunkService) ListPagedChunksByKnowledgeID(ctx context.Context,
logger.Info(ctx, "Start listing paged chunks by knowledge ID")
logger.Infof(ctx, "Knowledge ID: %s, page: %d, page size: %d", knowledgeID, page.Page, page.PageSize)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
chunks, total, err := s.chunkRepository.ListPagedChunksByKnowledgeID(ctx, tenantID, knowledgeID, page, chunkType, "")
if err != nil {
@@ -218,7 +218,7 @@ func (s *chunkService) DeleteChunk(ctx context.Context, id string) error {
logger.Info(ctx, "Start deleting chunk")
logger.Infof(ctx, "Deleting chunk, ID: %s", id)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
err := s.chunkRepository.DeleteChunk(ctx, tenantID, id)
@@ -249,7 +249,7 @@ func (s *chunkService) DeleteChunks(ctx context.Context, ids []string) error {
logger.Info(ctx, "Start deleting chunks in batch")
logger.Infof(ctx, "Deleting %d chunks", len(ids))
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
err := s.chunkRepository.DeleteChunks(ctx, tenantID, ids)
@@ -277,7 +277,7 @@ func (s *chunkService) DeleteChunksByKnowledgeID(ctx context.Context, knowledgeI
logger.Info(ctx, "Start deleting all chunks by knowledge ID")
logger.Infof(ctx, "Knowledge ID: %s", knowledgeID)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
err := s.chunkRepository.DeleteChunksByKnowledgeID(ctx, tenantID, knowledgeID)
@@ -297,7 +297,7 @@ func (s *chunkService) DeleteByKnowledgeList(ctx context.Context, ids []string)
logger.Info(ctx, "Start deleting all chunks by knowledge IDs")
logger.Infof(ctx, "Knowledge IDs: %v", ids)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
err := s.chunkRepository.DeleteByKnowledgeList(ctx, tenantID, ids)
@@ -313,7 +313,7 @@ func (s *chunkService) DeleteByKnowledgeList(ctx context.Context, ids []string)
return nil
}
func (s *chunkService) ListChunkByParentID(ctx context.Context, tenantID uint, parentID string) ([]*types.Chunk, error) {
func (s *chunkService) ListChunkByParentID(ctx context.Context, tenantID uint64, parentID string) ([]*types.Chunk, error) {
logger.Info(ctx, "Start listing chunk by parent ID")
logger.Infof(ctx, "Parent ID: %s", parentID)
+11 -2
View File
@@ -109,7 +109,7 @@ func (e *EvaluationService) EvaluationResult(ctx context.Context, taskID string)
return nil, err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(
ctx,
"Checking tenant ID match, task tenant ID: %d, current tenant ID: %d",
@@ -138,7 +138,7 @@ func (e *EvaluationService) Evaluation(ctx context.Context,
datasetID, knowledgeBaseID, chatModelID, rerankModelID)
// Get tenant ID from context for multi-tenancy support
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
// Handle knowledge base creation if not provided
@@ -154,6 +154,9 @@ func (e *EvaluationService) Evaluation(ctx context.Context,
var embeddingModelID, llmModelID string
for _, model := range models {
if model == nil {
continue
}
if model.Type == types.ModelTypeEmbedding {
embeddingModelID = model.ID
}
@@ -212,6 +215,9 @@ func (e *EvaluationService) Evaluation(ctx context.Context,
models, err := e.modelService.ListModels(ctx)
if err == nil {
for _, model := range models {
if model == nil {
continue
}
if model.Type == types.ModelTypeRerank {
rerankModelID = model.ID
break
@@ -230,6 +236,9 @@ func (e *EvaluationService) Evaluation(ctx context.Context,
models, err := e.modelService.ListModels(ctx)
if err == nil {
for _, model := range models {
if model == nil {
continue
}
if model.Type == types.ModelTypeKnowledgeQA {
chatModelID = model.ID
break
+1 -1
View File
@@ -16,7 +16,7 @@ import (
"github.com/hibiken/asynq"
)
func NewChunkExtractTask(ctx context.Context, client *asynq.Client, tenantID uint, chunkID string, modelID string) error {
func NewChunkExtractTask(ctx context.Context, client *asynq.Client, tenantID uint64, chunkID string, modelID string) error {
if strings.ToLower(os.Getenv("NEO4J_ENABLE")) != "true" {
logger.Warn(ctx, "NEO4J is not enabled, skip chunk extract task")
return nil
+1 -1
View File
@@ -46,7 +46,7 @@ func NewCosFileService(bucketName, region, secretId, secretKey, cosPathPrefix st
// SaveFile saves a file to COS storage
// It generates a unique name for the file and organizes it by tenant and knowledge ID
func (s *cosFileService) SaveFile(ctx context.Context,
file *multipart.FileHeader, tenantID uint, knowledgeID string,
file *multipart.FileHeader, tenantID uint64, knowledgeID string,
) (string, error) {
ext := filepath.Ext(file.Filename)
objectName := fmt.Sprintf("%s/%d/%s/%s%s", s.cosPathPrefix, tenantID, knowledgeID, uuid.New().String(), ext)
+1 -1
View File
@@ -22,7 +22,7 @@ func NewDummyFileService() interfaces.FileService {
// SaveFile pretends to save a file but just returns a random UUID
// This is useful for testing without actual file operations
func (s *DummyFileService) SaveFile(ctx context.Context,
file *multipart.FileHeader, tenantID uint, knowledgeID string,
file *multipart.FileHeader, tenantID uint64, knowledgeID string,
) (string, error) {
return uuid.New().String(), nil
}
+1 -1
View File
@@ -29,7 +29,7 @@ func NewLocalFileService(baseDir string) interfaces.FileService {
// The file is stored in a directory structure: baseDir/tenantID/knowledgeID/filename
// Returns the full file path or an error if saving fails
func (s *localFileService) SaveFile(ctx context.Context,
file *multipart.FileHeader, tenantID uint, knowledgeID string,
file *multipart.FileHeader, tenantID uint64, knowledgeID string,
) (string, error) {
logger.Info(ctx, "Starting to save file locally")
logger.Infof(ctx, "File information: name=%s, size=%d, tenant ID=%d, knowledge ID=%s",
+1 -1
View File
@@ -52,7 +52,7 @@ func NewMinioFileService(endpoint,
// SaveFile saves a file to MinIO
func (s *minioFileService) SaveFile(ctx context.Context,
file *multipart.FileHeader, tenantID uint, knowledgeID string,
file *multipart.FileHeader, tenantID uint64, knowledgeID string,
) (string, error) {
// Generate object name
ext := filepath.Ext(file.Filename)
+46
View File
@@ -131,6 +131,9 @@ func (b *graphBuilder) extractEntities(ctx context.Context, chunk *types.Chunk)
// Print detailed entity information in a clear format
log.Info("=========== EXTRACTED ENTITIES ===========")
for i, entity := range extractedEntities {
if entity == nil {
continue
}
log.Infof("[Entity %d] Title: '%s', Description: '%s'", i+1, entity.Title, entity.Description)
}
log.Info("=========================================")
@@ -156,6 +159,10 @@ func (b *graphBuilder) extractEntities(ctx context.Context, chunk *types.Chunk)
entities = append(entities, entity)
log.Debugf("New entity added: %s (ID: %s)", entity.Title, entity.ID)
} else {
if existEntity == nil {
log.Warnf("existEntity is nil, skip update")
continue
}
// Entity already exists, update its ChunkIDs
if !slices.Contains(existEntity.ChunkIDs, chunk.ID) {
existEntity.ChunkIDs = append(existEntity.ChunkIDs, chunk.ID)
@@ -231,6 +238,9 @@ func (b *graphBuilder) extractRelationships(ctx context.Context,
// Print detailed relationship information in a clear format
log.Info("========= EXTRACTED RELATIONSHIPS =========")
for i, rel := range extractedRelationships {
if rel == nil {
continue
}
log.Infof("[Relation %d] Source: '%s', Target: '%s', Description: '%s', Strength: %d",
i+1, rel.Source, rel.Target, rel.Description, rel.Strength)
}
@@ -243,6 +253,9 @@ func (b *graphBuilder) extractRelationships(ctx context.Context,
relationshipsAdded := 0
relationshipsUpdated := 0
for _, relationship := range extractedRelationships {
if relationship == nil {
continue
}
key := fmt.Sprintf("%s#%s", relationship.Source, relationship.Target)
relationChunkIDs := b.findRelationChunkIDs(relationship.Source, relationship.Target, entities)
if len(relationChunkIDs) == 0 {
@@ -291,6 +304,9 @@ func (b *graphBuilder) findRelationChunkIDs(source, target string, entities []*t
// Collect all document chunk IDs for source and target entities
for _, entity := range entities {
if entity == nil {
continue
}
if entity.Title == source || entity.Title == target {
for _, chunkID := range entity.ChunkIDs {
relationChunkIDs[chunkID] = struct{}{}
@@ -475,6 +491,9 @@ func (b *graphBuilder) calculateWeights(ctx context.Context) {
entityFrequency := make(map[string]int)
for _, entity := range b.entityMap {
if entity == nil {
continue
}
frequency := len(entity.ChunkIDs)
entityFrequency[entity.Title] = frequency
totalEntityOccurrences += frequency
@@ -483,6 +502,9 @@ func (b *graphBuilder) calculateWeights(ctx context.Context) {
// Calculate total relationship occurrences
totalRelOccurrences := 0
for _, rel := range b.relationshipMap {
if rel == nil {
continue
}
totalRelOccurrences += len(rel.ChunkIDs)
}
@@ -499,6 +521,9 @@ func (b *graphBuilder) calculateWeights(ctx context.Context) {
// First calculate PMI and find maximum values
pmiValues := make(map[string]float64)
for _, rel := range b.relationshipMap {
if rel == nil {
continue
}
sourceFreq := entityFrequency[rel.Source]
targetFreq := entityFrequency[rel.Target]
relFreq := len(rel.ChunkIDs)
@@ -564,11 +589,17 @@ func (b *graphBuilder) calculateDegrees(ctx context.Context) {
// Set degree for each entity
for _, entity := range b.entityMap {
if entity == nil {
continue
}
entity.Degree = inDegree[entity.Title] + outDegree[entity.Title]
}
// Set combined degree for relationships
for _, rel := range b.relationshipMap {
if rel == nil {
continue
}
sourceEntity := b.getEntityByTitle(rel.Source)
targetEntity := b.getEntityByTitle(rel.Target)
@@ -588,6 +619,9 @@ func (b *graphBuilder) buildChunkGraph(ctx context.Context) {
// Create document chunk relationship graph based on entity relationships
for _, rel := range b.relationshipMap {
if rel == nil {
continue
}
// Ensure source and target entities exist for the relationship
sourceEntity := b.entityMapByTitle[rel.Source]
targetEntity := b.entityMapByTitle[rel.Target]
@@ -665,6 +699,9 @@ func (b *graphBuilder) GetRelationChunks(chunkID string, topK int) []string {
// Collect related chunks with their weights and degrees
weightedChunks := make([]weightedChunk, 0)
for relationChunkID, relation := range b.chunkGraph[chunkID] {
if relation == nil {
continue
}
weightedChunks = append(weightedChunks, weightedChunk{
id: relationChunkID,
weight: relation.Weight,
@@ -737,8 +774,14 @@ func (b *graphBuilder) GetIndirectRelationChunks(chunkID string, topK int) []str
// Get first-degree connections
for directChunkID, directRelation := range b.chunkGraph[chunkID] {
if directRelation == nil {
continue
}
// Get second-degree connections
for indirectChunkID, indirectRelation := range b.chunkGraph[directChunkID] {
if indirectRelation == nil {
continue
}
// Skip self and all direct connections
if _, isDirect := directChunks[indirectChunkID]; isDirect {
continue
@@ -764,6 +807,9 @@ func (b *graphBuilder) GetIndirectRelationChunks(chunkID string, topK int) []str
// Convert to sortable slice
weightedChunks := make([]weightedChunk, 0, len(indirectChunkMap))
for id, relation := range indirectChunkMap {
if relation == nil {
continue
}
weightedChunks = append(weightedChunks, weightedChunk{
id: id,
weight: relation.Weight,
+34 -33
View File
@@ -190,7 +190,7 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
}
// Check if file already exists
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Checking if file exists, tenant ID: %d", tenantID)
exists, existingKnowledge, err := s.repo.CheckKnowledgeExists(ctx, tenantID, kbID, &types.KnowledgeCheckParams{
Type: "file",
@@ -339,7 +339,7 @@ func (s *knowledgeService) CreateKnowledgeFromURL(ctx context.Context,
}
// Check if URL already exists in the knowledge base
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Checking if URL exists, tenant ID: %d", tenantID)
fileHash := calculateStr(url)
exists, existingKnowledge, err := s.repo.CheckKnowledgeExists(ctx, tenantID, kbID, &types.KnowledgeCheckParams{
@@ -479,7 +479,7 @@ func (s *knowledgeService) CreateKnowledgeFromManual(ctx context.Context,
return nil, err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
now := time.Now()
title := safeTitle
if title == "" {
@@ -566,7 +566,7 @@ func (s *knowledgeService) createKnowledgeFromPassageInternal(ctx context.Contex
}
knowledge := &types.Knowledge{
ID: uuid.New().String(),
TenantID: ctx.Value(types.TenantIDContextKey).(uint),
TenantID: ctx.Value(types.TenantIDContextKey).(uint64),
KnowledgeBaseID: kbID,
Type: "passage",
ParseStatus: "pending",
@@ -591,7 +591,7 @@ func (s *knowledgeService) createKnowledgeFromPassageInternal(ctx context.Contex
} else {
// Enqueue passage processing task to Asynq
logger.Info(ctx, "Enqueuing passage processing task to Asynq")
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
taskPayload := types.DocumentProcessPayload{
TenantID: tenantID,
KnowledgeID: knowledge.ID,
@@ -624,7 +624,7 @@ func (s *knowledgeService) GetKnowledgeByID(ctx context.Context, id string) (*ty
logger.Info(ctx, "Start getting knowledge by ID")
logger.Infof(ctx, "Knowledge ID: %s", id)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, id)
@@ -644,7 +644,7 @@ func (s *knowledgeService) GetKnowledgeByID(ctx context.Context, id string) (*ty
func (s *knowledgeService) ListKnowledgeByKnowledgeBaseID(ctx context.Context,
kbID string,
) ([]*types.Knowledge, error) {
return s.repo.ListKnowledgeByKnowledgeBaseID(ctx, ctx.Value(types.TenantIDContextKey).(uint), kbID)
return s.repo.ListKnowledgeByKnowledgeBaseID(ctx, ctx.Value(types.TenantIDContextKey).(uint64), kbID)
}
// ListPagedKnowledgeByKnowledgeBaseID returns paginated knowledge entries in a knowledge base
@@ -652,7 +652,7 @@ func (s *knowledgeService) ListPagedKnowledgeByKnowledgeBaseID(ctx context.Conte
kbID string, page *types.Pagination, tagID string,
) (*types.PageResult, error) {
knowledges, total, err := s.repo.ListPagedKnowledgeByKnowledgeBaseID(ctx,
ctx.Value(types.TenantIDContextKey).(uint), kbID, page, tagID)
ctx.Value(types.TenantIDContextKey).(uint64), kbID, page, tagID)
if err != nil {
return nil, err
}
@@ -663,7 +663,7 @@ func (s *knowledgeService) ListPagedKnowledgeByKnowledgeBaseID(ctx context.Conte
// DeleteKnowledge deletes a knowledge entry and all related resources
func (s *knowledgeService) DeleteKnowledge(ctx context.Context, id string) error {
// Get the knowledge entry
knowledge, err := s.repo.GetKnowledgeByID(ctx, ctx.Value(types.TenantIDContextKey).(uint), id)
knowledge, err := s.repo.GetKnowledgeByID(ctx, ctx.Value(types.TenantIDContextKey).(uint64), id)
if err != nil {
return err
}
@@ -726,7 +726,7 @@ func (s *knowledgeService) DeleteKnowledge(ctx context.Context, id string) error
return err
}
// Delete the knowledge entry itself from the database
return s.repo.DeleteKnowledge(ctx, ctx.Value(types.TenantIDContextKey).(uint), id)
return s.repo.DeleteKnowledge(ctx, ctx.Value(types.TenantIDContextKey).(uint64), id)
}
// DeleteKnowledge deletes a knowledge entry and all related resources
@@ -1544,7 +1544,8 @@ func (s *knowledgeService) getSummary(ctx context.Context,
// GetKnowledgeFile retrieves the physical file associated with a knowledge entry
func (s *knowledgeService) GetKnowledgeFile(ctx context.Context, id string) (io.ReadCloser, string, error) {
// Get knowledge record
knowledge, err := s.repo.GetKnowledgeByID(ctx, ctx.Value(types.TenantIDContextKey).(uint), id)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, id)
if err != nil {
return nil, "", err
}
@@ -1559,7 +1560,7 @@ func (s *knowledgeService) GetKnowledgeFile(ctx context.Context, id string) (io.
}
func (s *knowledgeService) UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error {
record, err := s.repo.GetKnowledgeByID(ctx, ctx.Value(types.TenantIDContextKey).(uint), knowledge.ID)
record, err := s.repo.GetKnowledgeByID(ctx, ctx.Value(types.TenantIDContextKey).(uint64), knowledge.ID)
if err != nil {
logger.Errorf(ctx, "Failed to get knowledge record: %v", err)
return err
@@ -1608,7 +1609,7 @@ func (s *knowledgeService) UpdateManualKnowledge(ctx context.Context,
return nil, werrors.NewValidationError("状态仅支持 draft 或 publish")
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
existing, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID)
if err != nil {
logger.Errorf(ctx, "Failed to load knowledge: %v", err)
@@ -1714,7 +1715,7 @@ func isValidURL(url string) bool {
// GetKnowledgeBatch retrieves multiple knowledge entries by their IDs
func (s *knowledgeService) GetKnowledgeBatch(ctx context.Context,
tenantID uint, ids []string,
tenantID uint64, ids []string,
) ([]*types.Knowledge, error) {
if len(ids) == 0 {
return nil, nil
@@ -1885,7 +1886,7 @@ func (s *knowledgeService) UpdateImageInfo(ctx context.Context, knowledgeID stri
return err
}
chunk.ImageInfo = imageInfo
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
chunkChildren, err := s.chunkService.ListChunkByParentID(ctx, tenantID, chunkID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
@@ -2140,7 +2141,7 @@ func (s *knowledgeService) ListFAQEntries(ctx context.Context,
if err != nil {
return nil, err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
faqKnowledge, err := s.findFAQKnowledge(ctx, tenantID, kb.ID)
if err != nil {
return nil, err
@@ -2188,7 +2189,7 @@ func (s *knowledgeService) UpsertFAQEntries(ctx context.Context,
return "", err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
// 检查是否有正在进行的导入任务
runningKnowledge, err := s.getRunningFAQImportTask(ctx, kbID, tenantID)
@@ -2246,7 +2247,7 @@ func (s *knowledgeService) UpsertFAQEntries(ctx context.Context,
// calculateAppendOperations 计算Append模式下需要处理的条目,跳过已存在且内容相同的条目
func (s *knowledgeService) calculateAppendOperations(ctx context.Context,
tenantID uint, knowledgeID string, entries []types.FAQEntryPayload) ([]types.FAQEntryPayload, int, error) {
tenantID uint64, knowledgeID string, entries []types.FAQEntryPayload) ([]types.FAQEntryPayload, int, error) {
if len(entries) == 0 {
return []types.FAQEntryPayload{}, 0, nil
}
@@ -2255,7 +2256,7 @@ func (s *knowledgeService) calculateAppendOperations(ctx context.Context,
// calculateReplaceOperations 计算Replace模式下需要删除、创建、更新的条目
func (s *knowledgeService) calculateReplaceOperations(ctx context.Context,
tenantID uint, knowledgeID string, newEntries []types.FAQEntryPayload) ([]types.FAQEntryPayload, []*types.Chunk, int, error) {
tenantID uint64, knowledgeID string, newEntries []types.FAQEntryPayload) ([]types.FAQEntryPayload, []*types.Chunk, int, error) {
// 计算所有新条目的 content hash,并同时构建 hash 到 entry 的映射
type entryWithHash struct {
entry types.FAQEntryPayload
@@ -2322,7 +2323,7 @@ func (s *knowledgeService) calculateReplaceOperations(ctx context.Context,
// executeFAQImport 执行实际的FAQ导入逻辑
func (s *knowledgeService) executeFAQImport(ctx context.Context, taskID string, kbID string,
payload *types.FAQBatchUpsertPayload, tenantID uint, processedCount int) (err error) {
payload *types.FAQBatchUpsertPayload, tenantID uint64, processedCount int) (err error) {
// 保存知识库和embedding模型信息,用于清理索引
var kb *types.KnowledgeBase
var embeddingModel embedding.Embedder
@@ -2521,7 +2522,7 @@ func (s *knowledgeService) UpdateFAQEntry(ctx context.Context,
return err
}
kb.EnsureDefaults()
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, entryID)
if err != nil {
return err
@@ -2592,7 +2593,7 @@ func (s *knowledgeService) UpdateFAQEntryStatus(ctx context.Context,
if err != nil {
return err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, entryID)
if err != nil {
return err
@@ -2634,7 +2635,7 @@ func (s *knowledgeService) UpdateFAQEntryStatusBatch(ctx context.Context,
if err != nil {
return err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
// Get all chunks in batch
entryIDs := make([]string, 0, len(updates))
@@ -2684,7 +2685,7 @@ func (s *knowledgeService) UpdateFAQEntryStatusBatch(ctx context.Context,
// UpdateKnowledgeTag updates the tag assigned to a knowledge document.
func (s *knowledgeService) UpdateKnowledgeTag(ctx context.Context, knowledgeID string, tagID *string) error {
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID)
if err != nil {
return err
@@ -2711,7 +2712,7 @@ func (s *knowledgeService) UpdateKnowledgeTagBatch(ctx context.Context, updates
if len(updates) == 0 {
return nil
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
// Get all knowledge items in batch
knowledgeIDs := make([]string, 0, len(updates))
@@ -2784,7 +2785,7 @@ func (s *knowledgeService) UpdateFAQEntryTag(ctx context.Context, kbID string, e
if err != nil {
return err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, entryID)
if err != nil {
return err
@@ -2819,7 +2820,7 @@ func (s *knowledgeService) UpdateFAQEntryTagBatch(ctx context.Context, kbID stri
if err != nil {
return err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
// Get all chunks in batch
entryIDs := make([]string, 0, len(updates))
@@ -2942,7 +2943,7 @@ func (s *knowledgeService) SearchFAQEntries(ctx context.Context,
}
// Batch fetch chunks
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
chunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs)
if err != nil {
return nil, err
@@ -2997,7 +2998,7 @@ func (s *knowledgeService) DeleteFAQEntries(ctx context.Context,
return err
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
var faqKnowledge *types.Knowledge
chunksToRemove := make([]*types.Chunk, 0, len(entryIDs))
for _, id := range entryIDs {
@@ -3045,7 +3046,7 @@ func (s *knowledgeService) validateFAQKnowledgeBase(ctx context.Context, kbID st
return kb, nil
}
func (s *knowledgeService) findFAQKnowledge(ctx context.Context, tenantID uint, kbID string) (*types.Knowledge, error) {
func (s *knowledgeService) findFAQKnowledge(ctx context.Context, tenantID uint64, kbID string) (*types.Knowledge, error) {
knowledges, err := s.repo.ListKnowledgeByKnowledgeBaseID(ctx, tenantID, kbID)
if err != nil {
return nil, err
@@ -3058,7 +3059,7 @@ func (s *knowledgeService) findFAQKnowledge(ctx context.Context, tenantID uint,
return nil, nil
}
func (s *knowledgeService) ensureFAQKnowledge(ctx context.Context, tenantID uint, kb *types.KnowledgeBase) (*types.Knowledge, error) {
func (s *knowledgeService) ensureFAQKnowledge(ctx context.Context, tenantID uint64, kb *types.KnowledgeBase) (*types.Knowledge, error) {
existing, err := s.findFAQKnowledge(ctx, tenantID, kb.ID)
if err != nil {
return nil, err
@@ -3093,7 +3094,7 @@ func (s *knowledgeService) updateFAQImportStatus(ctx context.Context, knowledgeI
// updateFAQImportStatusWithRanges 更新FAQ Knowledge的导入任务状态,包含NextChunkIndex
func (s *knowledgeService) updateFAQImportStatusWithRanges(ctx context.Context, knowledgeID string, status types.FAQImportTaskStatus,
progress, total, processed int, errorMsg string) error {
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID)
if err != nil {
return err
@@ -3129,7 +3130,7 @@ func (s *knowledgeService) updateFAQImportStatusWithRanges(ctx context.Context,
}
// getRunningFAQImportTask 获取指定知识库的进行中导入任务
func (s *knowledgeService) getRunningFAQImportTask(ctx context.Context, kbID string, tenantID uint) (*types.Knowledge, error) {
func (s *knowledgeService) getRunningFAQImportTask(ctx context.Context, kbID string, tenantID uint64) (*types.Knowledge, error) {
faqKnowledge, err := s.findFAQKnowledge(ctx, tenantID, kbID)
if err != nil {
return nil, err
@@ -73,7 +73,7 @@ func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context,
kb.ID = uuid.New().String()
}
kb.CreatedAt = time.Now()
kb.TenantID = ctx.Value(types.TenantIDContextKey).(uint)
kb.TenantID = ctx.Value(types.TenantIDContextKey).(uint64)
kb.UpdatedAt = time.Now()
kb.EnsureDefaults()
@@ -112,7 +112,7 @@ func (s *knowledgeBaseService) GetKnowledgeBaseByID(ctx context.Context, id stri
// ListKnowledgeBases returns all knowledge bases for a tenant
func (s *knowledgeBaseService) ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error) {
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
kbs, err := s.repo.ListKnowledgeBasesByTenantID(ctx, tenantID)
if err != nil {
@@ -222,7 +222,7 @@ func (s *knowledgeBaseService) DeleteKnowledgeBase(ctx context.Context, id strin
logger.Infof(ctx, "Deleting knowledge base, ID: %s", id)
// Get tenant ID from context
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
// Step 1: Get all knowledge entries in this knowledge base
logger.Infof(ctx, "Fetching all knowledge entries in knowledge base, ID: %s", id)
@@ -390,7 +390,7 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
return nil, nil, err
}
sourceKB.EnsureDefaults()
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
var targetKB *types.KnowledgeBase
if dstKB != "" {
targetKB, err = s.repo.GetKnowledgeBaseByID(ctx, dstKB)
@@ -685,7 +685,7 @@ func (s *knowledgeBaseService) filterByNegativeQuestions(ctx context.Context,
return chunks
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
// Collect chunk IDs
chunkIDs := make([]string, 0, len(chunks))
@@ -772,7 +772,7 @@ func (s *knowledgeBaseService) processSearchResults(ctx context.Context,
return nil, nil
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
// Prepare data structures for efficient processing
var knowledgeIDs []string
@@ -950,7 +950,7 @@ func (s *knowledgeBaseService) isValidTextChunk(chunk *types.Chunk) bool {
// fetchKnowledgeData gets knowledge data in batch
func (s *knowledgeBaseService) fetchKnowledgeData(ctx context.Context,
tenantID uint,
tenantID uint64,
knowledgeIDs []string,
) (map[string]*types.Knowledge, error) {
knowledges, err := s.kgRepo.GetKnowledgeBatch(ctx, tenantID, knowledgeIDs)
+7 -7
View File
@@ -49,7 +49,7 @@ func (s *mcpServiceService) CreateMCPService(ctx context.Context, service *types
}
// GetMCPServiceByID retrieves an MCP service by ID
func (s *mcpServiceService) GetMCPServiceByID(ctx context.Context, tenantID uint, id string) (*types.MCPService, error) {
func (s *mcpServiceService) GetMCPServiceByID(ctx context.Context, tenantID uint64, id string) (*types.MCPService, error) {
service, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
if err != nil {
logger.GetLogger(ctx).Errorf("Failed to get MCP service: %v", err)
@@ -64,7 +64,7 @@ func (s *mcpServiceService) GetMCPServiceByID(ctx context.Context, tenantID uint
}
// ListMCPServices lists all MCP services for a tenant
func (s *mcpServiceService) ListMCPServices(ctx context.Context, tenantID uint) ([]*types.MCPService, error) {
func (s *mcpServiceService) ListMCPServices(ctx context.Context, tenantID uint64) ([]*types.MCPService, error) {
services, err := s.mcpServiceRepo.List(ctx, tenantID)
if err != nil {
logger.GetLogger(ctx).Errorf("Failed to list MCP services: %v", err)
@@ -80,7 +80,7 @@ func (s *mcpServiceService) ListMCPServices(ctx context.Context, tenantID uint)
}
// ListMCPServicesByIDs retrieves multiple MCP services by IDs
func (s *mcpServiceService) ListMCPServicesByIDs(ctx context.Context, tenantID uint, ids []string) ([]*types.MCPService, error) {
func (s *mcpServiceService) ListMCPServicesByIDs(ctx context.Context, tenantID uint64, ids []string) ([]*types.MCPService, error) {
if len(ids) == 0 {
return []*types.MCPService{}, nil
}
@@ -198,7 +198,7 @@ func (s *mcpServiceService) UpdateMCPService(ctx context.Context, service *types
}
// DeleteMCPService deletes an MCP service
func (s *mcpServiceService) DeleteMCPService(ctx context.Context, tenantID uint, id string) error {
func (s *mcpServiceService) DeleteMCPService(ctx context.Context, tenantID uint64, id string) error {
// Check if service exists
existing, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
if err != nil {
@@ -221,7 +221,7 @@ func (s *mcpServiceService) DeleteMCPService(ctx context.Context, tenantID uint,
}
// TestMCPService tests the connection to an MCP service and returns available tools/resources
func (s *mcpServiceService) TestMCPService(ctx context.Context, tenantID uint, id string) (*types.MCPTestResult, error) {
func (s *mcpServiceService) TestMCPService(ctx context.Context, tenantID uint64, id string) (*types.MCPTestResult, error) {
// Get service
service, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
if err != nil {
@@ -288,7 +288,7 @@ func (s *mcpServiceService) TestMCPService(ctx context.Context, tenantID uint, i
}
// GetMCPServiceTools retrieves the list of tools from an MCP service
func (s *mcpServiceService) GetMCPServiceTools(ctx context.Context, tenantID uint, id string) ([]*types.MCPTool, error) {
func (s *mcpServiceService) GetMCPServiceTools(ctx context.Context, tenantID uint64, id string) ([]*types.MCPTool, error) {
// Get service
service, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
if err != nil {
@@ -314,7 +314,7 @@ func (s *mcpServiceService) GetMCPServiceTools(ctx context.Context, tenantID uin
}
// GetMCPServiceResources retrieves the list of resources from an MCP service
func (s *mcpServiceService) GetMCPServiceResources(ctx context.Context, tenantID uint, id string) ([]*types.MCPResource, error) {
func (s *mcpServiceService) GetMCPServiceResources(ctx context.Context, tenantID uint64, id string) ([]*types.MCPResource, error) {
// Get service
service, err := s.mcpServiceRepo.GetByID(ctx, tenantID, id)
if err != nil {
+7 -7
View File
@@ -43,7 +43,7 @@ func (s *messageService) CreateMessage(ctx context.Context, message *types.Messa
logger.Infof(ctx, "Creating message for session ID: %s", message.SessionID)
// Check if the session exists to validate the message belongs to a valid session
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d, session ID: %s", tenantID, message.SessionID)
_, err := s.sessionRepo.Get(ctx, tenantID, message.SessionID)
if err != nil {
@@ -77,7 +77,7 @@ func (s *messageService) GetMessage(ctx context.Context, sessionID string, messa
logger.Infof(ctx, "Getting message, session ID: %s, message ID: %s", sessionID, messageID)
// Verify the session exists before attempting to retrieve the message
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionID)
if err != nil {
@@ -115,7 +115,7 @@ func (s *messageService) GetMessagesBySession(ctx context.Context,
logger.Infof(ctx, "Getting messages for session ID: %s, page: %d, pageSize: %d", sessionID, page, pageSize)
// Verify the session exists before retrieving messages
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionID)
if err != nil {
@@ -154,7 +154,7 @@ func (s *messageService) GetRecentMessagesBySession(ctx context.Context,
logger.Infof(ctx, "Getting recent messages for session ID: %s, limit: %d", sessionID, limit)
// Verify the session exists before retrieving messages
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionID)
if err != nil {
@@ -193,7 +193,7 @@ func (s *messageService) GetMessagesBySessionBeforeTime(ctx context.Context,
logger.Infof(ctx, "Getting messages before %v for session ID: %s, limit: %d", beforeTime, sessionID, limit)
// Verify the session exists before retrieving messages
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionID)
if err != nil {
@@ -228,7 +228,7 @@ func (s *messageService) UpdateMessage(ctx context.Context, message *types.Messa
logger.Infof(ctx, "Updating message, ID: %s, session ID: %s", message.ID, message.SessionID)
// Verify the session exists before updating the message
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, message.SessionID)
if err != nil {
@@ -263,7 +263,7 @@ func (s *messageService) DeleteMessage(ctx context.Context, sessionID string, me
logger.Infof(ctx, "Deleting message, session ID: %s, message ID: %s", sessionID, messageID)
// Verify the session exists before deleting the message
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionID)
if err != nil {
+5 -5
View File
@@ -101,7 +101,7 @@ func (s *modelService) GetModelByID(ctx context.Context, id string) (*types.Mode
return nil, errors.New("model ID cannot be empty")
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
// Fetch model from repository
model, err := s.repo.GetByID(ctx, tenantID, id)
@@ -145,7 +145,7 @@ func (s *modelService) GetModelByID(ctx context.Context, id string) (*types.Mode
func (s *modelService) ListModels(ctx context.Context) ([]*types.Model, error) {
logger.Info(ctx, "Start listing models")
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Listing models for tenant ID: %d", tenantID)
// List models from repository with no additional filters
@@ -167,7 +167,7 @@ func (s *modelService) UpdateModel(ctx context.Context, model *types.Model) erro
logger.Infof(ctx, "Updating model ID: %s, name: %s", model.ID, model.Name)
// Check if the model is builtin - builtin models cannot be updated
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
existingModel, err := s.repo.GetByID(ctx, tenantID, model.ID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
@@ -199,7 +199,7 @@ func (s *modelService) DeleteModel(ctx context.Context, id string) error {
logger.Info(ctx, "Start deleting model")
logger.Infof(ctx, "Deleting model ID: %s", id)
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Tenant ID: %d", tenantID)
// Check if the model is builtin - builtin models cannot be deleted
@@ -308,7 +308,7 @@ func (s *modelService) GetChatModel(ctx context.Context, modelId string) (chat.C
return nil, errors.New("model ID cannot be empty")
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
// Get the model directly from repository to avoid status checks
model, err := s.repo.GetByID(ctx, tenantID, modelId)
@@ -38,6 +38,9 @@ func (c *CompositeRetrieveEngine) Retrieve(ctx context.Context,
func(ctx context.Context, param types.RetrieveParams, results *[]*types.RetrieveResult, mu *sync.Mutex) error {
found := false
for _, engineInfo := range c.engineInfos {
if engineInfo == nil {
continue
}
if slices.Contains(engineInfo.retrieverType, param.RetrieverType) {
result, err := engineInfo.retrieveEngine.Retrieve(ctx, param)
if err != nil {
@@ -86,6 +89,9 @@ func NewCompositeRetrieveEngine(registry interfaces.RetrieveEngineRegistry, engi
// SupportRetriever checks if a retriever type is supported by any of the registered engines
func (c *CompositeRetrieveEngine) SupportRetriever(r types.RetrieverType) bool {
for _, engineInfo := range c.engineInfos {
if engineInfo == nil {
continue
}
if slices.Contains(engineInfo.retrieverType, r) {
return true
}
+14 -5
View File
@@ -108,7 +108,7 @@ func (s *sessionService) GetSession(ctx context.Context, id string) (*types.Sess
}
// Get tenant ID from context
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Retrieving session, ID: %s, tenant ID: %d", id, tenantID)
// Get session from repository
@@ -128,7 +128,7 @@ func (s *sessionService) GetSession(ctx context.Context, id string) (*types.Sess
// GetSessionsByTenant retrieves all sessions for the current tenant
func (s *sessionService) GetSessionsByTenant(ctx context.Context) ([]*types.Session, error) {
// Get tenant ID from context
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
logger.Infof(ctx, "Retrieving all sessions for tenant, tenant ID: %d", tenantID)
// Get sessions from repository
@@ -151,7 +151,7 @@ func (s *sessionService) GetPagedSessionsByTenant(ctx context.Context,
pagination *types.Pagination,
) (*types.PageResult, error) {
// Get tenant ID from context
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
// Get paged sessions from repository
sessions, total, err := s.sessionRepo.GetPagedByTenantID(ctx, tenantID, pagination)
if err != nil {
@@ -197,7 +197,7 @@ func (s *sessionService) DeleteSession(ctx context.Context, id string) error {
}
// Get tenant ID from context
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
// Cleanup temporary KB stored in Redis for this session
if err := s.DeleteWebSearchTempKBState(ctx, id); err != nil {
@@ -267,6 +267,9 @@ func (s *sessionService) GenerateTitle(ctx context.Context,
}
// Find first available KnowledgeQA model
for _, model := range models {
if model == nil {
continue
}
if model.Type == types.ModelTypeKnowledgeQA {
modelID = model.ID
logger.Infof(ctx, "Using first available KnowledgeQA model: %s", modelID)
@@ -746,6 +749,9 @@ func (s *sessionService) SearchKnowledge(ctx context.Context,
// Find the first available rerank model
for _, model := range models {
if model == nil {
continue
}
if model.Type == types.ModelTypeRerank {
chatManage.RerankModelID = model.ID
break
@@ -808,7 +814,7 @@ func (s *sessionService) SearchKnowledge(ctx context.Context,
// AgentQA performs agent-based question answering with conversation history and streaming support
func (s *sessionService) AgentQA(ctx context.Context, session *types.Session, query string, assistantMessageID string, eventBus *event.EventBus) error {
sessionID := session.ID
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
sessionJSON, err := json.Marshal(session)
if err != nil {
logger.Errorf(ctx, "Failed to marshal session, session ID: %s, error: %v", sessionID, err)
@@ -892,6 +898,9 @@ func (s *sessionService) AgentQA(ctx context.Context, session *types.Session, qu
// Extract knowledge base IDs
agentConfig.KnowledgeBases = make([]string, len(allKBs))
for i, kb := range allKBs {
if kb == nil {
continue
}
agentConfig.KnowledgeBases[i] = kb.ID
}
logger.Infof(ctx, "Agent defaulting to all %d knowledge base(s) in tenant: %v",
+5 -2
View File
@@ -48,6 +48,9 @@ func (s *knowledgeTagService) ListTags(ctx context.Context, kbID string) ([]*typ
results := make([]*types.KnowledgeTagWithStats, 0, len(tags))
for _, tag := range tags {
if tag == nil {
continue
}
kCount, cCount, err := s.repo.CountReferences(ctx, tenantID, kbID, tag.ID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
@@ -97,7 +100,7 @@ func (s *knowledgeTagService) UpdateTag(ctx context.Context, id string, name *st
if id == "" {
return nil, werrors.NewBadRequestError("标签ID不能为空")
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
tag, err := s.repo.GetByID(ctx, tenantID, id)
if err != nil {
return nil, err
@@ -128,7 +131,7 @@ func (s *knowledgeTagService) DeleteTag(ctx context.Context, id string, force bo
if id == "" {
return werrors.NewBadRequestError("标签ID不能为空")
}
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
tag, err := s.repo.GetByID(ctx, tenantID, id)
if err != nil {
return err
+6 -6
View File
@@ -80,7 +80,7 @@ func (s *tenantService) CreateTenant(ctx context.Context, tenant *types.Tenant)
}
// GetTenantByID retrieves a tenant by their ID
func (s *tenantService) GetTenantByID(ctx context.Context, id uint) (*types.Tenant, error) {
func (s *tenantService) GetTenantByID(ctx context.Context, id uint64) (*types.Tenant, error) {
if id == 0 {
logger.Error(ctx, "Tenant ID cannot be 0")
return nil, errors.New("tenant ID cannot be 0")
@@ -139,7 +139,7 @@ func (s *tenantService) UpdateTenant(ctx context.Context, tenant *types.Tenant)
}
// DeleteTenant removes a tenant by their ID
func (s *tenantService) DeleteTenant(ctx context.Context, id uint) error {
func (s *tenantService) DeleteTenant(ctx context.Context, id uint64) error {
logger.Info(ctx, "Start deleting tenant")
if id == 0 {
@@ -177,7 +177,7 @@ func (s *tenantService) DeleteTenant(ctx context.Context, id uint) error {
}
// UpdateAPIKey updates the API key for a specific tenant
func (s *tenantService) UpdateAPIKey(ctx context.Context, id uint) (string, error) {
func (s *tenantService) UpdateAPIKey(ctx context.Context, id uint64) (string, error) {
logger.Info(ctx, "Start updating tenant API Key")
if id == 0 {
@@ -208,7 +208,7 @@ func (s *tenantService) UpdateAPIKey(ctx context.Context, id uint) (string, erro
}
// generateApiKey generates a secure API key for tenant authentication
func (r *tenantService) generateApiKey(tenantID uint) string {
func (r *tenantService) generateApiKey(tenantID uint64) string {
// 1. Convert tenant_id to bytes
idBytes := make([]byte, 8)
binary.LittleEndian.PutUint64(idBytes, uint64(tenantID))
@@ -240,7 +240,7 @@ func (r *tenantService) generateApiKey(tenantID uint) string {
}
// ExtractTenantIDFromAPIKey extracts the tenant ID from an API key
func (r *tenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint, error) {
func (r *tenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint64, error) {
// 1. Validate format and extract encrypted part
parts := strings.SplitN(apiKey, "-", 2)
if len(parts) != 2 || parts[0] != "sk" {
@@ -278,5 +278,5 @@ func (r *tenantService) ExtractTenantIDFromAPIKey(apiKey string) (uint, error) {
// 5. Convert back to tenant_id
tenantID := binary.LittleEndian.Uint64(plaintext)
return uint(tenantID), nil
return tenantID, nil
}
+15 -20
View File
@@ -99,7 +99,7 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest)
}
}
egs = uniqueRetrieverEngine(egs)
logger.Debugf(ctx, "user register retriever engines: %v", egs)
logger.Debug(ctx, "user register retriever engines")
// Create default tenant for the user
tenant := &types.Tenant{
@@ -111,7 +111,7 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest)
createdTenant, err := s.tenantService.CreateTenant(ctx, tenant)
if err != nil {
logger.Errorf(ctx, "Failed to create tenant: %v", err)
logger.Errorf(ctx, "Failed to create tenant")
return nil, errors.New("failed to create workspace")
}
@@ -133,36 +133,33 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest)
return nil, errors.New("failed to create user")
}
logger.Infof(ctx, "User registered successfully: %s", user.Email)
logger.Info(ctx, "User registered successfully")
return user, nil
}
// Login authenticates a user and returns tokens
func (s *userService) Login(ctx context.Context, req *types.LoginRequest) (*types.LoginResponse, error) {
logger.Infof(ctx, "Start user login for email: %s", req.Email)
logger.Info(ctx, "Start user login")
// Get user by email
user, err := s.userRepo.GetUserByEmail(ctx, req.Email)
if err != nil {
logger.Errorf(ctx, "Failed to get user by email %s: %v", req.Email, err)
logger.Errorf(ctx, "Failed to get user by email: %v", err)
return &types.LoginResponse{
Success: false,
Message: "Invalid email or password",
}, nil
}
if user == nil {
logger.Warnf(ctx, "User not found for email: %s", req.Email)
logger.Warn(ctx, "User not found for email")
return &types.LoginResponse{
Success: false,
Message: "Invalid email or password",
}, nil
}
logger.Infof(ctx, "Found user: ID=%s, Email=%s, IsActive=%t", user.ID, user.Email, user.IsActive)
// Check if user is active
if !user.IsActive {
logger.Warnf(ctx, "User account is disabled for email: %s", req.Email)
logger.Warn(ctx, "User account is disabled")
return &types.LoginResponse{
Success: false,
Message: "Account is disabled",
@@ -170,39 +167,37 @@ func (s *userService) Login(ctx context.Context, req *types.LoginRequest) (*type
}
// Verify password
logger.Infof(ctx, "Verifying password for user: %s", user.Email)
err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password))
if err != nil {
logger.Warnf(ctx, "Password verification failed for user %s: %v", user.Email, err)
logger.Warn(ctx, "Password verification failed")
return &types.LoginResponse{
Success: false,
Message: "Invalid email or password",
}, nil
}
logger.Infof(ctx, "Password verification successful for user: %s", user.Email)
logger.Info(ctx, "Password verification successful")
// Generate tokens
logger.Infof(ctx, "Generating tokens for user: %s", user.Email)
logger.Info(ctx, "Generating tokens")
accessToken, refreshToken, err := s.GenerateTokens(ctx, user)
if err != nil {
logger.Errorf(ctx, "Failed to generate tokens for user %s: %v", user.Email, err)
logger.Errorf(ctx, "Failed to generate tokens: %v", err)
return &types.LoginResponse{
Success: false,
Message: "Login failed",
}, nil
}
logger.Infof(ctx, "Tokens generated successfully for user: %s", user.Email)
logger.Info(ctx, "Tokens generated successfully")
// Get tenant information
logger.Infof(ctx, "Getting tenant information for user %s, tenant ID: %s", user.Email, user.TenantID)
tenant, err := s.tenantService.GetTenantByID(ctx, user.TenantID)
if err != nil {
logger.Warnf(ctx, "Failed to get tenant info for user %s, tenant ID %s: %v", user.Email, user.TenantID, err)
logger.Warn(ctx, "Failed to get tenant info")
} else {
logger.Infof(ctx, "Tenant information retrieved successfully for user: %s", user.Email)
logger.Info(ctx, "Tenant information retrieved successfully")
}
logger.Infof(ctx, "User logged in successfully: %s", user.Email)
logger.Info(ctx, "User logged in successfully")
return &types.LoginResponse{
Success: true,
Message: "Login successful",
@@ -365,6 +365,9 @@ func ConvertWebSearchResults(webResults []*types.WebSearchResult) []*types.Searc
results := make([]*types.SearchResult, 0, len(webResults))
for i, webResult := range webResults {
if webResult == nil {
continue
}
// Use URL as ChunkID for web search results
chunkID := webResult.URL
if chunkID == "" {
@@ -82,6 +82,9 @@ func TestDuckDuckGoProvider_Search_HTMLSuccess(t *testing.T) {
// Build provider and inject our test client
prov, _ := NewDuckDuckGoProvider(config.WebSearchProviderConfig{})
dp := prov.(*DuckDuckGoProvider)
if dp == nil {
t.Fatalf("failed to build provider")
}
dp.client = newTestClient(ts)
ctx := context.Background()
@@ -138,6 +141,9 @@ func TestDuckDuckGoProvider_Search_APIFallback(t *testing.T) {
prov, _ := NewDuckDuckGoProvider(config.WebSearchProviderConfig{})
dp := prov.(*DuckDuckGoProvider)
if dp == nil {
t.Fatalf("failed to build provider")
}
dp.client = newTestClient(ts)
ctx := context.Background()
@@ -167,6 +173,9 @@ func TestDuckDuckGoProvider_Search_Real(t *testing.T) {
if err != nil {
t.Fatalf("Failed to create DuckDuckGo provider: %v", err)
}
if provider == nil {
t.Fatalf("failed to build provider")
}
// Test with a simple, general query that should return results
query := "Go programming language"
@@ -186,6 +195,9 @@ func TestDuckDuckGoProvider_Search_Real(t *testing.T) {
// Verify result structure
for i, result := range results {
if result == nil {
t.Fatalf("Result[%d]: is nil", i)
}
if result.Title == "" {
t.Errorf("Result[%d]: Title is empty", i)
}
@@ -229,6 +241,9 @@ func TestDuckDuckGoProvider_Search_Real_Chinese(t *testing.T) {
if err != nil {
t.Fatalf("Failed to create DuckDuckGo provider: %v", err)
}
if provider == nil {
t.Fatalf("failed to build provider")
}
// Test with a Chinese query
query := "WeKnora 企业级RAG框架 介绍 文档"
@@ -248,6 +263,9 @@ func TestDuckDuckGoProvider_Search_Real_Chinese(t *testing.T) {
// Verify result structure
for i, result := range results {
if result == nil {
t.Fatalf("Result[%d]: is nil", i)
}
if result.Title == "" {
t.Errorf("Result[%d]: Title is empty", i)
}