feat(server): unified scheduled-job registry and scheduler; module timers moved onto it

- modules/schedules: registerScheduledJob({key, defaults, run}) registry; defaults are
  synced into scheduled_job without overriding user-changed enabled/schedule
- scheduler runs only on the io worker, one instance via pg_try_advisory_lock held on a
  dedicated connection; due = enabled and next_run_at reached, or run requested;
  jobs run in parallel, never re-entrant; interval next = finish + period, cron next match;
  run-now does not move next_run_at and merges duplicate requests; skip advances one period;
  history trimmed to the last 50 runs; interrupted runs marked failed on takeover
- agent_check jobs: trigger condition checked first, goal template rendered, runAgent
  enqueued via startRun(trigger=schedule) with allowlist and budget, one run per time slot;
  allowRecover uses the autoInvestigate grant check; results harvested back into the run
  history and optionally reported as an info decision; 3 built-in checks, off by default
- sources-identity (feeds.poll, sites.snapshot, identity.review), acquisition-organize
  (downloads.sync, cache.threshold, downloads.orchestrate, slots.reevaluate,
  subscriptions.search, subscriptions.metadata, library.reconcile) and file-manager
  (trash.purge) register jobs instead of running their own setInterval; default
  intervals unchanged; backup registered as an unconfigured placeholder
- endpoints under /schedules (admin, console session only)

TODO: pi refreshPiTokens and auth-settings session cleanup still own their timers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
rootandClaude Opus 5.5 committed 2026-09-28 02:32:33 +08:00
1 parent f8f70d8e09
commit a68fcea13b
16 files changed
+1732 -127

No files matched your search

@@ -0,0 +1,61 @@
import type { ServerContext, ServerModule } from "../types.ts";
import { builtinAgentCheckDefs } from "./agent-checks.ts";
import { registerScheduledJob, scheduleRegistry } from "./registry.ts";
import { registerScheduleRoutes } from "./routes.ts";
import { Scheduler, type SchedulerOptions } from "./scheduler.ts";
export type { JobRunContext, JobRunResult, ScheduledJobDef, ScheduledJobDefaults } from "./registry.ts";
export { registerScheduledJob, scheduleRegistry } from "./registry.ts";
/**
* W7-C 定时任务统一注册表 + 看板(docs/runbook/schedules.md):
* 各模块 start() 用 registerScheduledJob 登记周期任务;本模块在 io worker 上起唯一调度器(PG 咨询锁)按表驱动,
* 并登记内置 Agent 巡检模板(默认关闭)与备份占位。看板 API 见 routes.ts(全部只接受控制台会话)。
* 须放在 SERVER_MODULES 末尾:start 时其它模块已登记完(之后再登记的也会在下一轮同步)。
*
* TODO(W7-A):pi 模块的 refreshPiTokens 目前在 pi/index.ts 自建 setInterval,
* 待其改为 registerScheduledJob({ key: "pi.token_refresh", defaults: { group: "maintain", ... } })。
*/
export interface SchedulesModuleOptions {
scheduler?: SchedulerOptions;
/** 缺省 true;测试可关掉内置巡检 */
builtinChecks?: boolean;
}
export function createSchedulesModule(opts: SchedulesModuleOptions = {}): ServerModule & {
scheduler(): Scheduler | null;
} {
let scheduler: Scheduler | null = null;
return {
name: "schedules",
scheduler: () => scheduler,
registerRoutes(app, ctx) {
registerScheduleRoutes(app, ctx, () => scheduleRegistry(ctx));
},
registerTasks() {},
start(ctx: ServerContext) {
if (opts.builtinChecks !== false) for (const def of builtinAgentCheckDefs(ctx)) registerScheduledJob(ctx, def);
// 备份目前由宿主机 scripts/backup.sh(cron / 手动)执行,这里只占位,看板上显示"未配置"
registerScheduledJob(ctx, {
key: "maintain.backup",
defaults: {
name: "备份",
description: "数据库与数据目录备份;目前由 scripts/backup.sh 在宿主机执行,未接入调度",
group: "maintain",
schedule: { type: "cron", cron: "30 3 * * *" },
enabled: false,
available: false,
},
run: async () => ({ status: "skipped", summary: "未配置" }),
});
scheduler = new Scheduler(ctx, scheduleRegistry(ctx), opts.scheduler);
scheduler.start();
},
async stop() {
await scheduler?.stop();
scheduler = null;
},
};
}
export const schedulesModule = createSchedulesModule();