fix: update environment configuration for debugging and logging, enhance SQLite FTS5 table management, and improve API base URL handling
This commit is contained in:
@@ -60,13 +60,44 @@ func NewSQLiteRetrieveEngineRepository(db *gorm.DB) interfaces.RetrieveEngineRep
|
||||
}
|
||||
|
||||
func initFTS5(db *gorm.DB) {
|
||||
sql := `CREATE VIRTUAL TABLE IF NOT EXISTS lite_embeddings_fts USING fts5(
|
||||
content, source_id, chunk_id, knowledge_id, knowledge_base_id,
|
||||
content='lite_embeddings', content_rowid='id',
|
||||
tokenize='unicode61'
|
||||
)`
|
||||
if err := db.Exec(sql).Error; err != nil {
|
||||
logger.GetLogger(context.Background()).Warnf("[SQLite] Failed to create FTS5 table: %v", err)
|
||||
var sqlStr string
|
||||
db.Raw("SELECT sql FROM sqlite_master WHERE type='table' AND name='lite_embeddings_fts'").Scan(&sqlStr)
|
||||
// If the table exists but is not contentless (i.e. uses content='lite_embeddings'), recreate it
|
||||
if sqlStr != "" && strings.Contains(sqlStr, "content='lite_embeddings'") {
|
||||
logger.GetLogger(context.Background()).Infof("[SQLite] Migrating FTS5 table to contentless table with manual bigram tokenization")
|
||||
db.Exec("DROP TABLE IF EXISTS lite_embeddings_fts")
|
||||
sqlStr = "" // Trigger recreate
|
||||
}
|
||||
|
||||
if sqlStr == "" {
|
||||
createSQL := `CREATE VIRTUAL TABLE IF NOT EXISTS lite_embeddings_fts USING fts5(
|
||||
content, source_id, chunk_id, knowledge_id, knowledge_base_id,
|
||||
content='',
|
||||
contentless_delete=1,
|
||||
tokenize='unicode61'
|
||||
)`
|
||||
if err := db.Exec(createSQL).Error; err != nil {
|
||||
logger.GetLogger(context.Background()).Warnf("[SQLite] Failed to create FTS5 table: %v", err)
|
||||
return
|
||||
}
|
||||
logger.GetLogger(context.Background()).Infof("[SQLite] Populating contentless FTS5 table from lite_embeddings with bigrams")
|
||||
|
||||
// To populate, we need to read all rows and insert them via Go to apply bigram tokenization
|
||||
type Row struct {
|
||||
ID uint
|
||||
Content string
|
||||
SourceID string
|
||||
ChunkID string
|
||||
KnowledgeID string
|
||||
KnowledgeBaseID string
|
||||
}
|
||||
var rows []Row
|
||||
db.Raw("SELECT id, content, source_id, chunk_id, knowledge_id, knowledge_base_id FROM lite_embeddings").Scan(&rows)
|
||||
for _, r := range rows {
|
||||
db.Exec(`INSERT INTO lite_embeddings_fts(rowid, content, source_id, chunk_id, knowledge_id, knowledge_base_id)
|
||||
VALUES(?, ?, ?, ?, ?, ?)`,
|
||||
r.ID, tokenizeCJKBigram(r.Content), r.SourceID, r.ChunkID, r.KnowledgeID, r.KnowledgeBaseID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,7 +307,7 @@ func (r *sqliteRepository) keywordsRetrieve(ctx context.Context, params types.Re
|
||||
SELECT e.id, e.source_id, e.source_type, e.chunk_id,
|
||||
e.knowledge_id, e.knowledge_base_id, e.tag_id,
|
||||
e.content,
|
||||
bm25(lite_embeddings_fts) AS score
|
||||
(bm25(lite_embeddings_fts) * -1000000.0) AS score
|
||||
FROM lite_embeddings_fts
|
||||
JOIN lite_embeddings e ON e.id = lite_embeddings_fts.rowid
|
||||
WHERE lite_embeddings_fts MATCH ?
|
||||
@@ -290,7 +321,7 @@ func (r *sqliteRepository) keywordsRetrieve(ctx context.Context, params types.Re
|
||||
args = append(args, wp.args...)
|
||||
}
|
||||
|
||||
sql += " ORDER BY score ASC LIMIT ?"
|
||||
sql += " ORDER BY score DESC LIMIT ?"
|
||||
args = append(args, params.TopK)
|
||||
|
||||
type ftsResult struct {
|
||||
@@ -315,11 +346,12 @@ func (r *sqliteRepository) keywordsRetrieve(ctx context.Context, params types.Re
|
||||
items := make([]*types.IndexWithScore, len(rows))
|
||||
for i, row := range rows {
|
||||
|
||||
// bm25 越小越相关 → 转成正向分数
|
||||
score := -row.Score
|
||||
// bm25 is originally negative and very small, we multiplied it by -1000000.0 in SQL
|
||||
// to make it positive and human-readable.
|
||||
score := row.Score
|
||||
|
||||
logger.GetLogger(ctx).Infof("[SQLite] keywordsRetrieve: #%d chunk_id=%s, bm25_raw=%.4f, score=%.4f, content_preview=%.60s",
|
||||
i+1, row.ChunkID, row.Score, score, row.Content)
|
||||
logger.GetLogger(ctx).Infof("[SQLite] keywordsRetrieve: #%d chunk_id=%s, score=%.4f, content_preview=%.60s",
|
||||
i+1, row.ChunkID, score, row.Content)
|
||||
|
||||
items[i] = &types.IndexWithScore{
|
||||
ID: fmt.Sprintf("%d", row.ID),
|
||||
@@ -488,6 +520,9 @@ func (r *sqliteRepository) deleteRowsAndVecs(_ context.Context, rows []sqliteEmb
|
||||
r.db.Exec(fmt.Sprintf("DELETE FROM %s WHERE rowid = ?", tbl), id)
|
||||
}
|
||||
}
|
||||
for _, row := range rows {
|
||||
r.db.Exec("DELETE FROM lite_embeddings_fts WHERE rowid = ?", row.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *sqliteRepository) copyVec(_ context.Context, srcID, dstID uint, dim int) {
|
||||
@@ -505,8 +540,9 @@ func (r *sqliteRepository) syncFTS5Insert(_ context.Context, row *sqliteEmbeddin
|
||||
if row.ID == 0 {
|
||||
return
|
||||
}
|
||||
tokenizedContent := tokenizeCJKBigram(row.Content)
|
||||
sql := `INSERT INTO lite_embeddings_fts(rowid, content, source_id, chunk_id, knowledge_id, knowledge_base_id) VALUES(?, ?, ?, ?, ?, ?)`
|
||||
r.db.Exec(sql, row.ID, row.Content, row.SourceID, row.ChunkID, row.KnowledgeID, row.KnowledgeBaseID)
|
||||
r.db.Exec(sql, row.ID, tokenizedContent, row.SourceID, row.ChunkID, row.KnowledgeID, row.KnowledgeBaseID)
|
||||
}
|
||||
|
||||
type whereClause struct {
|
||||
@@ -553,61 +589,77 @@ func toInterfaceSlice(ss []string) []interface{} {
|
||||
return out
|
||||
}
|
||||
|
||||
// sanitizeFTS5Query builds an FTS5 query from user input.
|
||||
// CJK characters are split into overlapping bigrams (mimicking CJK analyzers used
|
||||
// by Elasticsearch etc.) and joined with OR for broad partial matching.
|
||||
// Non-CJK words are kept intact. BM25 ranking naturally boosts documents
|
||||
// that match more tokens.
|
||||
// tokenizeCJKBigram splits continuous CJK character sequences into overlapping bigrams.
|
||||
// Non-CJK words are kept intact. This approach maximizes recall for CJK search.
|
||||
func tokenizeCJKBigram(text string) string {
|
||||
var parts []string
|
||||
var currentCJK []rune
|
||||
var currentNonCJK strings.Builder
|
||||
|
||||
flushCJK := func() {
|
||||
if len(currentCJK) == 0 {
|
||||
return
|
||||
}
|
||||
if len(currentCJK) == 1 {
|
||||
parts = append(parts, string(currentCJK[0]))
|
||||
} else {
|
||||
for i := 0; i < len(currentCJK)-1; i++ {
|
||||
parts = append(parts, string(currentCJK[i])+string(currentCJK[i+1]))
|
||||
}
|
||||
}
|
||||
currentCJK = currentCJK[:0]
|
||||
}
|
||||
|
||||
flushNonCJK := func() {
|
||||
if currentNonCJK.Len() > 0 {
|
||||
parts = append(parts, currentNonCJK.String())
|
||||
currentNonCJK.Reset()
|
||||
}
|
||||
}
|
||||
|
||||
for _, r := range text {
|
||||
// unicode.Han covers Chinese characters
|
||||
if unicode.Is(unicode.Han, r) {
|
||||
flushNonCJK()
|
||||
currentCJK = append(currentCJK, r)
|
||||
} else if unicode.IsSpace(r) || unicode.IsPunct(r) || unicode.IsSymbol(r) {
|
||||
// Delimiters
|
||||
flushCJK()
|
||||
flushNonCJK()
|
||||
} else {
|
||||
// Alphanumeric or other languages
|
||||
flushCJK()
|
||||
currentNonCJK.WriteRune(r)
|
||||
}
|
||||
}
|
||||
flushCJK()
|
||||
flushNonCJK()
|
||||
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
// sanitizeFTS5Query builds an FTS5 query from user input by applying bigram tokenization.
|
||||
func sanitizeFTS5Query(q string) string {
|
||||
q = strings.TrimSpace(q)
|
||||
if q == "" {
|
||||
return q
|
||||
}
|
||||
|
||||
var cjkRunes []rune
|
||||
var nonCJKWords []string
|
||||
var buf strings.Builder
|
||||
|
||||
flushNonCJK := func() {
|
||||
if buf.Len() > 0 {
|
||||
nonCJKWords = append(nonCJKWords, buf.String())
|
||||
buf.Reset()
|
||||
}
|
||||
}
|
||||
|
||||
for _, r := range q {
|
||||
if unicode.Is(unicode.Han, r) {
|
||||
flushNonCJK()
|
||||
cjkRunes = append(cjkRunes, r)
|
||||
} else if unicode.IsSpace(r) || r == '|' {
|
||||
flushNonCJK()
|
||||
} else if r == '"' || r == '*' || r == '(' || r == ')' || r == '{' || r == '}' {
|
||||
// skip FTS5 special characters
|
||||
} else {
|
||||
buf.WriteRune(r)
|
||||
}
|
||||
}
|
||||
flushNonCJK()
|
||||
// Tokenize input query with bigrams (same as during indexing)
|
||||
tokenized := tokenizeCJKBigram(q)
|
||||
fields := strings.Fields(tokenized)
|
||||
|
||||
var parts []string
|
||||
|
||||
// CJK bigrams for better matching (e.g. "苹果第四季度" → "苹果" OR "果第" OR "第四" OR ...)
|
||||
if len(cjkRunes) == 1 {
|
||||
parts = append(parts, `"`+string(cjkRunes[0])+`"`)
|
||||
} else {
|
||||
for i := 0; i < len(cjkRunes)-1; i++ {
|
||||
bigram := string(cjkRunes[i]) + string(cjkRunes[i+1])
|
||||
parts = append(parts, `"`+bigram+`"`)
|
||||
for _, f := range fields {
|
||||
if f != "" {
|
||||
parts = append(parts, `"`+f+`"`)
|
||||
}
|
||||
}
|
||||
|
||||
for _, w := range nonCJKWords {
|
||||
w = strings.ReplaceAll(w, `"`, `""`)
|
||||
parts = append(parts, `"`+w+`"`)
|
||||
}
|
||||
|
||||
if len(parts) == 0 {
|
||||
return `"` + strings.ReplaceAll(q, `"`, `""`) + `"`
|
||||
return ""
|
||||
}
|
||||
|
||||
// Use OR because we want fuzzy match across multiple bigrams/words
|
||||
return strings.Join(parts, " OR ")
|
||||
}
|
||||
|
||||
@@ -15,15 +15,15 @@ import (
|
||||
|
||||
// PluginSearch implements search functionality for chat pipeline
|
||||
type PluginSearch struct {
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
chunkService interfaces.ChunkService
|
||||
config *config.Config
|
||||
webSearchService interfaces.WebSearchService
|
||||
tenantService interfaces.TenantService
|
||||
sessionService interfaces.SessionService
|
||||
webSearchStateService interfaces.WebSearchStateService
|
||||
webSearchProviderRepo interfaces.WebSearchProviderRepository
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService
|
||||
knowledgeService interfaces.KnowledgeService
|
||||
chunkService interfaces.ChunkService
|
||||
config *config.Config
|
||||
webSearchService interfaces.WebSearchService
|
||||
tenantService interfaces.TenantService
|
||||
sessionService interfaces.SessionService
|
||||
webSearchStateService interfaces.WebSearchStateService
|
||||
webSearchProviderRepo interfaces.WebSearchProviderRepository
|
||||
}
|
||||
|
||||
func NewPluginSearch(eventManager *EventManager,
|
||||
@@ -620,21 +620,34 @@ func (p *PluginSearch) searchWebIfEnabled(ctx context.Context, chatManage *types
|
||||
return nil
|
||||
}
|
||||
tenant, _ := types.TenantInfoFromContext(ctx)
|
||||
if tenant == nil || tenant.WebSearchConfig == nil {
|
||||
providerID := chatManage.WebSearchProviderID
|
||||
|
||||
var webConfig *types.WebSearchConfig
|
||||
if tenant != nil && tenant.WebSearchConfig != nil {
|
||||
// Clone tenant config so we can safely override MaxResults
|
||||
cfg := *tenant.WebSearchConfig
|
||||
webConfig = &cfg
|
||||
} else if providerID != "" {
|
||||
webConfig = &types.WebSearchConfig{
|
||||
MaxResults: 10,
|
||||
}
|
||||
} else {
|
||||
pipelineWarn(ctx, "Search", "web_config_missing", map[string]interface{}{
|
||||
"tenant_id": chatManage.TenantID,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// Use provider ID already resolved by session layer (agent config > tenant default)
|
||||
providerID := chatManage.WebSearchProviderID
|
||||
// Apply agent-level web search overrides
|
||||
if chatManage.WebSearchMaxResults > 0 {
|
||||
webConfig.MaxResults = chatManage.WebSearchMaxResults
|
||||
}
|
||||
|
||||
pipelineInfo(ctx, "Search", "web_request", map[string]interface{}{
|
||||
"tenant_id": chatManage.TenantID,
|
||||
"provider_id": providerID,
|
||||
})
|
||||
webResults, err := p.webSearchService.Search(ctx, providerID, tenant.WebSearchConfig, chatManage.RewriteQuery)
|
||||
webResults, err := p.webSearchService.Search(ctx, providerID, webConfig, chatManage.RewriteQuery)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Search", "web_search_error", map[string]interface{}{
|
||||
"tenant_id": chatManage.TenantID,
|
||||
@@ -643,22 +656,22 @@ func (p *PluginSearch) searchWebIfEnabled(ctx context.Context, chatManage *types
|
||||
return nil
|
||||
}
|
||||
// Build questions using RewriteQuery only
|
||||
questions := []string{strings.TrimSpace(chatManage.RewriteQuery)}
|
||||
// questions := []string{strings.TrimSpace(chatManage.RewriteQuery)}
|
||||
// Load session-scoped temp KB state from Redis using WebSearchStateRepository
|
||||
tempKBID, seen, ids := p.webSearchStateService.GetWebSearchTempKBState(ctx, chatManage.SessionID)
|
||||
compressed, kbID, newSeen, newIDs, err := p.webSearchService.CompressWithRAG(
|
||||
ctx, chatManage.SessionID, tempKBID, questions, webResults, tenant.WebSearchConfig,
|
||||
p.knowledgeBaseService, p.knowledgeService, seen, ids,
|
||||
)
|
||||
if err != nil {
|
||||
pipelineWarn(ctx, "Search", "web_compress_error", map[string]interface{}{
|
||||
"error": err.Error(),
|
||||
})
|
||||
} else {
|
||||
webResults = compressed
|
||||
// Persist temp KB state back into Redis using WebSearchStateRepository
|
||||
p.webSearchStateService.SaveWebSearchTempKBState(ctx, chatManage.SessionID, kbID, newSeen, newIDs)
|
||||
}
|
||||
// tempKBID, seen, ids := p.webSearchStateService.GetWebSearchTempKBState(ctx, chatManage.SessionID)
|
||||
// compressed, kbID, newSeen, newIDs, err := p.webSearchService.CompressWithRAG(
|
||||
// ctx, chatManage.SessionID, tempKBID, questions, webResults, webConfig,
|
||||
// p.knowledgeBaseService, p.knowledgeService, seen, ids,
|
||||
// )
|
||||
// if err != nil {
|
||||
// pipelineWarn(ctx, "Search", "web_compress_error", map[string]interface{}{
|
||||
// "error": err.Error(),
|
||||
// })
|
||||
// } else {
|
||||
// webResults = compressed
|
||||
// // Persist temp KB state back into Redis using WebSearchStateRepository
|
||||
// p.webSearchStateService.SaveWebSearchTempKBState(ctx, chatManage.SessionID, kbID, newSeen, newIDs)
|
||||
// }
|
||||
res := searchutil.ConvertWebSearchResults(webResults)
|
||||
pipelineInfo(ctx, "Search", "web_hits", map[string]interface{}{
|
||||
"hit_count": len(res),
|
||||
|
||||
@@ -115,6 +115,7 @@ func (s *sessionService) KnowledgeQA(
|
||||
RewritePromptUser: s.cfg.Conversation.RewritePromptUser,
|
||||
WebSearchEnabled: req.WebSearchEnabled,
|
||||
WebSearchProviderID: s.resolveWebSearchProviderID(ctx, req, retrievalTenantID),
|
||||
WebSearchMaxResults: s.resolveWebSearchMaxResults(ctx, req),
|
||||
WebFetchEnabled: s.resolveWebFetchEnabled(req),
|
||||
WebFetchTopN: s.resolveWebFetchTopN(req),
|
||||
TenantID: retrievalTenantID,
|
||||
@@ -841,3 +842,16 @@ func (s *sessionService) resolveWebFetchTopN(req *types.QARequest) int {
|
||||
}
|
||||
return 3
|
||||
}
|
||||
|
||||
// resolveWebSearchMaxResults returns the max results for web search.
|
||||
// Priority: agent config > tenant default > default (10)
|
||||
func (s *sessionService) resolveWebSearchMaxResults(ctx context.Context, req *types.QARequest) int {
|
||||
if req.CustomAgent != nil && req.CustomAgent.Config.WebSearchMaxResults > 0 {
|
||||
return req.CustomAgent.Config.WebSearchMaxResults
|
||||
}
|
||||
tenantInfo, _ := types.TenantInfoFromContext(ctx)
|
||||
if tenantInfo != nil && tenantInfo.WebSearchConfig != nil && tenantInfo.WebSearchConfig.MaxResults > 0 {
|
||||
return tenantInfo.WebSearchConfig.MaxResults
|
||||
}
|
||||
return 10
|
||||
}
|
||||
|
||||
@@ -176,6 +176,11 @@ func (s *sessionService) applyAgentOverridesToChatManage(
|
||||
cm.FallbackPrompt = customAgent.Config.FallbackPrompt
|
||||
}
|
||||
|
||||
// Override web search settings
|
||||
if customAgent.Config.WebSearchMaxResults > 0 {
|
||||
cm.WebSearchMaxResults = customAgent.Config.WebSearchMaxResults
|
||||
}
|
||||
|
||||
// Override history turns
|
||||
if customAgent.Config.HistoryTurns > 0 {
|
||||
cm.MaxRounds = customAgent.Config.HistoryTurns
|
||||
|
||||
@@ -7,8 +7,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
infra_web_search "github.com/Tencent/WeKnora/internal/infrastructure/web_search"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
infra_web_search "github.com/Tencent/WeKnora/internal/infrastructure/web_search"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/searchutil"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
@@ -216,8 +216,8 @@ func (s *WebSearchService) CompressWithRAG(
|
||||
for _, q := range questions {
|
||||
params := types.SearchParams{
|
||||
QueryText: q,
|
||||
VectorThreshold: 0.5,
|
||||
KeywordThreshold: 0.5,
|
||||
VectorThreshold: 0.2,
|
||||
KeywordThreshold: 0.2,
|
||||
MatchCount: matchCount,
|
||||
}
|
||||
results, err := kbSvc.HybridSearch(ctx, tempKBID, params)
|
||||
|
||||
@@ -36,6 +36,9 @@ func (s *webSearchStateService) GetWebSearchTempKBState(
|
||||
ctx context.Context,
|
||||
sessionID string,
|
||||
) (tempKBID string, seenURLs map[string]bool, knowledgeIDs []string) {
|
||||
if s.redisClient == nil {
|
||||
return "", make(map[string]bool), []string{}
|
||||
}
|
||||
stateKey := fmt.Sprintf("tempkb:%s", sessionID)
|
||||
if raw, getErr := s.redisClient.Get(ctx, stateKey).Bytes(); getErr == nil && len(raw) > 0 {
|
||||
var state struct {
|
||||
@@ -65,6 +68,9 @@ func (s *webSearchStateService) SaveWebSearchTempKBState(
|
||||
seenURLs map[string]bool,
|
||||
knowledgeIDs []string,
|
||||
) {
|
||||
if s.redisClient == nil {
|
||||
return
|
||||
}
|
||||
stateKey := fmt.Sprintf("tempkb:%s", sessionID)
|
||||
state := struct {
|
||||
KBID string `json:"kbID"`
|
||||
|
||||
@@ -355,6 +355,7 @@ func initContextStorage(redisClient *redis.Client) (llmcontext.ContextStorage, e
|
||||
func initDatabase(cfg *config.Config) (*gorm.DB, error) {
|
||||
var dialector gorm.Dialector
|
||||
var migrateDSN string
|
||||
var sqliteDBPath string
|
||||
switch os.Getenv("DB_DRIVER") {
|
||||
case "postgres":
|
||||
// DSN for GORM (key-value format)
|
||||
@@ -412,6 +413,7 @@ func initDatabase(cfg *config.Config) (*gorm.DB, error) {
|
||||
sqlite_vec.Auto()
|
||||
dsn := dbPath + "?_journal_mode=WAL&_busy_timeout=5000&_foreign_keys=on"
|
||||
dialector = sqlite.Open(dsn)
|
||||
sqliteDBPath = dbPath
|
||||
migrateDSN = "sqlite3://" + dbPath
|
||||
logger.Infof(context.Background(), "DB Config: driver=sqlite path=%s", dbPath)
|
||||
default:
|
||||
@@ -445,6 +447,7 @@ func initDatabase(cfg *config.Config) (*gorm.DB, error) {
|
||||
autoRecover := os.Getenv("AUTO_RECOVER_DIRTY") != "false"
|
||||
migrationOpts := database.MigrationOptions{
|
||||
AutoRecoverDirty: autoRecover,
|
||||
SQLiteDBPath: sqliteDBPath,
|
||||
}
|
||||
|
||||
// Run base migrations (all versioned migrations including embeddings)
|
||||
@@ -505,6 +508,56 @@ func resolveStorageProviderPending(db *gorm.DB) {
|
||||
} else if result.RowsAffected > 0 {
|
||||
logger.Infof(context.Background(), "Resolved %d knowledge bases with __pending_env__ storage provider → %s", result.RowsAffected, storageType)
|
||||
}
|
||||
|
||||
// Reset any pending tasks left over from previous aborted runs (Lite App mode)
|
||||
resetPendingTasks(db)
|
||||
}
|
||||
|
||||
// resetPendingTasks resets the state of any knowledge items or sync logs stuck in processing
|
||||
// due to an unexpected application restart when using in-memory queues (Lite mode).
|
||||
func resetPendingTasks(db *gorm.DB) {
|
||||
if os.Getenv("REDIS_ADDR") != "" {
|
||||
return // Distributed queue (Asynq) will handle its own retries
|
||||
}
|
||||
|
||||
// 1. Reset knowledge parsing tasks
|
||||
result := db.Model(&types.Knowledge{}).
|
||||
Where("parse_status IN ?", []string{types.ParseStatusPending, types.ParseStatusProcessing, types.ParseStatusDeleting}).
|
||||
Updates(map[string]interface{}{
|
||||
"parse_status": types.ParseStatusFailed,
|
||||
"error_message": "Task interrupted due to application restart",
|
||||
})
|
||||
if result.Error != nil {
|
||||
logger.Warnf(context.Background(), "Failed to reset pending knowledge tasks: %v", result.Error)
|
||||
} else if result.RowsAffected > 0 {
|
||||
logger.Infof(context.Background(), "Reset %d stuck knowledge parsing tasks to failed state", result.RowsAffected)
|
||||
}
|
||||
|
||||
// 2. Reset knowledge summary tasks
|
||||
resultSummary := db.Model(&types.Knowledge{}).
|
||||
Where("summary_status IN ?", []string{types.SummaryStatusPending, types.SummaryStatusProcessing}).
|
||||
Updates(map[string]interface{}{
|
||||
"summary_status": types.SummaryStatusFailed,
|
||||
})
|
||||
if resultSummary.Error != nil {
|
||||
logger.Warnf(context.Background(), "Failed to reset pending summary tasks: %v", resultSummary.Error)
|
||||
} else if resultSummary.RowsAffected > 0 {
|
||||
logger.Infof(context.Background(), "Reset %d stuck summary generation tasks to failed state", resultSummary.RowsAffected)
|
||||
}
|
||||
|
||||
// 3. Reset data source sync tasks
|
||||
resultSync := db.Model(&types.SyncLog{}).
|
||||
Where("status IN ?", []string{types.SyncLogStatusRunning, "pending"}).
|
||||
Updates(map[string]interface{}{
|
||||
"status": types.SyncLogStatusFailed,
|
||||
"error_message": "Sync interrupted due to application restart",
|
||||
"end_time": time.Now(),
|
||||
})
|
||||
if resultSync.Error != nil {
|
||||
logger.Warnf(context.Background(), "Failed to reset pending data source sync tasks: %v", resultSync.Error)
|
||||
} else if resultSync.RowsAffected > 0 {
|
||||
logger.Infof(context.Background(), "Reset %d stuck data source sync tasks to failed state", resultSync.RowsAffected)
|
||||
}
|
||||
}
|
||||
|
||||
// initFileService initializes file storage service
|
||||
|
||||
@@ -2,6 +2,7 @@ package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
@@ -10,7 +11,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
_ "github.com/golang-migrate/migrate/v4/database/postgres"
|
||||
_ "github.com/golang-migrate/migrate/v4/database/sqlite3"
|
||||
sqlite3migrate "github.com/golang-migrate/migrate/v4/database/sqlite3"
|
||||
_ "github.com/golang-migrate/migrate/v4/source/file"
|
||||
)
|
||||
|
||||
@@ -46,6 +47,12 @@ type MigrationOptions struct {
|
||||
// AutoRecoverDirty when true, automatically attempts to recover from dirty state
|
||||
// by forcing to the previous version and retrying the migration
|
||||
AutoRecoverDirty bool
|
||||
|
||||
// SQLiteDBPath is the raw filesystem path to the SQLite database file.
|
||||
// When set, the migrator opens the DB directly via sql.Open instead of
|
||||
// parsing a URL-based DSN, which avoids breakage when the path contains
|
||||
// spaces (e.g. macOS "Application Support").
|
||||
SQLiteDBPath string
|
||||
}
|
||||
|
||||
// RunMigrationsWithOptions executes all pending database migrations with custom options
|
||||
@@ -59,10 +66,31 @@ func RunMigrationsWithOptions(dsn string, opts MigrationOptions) error {
|
||||
migrationsPath = "file://migrations/sqlite"
|
||||
}
|
||||
|
||||
m, err := migrate.New(migrationsPath, dsn)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to create migrate instance: %v", err)
|
||||
return fmt.Errorf("failed to create migrate instance: %w", err)
|
||||
var m *migrate.Migrate
|
||||
if opts.SQLiteDBPath != "" {
|
||||
sqlDB, err := sql.Open("sqlite3", opts.SQLiteDBPath)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to open sqlite db for migration: %v", err)
|
||||
return fmt.Errorf("failed to open sqlite db for migration: %w", err)
|
||||
}
|
||||
driver, err := sqlite3migrate.WithInstance(sqlDB, &sqlite3migrate.Config{})
|
||||
if err != nil {
|
||||
sqlDB.Close()
|
||||
logger.Errorf(ctx, "Failed to create sqlite3 migrate driver: %v", err)
|
||||
return fmt.Errorf("failed to create sqlite3 migrate driver: %w", err)
|
||||
}
|
||||
m, err = migrate.NewWithDatabaseInstance(migrationsPath, "sqlite3", driver)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to create migrate instance: %v", err)
|
||||
return fmt.Errorf("failed to create migrate instance: %w", err)
|
||||
}
|
||||
} else {
|
||||
var err error
|
||||
m, err = migrate.New(migrationsPath, dsn)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to create migrate instance: %v", err)
|
||||
return fmt.Errorf("failed to create migrate instance: %w", err)
|
||||
}
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
|
||||
@@ -394,9 +394,6 @@ func (c *Connector) fetchDatabase(ctx context.Context, client *notionClient, id
|
||||
if err != nil || len(records) == 0 {
|
||||
return nil
|
||||
}
|
||||
// Same database may be reached via two different IDs (data_source_id from search
|
||||
// vs database_container_id from child_database blocks). Mark the canonical
|
||||
// data_source_id as visited so the second path is deduped.
|
||||
if queryID != "" && queryID != id {
|
||||
if visited[queryID] {
|
||||
return nil
|
||||
@@ -404,18 +401,15 @@ func (c *Connector) fetchDatabase(ctx context.Context, client *notionClient, id
|
||||
visited[queryID] = true
|
||||
}
|
||||
|
||||
propNames := extractPropertySchema(records[0])
|
||||
var items []types.FetchedItem
|
||||
for _, record := range records {
|
||||
if record.InTrash {
|
||||
continue
|
||||
}
|
||||
item := c.buildRecordItem(ctx, client, record, propNames, dbTitle)
|
||||
if item != nil {
|
||||
items = append(items, *item)
|
||||
}
|
||||
visited[record.ID] = true // Mark records as visited to avoid duplicate fetchPage calls
|
||||
}
|
||||
return items
|
||||
|
||||
item := c.buildDatabaseItem(ctx, client, id, dbTitle, records)
|
||||
if item != nil {
|
||||
return []types.FetchedItem{*item}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetchDatabaseIncremental syncs only changed records by comparing edit times against cursor.
|
||||
@@ -438,32 +432,33 @@ func (c *Connector) fetchDatabaseIncremental(ctx context.Context, client *notion
|
||||
}
|
||||
|
||||
recordEditTimes := make(map[string]time.Time, len(records))
|
||||
var propNames []string
|
||||
if len(records) > 0 {
|
||||
propNames = extractPropertySchema(records[0])
|
||||
}
|
||||
|
||||
var items []types.FetchedItem
|
||||
changedCount := 0
|
||||
|
||||
for _, record := range records {
|
||||
visited[record.ID] = true // Mark records as visited to avoid duplicate fetchPage calls
|
||||
|
||||
if record.InTrash {
|
||||
continue
|
||||
}
|
||||
recordEditTimes[record.ID] = record.LastEditedTime
|
||||
|
||||
prevTime, existed := prevEditTimes[record.ID]
|
||||
if existed && record.LastEditedTime.Equal(prevTime) {
|
||||
continue
|
||||
}
|
||||
changedCount++
|
||||
item := c.buildRecordItem(ctx, client, record, propNames, dbTitle)
|
||||
if item != nil {
|
||||
items = append(items, *item)
|
||||
if !existed || !record.LastEditedTime.Equal(prevTime) {
|
||||
changedCount++
|
||||
}
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Notion] database %s incremental: %d changed out of %d records", id, changedCount, len(records))
|
||||
return items, recordEditTimes
|
||||
|
||||
// Rebuild the entire database table if any record changed, or if we don't have previous times (first sync)
|
||||
if changedCount > 0 || len(prevEditTimes) == 0 {
|
||||
item := c.buildDatabaseItem(ctx, client, id, dbTitle, records)
|
||||
if item != nil {
|
||||
return []types.FetchedItem{*item}, recordEditTimes
|
||||
}
|
||||
}
|
||||
|
||||
return nil, recordEditTimes
|
||||
}
|
||||
|
||||
// queryDatabaseRecords resolves the database ID and queries all records.
|
||||
@@ -545,6 +540,103 @@ func (c *Connector) buildRecordItem(ctx context.Context, client *notionClient, r
|
||||
}
|
||||
}
|
||||
|
||||
// buildDatabaseItem converts a database into a single Markdown table document.
|
||||
func (c *Connector) buildDatabaseItem(ctx context.Context, client *notionClient, id string, dbTitle string, records []notionPage) *types.FetchedItem {
|
||||
if len(records) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
propNames := extractPropertySchema(records[0])
|
||||
|
||||
var content strings.Builder
|
||||
title := dbTitle
|
||||
if title == "" {
|
||||
title = defaultUntitledName
|
||||
}
|
||||
content.WriteString("# " + title + "\n\n")
|
||||
|
||||
// Table header
|
||||
content.WriteString("| Title ")
|
||||
for _, name := range propNames {
|
||||
content.WriteString("| " + strings.ReplaceAll(name, "|", "\\|") + " ")
|
||||
}
|
||||
content.WriteString("|\n|")
|
||||
content.WriteString("---|")
|
||||
for range propNames {
|
||||
content.WriteString("---|")
|
||||
}
|
||||
content.WriteString("\n")
|
||||
|
||||
var extraContent strings.Builder
|
||||
|
||||
// Table rows
|
||||
for _, record := range records {
|
||||
if record.InTrash {
|
||||
continue
|
||||
}
|
||||
|
||||
recordTitle := record.Title
|
||||
if recordTitle == "" {
|
||||
recordTitle = defaultUntitledName
|
||||
}
|
||||
|
||||
content.WriteString("| " + strings.ReplaceAll(recordTitle, "|", "\\|") + " ")
|
||||
|
||||
if record.RawProperties != nil {
|
||||
var props map[string]interface{}
|
||||
json.Unmarshal(record.RawProperties, &props)
|
||||
for _, name := range propNames {
|
||||
val := ""
|
||||
if propMap, ok := props[name].(map[string]interface{}); ok {
|
||||
val = propertyToString(propMap)
|
||||
}
|
||||
val = strings.ReplaceAll(val, "\n", "<br>")
|
||||
val = strings.ReplaceAll(val, "|", "\\|")
|
||||
content.WriteString("| " + val + " ")
|
||||
}
|
||||
}
|
||||
content.WriteString("|\n")
|
||||
|
||||
// Fetch blocks for the record, in case it has page content
|
||||
blocks, err := client.GetBlockChildrenAll(ctx, record.ID)
|
||||
if err == nil && len(blocks) > 0 {
|
||||
resolveFileUploads(ctx, client, blocks)
|
||||
markdown, _ := BlocksToMarkdown(blocks)
|
||||
if strings.TrimSpace(markdown) != "" {
|
||||
extraContent.WriteString("\n## " + recordTitle + " 内容\n\n" + markdown + "\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if extraContent.Len() > 0 {
|
||||
content.WriteString("\n" + extraContent.String())
|
||||
}
|
||||
|
||||
bodyStr := strings.TrimSpace(content.String())
|
||||
if bodyStr == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
updatedAt := time.Now()
|
||||
if len(records) > 0 {
|
||||
updatedAt = records[0].LastEditedTime
|
||||
}
|
||||
|
||||
return &types.FetchedItem{
|
||||
ExternalID: id,
|
||||
Title: title,
|
||||
Content: []byte(bodyStr),
|
||||
ContentType: contentTypeMarkdown,
|
||||
FileName: title + ".md",
|
||||
URL: fmt.Sprintf("https://notion.so/%s", strings.ReplaceAll(id, "-", "")),
|
||||
UpdatedAt: updatedAt,
|
||||
Metadata: map[string]string{
|
||||
"channel": types.ChannelNotion,
|
||||
"object_type": objectTypeDatabase,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// discoverAllResources uses the Search API to find all pages and data_sources,
|
||||
// then filters by parent chain via BFS from the selected resource IDs.
|
||||
// Returns the included pages plus the excluded set (visible pages NOT under any
|
||||
|
||||
@@ -2,6 +2,7 @@ package notion
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
@@ -121,16 +122,13 @@ func TestConnectorFetchAll_Database(t *testing.T) {
|
||||
t.Fatal("expected at least 1 item")
|
||||
}
|
||||
|
||||
// Each database record should be synced as an individual knowledge item
|
||||
// The entire database should be synced as a single table knowledge item
|
||||
found := false
|
||||
for _, item := range items {
|
||||
if item.ExternalID == "record-1" {
|
||||
if item.ExternalID == "db-1" {
|
||||
found = true
|
||||
if item.Metadata["object_type"] != "page" {
|
||||
t.Errorf("object_type = %q, want %q", item.Metadata["object_type"], "page")
|
||||
}
|
||||
if item.Metadata["database"] != "Test Database" {
|
||||
t.Errorf("database = %q, want %q", item.Metadata["database"], "Test Database")
|
||||
if item.Metadata["object_type"] != "database" {
|
||||
t.Errorf("object_type = %q, want %q", item.Metadata["object_type"], "database")
|
||||
}
|
||||
if item.ContentType != "text/markdown" {
|
||||
t.Errorf("ContentType = %q", item.ContentType)
|
||||
@@ -138,10 +136,15 @@ func TestConnectorFetchAll_Database(t *testing.T) {
|
||||
if len(item.Content) == 0 {
|
||||
t.Error("expected non-empty content")
|
||||
}
|
||||
// Verify it contains table headers
|
||||
contentStr := string(item.Content)
|
||||
if !strings.Contains(contentStr, "| Title |") {
|
||||
t.Errorf("expected table header in content, got: %s", contentStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("record-1 not found in items")
|
||||
t.Error("db-1 not found in items")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -134,7 +134,7 @@ func TestBlocksToMarkdown_Paragraph(t *testing.T) {
|
||||
}),
|
||||
}
|
||||
md, attachments := BlocksToMarkdown(blocks)
|
||||
if md != "Hello world\n\n" {
|
||||
if md != "Hello world\n" {
|
||||
t.Errorf("markdown = %q", md)
|
||||
}
|
||||
if len(attachments) != 0 {
|
||||
@@ -161,7 +161,7 @@ func TestBlocksToMarkdown_Headings(t *testing.T) {
|
||||
}),
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
expected := "# H1\n\n## H2\n\n### H3\n\n"
|
||||
expected := "# H1\n\n## H2\n\n### H3\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
@@ -177,7 +177,7 @@ func TestBlocksToMarkdown_Code(t *testing.T) {
|
||||
}),
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
expected := "```go\nfmt.Println()\n```\n\n"
|
||||
expected := "```go\nfmt.Println()\n```\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
@@ -197,7 +197,7 @@ func TestBlocksToMarkdown_List(t *testing.T) {
|
||||
}),
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
expected := "- Item 1\n- Item 2\n\n"
|
||||
expected := "- Item 1\n- Item 2\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
@@ -219,7 +219,7 @@ func TestBlocksToMarkdown_ToDo(t *testing.T) {
|
||||
}),
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
expected := "- [ ] Unchecked\n- [x] Checked\n\n"
|
||||
expected := "- [ ] Unchecked\n- [x] Checked\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
@@ -234,7 +234,7 @@ func TestBlocksToMarkdown_Quote(t *testing.T) {
|
||||
}),
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
expected := "> A wise quote\n\n"
|
||||
expected := "> A wise quote\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
@@ -245,7 +245,7 @@ func TestBlocksToMarkdown_Divider(t *testing.T) {
|
||||
{ID: "blk-div", Type: "divider"},
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
if md != "---\n\n" {
|
||||
if md != "---\n" {
|
||||
t.Errorf("markdown = %q", md)
|
||||
}
|
||||
}
|
||||
@@ -257,7 +257,7 @@ func TestBlocksToMarkdown_Equation(t *testing.T) {
|
||||
}),
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
expected := "$$E = mc^2$$\n\n"
|
||||
expected := "$$E = mc^2$$\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
@@ -277,7 +277,7 @@ func TestBlocksToMarkdown_Image(t *testing.T) {
|
||||
}),
|
||||
}
|
||||
md, attachments := BlocksToMarkdown(blocks)
|
||||
if md != "\n\n" {
|
||||
if md != "\n" {
|
||||
t.Errorf("markdown = %q", md)
|
||||
}
|
||||
if len(attachments) != 1 {
|
||||
@@ -296,7 +296,7 @@ func TestBlocksToMarkdown_UnknownType(t *testing.T) {
|
||||
{ID: "blk-unknown", Type: "future_block_type"},
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
if md != "" {
|
||||
if md != "\n" {
|
||||
t.Errorf("unknown block should produce empty output, got %q", md)
|
||||
}
|
||||
}
|
||||
@@ -323,7 +323,7 @@ func TestBlocksToMarkdown_Table(t *testing.T) {
|
||||
},
|
||||
}
|
||||
md, _ := BlocksToMarkdown([]notionBlock{tableBlock})
|
||||
expected := "| Name | Age |\n| --- | --- |\n| Alice | 30 |\n\n"
|
||||
expected := "| Name | Age |\n| --- | --- |\n| Alice | 30 |\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
@@ -345,7 +345,7 @@ func TestBlocksToMarkdown_NestedList(t *testing.T) {
|
||||
}
|
||||
|
||||
md, _ := BlocksToMarkdown([]notionBlock{parent})
|
||||
expected := "- Parent\n - Child\n\n"
|
||||
expected := "- Parent\n - Child\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
|
||||
@@ -286,6 +286,7 @@ func (c *LongConnClient) SendStreamChunk(ctx context.Context, incoming *im.Incom
|
||||
}
|
||||
|
||||
// EndStream sends the final frame with the full accumulated content and cleans up.
|
||||
// It retries briefly if the connection is temporarily unavailable during a reconnect.
|
||||
func (c *LongConnClient) EndStream(ctx context.Context, incoming *im.IncomingMessage, streamID string) error {
|
||||
c.streamBufsMu.Lock()
|
||||
buf, ok := c.streamBufs[streamID]
|
||||
@@ -296,7 +297,23 @@ func (c *LongConnClient) EndStream(ctx context.Context, incoming *im.IncomingMes
|
||||
}
|
||||
c.streamBufsMu.Unlock()
|
||||
|
||||
return c.sendStreamFrame(incoming, streamID, fullContent, true)
|
||||
err := c.sendStreamFrame(incoming, streamID, fullContent, true)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Retry up to 3 times with short delays to ride out a reconnection window.
|
||||
for i := 0; i < 3; i++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
}
|
||||
if retryErr := c.sendStreamFrame(incoming, streamID, fullContent, true); retryErr == nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *LongConnClient) sendStreamFrame(incoming *im.IncomingMessage, streamID, content string, finish bool) error {
|
||||
@@ -342,12 +359,11 @@ func (c *LongConnClient) connectAndRun(ctx context.Context) error {
|
||||
c.conn = nil
|
||||
c.mu.Unlock()
|
||||
_ = conn.Close()
|
||||
|
||||
// Clear in-flight stream buffers to prevent memory leaks on reconnect.
|
||||
// Streams interrupted by a connection drop cannot be resumed.
|
||||
c.streamBufsMu.Lock()
|
||||
c.streamBufs = nil
|
||||
c.streamBufsMu.Unlock()
|
||||
// NOTE: streamBufs is intentionally NOT cleared on reconnect.
|
||||
// Active streams survive reconnections — the WeCom replace-based
|
||||
// protocol means the next SendStreamChunk will resend the full
|
||||
// accumulated content on the new connection. EndStream always
|
||||
// cleans up the buffer, so there is no memory leak.
|
||||
}()
|
||||
|
||||
// Authenticate
|
||||
|
||||
@@ -3,11 +3,14 @@ package logger
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/sirupsen/logrus"
|
||||
@@ -16,6 +19,11 @@ import (
|
||||
// appLogger 使用私有实例,避免外部依赖改写 logrus 全局状态导致日志丢失
|
||||
var appLogger = logrus.New()
|
||||
|
||||
var (
|
||||
loggerMu sync.Mutex
|
||||
activeLogFile *os.File
|
||||
)
|
||||
|
||||
// LogLevel 日志级别类型
|
||||
type LogLevel string
|
||||
|
||||
@@ -130,12 +138,38 @@ func (f *CustomFormatter) Format(entry *logrus.Entry) ([]byte, error) {
|
||||
|
||||
// 初始化全局日志设置
|
||||
func init() {
|
||||
ConfigureFromEnv()
|
||||
}
|
||||
|
||||
// ConfigureFromEnv 重新从环境变量应用日志配置。
|
||||
// 这允许在 main() 中加载 .env 后,让 LOG_LEVEL / LOG_PATH 立即生效。
|
||||
func ConfigureFromEnv() {
|
||||
loggerMu.Lock()
|
||||
defer loggerMu.Unlock()
|
||||
|
||||
if activeLogFile != nil {
|
||||
_ = activeLogFile.Close()
|
||||
activeLogFile = nil
|
||||
}
|
||||
|
||||
// 根据环境变量设置全局日志级别
|
||||
logLevel := getLogLevelFromEnv()
|
||||
appLogger.SetLevel(logLevel)
|
||||
|
||||
// 统一输出到 stdout,确保在 Docker 容器中与 GORM/GIN 日志合并展示
|
||||
appLogger.SetOutput(os.Stdout)
|
||||
writer := io.Writer(os.Stdout)
|
||||
logPath := resolveLogPathFromEnv()
|
||||
if logPath != "" {
|
||||
file, err := openLogFile(logPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "logger: failed to open log file %s: %v\n", logPath, err)
|
||||
} else {
|
||||
activeLogFile = file
|
||||
writer = io.MultiWriter(os.Stdout, file)
|
||||
}
|
||||
}
|
||||
|
||||
// 默认继续输出到 stdout,同时在可用时落盘到文件
|
||||
appLogger.SetOutput(writer)
|
||||
|
||||
// 非终端(如 Docker 日志采集)禁用 ANSI 颜色,避免日志聚合/检索异常
|
||||
forceColor := false
|
||||
@@ -199,6 +233,45 @@ func getLogLevelFromEnv() logrus.Level {
|
||||
}
|
||||
}
|
||||
|
||||
func resolveLogPathFromEnv() string {
|
||||
if logPath := strings.TrimSpace(os.Getenv("LOG_PATH")); logPath != "" {
|
||||
return filepath.Clean(logPath)
|
||||
}
|
||||
return defaultMacAppLogPath()
|
||||
}
|
||||
|
||||
func defaultMacAppLogPath() string {
|
||||
execPath, err := os.Executable()
|
||||
if err != nil || !strings.Contains(execPath, ".app/Contents/MacOS") {
|
||||
return ""
|
||||
}
|
||||
|
||||
homeDir, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
appName := "WeKnora Lite"
|
||||
if idx := strings.Index(execPath, ".app/Contents/MacOS"); idx >= 0 {
|
||||
bundleName := filepath.Base(execPath[:idx+4])
|
||||
if trimmed := strings.TrimSuffix(bundleName, ".app"); trimmed != "" {
|
||||
appName = trimmed
|
||||
}
|
||||
}
|
||||
|
||||
return filepath.Join(homeDir, "Library", "Logs", appName, appName+".log")
|
||||
}
|
||||
|
||||
func openLogFile(logPath string) (*os.File, error) {
|
||||
dir := filepath.Dir(logPath)
|
||||
if dir != "." {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
|
||||
}
|
||||
|
||||
// 添加调用者字段
|
||||
func addCaller(entry *logrus.Entry, skip int) *logrus.Entry {
|
||||
pc, file, line, ok := runtime.Caller(skip)
|
||||
|
||||
@@ -46,12 +46,13 @@ type PipelineRequest struct {
|
||||
ChatModelSupportsVision bool `json:"-"`
|
||||
|
||||
// Misc request-scoped config
|
||||
TenantID uint64 `json:"-"`
|
||||
WebSearchEnabled bool `json:"-"`
|
||||
WebSearchProviderID string `json:"-"` // Resolved from agent config or tenant default
|
||||
WebFetchEnabled bool `json:"-"` // Auto-fetch full page content for web search results after rerank
|
||||
WebFetchTopN int `json:"-"` // Max pages to fetch (default 3)
|
||||
Language string `json:"-"`
|
||||
TenantID uint64 `json:"-"`
|
||||
WebSearchEnabled bool `json:"-"`
|
||||
WebSearchProviderID string `json:"-"` // Resolved from agent config or tenant default
|
||||
WebSearchMaxResults int `json:"-"` // Resolved from agent config or tenant default
|
||||
WebFetchEnabled bool `json:"-"` // Auto-fetch full page content for web search results after rerank
|
||||
WebFetchTopN int `json:"-"` // Max pages to fetch (default 3)
|
||||
Language string `json:"-"`
|
||||
}
|
||||
|
||||
// QueryIntent represents the classified intent of a user query.
|
||||
@@ -187,9 +188,10 @@ func (c *ChatManage) Clone() *ChatManage {
|
||||
ChatModelSupportsVision: c.ChatModelSupportsVision,
|
||||
TenantID: c.TenantID,
|
||||
WebSearchEnabled: c.WebSearchEnabled,
|
||||
WebSearchProviderID: c.WebSearchProviderID,
|
||||
WebFetchEnabled: c.WebFetchEnabled,
|
||||
WebFetchTopN: c.WebFetchTopN,
|
||||
WebSearchProviderID: c.WebSearchProviderID,
|
||||
WebSearchMaxResults: c.WebSearchMaxResults,
|
||||
WebFetchEnabled: c.WebFetchEnabled,
|
||||
WebFetchTopN: c.WebFetchTopN,
|
||||
Language: c.Language,
|
||||
},
|
||||
PipelineState: PipelineState{
|
||||
|
||||
+18
-3
@@ -12,9 +12,24 @@ type JSON json.RawMessage
|
||||
|
||||
// Scan implements the sql.Scanner interface.
|
||||
func (j *JSON) Scan(value interface{}) error {
|
||||
bytes, ok := value.([]byte)
|
||||
if !ok {
|
||||
return errors.New("type assertion to []byte failed")
|
||||
if value == nil {
|
||||
*j = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
var bytes []byte
|
||||
switch v := value.(type) {
|
||||
case []byte:
|
||||
bytes = v
|
||||
case string:
|
||||
bytes = []byte(v)
|
||||
default:
|
||||
return errors.New("type assertion to []byte or string failed")
|
||||
}
|
||||
|
||||
if len(bytes) == 0 {
|
||||
*j = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
result := json.RawMessage{}
|
||||
|
||||
Reference in New Issue
Block a user