Skip to content

feat(cronjob): implement cron_sync - #3368

Draft
xrgzs wants to merge 18 commits into
OpenListTeam:mainfrom
xrgzs:feat/sync
Draft

xrgzs wants to merge 18 commits into
OpenListTeam:mainfrom
xrgzs:feat/sync

Conversation

@xrgzs

@xrgzs xrgzs commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

Summary / 摘要

为OpenList增加定时同步功能,实现文件单向同步。

  • This PR has breaking changes.
    / 此 PR 包含破坏性变更。
  • This PR changes public API, config, storage format, or migration behavior.
    / 此 PR 修改了公开 API、配置、存储格式或迁移行为。
  • This PR requires corresponding changes in related repositories.
    / 此 PR 需要关联仓库同步修改。

Related repository PRs / 关联仓库 PR:

Related Issues / 关联 Issue

Closes #428

Testing / 测试

  • go test ./...
  • Manual test / 手动测试: 已自用1个月。

TODO: 需要完善细节。

Checklist / 检查清单

  • I have read CONTRIBUTING.
    / 我已阅读 CONTRIBUTING。
  • I confirm this contribution follows the repository license, contribution policy, and code of conduct.
    / 我确认此贡献符合仓库许可证、贡献规范和行为准则。
  • I have formatted the changed code with gofmt, go fmt, or prettier where applicable.
    / 我已按适用情况使用 gofmt、go fmt 或 prettier 格式化变更代码。
  • I have requested review from relevant maintainers or code owners where applicable.
    / 我已在适用情况下请求相关维护者或代码所有者审查。

AI Disclosure / AI 使用声明

  • This PR includes AI-assisted content.
    / 此 PR 包含 AI 辅助内容。

Tools used / 使用工具:

  • ChatGPT
  • Codex
  • GitHub Copilot
  • Claude
  • Gemini
  • Other (please specify) / 其他(请注明): GLM 5.3

Usage scope / 使用范围:

  • Code generation / 代码生成

  • Refactoring / 重构

  • Documentation / 文档

  • Tests / 测试

  • Translation / 翻译

  • Review assistance / 审查辅助

  • I have reviewed and validated all AI-assisted content included in this PR.
    / 我已审核并验证此 PR 中的所有 AI 辅助内容。

  • I have ensured that all AI-assisted commits include Co-Authored-By attribution.
    / 我已确保所有 AI 辅助提交都包含 Co-Authored-By 归属信息。

  • I can reproduce all AI-assisted content included in this PR without any AI tools.
    / 我可以在没有任何 AI 工具的情况下重现此 PR 中包含的所有 AI 辅助内容。

@xrgzs xrgzs added the WIP An Issue already has a PR to fix label Nov 28, 2026
@xrgzs
xrgzs requested a max review from Copilot November 28, 2026 05:15

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved critical sync defects can delete valid or protected data and allow destructive runs to overlap after cancellation or restart.

29 open issues

And 9 more that still need to be addressed.

What changed in this PR

Adds scheduled, one-way file synchronization to OpenList’s existing filesystem and task-management infrastructure, addressing issue #428 and supporting the companion frontend work.

Changes:

  • Adds persisted cronjob configuration, handler metadata and multi-expression scheduling.
  • Implements filtered mirror synchronization using existing copy tasks, with progress and child-task tracking.
  • Adds administrator APIs, task-route integration and sync, scheduling and permission tests.
File Description
server/​router.go Registers cronjob administration and task routes.
server/​handles/​task.go Exposes the cron-sync task manager.
server/​handles/​cronjob.go Adds configuration, validation and manual-run APIs.
server/​handles/​cronjob_test.go Tests administrator-only creation and persistence.
pkg/​cron/​cron.go Adds five-field expressions and a polling scheduler.
pkg/​cron/​cron_test.go Adds cron-spec tests; removes the legacy smoke test.
internal/​model/​cronjob.go Defines persisted configuration and runtime fields.
internal/​db/​db.go Includes cronjobs in database migration.
internal/​db/​cronjob.go Adds configuration and runtime-state database operations.
internal/​cronjob/​task_data.go Stores and restores sync task state.
internal/​cronjob/​sync_test.go Adds end-to-end sync and scheduling tests.
internal/​cronjob/​sync_task.go Implements scanning, deletion, copying and progress tracking.
internal/​cronjob/​sync_info.go Describes sync fields for frontend forms.
internal/​cronjob/​sync_filters.go Implements exclusions and size/age filtering.
internal/​cronjob/​sync_compare_test.go Tests comparisons, filters and path helpers.
internal/​cronjob/​sync_args.go Defines and validates synchronization options.
internal/​cronjob/​specs.go Parses schedules and calculates the earliest next run.
internal/​cronjob/​scheduler.go Dispatches jobs and tracks execution state.
internal/​cronjob/​handler.go Defines handler contracts, registration and form metadata.
internal/​bootstrap/​task.go Initializes the sync manager and scheduler.
internal/​bootstrap/​data/​task.go Seeds persisted cron_sync task data.

Review effort: Max

Comment thread internal/bootstrap/task.go Resolved
Comment thread internal/bootstrap/task.go Resolved
Comment thread internal/cronjob/scheduler.go Resolved
Comment thread internal/cronjob/sync_task.go Resolved
Comment thread internal/cronjob/sync_task.go Resolved
Comment thread internal/cronjob/sync_task.go Resolved
Comment thread internal/cronjob/sync_task.go Resolved
Comment thread internal/cronjob/sync_task.go Resolved
Comment thread pkg/cron/cron.go Resolved
Comment thread pkg/cron/cron.go Resolved
xrgzs and others added 14 commits November 28, 2026 18:11
- Track whether a cron field uses wildcard syntax during parsing instead of
  inferring it from the expanded value set.
