2026-02-28 05:22:07 +00:00
|
|
|
package router
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"fmt"
|
|
|
|
|
"sync"
|
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/logger"
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/types"
|
|
|
|
|
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
|
|
|
|
"github.com/google/uuid"
|
|
|
|
|
"github.com/hibiken/asynq"
|
|
|
|
|
"go.uber.org/dig"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// SyncTaskExecutor executes tasks synchronously (in a goroutine) without Redis.
|
|
|
|
|
// Used in Lite mode as a drop-in replacement for *asynq.Client.
|
|
|
|
|
type SyncTaskExecutor struct {
|
|
|
|
|
mu sync.RWMutex
|
|
|
|
|
handlers map[string]func(context.Context, *asynq.Task) error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewSyncTaskExecutor() *SyncTaskExecutor {
|
|
|
|
|
return &SyncTaskExecutor{
|
|
|
|
|
handlers: make(map[string]func(context.Context, *asynq.Task) error),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// RegisterHandler registers a handler for a given task type pattern.
|
|
|
|
|
func (e *SyncTaskExecutor) RegisterHandler(pattern string, handler func(context.Context, *asynq.Task) error) {
|
|
|
|
|
e.mu.Lock()
|
|
|
|
|
defer e.mu.Unlock()
|
|
|
|
|
e.handlers[pattern] = handler
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Enqueue satisfies interfaces.TaskEnqueuer.
|
|
|
|
|
// Instead of queuing to Redis, it dispatches the task to a goroutine.
|
2026-04-28 10:08:20 +00:00
|
|
|
// Supports ProcessIn (delay) and MaxRetry options for parity with asynq.
|
|
|
|
|
func (e *SyncTaskExecutor) Enqueue(task *asynq.Task, opts ...asynq.Option) (*asynq.TaskInfo, error) {
|
2026-02-28 05:22:07 +00:00
|
|
|
e.mu.RLock()
|
|
|
|
|
handler, ok := e.handlers[task.Type()]
|
|
|
|
|
e.mu.RUnlock()
|
|
|
|
|
|
|
|
|
|
if !ok {
|
|
|
|
|
return nil, fmt.Errorf("sync task executor: no handler registered for type %q", task.Type())
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-28 10:08:20 +00:00
|
|
|
var delay time.Duration
|
|
|
|
|
maxRetry := 25 // asynq default
|
|
|
|
|
maxRetrySet := false
|
|
|
|
|
for _, opt := range opts {
|
|
|
|
|
switch opt.Type() {
|
|
|
|
|
case asynq.ProcessInOpt:
|
|
|
|
|
if d, ok := opt.Value().(time.Duration); ok {
|
|
|
|
|
delay = d
|
|
|
|
|
}
|
|
|
|
|
case asynq.MaxRetryOpt:
|
|
|
|
|
if n, ok := opt.Value().(int); ok {
|
|
|
|
|
maxRetry = n
|
|
|
|
|
maxRetrySet = true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
// Callers that explicitly pass MaxRetry(0) want no retries.
|
|
|
|
|
// Without the flag we can't distinguish "not set" from "set to 0".
|
|
|
|
|
if maxRetrySet && maxRetry < 0 {
|
|
|
|
|
maxRetry = 0
|
|
|
|
|
}
|
|
|
|
|
|
2026-02-28 05:22:07 +00:00
|
|
|
taskID := uuid.New().String()
|
|
|
|
|
info := &asynq.TaskInfo{
|
|
|
|
|
ID: taskID,
|
|
|
|
|
Queue: "sync",
|
|
|
|
|
Type: task.Type(),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
go func() {
|
2026-04-28 10:08:20 +00:00
|
|
|
if delay > 0 {
|
|
|
|
|
time.Sleep(delay)
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-09 10:30:44 +00:00
|
|
|
// Tag as a background worker execution so the per-model concurrency
|
|
|
|
|
// governor throttles Lite-mode ingestion/enrichment LLM calls, mirroring
|
|
|
|
|
// the asynq backgroundTaskMiddleware in the Redis path.
|
|
|
|
|
ctx := types.WithBackgroundTask(context.Background())
|
2026-02-28 05:22:07 +00:00
|
|
|
start := time.Now()
|
|
|
|
|
logger.Infof(ctx, "[SyncTask] Executing task type=%s id=%s", task.Type(), taskID)
|
2026-04-28 10:08:20 +00:00
|
|
|
|
|
|
|
|
var lastErr error
|
|
|
|
|
for attempt := 0; attempt <= maxRetry; attempt++ {
|
|
|
|
|
if attempt > 0 {
|
|
|
|
|
backoff := time.Duration(attempt) * 5 * time.Second
|
|
|
|
|
if backoff > 30*time.Second {
|
|
|
|
|
backoff = 30 * time.Second
|
|
|
|
|
}
|
|
|
|
|
logger.Infof(ctx, "[SyncTask] Retrying task type=%s id=%s attempt=%d/%d backoff=%s",
|
|
|
|
|
task.Type(), taskID, attempt, maxRetry, backoff)
|
|
|
|
|
time.Sleep(backoff)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
lastErr = handler(ctx, task)
|
|
|
|
|
if lastErr == nil {
|
|
|
|
|
logger.Infof(ctx, "[SyncTask] Task completed type=%s id=%s elapsed=%v",
|
|
|
|
|
task.Type(), taskID, time.Since(start))
|
|
|
|
|
return
|
|
|
|
|
}
|
2026-02-28 05:22:07 +00:00
|
|
|
}
|
2026-04-28 10:08:20 +00:00
|
|
|
|
|
|
|
|
logger.Errorf(ctx, "[SyncTask] Task failed (exhausted retries) type=%s id=%s elapsed=%v err=%v",
|
|
|
|
|
task.Type(), taskID, time.Since(start), lastErr)
|
2026-02-28 05:22:07 +00:00
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
return info, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type SyncTaskParams struct {
|
|
|
|
|
dig.In
|
|
|
|
|
|
|
|
|
|
Executor *SyncTaskExecutor
|
|
|
|
|
KnowledgeService interfaces.KnowledgeService
|
|
|
|
|
KnowledgeBaseService interfaces.KnowledgeBaseService
|
|
|
|
|
TagService interfaces.KnowledgeTagService
|
2026-03-27 07:02:40 +00:00
|
|
|
DataSourceService interfaces.DataSourceService
|
2026-02-28 05:22:07 +00:00
|
|
|
ChunkExtractor interfaces.TaskHandler `name:"chunkExtractor"`
|
|
|
|
|
DataTableSummary interfaces.TaskHandler `name:"dataTableSummary"`
|
|
|
|
|
ImageMultimodal interfaces.TaskHandler `name:"imageMultimodal"`
|
2026-04-16 06:59:23 +00:00
|
|
|
KnowledgePostProcess interfaces.TaskHandler `name:"knowledgePostProcess"`
|
feat: Implement comprehensive wiki feature for knowledge bases
This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:
**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
* Summary page generation using LLM
* Entity and concept extraction in a single LLM call
* Synthesis opportunity detection
* Index page rebuilding
* Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts
**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces
**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks
**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking
**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers
**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
|
|
|
WikiIngest interfaces.TaskHandler `name:"wikiIngest"`
|
2026-07-16 06:48:20 +00:00
|
|
|
TemporaryDocument interfaces.TemporaryDocumentService
|
2026-02-28 05:22:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// RegisterSyncHandlers registers all task handlers on the SyncTaskExecutor.
|
|
|
|
|
// Used in Lite mode instead of RunAsynqServer.
|
|
|
|
|
func RegisterSyncHandlers(params SyncTaskParams) {
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeChunkExtract, params.ChunkExtractor.Handle)
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeDataTableSummary, params.DataTableSummary.Handle)
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeDocumentProcess, params.KnowledgeService.ProcessDocument)
|
2026-07-16 06:48:20 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeTemporaryDocumentProcess, params.TemporaryDocument.Process)
|
2026-03-17 11:26:29 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeManualProcess, params.KnowledgeService.ProcessManualUpdate)
|
2026-02-28 05:22:07 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeFAQImport, params.KnowledgeService.ProcessFAQImport)
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeQuestionGeneration, params.KnowledgeService.ProcessQuestionGeneration)
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeSummaryGeneration, params.KnowledgeService.ProcessSummaryGeneration)
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeKBClone, params.KnowledgeService.ProcessKBClone)
|
2026-03-09 05:14:42 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeKnowledgeMove, params.KnowledgeService.ProcessKnowledgeMove)
|
2026-02-28 05:22:07 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeKnowledgeListDelete, params.KnowledgeService.ProcessKnowledgeListDelete)
|
2026-06-25 15:51:38 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeKnowledgeListReparse, params.KnowledgeService.ProcessKnowledgeListReparse)
|
2026-02-28 05:22:07 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeIndexDelete, params.TagService.ProcessIndexDelete)
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeKBDelete, params.KnowledgeBaseService.ProcessKBDelete)
|
|
|
|
|
params.Executor.RegisterHandler(types.TypeImageMultimodal, params.ImageMultimodal.Handle)
|
2026-04-16 06:59:23 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeKnowledgePostProcess, params.KnowledgePostProcess.Handle)
|
2026-03-27 07:02:40 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeDataSourceSync, params.DataSourceService.ProcessSync)
|
feat: Implement comprehensive wiki feature for knowledge bases
This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:
**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
* Summary page generation using LLM
* Entity and concept extraction in a single LLM call
* Synthesis opportunity detection
* Index page rebuilding
* Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts
**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces
**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks
**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking
**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers
**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeWikiIngest, params.WikiIngest.Handle)
|
2026-07-09 05:27:47 +00:00
|
|
|
params.Executor.RegisterHandler(types.TypeWikiFinalize, params.WikiIngest.Handle)
|
2026-02-28 05:22:07 +00:00
|
|
|
logger.Infof(context.Background(), "[SyncTask] All task handlers registered (Lite mode, no Redis)")
|
|
|
|
|
}
|