refactor(schedules): register pi.token_refresh and auth.cleanup as scheduled jobs

Pi token refresh (10 min) and auth session cleanup (1 h) no longer run
their own setInterval; both register in the maintain group of the
schedules registry with the same default intervals.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
rootandClaude Opus 5.5 committed 2026-09-28 13:44:48 +08:00
1 parent 31a54186c7
commit a0b0a64246
5 files changed
+90 -29

No files matched your search

+18 -9
View File
@@ -1,4 +1,5 @@
import { sql } from "@umt/db";
import { registerScheduledJob } from "../schedules/registry.ts";
import type { ServerContext, ServerModule } from "../types.ts";
import { registerAuthRoutes } from "./auth-routes.ts";
import { ensureSetupToken } from "./auth-service.ts";
@@ -18,7 +19,7 @@ export interface AuthSettingsModuleOptions {
engineSchema?: string;
/** api 角色启动时若未初始化管理员则生成并打印 setup token(默认 true;测试关掉自己调 ensureSetupToken) */
setupTokenOnStart?: boolean;
/** 过期会话/登录尝试清理间隔,默认 1 小时 */
/** 定时任务 auth.cleanup(过期会话/登录尝试清理)的默认周期,默认 1 小时;<=0 不登记 */
cleanupIntervalMs?: number;
}
@@ -30,7 +31,6 @@ export async function cleanupAuthTables(ctx: Pick<ServerContext, "db">): Promise
}
export function createAuthSettingsModule(opts: AuthSettingsModuleOptions = {}): ServerModule {
let timer: ReturnType<typeof setInterval> | null = null;
return {
name: "auth-settings",
registerRoutes(app, ctx) {
@@ -44,14 +44,23 @@ export function createAuthSettingsModule(opts: AuthSettingsModuleOptions = {}):
}
},
registerTasks() {},
/** 清理周期登记为定时任务 auth.cleanup(维护组,由 schedules 调度器驱动) */
start(ctx) {
const run = () => cleanupAuthTables(ctx).catch((err) => ctx.logger.warn({ err }, "认证表清理失败"));
timer = setInterval(run, opts.cleanupIntervalMs ?? 3600_000);
void run();
},
stop() {
if (timer) clearInterval(timer);
timer = null;
const everyMs = opts.cleanupIntervalMs ?? 3600_000;
if (everyMs <= 0) return;
registerScheduledJob(ctx, {
key: "auth.cleanup",
defaults: {
name: "登录会话清理",
description: "删除 7 天前的登录尝试和 30 天前过期或吊销的会话",
group: "maintain",
schedule: { type: "interval", everyMs },
},
run: async () => {
await cleanupAuthTables(ctx);
return { summary: "已清理" };
},
});
},
};
}