- Treat fields like `1-31` and `*/2` as restricted/wildcard per crontab syntax,
  so `0 0 1-31 * 1` runs daily instead of Mondays only.
- Add tests covering full-range DOM and step wildcard day matching.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Raise the bounded minute search in `NextAfter` to cover sparse schedules
  such as `0 0 29 2 *`, whose next occurrence can be several years away.
- Add a test asserting the leap-day schedule resolves to the next Feb 29.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Register the `sync` handler only once so a second `bootstrap.Start` does not
  panic on duplicate registration.
- Reset the scheduler's `started` flag and runtime maps on stop so the scheduler
  can be initialized again after shutdown.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Stop the cronjob scheduler and cancel/drain active sync and copy tasks before
  closing the database, preventing sync work from racing database closure.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Return an error when any listed alias backend fails instead of skipping it
  and returning an incomplete (possibly empty) result.
- Prevent destructive callers such as cron sync from classifying every
  destination entry as extra and deleting it during a backend outage.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Re-read `t.Ctx()` after `SetCtx` so the injected administrator and API URL are
  visible to subsequent `fs.Copy` calls.
- Prevent sync copy tasks from being created with a nil creator, which caused a
  panic when ordinary users queried the task list.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Compare logical (balanced-resolved) paths in addition to storage IDs so
  balanced mounts and aliases pointing back into the source are rejected.
- Detect sources and destinations that share the same backing store by
  comparing driver `GetPaths` configuration.
- Add `op.GetLogicalActualPath` returning a deterministic virtual mount and
  relative path suitable for overlap comparison.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Propagate source listing errors instead of treating a missing source
  directory as empty, which authorized deleting every destination entry.
- Include virtual child-mount entries in listings so existing destination
  directories with a mount's name are not classified as extra.
- Traverse destination-only directories with filters and depth limits,
  removing the directory only when no protected descendants remain (keeps
  `exclude="*.log"` from deleting `archive/keep.log`).
- Check cancellation before each extra-object removal.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Apply exclusion rules and destination listing to single-file sources so
  `exclude="*.log"` also skips a `file.log` source.
- Reuse the destination directory listing instead of re-listing it for every
  source file, avoiding O(N^2) remote listing during routine scans.
- Treat differing object types as different before comparing size or hashes,
  so a source file replaces an equal-sized destination directory and vice versa.
- Add a `remove_before` option (default false) that deletes the destination
  file before queuing its replacement, preserving the previous copy on failure.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Treat differing object types as a change before comparing size or hashes so a
  file replaces an equal-sized destination directory.
- Fall back to size comparison when only `checksum` is enabled but neither side
  exposes a common hash (for example Local storage), instead of treating
  different-sized files as identical.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Track pending child copy tasks in the sync task so a cleared child record no
  longer leaves the sync (and its cronjob lock) waiting forever.
- Count only succeeded, failed, and canceled children as finished; keep
  `StateErrored` as in-progress while the child is retrying.
- Cancel and wait for outstanding children on every unsuccessful planning exit
  before reporting the run finished.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Associate SyncTask with its CronJob ID and track running syncs independently
  of task records so the scheduler keeps the run lock even if the record is
  removed; avoid restarting a job whose recovered sync is still running.
- Defer scheduler ticks until storage loading finishes and wait for the storage
  readiness signal before restoring persisted sync tasks.
- Compile sync exclusion rules during create/update validation so invalid glob
  and regexp configurations are rejected before persistence.
- Wait on the sync task object directly instead of re-querying the manager,
  which previously returned early when the record was cleared.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Run update and delete inside the scheduler's run lock so a mutation cannot
  race a scheduled start and leave the job running an old configuration.
- Update only configurable fields on edit so `last_run_at` and `last_error`
  are no longer erased by a full save.
- Disable generic retry for cron_sync tasks because a direct retry bypasses the
  per-job run lock and reuses stale child state; use the run endpoint instead.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- Resolve the administrator and API URL in `runSync` before adding the task, so
  a task visible in the manager always has a non-nil creator.
- Prevent ordinary users' task queries from panicking on the pending sync task's
  nil creator while both workers are busy.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@xrgzs

xrgzs commented Nov 28, 2026 •

Copy link
Copy Markdown
Member Author

All review conversations have been addressed and resolved. Summary of the fixes (oldest → newest):

  • 5bbaa7ce fix(cron): use wildcard syntax for DOM/DOW matching
  • 09015f07 fix(cron): extend next-run search to cover leap-day gaps
  • 95f2f344 fix(cronjob): support repeated scheduler start in embedded lifecycle
  • d7f686d0 fix(bootstrap): stop cronjob scheduler on shutdown and release
  • f15d3cff fix(alias): propagate backend listing errors
  • f295c4cd fix(cronjob): re-read sync task context after SetCtx
  • ddc8b708 fix(cronjob): reject overlapping sync paths across mounts
  • 440fea95 fix(cronjob): make sync listing safe for destructive operations
  • 6aeb81e0 fix(cronjob): sync single files and type conflicts correctly
  • 54bad383 fix(cronjob): fix sync object comparison edge cases
  • 2c20695c fix(cronjob): track sync children independently of task records
  • 3f3bdd13 fix(cronjob): harden scheduler guard and recovery readiness
  • 359ae54c fix(server): serialize cronjob mutations and preserve run history
  • 9f10b5b5 fix(cronjob): assign sync task creator before queueing

Verification: go build ./... passes; go test ./internal/cronjob/ ./pkg/cron/ ./internal/op/ and go test ./server/handles/ pass.

Commited by Copilot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

WIP An Issue already has a PR to fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] 网盘间自动同步

2 participants