feat: harden cron execution recovery and expose scheduling diagnostics

Reconcile scheduled and system cron triggers, isolate concurrent executions and retain verifiable exit statistics across restarts. Add paged task history, log and script browsing, dashboard timing details and regression coverage.
This commit is contained in:
whyour committed 2026-11-17 01:01:57 +08:00
1 parent 3b6a873520
commit 8a9e70e90b
166 files changed
+18942 -1800

No files matched your search

+105 -17
View File
@@ -1,5 +1,9 @@
import { hasLiveCronProcess } from './cronProcess';
import { EventEmitter } from 'events';
import PQueue from 'p-queue-cjs';
import { triggerHistory, TriggerState } from './triggerHistory';
import { t } from './i18n';
import { spawn } from 'cross-spawn';
import { spawnCronCommand, releaseCronCommand } from './cronCommandProcess';
import taskLimit from './pLimit';
import Logger from '../loaders/logger';
import { ICron } from '../protos/cron';
@@ -8,14 +12,51 @@ import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
import dayjs from 'dayjs';
import { observeChildProcess, asError } from './childProcess';
export function runCron(
const waiting = new Map<string, () => void>();
// A backlog of missed timers can otherwise open hundreds of competing SQLite
// writer transactions on wake. Only serialize history writes, never commands.
const historyWrites = new PQueue({ concurrency: 1 });
export function cancelWaitingTriggers(ids: string[]) {
for (const id of ids) waiting.get(id)?.();
}
export async function runCron(
cmd: string,
cron: ICron,
isCurrent: () => boolean = () => true,
trigger?: { id: string; time: number; source: 'node' | 'recovery' },
): Promise<number | void> {
const history = trigger && triggerHistory();
const queuedAt = Date.now();
if (trigger && history) {
const cronId = Number(cron.id);
const admitted = await historyWrites.add(() => cron.skip_if_pending
? history.enqueueUnlessPending(trigger.id, cronId, trigger.source, trigger.time, queuedAt, cron.recovery_from)
: history.enqueue(trigger.id, cronId, trigger.source, trigger.time, queuedAt));
if (!admitted) return;
}
let reason = 'capacity';
let state: TriggerState = 'skipped';
let exitCode: number | null = null;
let claimed = false;
const deadline = cron.max_queue_wait ? queuedAt + cron.max_queue_wait * 1000 : Infinity;
let timer: NodeJS.Timeout | undefined;
const expiry = trigger ? new EventEmitter() : undefined;
const alive = () => isCurrent() && Date.now() < deadline;
if (trigger && expiry && Number.isFinite(deadline)) {
timer = setTimeout(() => {
reason = 'queue_timeout';
taskLimit.removeQueuedCron(cron.id, execute);
expiry.emit('expired');
}, Math.max(0, deadline - Date.now()));
timer.unref();
}
const execute = async () => {
if (trigger) waiting.delete(trigger.id);
reason = 'changed';
try {
if (!isCurrent()) return;
if (!alive()) { reason = isCurrent() ? 'queue_timeout' : 'changed'; return; }
let multiple = false;
// A single-instance trigger must not interrupt work already in progress.
try {
const existingCron = await CrontabModel.findOne({
@@ -26,10 +67,9 @@ export function runCron(
if (!isCurrent() || !existingCron || existingCron.isDisabled) return;
// Default to single instance mode (0) for backward compatibility
const allowSingleInstances =
existingCron?.allow_multiple_instances === 0;
multiple = existingCron.allow_multiple_instances === 1;
if (allowSingleInstances) {
if (!multiple) {
// A queued manual run is an active reservation, even if its stored PID
// belongs to a previous execution.
if (
@@ -41,26 +81,20 @@ export function runCron(
cron.id,
existingCron.pid,
);
reason = 'overlap';
return;
}
if (
existingCron.status === CrontabStatus.running &&
existingCron.pid
) {
let missing = false;
try {
process.kill(existingCron.pid, 0);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === 'ESRCH') missing = true;
else if (code !== 'EPERM') throw error;
}
if (!missing) {
if (hasLiveCronProcess(existingCron.status, existingCron.pid)) {
Logger.info(
'[schedule][Skip active single-instance task] Task ID: %s, PID: %s',
cron.id,
existingCron.pid,
);
reason = 'overlap';
return;
}
@@ -135,9 +169,39 @@ export function runCron(
command: cmd,
}),
);
const cp = spawn(cmd, { shell: '/bin/bash' });
clearTimeout(timer);
if (Date.now() >= deadline) {
reason = 'queue_timeout';
return;
}
if (trigger) {
claimed = await history!.start(trigger.id, Date.now(), multiple);
if (!claimed) { reason = 'overlap'; return; }
}
if (!isCurrent() || Date.now() >= deadline) {
reason = isCurrent() ? 'queue_timeout' : 'changed';
return;
}
let saveStart: Promise<void> | undefined;
const cp = spawnCronCommand(cmd, trigger?.id, trigger && history ? at => {
saveStart = history.recordCommandStart(trigger.id, at).catch(error => {
Logger.warn('[schedule] Could not record command start: %s', asError(error).message);
});
} : undefined);
let denied: string | undefined;
const { completed } = observeChildProcess(cp, {
onStart: async () => {
if (!trigger) return;
try {
if (await history!.bindCommand(trigger.id, cp.pid!) && !await history!.shouldStop(trigger.id)) {
if (!alive()) denied = isCurrent() ? 'queue_timeout' : 'changed';
else await releaseCronCommand(cp);
}
} finally {
cp.stdin.end();
}
},
onStderr: async (message) => {
Logger.info(
t('[schedule][任务标准错误] 命令: %s, 信息: %s'),
@@ -147,6 +211,11 @@ export function runCron(
},
});
const result = await completed;
await saveStart;
if (denied) { reason = denied; return; }
state = result.signal ? 'stopped' : result.error || result.code !== 0 ? 'failed' : 'finished';
reason = result.error ? 'spawn' : result.signal || '';
exitCode = result.code;
if (result.error) {
Logger.error(
t('[schedule][执行任务失败] 命令: %s, 错误: %s'),
@@ -161,6 +230,8 @@ export function runCron(
);
return { ...cron, command: cmd, pid: cp.pid, ...result } as any;
} catch (error) {
state = 'failed';
reason = 'spawn';
Logger.error(
t('[schedule][创建任务失败] 命令: %s, 错误: %s'),
cmd,
@@ -170,5 +241,22 @@ export function runCron(
taskLimit.removeQueuedCron(cron.id, execute);
}
};
return taskLimit.runWithCronLimit(cron, execute, undefined, isCurrent);
try {
if (trigger && expiry) waiting.set(trigger.id, () => {
taskLimit.removeQueuedCron(cron.id, execute);
expiry.emit('expired');
});
return await taskLimit.runWithCronLimit(cron, execute, undefined, isCurrent, () => { reason = 'pending'; }, expiry, trigger?.id, CrontabModel.sequelize);
} finally {
clearTimeout(timer);
if (trigger) waiting.delete(trigger.id);
if (trigger && history) {
const outcomeReason = state === 'skipped' && !isCurrent() ? 'changed' : reason;
const finishedAt = Date.now();
await historyWrites.add(() => state === 'skipped' && !claimed
? history.skipQueued(trigger.id, outcomeReason, finishedAt)
: history.complete(trigger.id, state, outcomeReason || null, exitCode, finishedAt),
{ priority: 1 });
}
}
}