feat(cron): expose run receipts and modularize execution

Return committed trigger IDs and add CLI wait and trigger-specific logs while
preserving API, CLI, transaction, deduplication and unknown-result semantics.

Move scheduling, lifecycle, settlement, queries and legacy adapters into
back/cron; remove obsolete internal import paths and circular dependencies.

Apply project formatting across the repository, cover CJS/MJS in formatting
hooks, add prettier:check and require formatting checks in AGENTS.md.

Validation: backend build; 1398 backend/frontend tests passed (17 platform
skips); 327 CLI tests passed (6 platform skips); 670 files pass format checks.
This commit is contained in:
whyour committed 2026-11-22 12:24:29 +08:00
1 parent 77ece406ac
commit c5458596c8
346 files changed
+32133 -11556

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
import { upcomingSlots } from './cronScheduler';
// Find only the latest eligible slot even for a second-level rule after hours
// offline. Search by time, so cost is logarithmic in the configured window.
export function latestMissedSlot(
schedule: string,
since: number,
until: number,
): number | null {
let low = Math.floor(since / 1000);
let high = Math.floor(until / 1000);
let latest: number | null = null;
while (low < high) {
const middle = Math.floor((low + high) / 2);
const [next] = upcomingSlots(schedule, middle * 1000);
if (next > until) high = middle;
else {
latest = next;
low = next / 1000;
}
}
return latest;
}
+167
View File
@@ -0,0 +1,167 @@
import CronExpressionParser from 'cron-parser';
import { validate } from 'node-cron';
import { ScheduleType } from '../../interface/schedule';
const aliases: Record<string, string> = {
'@yearly': '0 0 0 1 1 *',
'@annually': '0 0 0 1 1 *',
'@monthly': '0 0 0 1 * *',
'@weekly': '0 0 0 * * 0',
'@daily': '0 0 0 * * *',
'@midnight': '0 0 0 * * *',
'@hourly': '0 0 * * * *',
'@minutely': '0 * * * * *',
};
export interface CronSchedule {
patterns: string[];
dayCount: number;
nthDay: number;
}
// Validation and registration repeatedly see identical rules in large snapshots.
// Cache only immutable syntax, never dates or running tasks, and bound user input.
const scheduleCache = new Map<string, CronSchedule>();
const daysInMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Canonicalize legacy shorthand, aliases, names and numeric-start steps before
// node-cron sees them. Extend legacy aliases explicitly; reject H and bare /N.
export function parseCronSchedule(schedule: unknown): CronSchedule {
if (typeof schedule !== 'string' || !schedule.trim()) {
throw new Error('Invalid cron schedule');
}
let source = schedule.trim();
const cacheKey = source;
const cached = scheduleCache.get(cacheKey);
if (cached) return cached;
if (source.startsWith('@')) {
if (!Object.hasOwn(aliases, source)) throw new Error('Invalid cron alias');
source = aliases[source];
}
let parts = source.split(/\s+/);
if (
parts.length > 6 ||
parts.some((part) => /(^|,)\//.test(part) || /H(?:\(|\/|$)/i.test(part))
) {
throw new Error('Unsupported cron syntax');
}
parts = [
...['0', '*', '*', '*', '*', '*'].slice(0, 6 - parts.length),
...parts,
];
if (
parts.some(
(part, index) => index !== 3 && index !== 5 && part.includes('?'),
)
) {
throw new Error('Question mark is only valid in day fields');
}
const expression = CronExpressionParser.parse(parts.join(' '));
if (!expression.hasNext())
throw new Error('Cron schedule has no next execution');
let normalized = parts.map((part) => part.replace(/\?/g, '*'));
// cron-parser includes Sunday in stepped ranges ending in 7 even when the
// step does not land on 7. node-cron accepts those ranges with different days.
if (/(^|,)(?:\d+|[a-z]{3})-0*7\/\d+(?=,|$)/i.test(normalized[5])) {
normalized[5] = expression.fields.dayOfWeek.values.join(',');
}
// Most rules are already supported; only inspect individual fields on failure.
if (!validate(normalized.join(' '))) {
const fields = [
expression.fields.second,
expression.fields.minute,
expression.fields.hour,
expression.fields.dayOfMonth,
expression.fields.month,
expression.fields.dayOfWeek,
];
normalized = normalized.map((value, index) => {
// Preserve supported lists, ranges and names. Expand only fields node-cron
// cannot consume, such as numeric/name-start steps; never compress them.
const probe = ['0', '0', '0', '*', '*', '*'];
probe[index] = value;
if (validate(probe.join(' '))) return value;
const values = fields[index].values;
if (index === 5 && expression.fields.dayOfWeek.nthDay) {
// The legacy normalizer treated *#N / ?#N as an unrestricted weekday.
if (values.length === 8) return '*';
// # applies to a single weekday; normalize its numeric spelling only.
return values.length === 1
? `${values[0]}#${expression.fields.dayOfWeek.nthDay}`
: value;
}
return values.join(',');
});
}
const months = expression.fields.month.values;
// cron-parser 4 clipped dates outside a single selected month's maximum
// before deciding whether the day field covered the whole month.
const dayCount = expression.fields.dayOfMonth.values.filter(
(day) =>
months.length !== 1 ||
typeof day !== 'number' ||
day <= daysInMonth[months[0] - 1],
).length;
const weekCount = expression.fields.dayOfWeek.values.length;
// Preserve the legacy count-based wildcard rules, including repeated Sunday
// and L tokens: an ignored day field must not remain an AND constraint.
const weekdayPattern = [
...normalized.slice(0, 3),
'*',
...normalized.slice(4),
].join(' ');
const patterns =
weekCount === 8
? [[...normalized.slice(0, 5), '*'].join(' ')]
: dayCount < 31
? [[...normalized.slice(0, 5), '*'].join(' '), weekdayPattern]
: [weekdayPattern];
const valid = patterns.map((pattern) => validate(pattern));
if (patterns.length === 2 && !valid[0] && valid[1]) {
// A date branch can be impossible for all chosen months while the weekday
// branch still runs. Drop it only if its syntax is valid with any month.
if (validate([...normalized.slice(0, 4), '*', '*'].join(' '))) {
patterns.shift();
valid.shift();
}
}
if (!valid.every(Boolean)) {
throw new Error('Unsupported cron schedule');
}
const parsed = {
patterns,
dayCount,
nthDay: expression.fields.dayOfWeek.nthDay,
};
Object.freeze(patterns);
Object.freeze(parsed);
if (scheduleCache.size >= 512)
scheduleCache.delete(scheduleCache.keys().next().value);
scheduleCache.set(cacheKey, parsed);
return parsed;
}
export function isValidCronSchedule(schedule: unknown): schedule is string {
try {
parseCronSchedule(schedule);
return true;
} catch {
return false;
}
}
export function getInvalidCronSchedules(cron: {
schedule?: string;
extra_schedules?: Array<{ schedule: string }>;
}): unknown[] {
if (
cron.schedule?.startsWith(ScheduleType.ONCE) ||
cron.schedule?.startsWith(ScheduleType.BOOT)
) {
return [];
}
return [
cron.schedule,
...(cron.extra_schedules || []).map((x) => x.schedule),
].filter((schedule) => !isValidCronSchedule(schedule));
}
+165
View File
@@ -0,0 +1,165 @@
import { t } from '../../shared/i18n';
import { createTask, ScheduledTask } from 'node-cron';
import { parseCronSchedule } from './cronSchedule';
interface SchedulerLogger {
warn(message: string, ...args: unknown[]): unknown;
error(message: string, ...args: unknown[]): unknown;
}
export interface CronJob {
start(): void;
cancel(): void;
}
function acceptsSlot(
parsed: ReturnType<typeof parseCronSchedule>,
tasks: ScheduledTask[],
index: number,
date: Date,
) {
if (tasks.length === 1) return true;
// Preserve cron-parser 4's day/weekday OR semantics, including its
// month-dependent full-day range and the global nth-week constraint.
if (parsed.nthDay && Math.ceil(date.getDate() / 7) !== parsed.nthDay)
return false;
if (index === 1) return !tasks[0].match(date);
const monthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return parsed.dayCount < monthDays[date.getMonth()] || tasks[1].match(date);
}
// node-cron owns timers and calendar calculation; Qinglong owns execution
// concurrency and process lifetime. Missed in-process slots join that same queue.
export function createCronJob(
schedule: string,
callback: (date: Date) => unknown | Promise<unknown>,
options: { name: string; logger: SchedulerLogger; start?: boolean },
): CronJob {
const parsed = parseCronSchedule(schedule);
const tasks: ScheduledTask[] = [];
let cancelled = false;
let started = false;
const dispatch = async (index: number, date: Date, missed: boolean) => {
if (cancelled || !started || !acceptsSlot(parsed, tasks, index, date))
return;
if (missed) {
options.logger.warn(
t('[schedule][补执行迟到任务] 任务: %s, 计划时间: %s'),
options.name,
date.toISOString(),
);
}
try {
await callback(date);
} catch (error) {
options.logger.error(
t('[schedule][定时回调失败] 任务: %s, 错误: %s'),
options.name,
error instanceof Error ? error.message : String(error),
);
}
};
try {
for (const [index, pattern] of parsed.patterns.entries()) {
const task = createTask(
pattern,
(context) => dispatch(index, context.date, false),
{
noOverlap: false,
missedExecutionTolerance: 5000,
},
);
tasks.push(task);
task.on('execution:missed', (context) =>
dispatch(index, context.date, true),
);
// Fail before an existing schedule is cancelled, including impossible dates.
task.getNextRuns(1);
}
} catch (error) {
tasks.forEach((task) => task.destroy());
throw error;
}
const job: CronJob = {
start() {
if (started || cancelled) return;
started = true;
tasks.forEach((task) => task.start());
},
cancel() {
if (cancelled) return;
cancelled = true;
tasks.forEach((task) => task.destroy());
},
};
if (options.start !== false) job.start();
return job;
}
// node-cron 4.6.0 exposes getNextRuns only from the wall clock. Its pinned
// inline matcher also accepts an explicit cursor, needed for previews and recovery.
export function upcomingSlots(
schedule: string,
after: number,
count = 1,
through?: number,
): number[] {
const parsed = parseCronSchedule(schedule);
const tasks: ScheduledTask[] = [];
try {
const matchers = parsed.patterns.map((pattern) => {
const task = createTask(pattern, () => {});
tasks.push(task);
return (
task as ScheduledTask & {
timeMatcher: {
getNextMatch(date: Date): Date;
expressions: number[][];
};
}
).timeMatcher;
});
const next = matchers.map((matcher) =>
matcher.getNextMatch(new Date(after)),
);
// All calendar branches share their clock fields. For bounded audit ranges,
// resolve each matching minute once, including the matcher's DST choice.
const seconds =
through == null
? []
: [...new Set(matchers[0].expressions[0])].sort((a, b) => a - b);
const slots: number[] = [];
let horizon = after + 366 * 100 * 86400000;
while (slots.length < count) {
const time = Math.min(...next.map(Number));
if (through != null && time > through) break;
if (!Number.isFinite(time) || time > horizon)
throw new Error('No matching calendar date');
let accepted = false;
next.forEach((date, index) => {
if (+date !== time) return;
const valid = acceptsSlot(parsed, tasks, index, date);
accepted ||= valid;
// Both branches share the clock fields. Rejection applies to the
// entire local day, including schedules that fire every second.
const cursor = new Date(time);
if (!valid) cursor.setHours(23, 59, 59, 999);
else if (through != null) cursor.setTime(time - (time % 60000) + 59999);
next[index] = matchers[index].getNextMatch(cursor);
});
if (accepted) {
if (through == null) slots.push(time);
else
for (const second of seconds) {
const slot = time - (time % 60000) + second * 1000;
if (slot >= time && slot <= through && slots.length < count)
slots.push(slot);
}
horizon = time + 366 * 100 * 86400000;
}
}
return slots;
} finally {
tasks.forEach((task) => task.destroy());
}
}
+115
View File
@@ -0,0 +1,115 @@
import type { Crontab } from '../../data/cron';
import type { ICron } from '../../protos/cron';
import { execSync } from 'child_process';
import { ScheduleType } from '../../interface/schedule';
import { TASK_PREFIX, QL_PREFIX } from '../../config/const';
import { shellQuote } from '../../shared/shellQuote';
export type SchedulerMode = 'system' | 'node';
// Adapt persisted task definitions without reserving or starting an execution.
export function isNodeCron(cron: Crontab) {
const { schedule, extra_schedules } = cron;
const fields = schedule?.trim().split(/\s+/) || [];
// System crontab only receives portable numeric five-field expressions.
// Extended syntax, macros and legacy shorthand use the Node scheduler.
return (
Boolean(
cron.max_queue_wait || cron.catchup_seconds || cron.skip_if_pending,
) ||
fields.length !== 5 ||
/[^\d\s*,/\-]/.test(schedule || '') ||
Boolean(extra_schedules?.length) ||
// BusyBox treats N/step as a single value and doesn't support Sunday=7.
fields.some((field) =>
field.split(',').some((part) => /^\d+\//.test(part)),
) ||
fields[4].includes('7') ||
// BusyBox steps DOM from zero; its full-range day/week wildcard
// handling also differs from the legacy Node parser's OR semantics.
fields[2].includes('/') ||
(fields[2] !== '*' && fields[4] !== '*')
);
}
export function schedulerMode(): SchedulerMode {
const env = process.env.QL_SCHEDULER;
if (env === 'system') return 'system';
if (env === 'node') return 'node';
try {
execSync('which crond', { stdio: 'ignore' });
return 'system';
} catch {
return 'node';
}
}
export function shouldUseCronClient(cron: Crontab, mode: SchedulerMode) {
if (mode === 'node') {
return !isSpecialSchedule(cron.schedule);
}
return isNodeCron(cron) && !isSpecialSchedule(cron.schedule);
}
export function isOnceSchedule(schedule?: string) {
return schedule?.startsWith(ScheduleType.ONCE);
}
export function isBootSchedule(schedule?: string) {
return schedule?.startsWith(ScheduleType.BOOT);
}
export function isSpecialSchedule(schedule?: string) {
return isOnceSchedule(schedule) || isBootSchedule(schedule);
}
export function shellValue(value: string) {
return /^[a-zA-Z0-9_./-]+$/.test(value) ? value : shellQuote(value);
}
// Manual, Node and system-crond launches share the existing shell wire format.
export function makeCommand(tab: Crontab, realTime?: boolean) {
let command = tab.command.trim();
if (!command.startsWith(TASK_PREFIX) && !command.startsWith(QL_PREFIX)) {
command = `${TASK_PREFIX}${tab.command}`;
}
let commandVariable = `${
tab.recovery_from ? `QL_CRON_REVISION=${Number(tab.recovery_from)} ` : ''
}real_time=${Boolean(realTime)} no_tee=true ID=${tab.id} `;
// Only include log_name if it has a truthy value to avoid passing null/undefined to shell
if (tab.log_name) {
commandVariable += `log_name=${shellValue(tab.log_name)} `;
}
if (tab.task_before) {
commandVariable += `task_before='${tab.task_before
.replace(/'/g, "'\\''")
.replace(/;? *\n/g, ';')
.trim()}' `;
}
if (tab.task_after) {
commandVariable += `task_after='${tab.task_after
.replace(/'/g, "'\\''")
.replace(/;? *\n/g, ';')
.trim()}' `;
}
if (tab.work_dir) {
commandVariable += `work_dir='${tab.work_dir.replace(/'/g, "'\\''")}' `;
}
const crontab_job_string = `${commandVariable}${command}`;
return crontab_job_string;
}
export function nodeCron(doc: Crontab, command: string): ICron {
return {
name: doc.name || '',
id: String(doc.id),
schedule: doc.schedule!,
command,
extra_schedules: doc.extra_schedules || [],
max_queue_wait: doc.max_queue_wait,
skip_if_pending: Boolean(doc.skip_if_pending),
catchup_seconds: doc.catchup_seconds,
recovery_from: doc.recovery_from,
};
}
+341
View File
@@ -0,0 +1,341 @@
import { AnomalyPage } from '../queries/scheduleAnomalies';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { AddCronRequest, DeleteCronRequest } from '../../protos/cron';
import { upcomingSlots } from './cronScheduler';
import { slotId } from '../identity';
type Rule = {
cron_id: string;
rule_index: number;
schedule: string;
zone: string;
since: number;
until: number | null;
open_latest: number;
close_latest: number;
};
type Receipt = {
id: string;
cron_id: number;
scheduled_at: number;
observed_at: number;
state: string;
reason: string | null;
log_path: string | null;
source: 'node' | 'recovery';
command_started_at: number | null;
verified_exit: number;
script_started_at: number | null;
queued_at: number | null;
started_at: number | null;
};
export async function saveSchedulePlan(
db: Sequelize,
change: AddCronRequest | DeleteCronRequest,
at?: number,
token?: string,
) {
const rules =
'crons' in change
? [
...new Map(change.crons.map((task) => [task.id, task])).values(),
].flatMap((task) =>
[
task.schedule,
...(task.extra_schedules || []).map((extra) => extra.schedule),
].map((schedule, index) => ({ task: task.id, index, schedule })),
)
: [];
const ids =
'crons' in change ? change.crons.map((task) => task.id) : change.ids;
const replace = 'replace' in change && change.replace;
await db.transaction(async (transaction) => {
const now = at ?? Date.now();
const bind = {
rules: JSON.stringify(rules),
ids: JSON.stringify(ids),
replace: Number(replace),
zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
now,
token: token ?? null,
};
if (token)
await db.query(
'INSERT INTO CronPlanSwitches(token,staged_at) VALUES($token,$now)',
{ transaction, bind: { token, now } },
);
if (replace)
await db.query(
'INSERT OR IGNORE INTO CronPlanCoverage(id,since) VALUES(1,$now)',
{ transaction, bind: { now } },
);
const desired = `WITH desired AS (SELECT json_extract(value,'$.task') AS task, json_extract(value,'$.index') AS idx,
json_extract(value,'$.schedule') AS schedule FROM json_each($rules))`;
await db.query(
`${desired} UPDATE CronPlanRules SET until=$now,closed_by=$token WHERE until IS NULL
AND ($replace OR cron_id IN (SELECT value FROM json_each($ids)))
AND (cron_id,rule_index,schedule,zone) NOT IN (SELECT task,idx,schedule,$zone FROM desired)`,
{ transaction, bind },
);
await db.query(
`${desired} INSERT OR IGNORE INTO CronPlanRules(cron_id,rule_index,schedule,zone,since,opened_by)
SELECT task,idx,schedule,$zone,$now,$token FROM desired`,
{
transaction,
bind: { rules: bind.rules, zone: bind.zone, now, token: bind.token },
},
);
// Only the current local day is displayed. Keep an extra day for zone changes.
await db.query(
`DELETE FROM CronPlanRules WHERE until < $now - 3*86400000 AND
(closed_by IS NULL OR closed_by IN (SELECT token FROM CronPlanSwitches WHERE last_at < $now - 3*86400000))`,
{ transaction, bind: { now } },
);
});
}
// Persisting intent and installing timers are separated by an asynchronous
// SQLite commit. Only the synchronous timer swap defines the effective edges.
export async function confirmSchedulePlan(
db: Sequelize,
token: string,
first: number,
last: number,
replace: boolean,
) {
await db.transaction(async (transaction) => {
await db.query(
`UPDATE CronPlanSwitches SET first_at=$first,last_at=$last
WHERE token=$token AND last_at IS NULL`,
{ transaction, bind: { token, first, last } },
);
if (replace) {
// After a crash the former worker's switch time is unknowable. A complete
// replacement establishes the latest possible edge for older requests.
await db.query(
`UPDATE CronPlanSwitches SET first_at=staged_at,last_at=$last
WHERE last_at IS NULL AND seq<(SELECT seq FROM CronPlanSwitches WHERE token=$token)`,
{ transaction, bind: { token, last } },
);
}
await db.query(
`DELETE FROM CronPlanSwitches WHERE last_at < $last - 3*86400000
AND token NOT IN (SELECT opened_by FROM CronPlanRules WHERE opened_by IS NOT NULL)
AND token NOT IN (SELECT closed_by FROM CronPlanRules WHERE closed_by IS NOT NULL)`,
{ transaction, bind: { last } },
);
});
}
export const blockSize = 15 * 60000;
const calendar = new Map<string, number[]>();
export function blockSlots(schedule: string, zone: string, block: number) {
const key = JSON.stringify([zone, schedule, block]);
let times = calendar.get(key);
if (!times) {
times = upcomingSlots(schedule, block - 1, Infinity, block + blockSize - 1);
if (calendar.size >= 2048) calendar.delete(calendar.keys().next().value!);
calendar.set(key, times);
}
return times;
}
function lowerBound(times: number[], time: number) {
let lo = 0,
hi = times.length;
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (times[mid] < time) lo = mid + 1;
else hi = mid;
}
return lo;
}
function p95(values: number[]) {
return values.length
? values.sort((a, b) => a - b)[Math.ceil(values.length * 0.95) - 1]
: null;
}
export async function auditSchedule(
db: Sequelize,
dayStart: number,
now = Date.now(),
details?: AnomalyPage,
) {
// All counts use the same settled plan window and the same committed snapshot.
const nextDay = new Date(dayStart);
nextDay.setHours(24, 0, 0, 0);
const through = Math.min(now - 5000, nextDay.getTime() - 1);
const snapshot = await db.transaction(
{ type: Transaction.TYPES.DEFERRED },
async (transaction) => {
const [coverage] = await db.query<{ since: number }>(
`SELECT MAX(since,$dayStart,
COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)) AS since FROM CronPlanCoverage WHERE id=1`,
{ transaction, bind: { dayStart }, type: QueryTypes.SELECT },
);
if (!coverage || coverage.since > through) return;
const bind = { since: coverage.since, through };
const rules = await db.query<Rule>(
`SELECT r.cron_id,r.rule_index,r.schedule,r.zone,COALESCE(o.first_at,r.since) AS since,
CASE WHEN o.token IS NULL THEN r.since ELSE COALESCE(o.last_at,$through) END AS open_latest,
COALESCE(c.first_at,r.until) AS until,
CASE WHEN c.token IS NULL THEN COALESCE(r.until,$through) ELSE COALESCE(c.last_at,$through) END AS close_latest
FROM CronPlanRules r LEFT JOIN CronPlanSwitches o ON o.token=r.opened_by
LEFT JOIN CronPlanSwitches c ON c.token=r.closed_by
WHERE r.since < $through AND close_latest >= $since ORDER BY r.cron_id,r.rule_index,r.since,r.rowid`,
{ transaction, bind, type: QueryTypes.SELECT },
);
const receipts = await db.query<Receipt>(
`SELECT id,cron_id,scheduled_at,observed_at,state,${
details ? 'source,reason,log_path,' : ''
}
command_started_at,script_started_at,queued_at,COALESCE(dequeued_at,started_at) AS started_at,
EXISTS(SELECT 1 FROM CronLegacyExitBookings b WHERE b.trigger_id=CronTriggers.id AND b.bound=1) AS verified_exit FROM CronTriggers
WHERE scheduled_at BETWEEN $since AND $through AND source IN ('node','recovery') ${
details ? 'ORDER BY cron_id,scheduled_at,id' : ''
}`,
{ transaction, bind, type: QueryTypes.SELECT },
);
return { since: coverage.since, rules, receipts };
},
);
if (!snapshot) return null;
const byTaskBlock = new Map<string, Receipt[]>();
for (const row of snapshot.receipts) {
const block = row.scheduled_at - (row.scheduled_at % blockSize);
const key = row.cron_id + '/' + block;
const group = byTaskBlock.get(key);
if (group) group.push(row);
else byTaskBlock.set(key, [row]);
}
const deviations: number[] = [],
starts: number[] = [],
entries: number[] = [],
waits: number[] = [];
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
let partial = false;
let expected = 0,
onTime = 0,
skipped = 0,
queued = 0,
dispatched = 0;
for (const rule of snapshot.rules) {
const first = Math.max(snapshot.since, rule.since + 1);
const last = Math.min(through, rule.close_latest);
const certainFirst = Math.max(first, rule.open_latest + 1);
const certainLast = Math.min(last, rule.until ?? last);
if (first > last) continue;
// A wall clock rule registered in another time zone cannot be replayed
// against the current local calendar.
if (rule.zone !== zone) return null;
for (
let block = first - (first % blockSize);
block <= last;
block += blockSize
) {
const times = blockSlots(rule.schedule, zone, block);
const possible = lowerBound(times, last + 1) - lowerBound(times, first);
const certain = Math.max(
0,
lowerBound(times, certainLast + 1) - lowerBound(times, certainFirst),
);
if (certain < possible) partial = true;
expected += certain;
const received =
details?.kind === 'missing' && certain ? new Set<number>() : null;
for (const row of byTaskBlock.get(rule.cron_id + '/' + block) ?? []) {
const time = row.scheduled_at;
if (
time < certainFirst ||
time > certainLast ||
times[lowerBound(times, time)] !== time ||
row.id !== slotId(rule.cron_id, rule.rule_index, rule.schedule, time)
)
continue;
received?.add(time);
const deviation = Math.abs(row.observed_at - time);
deviations.push(deviation);
if (deviation <= 5000) onTime++;
if (
row.command_started_at != null ||
row.script_started_at != null ||
row.verified_exit
) {
dispatched++;
if (row.command_started_at != null && row.command_started_at >= time)
starts.push(row.command_started_at - time);
} else if (row.state === 'queued') {
queued++;
} else {
const kind = row.state === 'skipped' ? 'skipped' : 'unconfirmed';
if (kind === 'skipped') skipped++;
if (details?.kind === kind)
details.add({
task: row.cron_id,
rule: rule.schedule,
ruleIndex: rule.rule_index,
time,
source: row.source,
trigger: row.id,
observed: row.observed_at,
reason: row.reason,
logPath: row.log_path,
});
}
if (row.script_started_at != null && row.script_started_at >= time)
entries.push(row.script_started_at - time);
if (
row.started_at != null &&
row.queued_at != null &&
row.started_at >= row.queued_at
)
waits.push(row.started_at - row.queued_at);
}
if (details && received && received.size < certain) {
for (
let i = lowerBound(times, certainFirst);
i < times.length && times[i] <= certainLast;
i++
) {
if (!received.has(times[i]))
details.add({
task: Number(rule.cron_id),
rule: rule.schedule,
ruleIndex: rule.rule_index,
time: times[i],
source: 'node',
trigger: null,
observed: null,
reason: null,
logPath: null,
});
}
}
}
}
const observed = deviations.length;
return {
since: snapshot.since,
through,
zone,
partial,
expected,
observed,
missing: expected - observed,
onTime,
skipped,
queued,
dispatched,
commandSamples: starts.length,
unconfirmed: observed - dispatched - skipped - queued,
triggerDeviationP95: p95(deviations),
waitP95: p95(waits),
waitSamples: waits.length,
commandStartP95: p95(starts),
scriptStartP95: p95(entries),
scriptSamples: entries.length,
};
}
@@ -0,0 +1,40 @@
import lockfile from 'proper-lockfile';
import config from '../../config/index';
// HTTP and gRPC both mutate cron definitions. Hold one shared lock from the
// initial DB read/write through scheduler registration (including rollback).
// Recovery takes the same lock before reading its replacement snapshot.
export async function withSchedulerMutation<T>(
operation: () => Promise<T>,
): Promise<T> {
let release: () => Promise<void>;
try {
// proper-lockfile indexes held locks by target, not lockfilePath. Keep
// this identity separate from nested writeFileWithLock(crontabFile).
release = await lockfile.lock(`${config.crontabFile}.scheduler`, {
realpath: false,
lockfilePath: `${config.crontabFile}.scheduler.lock`,
stale: 30000,
update: 10000,
retries: { retries: 50, factor: 1, minTimeout: 100, maxTimeout: 100 },
});
} catch (cause) {
throw Object.assign(
new Error('Scheduler configuration is busy', { cause }),
{
status: 503,
},
);
}
try {
return await operation();
} finally {
await release();
}
}
export function schedulerRegistrationError(message: string, cause: any): Error {
return Object.assign(new Error(message, { cause }), {
status: cause?.status === 503 ? 503 : 500,
});
}
@@ -0,0 +1,80 @@
// Recovery is single-flight and retried only while unavailable, never at idle.
export class SchedulerReadiness {
private ready = false;
private generation = 0;
private restore?: () => Promise<void>;
private pending?: Promise<boolean>;
private retry?: NodeJS.Timeout;
constructor(private probe: () => Promise<void>, private retryMs = 1000) {}
configure(restore: () => Promise<void>) {
this.restore = restore;
}
invalidate() {
this.ready = false;
this.generation++;
void this.recover();
}
recover(): Promise<boolean> {
if (this.pending) return this.pending;
if (!this.restore) return Promise.resolve(false);
clearTimeout(this.retry);
const generation = this.generation;
this.ready = false;
this.pending = (async () => {
try {
await this.probe();
await this.restore!();
await this.probe();
this.ready = generation === this.generation;
} catch {
this.ready = false;
}
return this.ready;
})().finally(() => {
this.pending = undefined;
if (!this.ready) {
this.retry = setTimeout(() => void this.recover(), this.retryMs);
this.retry.unref();
}
});
return this.pending;
}
async check(): Promise<boolean> {
if (!this.ready) return false;
const generation = this.generation;
try {
await this.probe();
return this.ready && generation === this.generation;
} catch {
this.invalidate();
return false;
}
}
async ensureReady(timeoutMs = 2000): Promise<void> {
let timer: NodeJS.Timeout | undefined;
try {
const available = await Promise.race([
(async () => (await this.check()) || (await this.recover()))(),
new Promise<boolean>((resolve) => {
timer = setTimeout(() => resolve(false), timeoutMs);
}),
]);
if (!available) {
throw Object.assign(
new Error('Scheduler is recovering; try again later'),
{
status: 503,
},
);
}
} finally {
clearTimeout(timer);
}
}
}
+100
View File
@@ -0,0 +1,100 @@
import type { Crontab } from '../../data/cron';
import { CrontabModel } from '../../data/cron';
import type { Logger } from 'winston';
import config from '../../config/index';
import { execFileSync } from 'child_process';
import cronClient from '../../schedule/client';
import {
confirmSystemPlan,
stageSystemPlan,
suspendSystemPlan,
SystemRule,
} from './systemScheduleAudit';
import {
isNodeCron,
isSpecialSchedule,
makeCommand,
schedulerMode,
SchedulerMode,
} from './cronScheduling';
import { shellQuote } from '../../shared/shellQuote';
import { writeFileWithLock } from '../../shared/utils';
import { asError } from '../../shared/childProcess';
import { t } from '../../shared/i18n';
// Publication is called under the service's scheduler mutation lock. Staging,
// installation and confirmation keep their existing order and failure semantics.
export class SystemCronAdapter {
constructor(private logger: Logger) {}
async publish(
crons: Crontab[],
mode: () => SchedulerMode = schedulerMode,
command: (cron: Crontab) => string = makeCommand,
) {
const rules: SystemRule[] = [];
var crontab_string = '';
crons.forEach((tab) => {
if (
tab.isDisabled === 1 ||
isNodeCron(tab) ||
isSpecialSchedule(tab.schedule)
) {
crontab_string += '# ';
crontab_string += tab.schedule;
crontab_string += ' ';
crontab_string += command(tab);
crontab_string += '\n';
} else {
crontab_string += tab.schedule;
crontab_string += ' ';
rules.push({
id: tab.id!,
schedule: tab.schedule!,
name: tab.name || tab.command,
});
crontab_string += `QL_SYSTEM_DISPATCHED=$(date +\\%s) QL_SYSTEM_RULE=${shellQuote(
tab.schedule!,
)} ID=${
tab.id
} QL_TRIGGER_SOURCE=system bash "$QL_DIR/shell/system-cron.sh" ${shellQuote(
command(tab),
)}`;
crontab_string += '\n';
}
});
try {
const system = mode() === 'system';
const db = CrontabModel.sequelize!;
const plan = system ? await stageSystemPlan(db, rules) : undefined;
if (!system) await suspendSystemPlan(db);
await writeFileWithLock(config.crontabFile, crontab_string);
if (plan !== undefined) {
execFileSync('crontab', [config.crontabFile]);
await confirmSystemPlan(db, plan);
}
} catch (error) {
this.logger.error(
'[crontab] Failed to publish crontab:',
asError(error).message,
);
cronClient.readiness.invalidate();
if (process.env.SERVICE_TYPE === 'grpc')
process.send?.('crontab-install-failed');
// A fresh host may have no installed crontab at all. A previous boot's
// saved flag does not confirm any portable rule in the failed snapshot.
if (mode() === 'system') {
const ids = crons
.filter((row) => !isNodeCron(row) && !isSpecialSchedule(row.schedule))
.map((row) => row.id!);
if (ids.length)
await CrontabModel.update({ saved: false }, { where: { id: ids } });
}
throw Object.assign(
new Error(t('系统定时规则安装失败,旧规则可能仍在运行,正在重试')),
{ status: 503 },
);
}
}
}
+373
View File
@@ -0,0 +1,373 @@
import { AnomalyPage } from '../queries/scheduleAnomalies';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { blockSize, blockSlots } from './scheduleAudit';
export type SystemRule = { id: number; schedule: string; name?: string };
type Install = {
id: number;
staged: number;
confirmed: number | null;
zone: string;
rules: string;
};
type Receipt = {
id: string;
cron_id: number;
system_rule: string | null;
observed_at: number;
system_dispatch_at: number | null;
reason: string | null;
log_path: string | null;
launched: number;
state: string;
};
export async function stageSystemPlan(
db: Sequelize,
rules: SystemRule[],
at = Date.now(),
) {
const bind = {
at,
zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
rules: JSON.stringify([...rules].sort((a, b) => a.id - b.id)),
};
return db.transaction(
{ type: Transaction.TYPES.IMMEDIATE },
async (transaction) => {
const [pending] = await db.query<{ id: number }>(
`SELECT id FROM (SELECT * FROM CronSystemPlans ORDER BY id DESC LIMIT 1)
WHERE confirmed IS NULL AND zone=$zone AND rules=$rules`,
{
bind: { zone: bind.zone, rules: bind.rules },
transaction,
type: QueryTypes.SELECT,
},
);
if (pending) return pending.id;
const [id] = await db.query(
'INSERT INTO CronSystemPlans(staged,zone,rules) VALUES ($at,$zone,$rules)',
{ bind, transaction, type: QueryTypes.INSERT },
);
return id;
},
);
}
// On a switch to Node the service can no longer attest the installed daemon rules.
export async function suspendSystemPlan(db: Sequelize) {
await db.query(
`INSERT INTO CronSystemPlans(staged,zone,rules)
SELECT $now,zone,'[]' FROM (SELECT zone,confirmed FROM CronSystemPlans ORDER BY id DESC LIMIT 1)
WHERE confirmed IS NOT NULL`,
{ bind: { now: Date.now() } },
);
}
export async function confirmSystemPlan(
db: Sequelize,
id: number,
at = Date.now(),
) {
await db.transaction(async (transaction) => {
await db.query(
'UPDATE CronSystemPlans SET confirmed=$at WHERE id=$id AND confirmed IS NULL',
{ transaction, bind: { id, at } },
);
// Keep the effective snapshot preceding the retention window.
await db.query(
'DELETE FROM CronSystemPlans WHERE id < (SELECT MAX(id) FROM CronSystemPlans WHERE staged < $cutoff AND confirmed IS NOT NULL)',
{ transaction, bind: { cutoff: at - 3 * 86400000 } },
);
});
}
export async function systemScheduleAudit(
db: Sequelize,
dayStart: number,
now = Date.now(),
details?: AnomalyPage,
) {
const next = new Date(dayStart);
next.setHours(24, 0, 0, 0);
const through = Math.min(now - 5000, +next - 1);
const { since, installs, receipts } = await db.transaction(
{ type: Transaction.TYPES.DEFERRED },
async (transaction) => {
const [retention] = await db.query<{ since: number }>(
'SELECT MAX($dayStart,COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)) AS since',
{ transaction, bind: { dayStart }, type: QueryTypes.SELECT },
);
const since = retention.since;
const installs = await db.query<Install>(
`SELECT * FROM CronSystemPlans WHERE id >= COALESCE((SELECT MAX(id) FROM CronSystemPlans
WHERE confirmed < $since - 60000),0) AND staged <= $now ORDER BY id`,
{ transaction, bind: { since, now }, type: QueryTypes.SELECT },
);
const receipts = await db.query<Receipt>(
`SELECT id,cron_id,system_rule,system_dispatch_at,observed_at,state,${
details ? 'reason,log_path,' : ''
}
(command_started_at IS NOT NULL OR script_started_at IS NOT NULL OR
(started_at IS NOT NULL AND EXISTS (SELECT 1 FROM CronLegacyExitBookings b
WHERE b.trigger_id=CronTriggers.id AND b.bound=1 AND b.disputed=0))) AS launched
FROM CronTriggers
WHERE source='system' AND COALESCE(system_dispatch_at,observed_at) >= $since
AND COALESCE(system_dispatch_at,observed_at) < $end ORDER BY observed_at,id`,
{
transaction,
bind: {
since,
end: Math.min(
+next,
Math.floor(through / 60000) * 60000 + 60000,
now + 1,
),
},
type: QueryTypes.SELECT,
},
);
return { since, installs, receipts };
},
);
if (!installs.length && !receipts.length) return null;
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const minute = 60000;
const plans = installs.map((plan) => ({
...plan,
tasks: new Map(
(JSON.parse(plan.rules) as SystemRule[]).map((rule) => [rule.id, rule]),
),
}));
const matched =
details && details.kind !== 'missing'
? new Map<string, { time: number; name?: string }>()
: null;
const groups = new Map<string, Receipt[]>();
const dispatchedTasks = new Set<string>();
const legacyThrough = new Map<string, number>();
const receiptKey = (task: number, rule: string | null, time: number) =>
JSON.stringify([task, rule, time]);
for (const row of receipts) {
if (row.system_dispatch_at == null || !row.system_rule) {
const key = JSON.stringify([row.cron_id, row.system_rule]);
legacyThrough.set(
key,
Math.max(legacyThrough.get(key) ?? 0, row.observed_at),
);
continue;
}
dispatchedTasks.add(
row.cron_id + '/' + Math.floor(row.system_dispatch_at / minute),
);
const key = receiptKey(
row.cron_id,
row.system_rule,
Math.floor(row.system_dispatch_at / minute) * minute,
);
const group = groups.get(key) ?? [];
group.push(row);
groups.set(key, group);
}
let expected = 0,
observed = 0,
dispatched = 0,
skipped = 0,
missing = 0,
duplicates = 0,
matchedReceipts = 0;
let uncertain = 0,
awaiting = 0,
switchSlots = 0,
partial = false;
type Slot = {
time: number;
task: number;
name?: string;
status: string;
triggerCount: number;
startCount: number;
skipCount: number;
unknownExitCount: number;
id?: string;
};
const recent: Slot[] = [];
const dst =
new Date(dayStart).getTimezoneOffset() !==
new Date(+next - 1).getTimezoneOffset();
let baseline = -1,
last = -1;
const calendar = new Map<string, Set<number>>();
for (
let time =
Math.ceil(Math.max(since, plans[0]?.staged ?? since) / minute) * minute;
time <= through;
time += minute
) {
// A successful crontab install acknowledges the file. crond reads changes at
// its minute tick. Around that tick either file can still explain a callback.
while (last + 1 < plans.length && plans[last + 1].staged <= time + 5000)
last++;
while (baseline + 1 <= last) {
let confirmed = baseline + 1;
while (confirmed <= last && plans[confirmed].confirmed == null)
confirmed++;
if (confirmed > last || plans[confirmed].confirmed! >= time - minute)
break;
baseline = confirmed;
}
if (last < 0) continue;
const possible = plans.slice(Math.max(0, baseline), last + 1);
if (dst || possible.some((plan) => plan.zone !== zone)) {
partial = true;
continue;
}
const tasks = new Set<number>();
for (const plan of possible)
for (const id of plan.tasks.keys()) tasks.add(id);
const block = time - (time % blockSize);
if (time === block) calendar.clear();
const entries: Slot[] = [];
for (const task of tasks) {
const schedules = new Set<string>();
let name: string | undefined;
for (const plan of possible) {
const rule = plan.tasks.get(task);
if (!rule) continue;
name = rule.name;
let times = calendar.get(rule.schedule);
if (!times) {
times = new Set(blockSlots(rule.schedule, zone, block));
calendar.set(rule.schedule, times);
}
if (times.has(time)) schedules.add(rule.schedule);
}
if (!schedules.size) continue;
const [schedule] = schedules;
const stable =
baseline >= 0 &&
schedules.size === 1 &&
possible.every(
(plan) =>
plan.confirmed != null &&
plan.tasks.get(task)?.schedule === schedule,
);
const group = [...schedules].flatMap(
(rule) => groups.get(receiptKey(task, rule, time)) ?? [],
);
let status: string;
const launched = group.find((row) => row.launched === 1);
const skip = group.find(
(row) => !row.launched && row.state === 'skipped',
);
if (group.length) {
++expected;
++observed;
if (matched)
for (const row of group) matched.set(row.id, { time, name });
matchedReceipts += group.length;
duplicates += group.length - 1;
if (launched) ++dispatched;
else if (skip) ++skipped;
status = launched ? 'started' : skip ? 'skipped' : 'unconfirmed';
} else if (!stable) {
++switchSlots;
partial = true;
status = 'switch';
} else {
++expected;
const lastUndated = Math.max(
legacyThrough.get(JSON.stringify([task, null])) ?? 0,
legacyThrough.get(JSON.stringify([task, schedule])) ?? 0,
);
if (
time <= lastUndated ||
dispatchedTasks.has(task + '/' + time / minute)
) {
++uncertain;
status = 'uncertain';
} else if (time + minute > now) {
++awaiting;
status = 'awaiting';
} else {
++missing;
if (details?.kind === 'missing')
details.add({
task,
name,
rule: schedule,
time,
source: 'system',
trigger: null,
observed: null,
reason: null,
logPath: null,
});
status = 'missing';
}
}
entries.push({
time,
task,
name,
status,
triggerCount: group.length,
startCount: group.filter((row) => row.launched === 1).length,
skipCount: group.filter(
(row) => !row.launched && row.state === 'skipped',
).length,
unknownExitCount: group.filter(
(row) => row.launched === 1 && row.state === 'unknown',
).length,
id: (launched || skip || group[0])?.id,
});
}
if (entries.length)
recent.unshift(...entries.sort((a, b) => a.task - b.task).slice(0, 25));
recent.splice(25);
}
let actualSkips = 0,
actualUnconfirmed = 0;
for (const row of receipts) {
if (row.launched === 1) continue;
const kind = row.state === 'skipped' ? 'skipped' : 'unconfirmed';
if (kind === 'skipped') actualSkips++;
else actualUnconfirmed++;
if (details?.kind === kind) {
const slot = matched?.get(row.id);
details.add({
task: row.cron_id,
name: slot?.name,
rule: row.system_rule,
time: slot?.time ?? null,
source: 'system',
trigger: row.id,
observed: row.observed_at,
reason: row.reason,
logPath: row.log_path,
});
}
}
return {
since: Math.max(since, plans[0]?.staged ?? since),
through,
confirmedAt:
[...plans].reverse().find((p) => p.confirmed != null)?.confirmed ?? null,
pending: plans.at(-1)?.confirmed == null,
partial,
expected,
observed,
dispatched,
skipped,
missing,
duplicates,
uncertain,
awaiting,
switchSlots,
actualSkips,
actualUnconfirmed,
actualStarts: receipts.filter((row) => row.launched === 1).length,
unmatched: receipts.length - matchedReceipts,
recent,
};
}