Repository navigation
Go: file syncer service framework - #16579
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughThis PR adds a new ChangesSyncer Server Mode
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant Main
participant runSyncer
participant Syncer
participant AdminServer
Main->>runSyncer: runSyncer(arguments)
runSyncer->>Syncer: NewSyncer(...) + Start()
runSyncer->>AdminServer: heartbeat updates
alt OS signal
runSyncer->>Syncer: Stop()
else ShutdownCh closes
runSyncer->>Syncer: Stop()
end
Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
cmd/ragflow_main.go (2)
149-165: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winGeneric help text omits the new
--syncermode.The no-mode
printHelpbranch lists--api|--admin|--ingestorand documents each mode individually, but doesn't mention--synceranywhere, even though it's a valid mode now supported byparseArgs.📝 Proposed fix
- fmt.Fprintf(os.Stderr, "Usage: %s --api|--admin|--ingestor [OPTIONS]\n\n", os.Args[0]) + fmt.Fprintf(os.Stderr, "Usage: %s --api|--admin|--ingestor|--syncer [OPTIONS]\n\n", os.Args[0]) fmt.Fprintf(os.Stderr, "RAGFlow Server - Open-source RAG engine based on deep document understanding\n\n") fmt.Fprintf(os.Stderr, "Mode selection (default: --api):\n") fmt.Fprintf(os.Stderr, " --api \tRun as API server\n") fmt.Fprintf(os.Stderr, " --admin \tRun as admin server\n") - fmt.Fprintf(os.Stderr, " --ingestor \tRun as ingestion worker\n\n") + fmt.Fprintf(os.Stderr, " --ingestor \tRun as ingestion worker\n") + fmt.Fprintf(os.Stderr, " --syncer \tRun as file syncer service\n\n") fmt.Fprintf(os.Stderr, "Common options:\n") fmt.Fprintf(os.Stderr, " --config string\tPath to configuration file\n") fmt.Fprintf(os.Stderr, " -v, --version \tPrint version information and exit\n") fmt.Fprintf(os.Stderr, " --debug \tEnable debug-level logging\n") fmt.Fprintf(os.Stderr, " -h, --help \tShow this help message and exit\n\n") fmt.Fprintf(os.Stderr, "Run '%s --api --help' for API server options.\n", os.Args[0]) fmt.Fprintf(os.Stderr, "Run '%s --admin --help' for admin server options.\n", os.Args[0]) fmt.Fprintf(os.Stderr, "Run '%s --ingestor --help' for ingester options.\n", os.Args[0]) + fmt.Fprintf(os.Stderr, "Run '%s --syncer --help' for syncer options.\n", os.Args[0])🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@cmd/ragflow_main.go` around lines 149 - 165, Update the no-mode branch in printHelp so the usage line and mode list include the new --syncer mode alongside --api, --admin, and --ingestor, and add a matching short description for it. Also add the corresponding “Run ... --syncer --help” hint near the other mode-specific help lines so the help text stays aligned with parseArgs and the supported serverArgs.mode values.
545-618: 🩺 Stability & Availability | 🔵 Trivial | ⚖️ Poor tradeoff
runSyncergraceful-shutdown context is created but never used.
context.WithTimeout(...)at Line 610 produces a context that is discarded (_);fileSyncer.Stop()(Line 613) doesn't accept or honor any context/deadline and simply blocks onworkerWg.Wait(). If a worker hangs (e.g., during a long DB call oncepollAndExecuteis implemented), shutdown can block indefinitely despite the apparent 30s timeout. This mirrors the existingrunIngestorpattern (Lines 534-538), so it's a pre-existing issue rather than new, but worth addressing here sinceSyncer.Stop()is new code.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@cmd/ragflow_main.go` around lines 545 - 618, `runSyncer` creates a timeout context but never uses it, so shutdown can still block forever in `fileSyncer.Stop()`. Update `runSyncer` and the `syncer.Syncer.Stop` path to accept and honor the context/deadline instead of discarding it, and use that context when waiting for workers so shutdown can fail fast after 30 seconds. Keep the fix aligned with the `runSyncer`/`fileSyncer.Stop` flow and the existing timeout pattern used elsewhere.internal/syncer/syncer.go (1)
104-128: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
pollAndExecuteis a no-op stub —executeSyncTask/executePruneTaskare currently unreachable.
pollAndExecuteonly logs and never queriessync_logs/dispatches tasks, soexecuteSyncTaskandexecutePruneTaskare dead code for now. If this is an intentional first-pass "framework" scaffold (per PR description), consider adding a// TODOinpollAndExecuteitself for clarity, matching the TODOs already present inexecuteSyncTask/executePruneTask.Also, for the future real implementation: since every worker runs its own ticker at the same
pollIntervaland polls independently (Line 98-100), you'll need a concurrency-safe task-claiming mechanism (e.g.,SELECT ... FOR UPDATE SKIP LOCKEDor an atomic status transition) to avoid multiple workers picking up and double-processing the same due task.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/syncer/syncer.go` around lines 104 - 128, `pollAndExecute` is currently just a logging stub, so `executeSyncTask` and `executePruneTask` never get reached. Update `Syncer.pollAndExecute` to either clearly mark it as an intentional TODO scaffold or implement the task lookup/dispatch flow against `sync_logs` so due tasks are actually picked and routed to `executeSyncTask` or `executePruneTask`. Keep the existing task handlers (`executeSyncTask`, `executePruneTask`) as the execution paths, and for the eventual real polling logic make task claiming concurrency-safe so multiple workers don’t process the same task twice.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/syncer/syncer.go`:
- Around line 47-58: `NewSyncer` currently accepts any `pollInterval`, but
`workerLoop` later passes it to `time.NewTicker`, which panics on zero or
negative values. Add validation in `NewSyncer` (or before `workerLoop` creates
the ticker) to reject or normalize non-positive intervals, and make sure
`Start`/`workerLoop` never launches a ticker with an invalid duration. Use the
existing `NewSyncer` and `workerLoop` symbols to keep the fix localized and
prevent the goroutine panic path.
- Around line 131-143: The markTaskDone method is ignoring database update
failures, which can leave SyncLogs and Connector states inconsistent. Update the
two dao.GetDB().Model(...).Updates(...) calls to capture and check the returned
gorm result, and handle result.Error (and optionally RowsAffected) with
appropriate logging or error propagation. Use the markTaskDone method plus the
SyncLogs and Connector updates to locate the change.
---
Nitpick comments:
In `@cmd/ragflow_main.go`:
- Around line 149-165: Update the no-mode branch in printHelp so the usage line
and mode list include the new --syncer mode alongside --api, --admin, and
--ingestor, and add a matching short description for it. Also add the
corresponding “Run ... --syncer --help” hint near the other mode-specific help
lines so the help text stays aligned with parseArgs and the supported
serverArgs.mode values.
- Around line 545-618: `runSyncer` creates a timeout context but never uses it,
so shutdown can still block forever in `fileSyncer.Stop()`. Update `runSyncer`
and the `syncer.Syncer.Stop` path to accept and honor the context/deadline
instead of discarding it, and use that context when waiting for workers so
shutdown can fail fast after 30 seconds. Keep the fix aligned with the
`runSyncer`/`fileSyncer.Stop` flow and the existing timeout pattern used
elsewhere.
In `@internal/syncer/syncer.go`:
- Around line 104-128: `pollAndExecute` is currently just a logging stub, so
`executeSyncTask` and `executePruneTask` never get reached. Update
`Syncer.pollAndExecute` to either clearly mark it as an intentional TODO
scaffold or implement the task lookup/dispatch flow against `sync_logs` so due
tasks are actually picked and routed to `executeSyncTask` or `executePruneTask`.
Keep the existing task handlers (`executeSyncTask`, `executePruneTask`) as the
execution paths, and for the eventual real polling logic make task claiming
concurrency-safe so multiple workers don’t process the same task twice.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 7e367bf4-7d66-47a5-96fa-c785a091e467
📒 Files selected for processing (6)
cmd/ragflow_main.goconf/service_conf.yamldocker/service_conf.yaml.templateinternal/common/status_message.gointernal/server/config.gointernal/syncer/syncer.go
| // NewSyncer creates a syncer with the given concurrency and poll interval. | ||
| func NewSyncer(maxConcurrency int, pollInterval time.Duration) *Syncer { | ||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| return &Syncer{ | ||
| id: common.GenerateUUID(), | ||
| maxConcurrency: maxConcurrency, | ||
| pollInterval: pollInterval, | ||
| ctx: ctx, | ||
| cancel: cancel, | ||
| ShutdownCh: make(chan struct{}), | ||
| } | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win
Panic risk: time.NewTicker with non-positive interval.
NewSyncer stores pollInterval without validation, and workerLoop calls time.NewTicker(s.pollInterval) at Line 90. If config.FileSyncer.SyncInterval is 0 (e.g., unset/misconfigured YAML, or overridden to 0), time.NewTicker panics. This happens inside a bare goroutine (go s.workerLoop(i), spawned from Start()), so an unrecovered panic will crash the entire process.
🛡️ Proposed fix
func NewSyncer(maxConcurrency int, pollInterval time.Duration) *Syncer {
ctx, cancel := context.WithCancel(context.Background())
+ if maxConcurrency <= 0 {
+ maxConcurrency = 1
+ }
+ if pollInterval <= 0 {
+ pollInterval = time.Second
+ }
return &Syncer{
id: common.GenerateUUID(),Also applies to: 90-91
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/syncer/syncer.go` around lines 47 - 58, `NewSyncer` currently
accepts any `pollInterval`, but `workerLoop` later passes it to
`time.NewTicker`, which panics on zero or negative values. Add validation in
`NewSyncer` (or before `workerLoop` creates the ticker) to reject or normalize
non-positive intervals, and make sure `Start`/`workerLoop` never launches a
ticker with an invalid duration. Use the existing `NewSyncer` and `workerLoop`
symbols to keep the fix localized and prevent the goroutine panic path.
| func (s *Syncer) markTaskDone(taskID, connectorID string) { | ||
| db := dao.GetDB() | ||
| now := time.Now().Local() | ||
|
|
||
| db.Model(&entity.SyncLogs{}).Where("id = ?", taskID).Updates(map[string]interface{}{ | ||
| "status": string(entity.TaskStatusDone), | ||
| "update_time": now, | ||
| }) | ||
| db.Model(&entity.Connector{}).Where("id = ?", connectorID).Updates(map[string]interface{}{ | ||
| "status": string(entity.TaskStatusDone), | ||
| "update_time": now, | ||
| }) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Unchecked DB update errors in markTaskDone.
Both db.Model(...).Updates(...) calls (Lines 135-142) ignore the returned *gorm.DB (and its .Error/.RowsAffected). A failed update (e.g., DB connectivity issue) will silently leave a task/connector stuck in an inconsistent status with no log or retry.
🛡️ Proposed fix
- db.Model(&entity.SyncLogs{}).Where("id = ?", taskID).Updates(map[string]interface{}{
+ if err := db.Model(&entity.SyncLogs{}).Where("id = ?", taskID).Updates(map[string]interface{}{
"status": string(entity.TaskStatusDone),
"update_time": now,
- })
- db.Model(&entity.Connector{}).Where("id = ?", connectorID).Updates(map[string]interface{}{
+ }).Error; err != nil {
+ common.Error("Failed to update sync task status", err)
+ }
+ if err := db.Model(&entity.Connector{}).Where("id = ?", connectorID).Updates(map[string]interface{}{
"status": string(entity.TaskStatusDone),
"update_time": now,
- })
+ }).Error; err != nil {
+ common.Error("Failed to update connector status", err)
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| func (s *Syncer) markTaskDone(taskID, connectorID string) { | |
| db := dao.GetDB() | |
| now := time.Now().Local() | |
| db.Model(&entity.SyncLogs{}).Where("id = ?", taskID).Updates(map[string]interface{}{ | |
| "status": string(entity.TaskStatusDone), | |
| "update_time": now, | |
| }) | |
| db.Model(&entity.Connector{}).Where("id = ?", connectorID).Updates(map[string]interface{}{ | |
| "status": string(entity.TaskStatusDone), | |
| "update_time": now, | |
| }) | |
| } | |
| func (s *Syncer) markTaskDone(taskID, connectorID string) { | |
| db := dao.GetDB() | |
| now := time.Now().Local() | |
| if err := db.Model(&entity.SyncLogs{}).Where("id = ?", taskID).Updates(map[string]interface{}{ | |
| "status": string(entity.TaskStatusDone), | |
| "update_time": now, | |
| }).Error; err != nil { | |
| common.Error("Failed to update sync task status", err) | |
| } | |
| if err := db.Model(&entity.Connector{}).Where("id = ?", connectorID).Updates(map[string]interface{}{ | |
| "status": string(entity.TaskStatusDone), | |
| "update_time": now, | |
| }).Error; err != nil { | |
| common.Error("Failed to update connector status", err) | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/syncer/syncer.go` around lines 131 - 143, The markTaskDone method is
ignoring database update failures, which can leave SyncLogs and Connector states
inconsistent. Update the two dao.GetDB().Model(...).Updates(...) calls to
capture and check the returned gorm result, and handle result.Error (and
optionally RowsAffected) with appropriate logging or error propagation. Use the
markTaskDone method plus the SyncLogs and Connector updates to locate the
change.
### Summary ./ragflow_main --syncer to start file syncer config yaml file has following config ``` file_syncer: max_concurrent_syncs: 4 # concurrent file sync threads sync_interval: 3 # check interval ``` --------- Signed-off-by: Jin Hai <[email protected]>
### Summary ./ragflow_main --syncer to start file syncer config yaml file has following config ``` file_syncer: max_concurrent_syncs: 4 # concurrent file sync threads sync_interval: 3 # check interval ``` --------- Signed-off-by: Jin Hai <[email protected]>
Summary
./ragflow_main --syncer to start file syncer
config yaml file has following config