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

+637
View File
@@ -0,0 +1,637 @@
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { createHash } from 'crypto';
import { executionIdPattern } from '../identity';
import {
isProcessDescendant,
legacyProcessOwner,
systemOwner,
} from '../execution/cronProcess';
import type { TriggerSource, TriggerState } from '../types';
import type { TriggerLifecycle } from '../execution/triggerLifecycle';
import type { TriggerSettlement } from '../settlement/triggerSettlement';
export type LegacyClientLifecycle = Pick<TriggerLifecycle, 'claimSummary'>;
export type LegacyClientSettlement = Pick<
TriggerSettlement,
| 'recordShellResult'
| 'hasBoundConflict'
| 'completeInTransaction'
| 'readScriptSample'
| 'saveScriptSample'
| 'settleInstance'
>;
// Adapt PID-only and identified Shell reports without treating a wrapper exit
// as the managed command's result. Every state/settlement write keeps its transaction.
export class LegacyClientAdapter {
constructor(
private database: Sequelize,
private lifecycle: LegacyClientLifecycle,
private settlement: LegacyClientSettlement,
) {}
// Old shell-only executions publish status and statistics independently.
// Either final receipt can settle that execution if the other was lost.
async recordShellResult(
id: string,
cronId: number,
code: number,
elapsedMs: number,
now: number,
finishedAt?: number,
) {
return this.settlement.recordShellResult(
id,
cronId,
code,
elapsedMs,
now,
finishedAt,
);
}
async shellReport(
id: string,
cronId: number,
system: boolean,
running: boolean,
log: string,
seconds: number,
exitCode?: number,
stopped = false,
transaction?: Transaction,
elapsedMs?: number,
finishedAt?: number,
): Promise<void | false> {
if (!transaction)
return this.database.transaction((tx) =>
this.shellReport(
id,
cronId,
system,
running,
log,
seconds,
exitCode,
stopped,
tx,
elapsedMs,
finishedAt,
),
);
if (await this.settlement.hasBoundConflict(id, transaction)) return false;
if (system || executionIdPattern.test(id)) {
// Standalone clients supply neither a scheduled instant nor a queue observation.
const dated = Number.isSafeInteger(seconds) && seconds > 0;
const start = dated ? seconds * 1000 : Date.now();
const standalone =
executionIdPattern.test(id) || id.startsWith('system-cli-');
const lastKnownTime =
standalone &&
!running &&
dated &&
finishedAt &&
finishedAt >= start &&
finishedAt <= Date.now()
? finishedAt
: start;
await this.database.query(
`INSERT INTO CronTriggers(id,cron_id,source,state,started_at,observed_at)
SELECT $id,$cronId,$source,'running',$start,$start
WHERE NOT EXISTS (SELECT 1 FROM CronHistoryRetention WHERE id=1 AND ($dated=0 OR cutoff>$lastKnownTime))
ON CONFLICT(id) DO NOTHING`,
{
transaction,
bind: {
id,
cronId,
start,
lastKnownTime,
dated: Number(dated),
source: system ? 'system' : 'client',
},
},
);
}
await this.database.query(
`UPDATE CronTriggers SET log_path=COALESCE(log_path,$log) WHERE id=$id AND cron_id=$cronId`,
{ transaction, bind: { id, cronId, log } },
);
if (!running) {
// For a managed command the wrapper may be only the first segment.
// Only its supervisor can report the whole command's exit.
const [legacy] = await this.database.query(
'SELECT 1 FROM CronTriggers WHERE id=$id AND cron_id=$cronId AND owner IS NULL',
{ transaction, type: QueryTypes.SELECT, bind: { id, cronId } },
);
if (legacy) {
const state = stopped
? 'stopped'
: exitCode == null
? 'unknown'
: exitCode === 0
? 'finished'
: 'failed';
await this.settlement.completeInTransaction(
id,
state,
null,
exitCode ?? null,
transaction,
elapsedMs,
finishedAt,
);
}
}
}
async reportLegacy(
cronId: number,
running: boolean,
pid: number,
log: string,
seconds: number,
elapsed: number,
code?: number,
) {
return this.database.transaction((transaction) =>
this.applyLegacyReceipt(
cronId,
running,
pid,
log,
seconds,
elapsed,
transaction,
code,
),
);
}
private async applyLegacyReceipt(
cronId: number,
running: boolean,
pid: number,
log: string,
seconds: number,
elapsed: number,
transaction: Transaction,
code?: number,
) {
const start = seconds * 1000;
const receipt =
'legacy-' +
createHash('sha256')
.update(JSON.stringify([cronId, pid, seconds, log || null]))
.digest('hex');
// A verified child stays attached to its supervisor even after the OS recycles its PID.
const [bound] = await this.database.query(
'SELECT 1 FROM CronShellBindings WHERE receipt=$receipt',
{ transaction, type: QueryTypes.SELECT, bind: { receipt } },
);
if (bound) return;
const rows = await this.database.query<{
instance: number;
status: number;
finished_at: number | null;
exit_code: number | null;
id: string | null;
source: TriggerSource | null;
log_path: string | null;
}>(
`SELECT i.id AS instance,i.status,i.finished_at,i.exit_code,i.log_path,t.id,t.source FROM RunningInstances i
LEFT JOIN CronTriggers t ON t.instance_id=i.id WHERE i.cron_id=$cronId AND i.pid=$pid
AND (t.id IS NULL OR t.source='legacy' OR t.owner IS NOT NULL)
AND i.started_at=$seconds AND (i.log_path IS $log OR $log IS NULL OR i.log_path IS NULL) LIMIT 2`,
{
transaction,
type: QueryTypes.SELECT,
bind: { cronId, pid, seconds, log: log || null },
},
);
const [old] = rows;
if (rows.length > 1) return;
if (old) {
if (!old.id && old.status === 4) {
const [expired] = await this.database.query(
'SELECT 1 FROM CronHistoryRetention WHERE cutoff>$end',
{
transaction,
type: QueryTypes.SELECT,
bind: { end: (old.finished_at ?? seconds) * 1000 },
},
);
if (expired) return;
}
if (old.status !== 0 && old.status !== 4) {
if (!old.id && old.finished_at != null) {
// The old panel owned the daily aggregate. Import its committed result
// without replaying an anonymous statistics increment.
const state =
old.status === 1
? 'finished'
: old.status === 2
? 'stopped'
: 'failed';
const inserted = await this.database.query(
`INSERT INTO CronTriggers
(id,cron_id,source,state,observed_at,started_at,finished_at,instance_id,log_path,exit_code,counted)
SELECT $id,$cronId,'legacy',$state,$start,$start,$end,$instance,$log,$exit,1
WHERE $end >= $start AND $end>=COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)
AND NOT EXISTS (SELECT 1 FROM RunningInstances sibling
LEFT JOIN CronTriggers linked ON linked.instance_id=sibling.id
WHERE sibling.cron_id=$cronId
AND sibling.pid=$pid AND sibling.finished_at=$end/1000 AND sibling.id<>$instance
AND sibling.status IN (1,3) AND (linked.id IS NULL OR (linked.source='legacy' AND linked.owner IS NULL)))
ON CONFLICT DO NOTHING`,
{
transaction,
type: QueryTypes.BULKUPDATE,
bind: {
id: receipt,
cronId,
pid,
state,
start,
end: old.finished_at * 1000,
instance: old.instance,
log: old.log_path,
exit: old.exit_code,
},
},
);
if (inserted)
await this.lifecycle.claimSummary(
cronId,
old.instance,
seconds,
transaction,
true,
Math.max(0, old.finished_at - seconds),
);
}
return;
}
if (running && (old.id || old.status === 4)) return;
if (old.id && old.source !== 'legacy') return;
}
let identity: string | undefined;
if (!old) {
const [prior] = await this.database.query(
'SELECT 1 FROM CronTriggers WHERE id=$receipt UNION ALL SELECT 1 FROM CronHistoryRetention WHERE cutoff>$start',
{ transaction, type: QueryTypes.SELECT, bind: { receipt, start } },
);
if (prior) return;
identity = legacyProcessOwner(pid, seconds);
const roots = await this.database.query<{
id: string;
command_identity: string;
}>(
`SELECT id,command_identity FROM CronTriggers WHERE cron_id=$cronId AND state='running'
AND command_identity IS NOT NULL AND started_at < $end`,
{
transaction,
type: QueryTypes.SELECT,
bind: { cronId, end: start + 1000 },
},
);
for (const root of roots) {
if (!identity) break;
const parent = Number(root.command_identity.split(':')[1]);
try {
if (
!isProcessDescendant(pid, parent) ||
systemOwner(parent) !== root.command_identity
)
continue;
} catch (error) {
if (
['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)
)
continue;
throw error;
}
await this.database.query(
'INSERT INTO CronShellBindings(receipt,trigger_id) VALUES ($receipt,$id)',
{ transaction, bind: { receipt, id: root.id } },
);
if (running)
await this.attachShellLog(root.id, cronId, log, transaction);
return;
}
}
const id = old?.id ?? receipt;
if (!old?.id) {
// A later use of the same numeric PID proves the older process is gone.
const others = await this.database.query<{
id: string;
started_at: number;
}>(
`SELECT t.id,i.started_at FROM RunningInstances i LEFT JOIN CronTriggers t ON t.instance_id=i.id
WHERE i.cron_id=$cronId AND i.pid=$pid AND i.started_at<>$seconds
AND (i.started_at>$seconds OR (i.status=0 AND t.source='legacy'))`,
{
transaction,
type: QueryTypes.SELECT,
bind: { cronId, pid, seconds },
},
);
if (running && old) identity = legacyProcessOwner(pid, seconds);
const historical =
!running ||
!identity ||
others.some((other) => other.started_at > seconds);
let instance = old?.instance;
if (!instance) {
[instance] = await this.database.query(
`INSERT INTO RunningInstances(cron_id,pid,log_path,started_at,status,finished_at,createdAt,updatedAt)
VALUES ($cronId,$pid,$log,$seconds,$status,$finished,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)`,
{
transaction,
type: QueryTypes.INSERT,
bind: {
cronId,
pid,
log: log || null,
seconds,
status: historical ? 4 : 0,
finished: historical ? Math.floor(Date.now() / 1000) : null,
},
},
);
}
const unknown = historical || old?.status === 4;
await this.database.query(
`INSERT INTO CronTriggers
(id,cron_id,source,state,observed_at,started_at,finished_at,instance_id,log_path,process_identity,reason)
VALUES ($id,$cronId,'legacy',$state,$start,$start,$end,$instance,$log,$identity,$reason)`,
{
transaction,
bind: {
id,
cronId,
start,
instance,
log: old?.log_path ?? (log || null),
identity: !unknown && running ? identity ?? null : null,
reason: old && running && !unknown ? 'restart' : null,
state: unknown ? 'unknown' : 'running',
end: unknown
? old?.finished_at
? old.finished_at * 1000
: Date.now()
: null,
},
},
);
await this.lifecycle.claimSummary(
cronId,
instance!,
seconds,
transaction,
old?.status === 0 || (running && !unknown),
);
for (const other of others) {
if (other.started_at < seconds)
await this.settlement.completeInTransaction(
other.id,
'unknown',
null,
null,
transaction,
);
}
if (running && !unknown)
await this.database.query(
`UPDATE Crontabs SET status=0,pid=$pid,log_path=$log
WHERE id=$cronId AND status IS NOT 3 AND $instance=(
SELECT id FROM RunningInstances WHERE cron_id=$cronId AND status=0 ORDER BY id DESC LIMIT 1)`,
{ transaction, bind: { cronId, pid, log: log || null, instance } },
);
if (unknown && old?.status === 0 && running)
await this.settlement.settleInstance(id, transaction);
}
if (!running) {
const state =
code == null ? 'unknown' : code === 0 ? 'finished' : 'failed';
await this.settlement.completeInTransaction(
id,
state,
null,
code ?? null,
transaction,
Math.max(0, elapsed) * 1000,
);
}
}
private async attachShellLog(
id: string,
cronId: number,
log: string,
transaction: Transaction,
) {
const attached = await this.database.query(
`UPDATE RunningInstances SET log_path=$log WHERE status=0 AND log_path IS NULL
AND id=(SELECT instance_id FROM CronTriggers WHERE id=$id AND cron_id=$cronId AND state='running')`,
{ transaction, type: QueryTypes.BULKUPDATE, bind: { id, cronId, log } },
);
if (attached) {
await this.database.query(
'UPDATE CronTriggers SET log_path=COALESCE(log_path,$log) WHERE id=$id',
{ transaction, bind: { id, log } },
);
await this.database.query(
`UPDATE Crontabs SET log_path=$log WHERE id=$cronId AND status=0 AND pid=(
SELECT i.pid FROM RunningInstances i JOIN CronTriggers t ON t.instance_id=i.id WHERE t.id=$id)`,
{ transaction, bind: { id, cronId, log } },
);
}
}
// Link the Shell instance and its trigger in the same IMMEDIATE write transaction.
async reportInstance(
id: string,
cronId: number,
running: boolean,
pid: number,
log: string,
seconds: number,
elapsed: number | undefined,
code?: number,
stopped = false,
finishedAt?: number,
) {
const sample = running
? undefined
: await this.settlement.readScriptSample(id);
await this.database.transaction(async (transaction) => {
const accepted = await this.shellReport(
id,
cronId,
id.startsWith('system-'),
running,
log,
seconds,
code,
stopped,
transaction,
elapsed == null ? undefined : elapsed * 1000,
finishedAt,
);
if (accepted === false) return;
const [row] = await this.database.query<{
state: TriggerState;
started_at: number | null;
instance_id: number | null;
command_identity: string | null;
owner: string | null;
}>(
'SELECT state,started_at,instance_id,command_identity,owner FROM CronTriggers WHERE id=$id AND cron_id=$cronId',
{ transaction, bind: { id, cronId }, type: QueryTypes.SELECT },
);
if (!row) return;
const startSeconds =
seconds > 0
? seconds
: Math.floor((row.started_at ?? Date.now()) / 1000);
if (
['finished', 'failed', 'stopped', 'unknown'].includes(row.state) &&
row.owner === null &&
row.instance_id === null
) {
// The CLI exit can commit before its first start. Link a terminal history
// row directly without ever publishing this PID as the current instance.
const [instance] = await this.database.query(
`INSERT INTO RunningInstances
(cron_id,pid,log_path,started_at,finished_at,status,exit_code,createdAt,updatedAt)
SELECT cron_id,$pid,log_path,CAST(started_at/1000 AS INTEGER),CAST(finished_at/1000 AS INTEGER),
CASE state WHEN 'finished' THEN 1 WHEN 'stopped' THEN 2 WHEN 'failed' THEN 3 ELSE 4 END,
exit_code,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP FROM CronTriggers
WHERE id=$id AND state IN ('finished','failed','stopped','unknown')`,
{
transaction,
type: QueryTypes.INSERT,
bind: { id, pid: pid || null },
},
);
if (instance) {
await this.database.query(
'UPDATE CronTriggers SET instance_id=$instance WHERE id=$id',
{ transaction, bind: { instance, id } },
);
await this.lifecycle.claimSummary(
cronId,
instance,
startSeconds,
transaction,
false,
row.state === 'unknown' ? null : elapsed ?? null,
);
}
return;
}
if (running && row.state !== 'running') return;
if (running && row.instance_id === null) {
let identity = row.command_identity;
if (identity?.startsWith('crond:')) {
pid = Number(identity.split(':')[1]);
} else if (pid) {
try {
identity = systemOwner(pid);
} catch {
/* A short child may have exited. */
}
}
const [instance] = await this.database.query(
`INSERT INTO RunningInstances(cron_id,pid,log_path,started_at,status,createdAt,updatedAt)
VALUES ($cronId,$pid,$log,$seconds,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)`,
{
transaction,
type: QueryTypes.INSERT,
bind: { cronId, pid, log, seconds: startSeconds },
},
);
await this.database.query(
'UPDATE CronTriggers SET instance_id=$instance,process_identity=$identity WHERE id=$id',
{ transaction, bind: { instance, identity, id } },
);
await this.lifecycle.claimSummary(
cronId,
instance,
startSeconds,
transaction,
true,
);
await this.database.query(
`UPDATE Crontabs SET status=0,pid=$pid,log_path=$log
WHERE id=$cronId AND (status IS NOT 3 OR queued_token || '-' || id=$id)`,
{ transaction, bind: { cronId, id, pid, log } },
);
}
if (running && row.instance_id !== null) {
await this.attachShellLog(id, cronId, log, transaction);
}
if (!running)
await this.settlement.saveScriptSample(id, sample, transaction);
});
}
async reconcileInstances() {
await this.database.transaction(async (transaction) => {
// Released panels created instance rows before trigger IDs existed. Link
// their outstanding starts before cleanup so the original CLI can finish.
const unlinked = await this.database.query<{
cron_id: number;
pid: number;
log_path: string | null;
started_at: number;
}>(
`WITH outstanding AS (SELECT DISTINCT cron_id,started_at FROM RunningInstances WHERE status=0)
SELECT i.cron_id,i.pid,i.log_path,i.started_at FROM outstanding o
JOIN RunningInstances i ON i.cron_id=o.cron_id AND i.started_at=o.started_at
JOIN Crontabs c ON c.id=i.cron_id WHERE i.pid>0 AND i.started_at>0
AND NOT EXISTS (SELECT 1 FROM CronTriggers t WHERE t.instance_id=i.id)
AND NOT EXISTS (SELECT 1 FROM CronStopRequests s WHERE s.instance_id=i.id)
ORDER BY i.started_at,i.id`,
{ transaction, type: QueryTypes.SELECT },
);
for (const row of unlinked) {
await this.applyLegacyReceipt(
row.cron_id,
true,
row.pid,
row.log_path || '',
row.started_at,
0,
transaction,
);
}
// Older versions mapped an unknown exit to error or stopped in instance history.
await this.database.query(
`UPDATE RunningInstances SET status=4,finished_at=COALESCE(finished_at,$now),updatedAt=CURRENT_TIMESTAMP
WHERE status IN (0,2,3) AND id IN
(SELECT instance_id FROM CronTriggers WHERE state='unknown' AND instance_id IS NOT NULL)`,
{ transaction, bind: { now: Math.floor(Date.now() / 1000) } },
);
// HTTP and gRPC restart independently. Another worker or crond may still own the run.
await this.database.query(
`UPDATE RunningInstances SET status=2,finished_at=$now,updatedAt=CURRENT_TIMESTAMP
WHERE status=0 AND NOT EXISTS (SELECT 1 FROM CronStopRequests s WHERE s.instance_id=RunningInstances.id)
AND NOT EXISTS (SELECT 1 FROM CronTriggers t WHERE t.instance_id=RunningInstances.id AND t.state='running')`,
{ transaction, bind: { now: Math.floor(Date.now() / 1000) } },
);
await this.database.query(
`UPDATE Crontabs SET status=1,pid=NULL,queued_token=NULL
WHERE status IN (0,3) AND NOT EXISTS (SELECT 1 FROM CronStopRequests s WHERE s.cron_id=Crontabs.id)
AND NOT EXISTS (SELECT 1 FROM CronTriggers t
WHERE t.cron_id=Crontabs.id AND t.state IN ('running','queued'))`,
{ transaction },
);
});
}
}
+11
View File
@@ -0,0 +1,11 @@
// Match command text literally: looking up a task must never execute its input.
export function findCronId(crontab: string, command: string): string {
if (!command) return '';
for (const line of crontab.split('\n')) {
const id = /\bID=(\d+)\s/.exec(line);
if (id && line.includes(command, id.index + id[0].length)) {
return id[1];
}
}
return '';
}
+61
View File
@@ -0,0 +1,61 @@
import { join } from 'path';
import { existsSync } from 'fs';
import { receiptPath } from '../settlement/exitReceipt.cjs';
import { spawn } from 'cross-spawn';
import type { ChildProcessWithoutNullStreams } from 'child_process';
import type { Readable } from 'stream';
// A managed command waits on its parent's pipe. EOF before authorization exits
// without interpreting the command, even when the worker is killed by SIGKILL.
export function spawnCronCommand(
command: string,
triggerId?: string,
onCommandStart?: (at: number) => void,
outputPath?: string,
) {
if (!triggerId) return spawn(command, { shell: '/bin/bash' });
const sourceScript = join(__dirname, '../../../shell/cron-command.py');
const supervisor = existsSync(sourceScript)
? sourceScript
: join(process.env.QL_DIR!, 'shell/cron-command.py');
const args = [
'-I',
'-S',
supervisor,
command,
String(process.pid),
receiptPath(triggerId) || '',
process.execPath,
join(__dirname, '../../shared/managedExit.cjs'),
];
if (onCommandStart) args.push('report-start');
if (outputPath) args.push('log-output', outputPath);
const child = spawn('python3', args, {
env: { ...process.env, QL_TRIGGER_ID: triggerId },
stdio: onCommandStart ? ['pipe', 'pipe', 'pipe', 'pipe'] : 'pipe',
}) as ChildProcessWithoutNullStreams;
if (onCommandStart && child.stdio[3]) {
const timing = child.stdio[3] as Readable;
let stamp = '';
timing.setEncoding('ascii').on('data', (chunk) => {
stamp += chunk;
});
timing.once('end', () => {
if (/^\d{13}$/.test(stamp)) onCommandStart(Number(stamp));
});
timing.on('error', () => {}); // Missing telemetry must not change the command result.
}
// A concurrent stop can close the pipe before the authorization write.
child.stdin.on('error', () => {});
return child;
}
export function releaseCronCommand(
child: ChildProcessWithoutNullStreams,
): Promise<void> {
return new Promise((resolve, reject) =>
child.stdin.end('run\n', (error?: Error) =>
error ? reject(error) : resolve(),
),
);
}
+930
View File
@@ -0,0 +1,930 @@
import type { Logger } from 'winston';
import { randomUUID } from 'crypto';
import {
Op,
where,
col as colFn,
FindOptions,
QueryTypes,
Transaction,
} from 'sequelize';
import config from '../../config/index';
import { Crontab, CrontabModel, CrontabStatus } from '../../data/cron';
import {
RunningInstanceModel,
InstanceStatus,
} from '../../data/runningInstance';
import { TriggerHistory, TriggerState } from '../history';
import {
finishStoppedTree,
hasLiveCronProcess,
pidNamespaceOwner,
systemOwner,
verifyCronProcess,
} from './cronProcess';
import { killTask, getUniqPath } from '../../config/util';
import { resolveLogPath } from '../../shared/logPath';
import { resolveFileAccess } from '../../shared/fileAccess';
import { shellValue } from '../scheduling/cronScheduling';
import taskLimit from './cronLimit';
import { logStreamManager } from '../../shared/logStreamManager';
import { spawnCronCommand, releaseCronCommand } from './cronCommandProcess';
import { observeChildProcess, asError } from '../../shared/childProcess';
import { t } from '../../shared/i18n';
import fs from 'fs/promises';
import path from 'path';
import dayjs from 'dayjs';
type BatchStopSnapshot = {
docs: Array<
Pick<
Crontab,
| 'id'
| 'status'
| 'pid'
| 'log_path'
| 'queued_token'
| 'last_execution_time'
>
>;
instances: Array<{ id?: number; cron_id: number; pid?: number }>;
cancelled: string[];
missingPids?: number[];
missingTargets?: string[];
identityConflict: boolean;
};
type StopResult = { code: number; message: string; data?: { outcome: string } };
// Boundary to the existing service facade; no dependency on CronService itself.
export interface CronExecutionHost {
getDb(query: FindOptions<Crontab>['where']): Promise<Crontab>;
makeCommand(tab: Crontab, realTime?: boolean): string;
runSingle(
cronId: number,
expectedToken?: string,
triggerId?: string,
submitted?: Crontab,
): Promise<number | void>;
stopInstance(cronId: number, instanceId: number): Promise<StopResult>;
stop(ids: number[], requestId?: string): Promise<void>;
}
export class CronExecution {
constructor(private logger: Logger, private host: CronExecutionHost) {}
public async run(ids: number[], source: 'manual' | 'boot' = 'manual') {
const token = randomUUID();
const database = CrontabModel.sequelize!;
const history = new TriggerHistory(database);
const submission = await database.transaction(async (transaction) => {
const rows = await CrontabModel.findAll({
where: { id: ids },
transaction,
});
const accepted: Crontab[] = [];
const triggers: Array<{
taskId: number;
triggerId: string;
state: 'queued' | 'skipped';
reason: 'overlap' | null;
}> = [];
for (const row of rows) {
const id = row.id!;
const trigger = token + '-' + id;
await history.enqueue(
trigger,
id,
source,
null,
Date.now(),
transaction,
);
if (
!row.allow_multiple_instances &&
(hasLiveCronProcess(row.status, row.pid) ||
(await history.isRunning(id, transaction)))
) {
await history.finish(
trigger,
'skipped',
'overlap',
null,
transaction,
);
triggers.push({
taskId: id,
triggerId: trigger,
state: 'skipped',
reason: 'overlap',
});
} else {
accepted.push(row.get({ plain: true }));
triggers.push({
taskId: id,
triggerId: trigger,
state: 'queued',
reason: null,
});
}
}
await CrontabModel.update(
{ status: CrontabStatus.queued, queued_token: token },
{
where: { id: accepted.map((row) => row.id!) },
transaction,
},
);
return { queued: accepted, triggers };
});
for (const row of submission.queued) {
const id = row.id!;
void this.host
.runSingle(id, token, token + '-' + id, row)
.catch((err) => this.logger.error(String(err)));
}
return submission.triggers;
}
private readonly stoppingBatches = new Map<string, Promise<void>>();
public async stop(ids: number[], requestId?: string) {
if (!ids.length && !requestId) return;
const targets = [...new Set(ids)].sort((a, b) => a - b);
const cronIds = JSON.stringify(targets);
if (!requestId) return this.stopBatch(targets, cronIds);
const key = requestId + '/' + cronIds;
const pending = this.stoppingBatches.get(key);
if (pending) return pending;
// The database arbitrates different payloads and competing workers.
const done = this.stopBatch(targets, cronIds, requestId).finally(() =>
this.stoppingBatches.delete(key),
);
this.stoppingBatches.set(key, done);
return done;
}
private async stopBatch(ids: number[], cronIds: string, requestId?: string) {
const database = CrontabModel.sequelize!;
const history = new TriggerHistory(database);
const snapshot = await database.transaction(
{ type: Transaction.TYPES.IMMEDIATE },
async (transaction): Promise<BatchStopSnapshot | null> => {
if (requestId) {
const [existing] = await database.query<{
cron_ids: string;
snapshot: string | null;
status_code: number;
}>(
'SELECT cron_ids,snapshot,status_code FROM CronStopBatches WHERE request_id=$requestId',
{ transaction, bind: { requestId }, type: QueryTypes.SELECT },
);
if (existing) {
if (existing.cron_ids !== cronIds)
throw Object.assign(
new Error('Idempotency-Key already used for different tasks'),
{ status: 409 },
);
if (existing.status_code === 409)
throw Object.assign(new Error(t('实例不存在或已停止')), {
status: 409,
});
return existing.snapshot ? JSON.parse(existing.snapshot) : null;
}
}
const docs = await CrontabModel.findAll({
attributes: [
'id',
'status',
'pid',
'log_path',
'queued_token',
'last_execution_time',
],
where: { id: ids },
transaction,
raw: true,
});
const cancelled = await history.cancelQueuedInTransaction(
ids,
transaction,
);
const instances = await RunningInstanceModel.findAll({
attributes: ['id', 'cron_id', 'pid'],
where: { cron_id: ids, status: InstanceStatus.running },
transaction,
raw: true,
});
const { missingTargets, identityConflict } =
await this.attachLegacyStopTargets(
docs,
instances,
history,
transaction,
);
for (const instance of instances) {
if (instance.pid)
await history.queueInstanceStop(
instance.id!,
instance.cron_id,
instance.pid,
transaction,
);
}
for (const doc of docs) {
if (doc.status === CrontabStatus.queued) {
await CrontabModel.update(
{
status: CrontabStatus.idle,
pid: null,
queued_token: null,
} as any,
{
where: { id: doc.id, status: CrontabStatus.queued },
transaction,
},
);
}
}
const batch = {
docs,
cancelled,
instances,
missingTargets,
identityConflict,
};
if (requestId) {
await database.query(
'INSERT INTO CronStopBatches(request_id,cron_ids,snapshot) VALUES ($requestId,$cronIds,$snapshot)',
{
transaction,
bind: { requestId, cronIds, snapshot: JSON.stringify(batch) },
},
);
}
return batch;
},
);
if (!snapshot) return;
const {
docs,
cancelled,
instances,
missingPids,
missingTargets,
identityConflict,
} = snapshot;
if (cancelled.length)
process.send?.({ type: 'cancel-queued-triggers', ids: cancelled });
const stopped = new Set(missingTargets);
let failure: Error | undefined;
for (const instance of instances) {
try {
const result = await this.host.stopInstance(
instance.cron_id,
instance.id!,
);
if (result.code === 409)
failure ??= Object.assign(new Error(result.message), { status: 409 });
if (
instance.pid &&
'data' in result &&
result.data?.outcome === 'stopped'
)
stopped.add(instance.cron_id + '/' + instance.pid);
} catch (error) {
failure ??= asError(error);
}
}
for (const doc of docs) {
if (
doc.status !== CrontabStatus.running ||
(doc.pid &&
!missingPids?.includes(doc.pid) &&
!stopped.has(doc.id + '/' + doc.pid))
)
continue;
const remaining = await RunningInstanceModel.count({
where: { cron_id: doc.id, status: InstanceStatus.running },
});
if (remaining) continue;
await CrontabModel.update(
{ status: CrontabStatus.idle, pid: null, queued_token: null } as any,
{
where: {
id: doc.id,
status: CrontabStatus.running,
[Op.and]: [
where(colFn('queued_token'), {
[Op.eq]: doc.queued_token ?? null,
}),
where(colFn('pid'), { [Op.eq]: doc.pid ?? null }),
where(colFn('log_path'), { [Op.eq]: doc.log_path ?? null }),
],
},
},
);
}
if (failure) throw failure;
// Retain the key after success. Even a much later retry must never take a new snapshot.
if (requestId)
await database.query(
'UPDATE CronStopBatches SET snapshot=NULL,status_code=$status WHERE request_id=$requestId AND snapshot IS NOT NULL',
{ bind: { requestId, status: identityConflict ? 409 : 200 } },
);
if (identityConflict)
throw Object.assign(new Error(t('实例不存在或已停止')), { status: 409 });
}
// Older databases may have a PID or command receipt without an instance.
// Attach verified targets before releasing the stop snapshot transaction.
private async attachLegacyStopTargets(
docs: BatchStopSnapshot['docs'],
instances: BatchStopSnapshot['instances'],
history: TriggerHistory,
transaction: Transaction,
) {
const commands = await history.activeCommands(
docs.map((doc) => doc.id!),
transaction,
);
const registered = new Set(
instances.map((row) => row.cron_id + '/' + row.pid),
);
const registeredPids = new Set(instances.map((row) => row.pid));
const legacy = new Map<
string,
{
pid: number;
cronId: number;
trigger?: string;
identity?: string;
started?: number;
log?: string;
}
>();
for (const doc of docs) {
const key = doc.id + '/' + doc.pid;
if (
doc.status === CrontabStatus.running &&
doc.pid &&
!registered.has(key)
)
legacy.set(key, {
pid: doc.pid,
cronId: doc.id!,
started: doc.last_execution_time,
log: doc.log_path,
});
}
for (const command of commands) {
const pid = Number(command.command_identity.split(':')[1]);
const key = command.cron_id + '/' + pid;
if (!registered.has(key))
legacy.set(key, {
pid,
cronId: command.cron_id,
trigger: command.id,
identity: command.command_identity,
started: Math.floor(command.started_at / 1000),
log: command.log_path,
});
}
let identityConflict = false;
const missingTargets: string[] = [];
for (const target of legacy.values()) {
const { pid } = target;
// A different task already owns this PID in the snapshot.
if (registeredPids.has(pid)) {
identityConflict = true;
continue;
}
let identity: string;
try {
identity = systemOwner(pid);
verifyCronProcess(pid, target.cronId, target.identity, target.started);
} catch (error) {
if (
['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)
)
missingTargets.push(target.cronId + '/' + pid);
else if ((error as { status?: number }).status === 409)
identityConflict = true;
else throw error;
continue;
}
const row = await RunningInstanceModel.create(
{
cron_id: target.cronId,
pid,
status: InstanceStatus.running,
started_at: target.started || dayjs().unix(),
log_path: target.log,
},
{ transaction },
);
if (target.trigger)
await CrontabModel.sequelize!.query(
"UPDATE CronTriggers SET instance_id=$id,process_identity=$identity WHERE id=$trigger AND state='running'",
{
transaction,
bind: { id: row.id, identity, trigger: target.trigger },
},
);
await history.queueInstanceStop(
row.id!,
target.cronId,
pid,
transaction,
identity,
);
instances.push({ id: row.id, cron_id: target.cronId, pid });
}
return { missingTargets, identityConflict };
}
public async resumePendingStops(
history: TriggerHistory,
requests: Awaited<ReturnType<TriggerHistory['pendingStops']>>,
batches: Awaited<ReturnType<TriggerHistory['pendingStopBatches']>> = [],
) {
for (const row of requests) {
try {
const result = await this.host.stopInstance(
row.cron_id,
row.instance_id,
);
if (result.code !== 200) this.logger.warn(result.message);
} catch (error) {
this.logger.error(
t('[panel][停止实例失败] 实例ID: %s, PID: %s, 错误: %s'),
row.instance_id,
row.pid,
asError(error).message,
);
}
}
for (const batch of batches) {
try {
await this.host.stop(JSON.parse(batch.cron_ids), batch.request_id);
} catch (error) {
this.logger.error(asError(error).message);
}
}
await history.recoverSystemOwners();
}
private readonly stoppingInstances = new Map<
string,
Promise<{ code: number; message: string; data?: { outcome: string } }>
>();
public stopInstance(cronId: number, instanceId: number) {
const key = `${cronId}/${instanceId}`;
const pending = this.stoppingInstances.get(key);
if (pending) return pending;
const stop = this.stopOneInstance(cronId, instanceId).finally(() =>
this.stoppingInstances.delete(key),
);
this.stoppingInstances.set(key, stop);
return stop;
}
private async stopOneInstance(cronId: number, instanceId: number) {
const ended = {
code: 200,
data: { outcome: 'ended' },
message: t('实例已结束'),
};
const stopped = {
code: 200,
data: { outcome: 'stopped' },
message: t('实例已停止'),
};
const history = new TriggerHistory(CrontabModel.sequelize!);
const instance = await RunningInstanceModel.findOne({
where: { id: instanceId, cron_id: cronId },
});
if (!instance) {
await CrontabModel.sequelize!.query(
'DELETE FROM CronStopRequests WHERE instance_id=$instanceId AND cron_id=$cronId',
{ bind: { instanceId, cronId } },
);
return { code: 404, message: t('实例不存在或已停止') };
}
const pending = await history.pendingStop(instanceId);
const savedTargets: string[] = pending?.targets
? JSON.parse(pending.targets)
: [];
const settle = () =>
history.stopVerifiedInstance(instanceId, (transaction) =>
this.settleLegacyStop(instanceId, cronId, instance.pid, transaction),
);
const finishClaim = async (claim: NonNullable<typeof pending>) => {
await finishStoppedTree(
claim.targets ? JSON.parse(claim.targets) : [],
claim.signalled_at,
);
return (await settle()) ? stopped : ended;
};
const releaseUnsignalled = async (recoverEnded = false) => {
const claimed = await history.forgetStop(
instanceId,
recoverEnded
? async (tx) => {
await history.recoverSystemOwners(cronId, tx, instanceId);
if (
(await history.instanceStopRequested(instanceId, tx)) ===
undefined
)
await this.settleLegacyStop(
instanceId,
cronId,
instance.pid,
tx,
InstanceStatus.unknown,
);
}
: undefined,
);
if (claimed) return finishClaim(claimed);
};
if (pending?.signalled) return finishClaim(pending);
if (instance.status !== InstanceStatus.running) {
if (savedTargets.length) await finishStoppedTree(savedTargets);
const claimed = pending && (await releaseUnsignalled());
return (
claimed ??
(instance.status === InstanceStatus.stopped ? stopped : ended)
);
}
// A cold restart destroys the old process tree. The same numeric PIDs
// may already belong to another execution, even when script and log match.
if (
pending?.namespace_owner &&
pending.namespace_owner !== pidNamespaceOwner()
) {
return (await releaseUnsignalled(true)) ?? ended;
}
if (!instance.pid || instance.pid < 1) {
return { code: 409, message: t('实例不存在或已停止') };
}
let identity =
pending?.root_identity ||
(await history.instanceIdentity(instanceId)) ||
savedTargets.find((birth) => birth.startsWith(`crond:${instance.pid}:`));
const verify = () =>
verifyCronProcess(instance.pid!, cronId, identity, instance.started_at, {
logPath: instance.log_path,
});
if (
!identity &&
(await RunningInstanceModel.count({
where: {
id: { [Op.ne]: instanceId },
status: InstanceStatus.running,
pid: instance.pid,
},
}))
) {
const claimed = await releaseUnsignalled();
return claimed ?? { code: 409, message: t('实例不存在或已停止') };
}
try {
identity = verify() ?? identity;
// Traversing the process tree is asynchronous. Persist the individual
// request before traversal so a restart here also resumes this stop.
if (!pending || (!pending.root_identity && identity))
await history.queueInstanceStop(
instanceId,
cronId,
instance.pid,
undefined,
identity ?? undefined,
);
await killTask(instance.pid, true, verify, (signal, targets) =>
history.requestInstanceStop(instanceId, instance.pid!, signal, targets),
);
return (await settle()) ? stopped : ended;
} catch (error) {
const cause = (error as NodeJS.ErrnoException).code;
if (cause === 'ESRCH' || cause === 'PID_REUSED') {
if (savedTargets.length) await finishStoppedTree(savedTargets);
const claimed = await releaseUnsignalled(true);
if (claimed) return claimed;
const latest = await RunningInstanceModel.findOne({
where: { id: instanceId, cron_id: cronId },
});
if (latest?.status === InstanceStatus.stopped) return stopped;
if (latest?.status === InstanceStatus.running) {
const requested = await history.instanceStopRequested(instanceId);
if (requested) return stopped;
if (cause === 'PID_REUSED' || requested === undefined)
return { code: 409, message: t('实例不存在或已停止') };
}
return ended;
}
if ((error as { status?: number }).status === 409) {
if (savedTargets.length) await finishStoppedTree(savedTargets);
const claimed = await releaseUnsignalled();
return claimed ?? { code: 409, message: t('实例不存在或已停止') };
}
this.logger.error(
t('[panel][停止实例失败] 实例ID: %s, PID: %s, 错误: %s'),
instanceId,
instance.pid,
error,
);
throw error;
}
}
private async settleLegacyStop(
instanceId: number,
cronId: number,
pid: number | undefined,
transaction: Transaction,
status = InstanceStatus.stopped,
) {
const [updated] = await RunningInstanceModel.update(
{ status, finished_at: dayjs().unix() },
{
where: {
id: instanceId,
cron_id: cronId,
status: InstanceStatus.running,
},
transaction,
},
);
if (!updated) {
const latest = await RunningInstanceModel.findOne({
where: { id: instanceId, cron_id: cronId },
transaction,
});
return latest?.status === InstanceStatus.stopped;
}
// Check if there are still other running instances for this cron
const otherRunning = await RunningInstanceModel.count({
where: { cron_id: cronId, status: InstanceStatus.running },
transaction,
});
if (otherRunning === 0) {
await CrontabModel.update(
{ status: CrontabStatus.idle, pid: null } as any,
{
where: { id: cronId, status: CrontabStatus.running, pid },
transaction,
},
);
}
return status === InstanceStatus.stopped;
}
public async runSingle(
cronId: number,
expectedToken?: string,
triggerId?: string,
submitted?: Crontab,
): Promise<number | void> {
return taskLimit.manualRunWithCronLimit(
async () => {
let absolutePath: string | undefined;
let logPath: string | undefined;
let queuedLogPath: string | null | undefined;
let queuedToken: string | null = null;
let claimed = false;
const history = new TriggerHistory(CrontabModel.sequelize!);
let state: TriggerState = 'skipped';
let reason: string | null = 'changed';
let exitCode: number | null = null;
try {
const cron = await this.host.getDb({ id: cronId });
const independent = Boolean(
triggerId &&
submitted?.allow_multiple_instances &&
cron.allow_multiple_instances,
);
if (
!independent &&
(cron.status !== CrontabStatus.queued ||
(expectedToken !== undefined &&
cron.queued_token !== expectedToken))
)
return;
queuedLogPath = cron.log_path ?? null;
if (
submitted &&
(submitted.recovery_from !== cron.recovery_from ||
submitted.isDisabled !== cron.isDisabled ||
submitted.command !== cron.command)
) {
queuedToken = expectedToken ?? null;
return;
}
queuedToken = cron.queued_token ?? null;
const { id, command, log_name } = cron;
if (log_name === '/dev/null') {
logPath = '/dev/null';
} else {
const uniqPath = log_name
? path.relative(
config.logPath,
resolveLogPath(config.logPath, log_name),
)
: await getUniqPath(command, `${id}`);
const logTime = dayjs().format('YYYY-MM-DD-HH-mm-ss-SSS');
logPath = `${uniqPath}/${logTime}${
independent ? '-' + expectedToken : ''
}.log`;
absolutePath = resolveFileAccess(config.logPath, [logPath]);
if (!absolutePath)
throw new Error('Log path is outside the log directory');
await fs.mkdir(path.dirname(absolutePath), { recursive: true });
}
const outputPath = absolutePath;
if (triggerId && submitted) {
const claim = await history.claimManual(
triggerId,
submitted,
expectedToken!,
independent,
);
if (claim !== 'started') {
reason = claim;
queuedToken = expectedToken!;
return;
}
}
const launchCommand = `real_log_path=${shellValue(
logPath,
)} no_delay=true ${this.host.makeCommand(cron, true)}`;
// Let the independent supervisor own the log, while the command keeps
// writing to a drained pipe even if the worker dies or the log fills up.
const supervisedLog = Boolean(triggerId && outputPath);
const cp = spawnCronCommand(
launchCommand,
triggerId,
undefined,
outputPath,
);
// Install observers before the first await: very short children may already exit.
const { completed } = observeChildProcess(cp, {
onStart: async () => {
try {
if (
triggerId &&
!(await history.bindCommand(triggerId, cp.pid!, logPath))
)
throw new Error('Task was cancelled before startup');
const [count] = await CrontabModel.update(
{
status: CrontabStatus.running,
pid: cp.pid,
log_path: logPath,
...(!triggerId && {
last_execution_time: dayjs().unix(),
last_running_time: null,
}),
},
{
where: {
id,
...(independent
? {}
: {
status: CrontabStatus.queued,
[Op.and]: [
where(colFn('queued_token'), {
[Op.eq]: queuedToken,
}),
where(colFn('log_path'), {
[Op.eq]: queuedLogPath,
}),
],
}),
},
},
);
if (count !== 1)
throw new Error(
'Task was stopped or superseded before startup',
);
claimed = true;
if (triggerId) {
if (await history.shouldStop(triggerId)) cp.stdin.end();
else await releaseCronCommand(cp);
}
} catch (error) {
if (triggerId) cp.stdin.destroy();
else if (cp.pid) await killTask(cp.pid, true);
throw error;
}
},
onStdout:
outputPath && !supervisedLog
? (message) => logStreamManager.write(outputPath, message)
: undefined,
onStderr: supervisedLog
? async (message) => {
this.logger.error(
'[panel][Command supervisor] Task ID: %s, %s',
id,
message.trim(),
);
}
: outputPath
? (message) => logStreamManager.write(outputPath, message)
: undefined,
});
const result = await completed;
state = result.signal
? 'stopped'
: result.error || result.code !== 0
? 'failed'
: 'finished';
reason = result.error ? 'spawn' : result.signal || null;
exitCode = result.code;
if (result.error) {
this.logger.error(
t('[panel][执行任务失败] 任务ID: %s, 错误: %s'),
id,
result.error.message,
);
}
this.logger.info(
t('[panel][执行任务结束] 任务ID: %s, 退出码: %j'),
id,
result.code,
);
return { ...cron, pid: cp.pid, ...result } as any;
} catch (error) {
state = 'failed';
reason = 'spawn';
this.logger.error(
t('[panel][创建任务失败] 任务ID: %s, 错误: %s'),
cronId,
asError(error).message,
);
} finally {
try {
if (absolutePath) await logStreamManager.closeStream(absolutePath);
} catch (error) {
this.logger.error(
t('[panel][关闭任务日志失败] %s'),
asError(error).message,
);
}
try {
// Do not overwrite a newer run's state or its script-reported exit code.
await CrontabModel.update(
{
status: CrontabStatus.idle,
pid: null,
queued_token: null,
} as any,
{
where: {
id: cronId,
[Op.and]: where(colFn('queued_token'), {
[Op.eq]: queuedToken,
}),
[Op.or]: [
...(queuedLogPath !== undefined && !claimed
? [
{
status: CrontabStatus.queued,
[Op.and]: where(colFn('log_path'), {
[Op.eq]: queuedLogPath,
}),
},
]
: []),
...(claimed && logPath
? [{ log_path: logPath, status: CrontabStatus.running }]
: []),
],
},
},
);
} catch (error) {
this.logger.error(
t('[panel][清理任务状态失败] %s'),
asError(error).message,
);
}
if (triggerId)
await history.complete(triggerId, state, reason, exitCode);
}
},
undefined,
{
id: triggerId,
name: submitted?.name || submitted?.command || String(cronId),
},
CrontabModel.sequelize,
);
}
}
+253
View File
@@ -0,0 +1,253 @@
import { EventEmitter } from 'events';
import PQueue, { QueueAddOptions } from 'p-queue-cjs';
import os from 'os';
import type { Sequelize } from 'sequelize';
import {
QueueOccupants,
recordQueueAdmission,
} from '../queries/queueDiagnostics';
import { CronWaitQueue, CronQueueOptions } from './cronWaitQueue';
import { AuthDataType, SystemModel } from '../../data/system';
import Logger from '../../loaders/logger';
import { t, tf } from '../../shared/i18n';
import type { ICronFn, TCron } from '../../shared/interface';
import config from '../../config';
import { credentials } from '@grpc/grpc-js';
import { ApiClient } from '../../protos/api';
import { getGrpcCerts } from '../../config/grpcCerts';
// One scheduler/manual queue owner per process; services and execution share it.
class CronLimit {
private queuedCrons = new Map<string, ICronFn<any>[]>();
private repeatCronNotifyMap = new Map<string, number>();
private warnSampling = (error: Error) =>
Logger.warn('[queue] Could not save occupancy: %s', error.message);
private scheduledOccupants = new QueueOccupants(
'scheduled',
() => this.cronLimit.concurrency,
this.warnSampling,
);
private manualOccupants = new QueueOccupants(
'manual',
() => this.manualCronoLimit.concurrency,
this.warnSampling,
);
private cronLimit = new PQueue<CronWaitQueue, CronQueueOptions>({
queueClass: CronWaitQueue,
concurrency: Math.max(os.cpus().length, 4),
});
private manualCronoLimit = new PQueue({
concurrency: Math.max(os.cpus().length, 4),
});
private _client: ApiClient | null = null;
private get client(): ApiClient {
if (!this._client) {
const tlsConfig = getGrpcCerts();
const creds = tlsConfig
? credentials.createSsl(
Buffer.from(tlsConfig.caCert),
Buffer.from(tlsConfig.clientKey),
Buffer.from(tlsConfig.clientCert),
)
: credentials.createInsecure();
this._client = new ApiClient(`localhost:${config.grpcPort}`, creds, {
'grpc.enable_http_proxy': 0,
});
}
return this._client;
}
get cronLimitActiveCount() {
return this.cronLimit.pending;
}
get cronLimitPendingCount() {
return this.cronLimit.size;
}
constructor() {
this.setCustomLimit();
this.handleEvents();
}
private handleEvents() {
this.cronLimit.on('add', () => {
Logger.info(
t('[schedule][任务加入队列] 运行中任务数: %s, 等待中任务数: %s'),
this.cronLimitActiveCount,
this.cronLimitPendingCount,
);
});
this.cronLimit.on('active', () => {
Logger.info(
t('[schedule][开始处理任务] 运行中任务数: %s, 等待中任务数: %s'),
this.cronLimitActiveCount + 1,
this.cronLimitPendingCount,
);
});
this.cronLimit.on('completed', (param) => {
Logger.info(t('[schedule][任务处理成功] 参数 %s'), JSON.stringify(param));
});
this.cronLimit.on('error', (error) => {
Logger.error(
t('[schedule][任务处理错误] 参数 %s'),
JSON.stringify(error),
);
});
this.cronLimit.on('next', () => {
Logger.info(
t('[schedule][任务处理结束] 运行中任务数: %s, 等待中任务数: %s'),
this.cronLimitActiveCount,
this.cronLimitPendingCount,
);
});
this.cronLimit.on('idle', () => {
Logger.info(t(`[schedule][任务队列] 空闲中...`));
});
}
public removeQueuedCron(id: string, completed?: ICronFn<any>) {
if (this.queuedCrons.has(id)) {
const runs = this.queuedCrons.get(id);
if (runs && runs.length > 0) {
const remaining = completed
? runs.filter((run) => run !== completed)
: runs.slice(0, -1);
if (remaining.length) this.queuedCrons.set(id, remaining);
else this.queuedCrons.delete(id);
}
}
}
public get cronConcurrency() {
return this.manualCronoLimit.concurrency;
}
public async setCustomLimit(limit?: number) {
if (limit) {
this.cronLimit.concurrency = limit;
this.manualCronoLimit.concurrency = limit;
this.scheduledOccupants.refresh();
this.manualOccupants.refresh();
return;
}
await SystemModel.sync();
const doc = await SystemModel.findOne({
where: { type: AuthDataType.systemConfig },
});
if (doc?.info?.cronConcurrency) {
await this.setCustomLimit(doc.info.cronConcurrency);
}
}
public async runWithCronLimit<T>(
cron: TCron,
fn: ICronFn<T>,
options?: Partial<QueueAddOptions>,
isCurrent: () => boolean = () => true,
onPending?: () => void,
waitingSignal?: EventEmitter,
triggerId?: string,
db?: Sequelize,
): Promise<T | void> {
if (!isCurrent()) return;
fn.cron = cron;
fn.isCurrent = isCurrent;
// Invalidated snapshots must not consume the new revision's repeat budget.
const runs = this.queuedCrons
.get(cron.id)
?.filter((run) => run.isCurrent?.() !== false);
if (cron.skip_if_pending && runs?.length) {
onPending?.();
return;
}
const result = runs?.length ? [...runs, fn] : [fn];
const repeatTimes = this.repeatCronNotifyMap.get(cron.id) || 0;
if (result?.length > 5) {
if (repeatTimes < 3) {
this.repeatCronNotifyMap.set(cron.id, repeatTimes + 1);
this.client.systemNotify(
{
title: t('任务重复运行'),
content: tf(
'任务:%s,命令:%s,定时:%s,处于运行中的超过 %d 个,请检查定时设置',
cron.name || '',
cron.command || '',
cron.schedule || '',
5,
),
},
(err, res) => {
if (err) {
Logger.error(
t('[schedule][任务重复运行] 通知失败 %s'),
JSON.stringify(err),
);
}
},
);
}
Logger.warn(t('[schedule][任务重复运行] 参数 %s'), JSON.stringify(cron));
return;
}
this.queuedCrons.set(cron.id, result);
const run = this.trackAdmission(
this.scheduledOccupants,
this.cronLimit.concurrency,
fn,
{ id: triggerId, name: cron.name || cron.id },
db,
);
if (!waitingSignal) return this.cronLimit.add(run, options);
return new Promise<T | void>((resolve, reject) => {
this.cronLimit
.add(run, {
...options,
waitingSignal,
onRemoved: () => {
this.scheduledOccupants.forget(triggerId);
resolve();
},
})
.then(resolve, reject);
});
}
private trackAdmission<T>(
pool: QueueOccupants,
limit: number,
fn: () => Promise<T>,
occupant: { id?: string; name: string },
db?: Sequelize,
) {
const admission = pool.admission(limit);
if (occupant.id && admission && db) {
pool.watch(occupant.id, db);
void recordQueueAdmission(db, occupant.id, admission).catch((error) =>
Logger.warn('[queue] Failed to record wait reason: %s', error.message),
);
}
return pool.track(fn, occupant, db);
}
public async manualRunWithCronLimit<T>(
fn: () => Promise<T>,
options?: Partial<QueueAddOptions>,
occupant: { id?: string; name: string } = { name: '—' },
db?: Sequelize,
): Promise<T | void> {
return this.manualCronoLimit.add(
this.trackAdmission(
this.manualOccupants,
this.manualCronoLimit.concurrency,
fn,
occupant,
db,
),
options,
);
}
}
export default new CronLimit();
+63
View File
@@ -0,0 +1,63 @@
// Read literal shell words only. Never expand or execute a command to derive a
// path. Adjacent quoted/unquoted fragments belong to the same argument.
function words(command: string): string[] {
const result: string[] = [];
let value = '',
quote = '',
active = false;
for (let i = 0; i < command.length; i++) {
const c = command[i];
if (quote && c === quote) {
quote = '';
continue;
}
if (!quote && (c === "'" || c === '"')) {
quote = c;
active = true;
continue;
}
if (c === '\\' && quote !== "'") {
const next = command[++i];
if (next === undefined) return [];
if (quote === '"' && !/[$`"\\\n]/.test(next)) value += '\\';
if (next !== '\n') {
value += next;
active = true;
}
continue;
}
if (!quote && /[;&|<>()\n]/.test(c)) break;
if (!quote && /\s/.test(c)) {
if (active) result.push(value);
value = '';
active = false;
continue;
}
if (!active && !quote && c === '#') break;
value += c;
active = true;
}
if (quote) return [];
if (active) result.push(value);
return result;
}
export function cronOperand(
command: string,
taskOnly = false,
): string | undefined {
const args = words(command.trim());
if (args[0] === 'task') args.shift();
else if (taskOnly && args[0] === 'ql') return;
while (args[0] === '-l' || args[0] === '-m') {
if (args.shift() === '-m') args.shift();
}
if (
args.length > 1 &&
/^(?:.*\/)?(?:node|python3?|bash|sh|ts-node(?:-transpile-only)?)$/.test(
args[0],
)
)
args.shift();
return args[0];
}
+237
View File
@@ -0,0 +1,237 @@
import { readFileSync } from 'fs';
import { execFileSync, spawnSync } from 'child_process';
// Legacy runs can outlive a scheduler restart without an active trigger receipt.
export function hasLiveCronProcess(status?: number, pid?: number | null) {
if (status !== 0 || !pid || pid < 0) return false; // CrontabStatus.running
try {
process.kill(pid, 0);
return true;
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === 'ESRCH') return false;
if (code === 'EPERM') return true;
throw error;
}
}
function readBsdProcessField(pid: number, field: 'lstart' | 'ppid') {
const result = spawnSync('ps', ['-p', String(pid), '-o', field + '='], {
encoding: 'utf8',
env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
});
// ENOENT from spawning ps refers to the executable, not the target PID.
if (result.error)
throw new Error('Cannot run ps: ' + result.error.message, {
cause: result.error,
});
const value = result.stdout.trim();
if (result.status === 0 && value) return value;
// BSD ps exits 1 without output when the selected PID has already exited.
if (result.status === 1 && !value && !result.stderr.trim())
throw Object.assign(new Error('Process has exited'), { code: 'ESRCH' });
throw new Error(
`Cannot read ${field} for PID ${pid}: ${
result.stderr.trim() || result.signal || 'ps status ' + result.status
}`,
);
}
export function systemOwner(pid: number) {
if (process.platform !== 'linux') {
// BSD crontab installations have no procfs. ps exposes the process birth time.
process.kill(pid, 0);
const birth = readBsdProcessField(pid, 'lstart');
return `crond:${pid}:${birth}`;
}
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
if (['Z', 'X', 'x'].includes(fields[0]))
throw Object.assign(new Error('Process has exited'), { code: 'ESRCH' });
const startTicks = fields[19];
const boot = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
return `crond:${pid}:${startTicks}:${boot}`;
}
let linuxClockTicks: number | undefined;
// A start packet may arrive after its PID was recycled, before the replacement reports.
export function legacyProcessOwner(
pid: number,
started: number,
): string | undefined {
try {
const identity = systemOwner(pid);
const birth = identity.slice(`crond:${pid}:`.length);
let bornAt: number;
if (process.platform === 'linux') {
linuxClockTicks ??= Number(
execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' }),
);
const boot = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
if (!boot || !(linuxClockTicks > 0))
throw new Error('Cannot read process birth time');
bornAt = Number(boot[1]) + Number(birth.split(':')[0]) / linuxClockTicks;
} else {
bornAt = Date.parse(birth + ' UTC') / 1000;
}
// Both the callback and Linux boot time have one-second precision.
return Math.floor(bornAt) <= started + 1 ? identity : undefined;
} catch (error) {
if (['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!))
return undefined;
throw error;
}
}
// PID 1 survives worker restarts, but changes when a container or Linux host restarts.
export function pidNamespaceOwner() {
return process.platform === 'linux' ? systemOwner(1) : null;
}
// psTree enumerates asynchronously. Reject a PID already reparented or recycled
// between enumeration and the birth-token snapshot.
export function isProcessDescendant(pid: number, root: number) {
const seen = new Set<number>();
while (pid > 1 && !seen.has(pid)) {
if (pid === root) return true;
seen.add(pid);
if (process.platform === 'linux') {
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
pid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
} else {
pid = Number(readBsdProcessField(pid, 'ppid'));
}
}
return false;
}
// For an individual legacy instance the task ID alone also matches its siblings.
export function verifyCronProcess(
pid: number,
cronId: number,
identity?: string | null,
started?: number,
instance?: { logPath?: string },
) {
const conflict = () =>
Object.assign(new Error('Task process identity could not be verified'), {
status: 409,
});
if (!Number.isInteger(pid) || pid <= 1) throw conflict();
if (identity) {
// A birth token for this PID proves the original process is gone if the
// kernel now reports a different birth. Access errors remain retryable.
if (!identity.startsWith(`crond:${pid}:`)) throw conflict();
let current: string;
try {
current = systemOwner(pid);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT')
throw Object.assign(new Error('Command already exited'), {
code: 'ESRCH',
});
throw error;
}
if (current !== identity)
throw Object.assign(new Error('Command PID was reused'), {
code: 'PID_REUSED',
status: 409,
});
return current;
}
try {
if (process.platform === 'linux') {
const env = readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0');
if (
instance &&
(!instance.logPath ||
instance.logPath === '/dev/null' ||
!env.includes('real_log_path=' + instance.logPath))
)
throw conflict();
if (env.includes('ID=' + cronId) && started) {
const boot = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
const birth = systemOwner(pid);
const ticks = Number(birth.split(':')[2]);
const hz = Number(
execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' }),
);
if (
boot &&
hz > 0 &&
Math.floor(Number(boot[1]) + ticks / hz) <= started + 1
)
return birth;
}
}
} catch (error) {
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) {
// Distinguish a completed child whose receipt is still being written
// from a live PID with an unverifiable identity.
try {
systemOwner(pid);
} catch (probe) {
if (
['ENOENT', 'ESRCH'].includes((probe as NodeJS.ErrnoException).code!)
)
throw Object.assign(new Error('Command already exited'), {
code: 'ESRCH',
});
}
}
}
throw conflict();
}
// After a stop worker exits, descendants may already have been adopted by PID 1.
// A saved birth identity still identifies them; walking the dead root no longer can.
export async function finishStoppedTree(
identities: string[],
signalledAt?: number | null,
) {
const surviving = () =>
identities.flatMap((identity) => {
const pid = Number(identity.split(':')[1]);
if (!Number.isSafeInteger(pid) || pid <= 1)
throw new Error('Invalid saved process identity');
try {
return systemOwner(pid) === identity ? [pid] : [];
} catch (error) {
if (
['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)
)
return [];
throw error;
}
});
const remainingGrace = Math.min(
1000,
Math.max(0, (signalledAt ?? Date.now()) + 1000 - Date.now()),
);
const graceDeadline = Date.now() + remainingGrace;
while (surviving().length) {
const remaining = graceDeadline - Date.now();
if (remaining <= 0) break;
await new Promise((resolve) =>
setTimeout(resolve, Math.min(20, remaining)),
);
}
if (!surviving().length) return;
// Revalidate each PID immediately before signalling, including after the grace period.
for (const identity of identities) {
const pid = Number(identity.split(':')[1]);
try {
if (systemOwner(pid) === identity) process.kill(pid, 'SIGKILL');
} catch (error) {
if (!['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!))
throw error;
}
}
const deadline = Date.now() + 1000;
while (surviving().length) {
if (Date.now() >= deadline)
throw new Error('Stopped process tree did not exit');
await new Promise((resolve) => setTimeout(resolve, 20));
}
}
+54
View File
@@ -0,0 +1,54 @@
import { EventEmitter } from 'events';
import { QueueAddOptions } from 'p-queue-cjs';
type Job = () => Promise<unknown>;
export interface CronQueueOptions extends QueueAddOptions {
waitingSignal?: EventEmitter;
onRemoved?: () => void;
}
// p-queue checks its signal only after dequeue. Remove expired waits while the
// execution slots are still occupied, without aborting a running child.
export class CronWaitQueue {
private entries: { run: Job; priority: number; detach: () => void }[] = [];
get size() {
return this.entries.length;
}
enqueue(run: Job, options: Partial<CronQueueOptions> = {}) {
const { priority = 0, waitingSignal, onRemoved } = options;
const remove = () => {
const index = this.entries.indexOf(entry);
if (index < 0) return;
this.entries.splice(index, 1);
onRemoved?.();
};
const entry = {
run,
priority,
detach: () => waitingSignal?.off('expired', remove),
};
const last = this.entries[this.size - 1];
if (!last || last.priority >= priority) this.entries.push(entry);
else
this.entries.splice(
this.entries.findIndex((job) => job.priority < priority),
0,
entry,
);
waitingSignal?.once('expired', remove);
}
dequeue() {
const next = this.entries.shift();
next?.detach();
return next?.run;
}
filter(options: Partial<CronQueueOptions>) {
return this.entries
.filter((entry) => entry.priority === options.priority)
.map((entry) => entry.run);
}
}
+331
View File
@@ -0,0 +1,331 @@
import { hasLiveCronProcess } from './cronProcess';
import { EventEmitter } from 'events';
import PQueue from 'p-queue-cjs';
import { triggerHistory, TriggerState } from '../history';
import { t } from '../../shared/i18n';
import { spawnCronCommand, releaseCronCommand } from './cronCommandProcess';
import taskLimit from './cronLimit';
import Logger from '../../loaders/logger';
import { ICron } from '../../protos/cron';
import { CrontabModel, CrontabStatus } from '../../data/cron';
import {
RunningInstanceModel,
InstanceStatus,
} from '../../data/runningInstance';
import dayjs from 'dayjs';
import { observeChildProcess, asError } from '../../shared/childProcess';
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 (!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({
where: { id: Number(cron.id) },
});
// A mutation may commit while this queued run is reading the database.
if (!isCurrent() || !existingCron || existingCron.isDisabled) return;
// Default to single instance mode (0) for backward compatibility
multiple = existingCron.allow_multiple_instances === 1;
if (!multiple) {
// A queued manual run is an active reservation, even if its stored PID
// belongs to a previous execution.
if (
existingCron.status === CrontabStatus.queued &&
existingCron.pid
) {
Logger.info(
'[schedule][Skip queued single-instance task] Task ID: %s, PID: %s',
cron.id,
existingCron.pid,
);
reason = 'overlap';
return;
}
if (
existingCron.status === CrontabStatus.running &&
existingCron.pid
) {
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;
}
// Capture old instance IDs before releasing the stale cron state so
// a concurrent replacement cannot have its instance marked stopped.
const staleInstances = await RunningInstanceModel.findAll({
attributes: ['id'],
where: {
cron_id: Number(cron.id),
pid: existingCron.pid,
status: InstanceStatus.running,
},
});
if (!isCurrent()) return;
const [recovered] = await CrontabModel.update(
{
status: CrontabStatus.idle,
pid: null,
queued_token: null,
} as any,
{
where: {
id: Number(cron.id),
pid: existingCron.pid,
status: CrontabStatus.running,
...(existingCron.log_path !== undefined
? { log_path: existingCron.log_path }
: {}),
...(existingCron.queued_token !== undefined
? { queued_token: existingCron.queued_token }
: {}),
...(existingCron.last_execution_time !== undefined
? { last_execution_time: existingCron.last_execution_time }
: {}),
...(existingCron.isDisabled !== undefined
? { isDisabled: existingCron.isDisabled }
: {}),
allow_multiple_instances: 0,
},
},
);
if (recovered !== 1) return;
const staleIds = staleInstances.map((instance) => instance.id!);
if (staleIds.length) {
await RunningInstanceModel.update(
{ status: InstanceStatus.stopped, finished_at: dayjs().unix() },
{ where: { id: staleIds, status: InstanceStatus.running } },
);
}
Logger.info(
'[schedule][Recovered stale single-instance task] Task ID: %s, PID: %s',
cron.id,
existingCron.pid,
);
}
}
} catch (error) {
Logger.error(
t('[schedule][检查已运行任务失败] 任务ID: %s, 错误: %s'),
cron.id,
error,
);
throw error;
}
// Invalidation can happen during the asynchronous database check.
if (!isCurrent()) return;
Logger.info(
t('[schedule][开始执行任务] 参数 %s'),
JSON.stringify({
...cron,
command: cmd,
}),
);
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'),
cmd,
message,
);
},
});
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'),
cmd,
result.error.message,
);
}
Logger.info(
t('[schedule][执行任务结束] 任务ID: %s, 退出码: %j'),
cron.id,
result.code,
);
return { ...cron, command: cmd, pid: cp.pid, ...result } as any;
} catch (error) {
state = 'failed';
reason = 'spawn';
Logger.error(
t('[schedule][创建任务失败] 命令: %s, 错误: %s'),
cmd,
asError(error).message,
);
} finally {
taskLimit.removeQueuedCron(cron.id, execute);
}
};
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 },
);
}
}
}
+806
View File
@@ -0,0 +1,806 @@
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import type { Crontab } from '../../data/cron';
import type {
TriggerSource,
TriggerState,
VerifiedSupervisorExit,
} from '../types';
import type { readExit } from '../settlement/exitReceipt.cjs';
import {
hasLiveCronProcess,
pidNamespaceOwner,
systemOwner,
} from './cronProcess';
type ExitReceipt = Awaited<ReturnType<typeof readExit>>;
// Evidence inspection and settlement remain in the existing ledger. Callers must
// use the supplied transaction so state, stop claims and statistics commit together.
export interface TriggerLifecycleEvidence {
exitBeforeStop(id: string): Promise<{
canonical: ExitReceipt;
recovered: ExitReceipt[];
published: boolean;
unreadable: boolean;
}>;
completeCommandExit(
id: string,
state: TriggerState,
reason: string | null,
code: number | null,
transaction: Transaction,
receipt?: ExitReceipt,
finishedAt?: number,
report?: VerifiedSupervisorExit | 'legacy',
recoveredCopies?: ExitReceipt[],
): Promise<void>;
recoverScriptSample(id: string, transaction: Transaction): Promise<void>;
replayPublishedExits(transaction: Transaction): Promise<void>;
}
// Persisted transitions shared by manual, Node and system-crond executions.
// In particular, recovery may reclaim an unstarted slot, never an unknown result.
export class TriggerLifecycle {
constructor(
private database: Sequelize,
private evidence: TriggerLifecycleEvidence,
) {}
// Only unclaimed scheduler work can expire; its owner controls claimed runs.
async skipQueued(id: string, reason: string, finishedAt: number) {
await this.database.query(
`UPDATE CronTriggers SET state='skipped', reason=$reason, finished_at=$finishedAt
WHERE id=$id AND source IN ('node','recovery') AND state='queued' AND started_at IS NULL`,
{ bind: { id, reason, finishedAt }, type: QueryTypes.BULKUPDATE },
);
}
async enqueue(
id: string,
cronId: number,
source: TriggerSource,
scheduledAt: number | null,
now = Date.now(),
transaction?: Transaction,
) {
// The SQLite driver returns changes on the statement that claimed this slot.
const changed = await this.database.query(
`INSERT INTO CronTriggers(id, cron_id, source, scheduled_at, queued_at, observed_at, owner, state)
VALUES ($id,$cronId,$source,$scheduledAt,$now,$now,$owner,'queued')
ON CONFLICT(id) DO UPDATE SET state='queued', reason=NULL, finished_at=NULL,
queued_at=excluded.queued_at, dequeued_at=NULL, queue_context=NULL, queue_live_context=NULL,
source=excluded.source, owner=excluded.owner
WHERE excluded.source='recovery' AND state='skipped' AND reason='restart' AND started_at IS NULL`,
{
bind: {
id,
cronId,
source,
scheduledAt,
now,
owner: process.env.SERVICE_TYPE || 'http',
},
transaction,
type: QueryTypes.BULKUPDATE,
},
);
return changed === 1;
}
// Admission and competing pending runs share one write transaction.
async enqueueUnlessPending(
id: string,
cronId: number,
source: 'node' | 'recovery',
scheduledAt: number,
now: number,
revision = 0,
) {
return this.database.transaction(async (transaction) => {
if (
!(await this.enqueue(id, cronId, source, scheduledAt, now, transaction))
)
return false;
await this.recoverSystemOwners(cronId, transaction);
const pending = await this.database.query(
`SELECT 1 FROM CronTriggers WHERE cron_id=$cronId AND id<>$id
AND source IN ('node','recovery','system')
AND (state='running' OR (state='queued' AND queued_at >= $revision)) LIMIT 1`,
{
transaction,
bind: { cronId, id, revision },
type: QueryTypes.SELECT,
},
);
if (!pending.length) return true;
await this.finish(id, 'skipped', 'pending', null, transaction);
return false;
});
}
async start(
id: string,
now = Date.now(),
multiple = false,
transaction?: Transaction,
) {
const claim = () =>
this.database.query(
`UPDATE CronTriggers SET state='running', started_at=$now WHERE id=$id AND state='queued'
AND ($multiple OR NOT EXISTS (SELECT 1 FROM CronTriggers AS active
WHERE active.cron_id=CronTriggers.cron_id AND active.state='running'))`,
{
transaction,
bind: { id, now, multiple: Number(multiple) },
type: QueryTypes.BULKUPDATE,
},
);
let changed = await claim();
if (!changed && !multiple && !transaction) {
const [task] = await this.database.query<{ cron_id: number }>(
"SELECT cron_id FROM CronTriggers WHERE id=$id AND state='queued'",
{ bind: { id }, type: QueryTypes.SELECT },
);
if (task && (await this.recoverSystemOwners(task.cron_id)))
changed = await claim();
}
return changed === 1;
}
async claimManual(
id: string,
snapshot: Crontab,
token: string,
independent: boolean,
) {
return this.database.transaction(async (transaction) => {
// The write transaction orders a configuration save and a manual claim.
const rows = await this.database.query(
`SELECT 1 FROM Crontabs WHERE id=$cronId AND recovery_from IS $revision
AND command=$command AND COALESCE(isDisabled,0)=$disabled
AND COALESCE(allow_multiple_instances,0)=$multiple
AND ($independent OR (status=3 AND queued_token=$token))`,
{
transaction,
type: QueryTypes.SELECT,
bind: {
cronId: snapshot.id,
revision: snapshot.recovery_from ?? null,
command: snapshot.command,
disabled: snapshot.isDisabled || 0,
multiple: snapshot.allow_multiple_instances || 0,
independent: Number(independent),
token,
},
},
);
if (!rows.length) return 'changed';
if (!independent)
await this.recoverSystemOwners(snapshot.id, transaction);
return (await this.start(id, Date.now(), independent, transaction))
? 'started'
: 'overlap';
});
}
async finish(
id: string,
state: TriggerState,
reason: string | null = null,
code: number | null = null,
transaction?: Transaction,
finishedAt?: number,
) {
// A managed supervisor can observe the clock moving backwards during a run.
// Clients supply their own timestamps; validate those against the recorded start.
return this.database.query(
`UPDATE CronTriggers SET state=$state, reason=$reason, exit_code=$code,
started_at=CASE WHEN $state='skipped' THEN NULL ELSE started_at END,
finished_at=COALESCE(CASE WHEN owner IS NOT NULL OR $finishedAt >= started_at THEN $finishedAt END,CASE WHEN state='unknown' THEN finished_at END,$now)
WHERE id=$id AND (state IN ('running','queued') OR
(state='unknown' AND $state IN ('finished','failed','stopped')))`,
{
transaction,
type: QueryTypes.BULKUPDATE,
bind: {
id,
state,
reason,
code,
finishedAt: finishedAt ?? null,
now: Date.now(),
},
},
);
}
async claimSummary(
cronId: number,
instance: number,
seconds: number,
transaction: Transaction,
observedStart: boolean,
duration: number | null = null,
) {
await this.database.query(
`UPDATE Crontabs SET last_instance_id=$instance,
last_execution_time=$seconds,last_running_time=$duration WHERE id=$cronId AND
(last_execution_time IS NULL OR last_execution_time<$seconds OR
(last_execution_time=$seconds AND (last_instance_id IS NULL OR
($observedStart AND last_instance_id<$instance))))`,
{
transaction,
bind: {
cronId,
instance,
seconds,
duration,
observedStart: Number(observedStart),
},
},
);
}
async isRunning(cronId: number, transaction: Transaction) {
await this.recoverSystemOwners(cronId, transaction);
const rows = await this.database.query(
"SELECT 1 FROM CronTriggers WHERE cron_id=$cronId AND state='running' LIMIT 1",
{ bind: { cronId }, transaction, type: QueryTypes.SELECT },
);
return rows.length !== 0;
}
async cancelQueued(ids: number[]) {
if (!ids.length) return [];
return this.database.transaction((tx) =>
this.cancelQueuedInTransaction(ids, tx),
);
}
async cancelQueuedInTransaction(ids: number[], transaction: Transaction) {
await this.database.query(
"UPDATE CronTriggers SET stop_requested=1 WHERE cron_id IN (:ids) AND state='running' AND command_identity IS NULL AND instance_id IS NULL",
{ replacements: { ids }, transaction },
);
const rows = await this.database.query<{ id: string }>(
"SELECT id FROM CronTriggers WHERE cron_id IN (:ids) AND state='queued'",
{ replacements: { ids }, transaction, type: QueryTypes.SELECT },
);
await this.database.query(
`UPDATE CronTriggers SET state='stopped',reason='cancelled',finished_at=:now
WHERE cron_id IN (:ids) AND state='queued'`,
{ replacements: { ids, now: Date.now() }, transaction },
);
return rows.map((r) => r.id);
}
async queueInstanceStop(
instanceId: number,
cronId: number,
pid: number,
transaction?: Transaction,
identity?: string,
) {
await this.database.query(
`INSERT INTO CronStopRequests(instance_id,cron_id,pid,root_identity,namespace_owner)
VALUES ($instanceId,$cronId,$pid,$identity,$namespace)
ON CONFLICT(instance_id) DO UPDATE SET root_identity=excluded.root_identity
WHERE root_identity IS NULL AND excluded.root_identity IS NOT NULL AND pid=excluded.pid AND signalled=0`,
{
transaction,
bind: {
instanceId,
cronId,
pid,
identity: identity ?? null,
namespace: pidNamespaceOwner(),
},
},
);
}
async pendingStop(instanceId: number, transaction?: Transaction) {
const [row] = await this.database.query<{
targets: string | null;
signalled: number;
signalled_at: number | null;
root_identity: string | null;
namespace_owner: string | null;
}>(
'SELECT targets,signalled,signalled_at,root_identity,namespace_owner FROM CronStopRequests WHERE instance_id=$instanceId',
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
);
return row;
}
async pendingStopBatches() {
return this.database.query<{ request_id: string; cron_ids: string }>(
'SELECT request_id,cron_ids FROM CronStopBatches WHERE snapshot IS NOT NULL',
{ type: QueryTypes.SELECT },
);
}
async pendingStops() {
return this.database.query<{
instance_id: number;
cron_id: number;
pid: number;
targets: string | null;
}>(
'SELECT instance_id,cron_id,pid,targets FROM CronStopRequests ORDER BY instance_id',
{ type: QueryTypes.SELECT },
);
}
async forgetStop(
instanceId: number,
onEnded?: (tx: Transaction) => Promise<void>,
) {
return this.database.transaction(async (transaction) => {
await this.database.query(
'DELETE FROM CronStopRequests WHERE instance_id=$instanceId AND signalled=0',
{ transaction, bind: { instanceId } },
);
const claimed = await this.pendingStop(instanceId, transaction);
if (!claimed && onEnded) await onEnded(transaction);
return claimed;
});
}
async shouldStop(id: string, transaction?: Transaction) {
const rows = await this.database.query(
'SELECT 1 FROM CronTriggers WHERE id=$id AND stop_requested=1',
{ transaction, bind: { id }, type: QueryTypes.SELECT },
);
return rows.length > 0;
}
// The outer command can outlive any of its task wrappers.
async recordCommandStart(id: string, at: number) {
await this.database.query(
`UPDATE CronTriggers SET command_started_at=$at
WHERE id=$id AND command_started_at IS NULL AND started_at IS NOT NULL`,
{ bind: { id, at } },
);
}
async bindCommand(id: string, pid: number, log?: string) {
let identity: string;
try {
identity = systemOwner(pid);
} catch (error) {
if (['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!))
return false;
throw error;
}
return this.database.transaction(async (transaction) => {
const [row] = await this.database.query<{
instance_id: number | null;
cron_id: number;
started_at: number;
}>(
"SELECT instance_id,cron_id,started_at FROM CronTriggers WHERE id=$id AND state='running'",
{ transaction, bind: { id }, type: QueryTypes.SELECT },
);
if (!row) return false;
await this.database.query(
'UPDATE CronTriggers SET command_identity=$identity WHERE id=$id',
{ transaction, bind: { identity, id } },
);
if (row.instance_id) {
await this.database.query(
'UPDATE RunningInstances SET pid=$pid WHERE id=$instance AND status=0',
{ transaction, bind: { pid, instance: row.instance_id } },
);
await this.database.query(
'UPDATE CronTriggers SET process_identity=$identity WHERE id=$id',
{ transaction, bind: { identity, id } },
);
await this.database.query(
'UPDATE Crontabs SET pid=$pid WHERE id=$cronId AND log_path=(SELECT log_path FROM CronTriggers WHERE id=$id) AND status=0',
{ transaction, bind: { pid, cronId: row.cron_id, id } },
);
} else {
await this.registerCommandInstance(
id,
row.cron_id,
pid,
identity,
row.started_at,
log,
transaction,
);
}
return true;
});
}
private async registerCommandInstance(
id: string,
cronId: number,
pid: number,
identity: string,
started: number,
log: string | undefined,
transaction: Transaction,
) {
const seconds = Math.floor(started / 1000);
const [instance] = await this.database.query(
`INSERT INTO RunningInstances(cron_id,pid,log_path,started_at,status,createdAt,updatedAt)
VALUES ($cronId,$pid,$log,$seconds,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)`,
{
transaction,
type: QueryTypes.INSERT,
bind: { cronId, pid, log: log ?? null, seconds },
},
);
await this.database.query(
'UPDATE CronTriggers SET log_path=$log,instance_id=$instance,process_identity=$identity WHERE id=$id',
{ transaction, bind: { id, log: log ?? null, instance, identity } },
);
await this.claimSummary(cronId, instance, seconds, transaction, true);
if (log === undefined)
await this.database.query(
'UPDATE Crontabs SET status=0,pid=$pid,log_path=NULL WHERE id=$cronId AND status IS NOT 3',
{ transaction, bind: { cronId, pid } },
);
}
async activeCommands(ids: number[], transaction?: Transaction) {
if (!ids.length) return [];
return this.database.query<{
id: string;
cron_id: number;
command_identity: string;
started_at: number;
log_path: string;
}>(
"SELECT id,cron_id,command_identity,started_at,log_path FROM CronTriggers WHERE cron_id IN (:ids) AND state='running' AND instance_id IS NULL AND command_identity IS NOT NULL",
{ replacements: { ids }, transaction, type: QueryTypes.SELECT },
);
}
async instanceIdentity(instanceId: number) {
const [row] = await this.database.query<{
process_identity: string | null;
}>(
'SELECT process_identity FROM CronTriggers WHERE instance_id=$instanceId',
{ bind: { instanceId }, type: QueryTypes.SELECT },
);
return row?.process_identity;
}
async requestInstanceStop(
instanceId: number,
pid: number,
signalTree: () => void | Error,
targets?: string[],
) {
// Commit the verified tree BEFORE the first signal. If this worker dies even
// inside the following transaction, its replacement still has the original PIDs.
if (targets)
await this.database.query(
`INSERT INTO CronStopRequests(instance_id,cron_id,pid,targets)
SELECT i.id,i.cron_id,i.pid,$targets FROM RunningInstances i WHERE i.id=$instanceId AND i.pid=$pid AND i.status=0
ON CONFLICT(instance_id) DO UPDATE SET targets=(
SELECT json_group_array(value) FROM (SELECT value FROM json_each(CronStopRequests.targets)
UNION SELECT value FROM json_each(excluded.targets))) WHERE CronStopRequests.signalled=0`,
{ bind: { instanceId, pid, targets: JSON.stringify(targets) } },
);
const result = await this.database.transaction(
{ type: Transaction.TYPES.IMMEDIATE },
async (transaction) => {
const [row] = await this.database.query<{
id: string | null;
pid: number;
status: number;
state: TriggerState | null;
stop_requested: number | null;
}>(
`SELECT t.id,i.pid,i.status,t.state,t.stop_requested FROM RunningInstances i
LEFT JOIN CronTriggers t ON t.instance_id=i.id WHERE i.id=$instanceId`,
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
);
if (
!row ||
row.status !== 0 ||
(row.state && row.state !== 'running')
) {
throw Object.assign(new Error('Instance already ended'), {
code: 'ESRCH',
});
}
if (row.pid !== pid)
throw Object.assign(new Error('Instance process changed'), {
status: 409,
});
if (row.stop_requested && !targets) return;
const existing = await this.pendingStop(instanceId, transaction);
const savedTargets: string[] = existing?.targets
? JSON.parse(existing.targets)
: [];
if (existing?.signalled)
return { targets: savedTargets, signalledAt: existing.signalled_at };
// The supervisor can still be draining output after the command has exited.
if (row.id) {
const exit = await this.evidence.exitBeforeStop(row.id);
// An I/O error alone cannot prove a live process has already exited.
if (!exit.published && exit.unreadable)
throw Object.assign(
new Error('Cannot verify command exit. Retry the stop request.'),
{ status: 503 },
);
if (exit.published) {
await this.evidence.completeCommandExit(
row.id,
'unknown',
null,
null,
transaction,
exit.canonical,
undefined,
undefined,
exit.recovered,
);
return { ended: true };
}
}
if (targets && !existing?.targets) {
// Another worker released the prepared tree. Retry from a durable
// snapshot before issuing an irreversible signal.
throw Object.assign(
new Error('Stop target snapshot changed. Retry the stop request.'),
{ status: 503 },
);
}
const signalledAt = Date.now();
await this.database.query(
'UPDATE CronStopRequests SET signalled=1,signalled_at=$signalledAt WHERE instance_id=$instanceId',
{ transaction, bind: { instanceId, signalledAt } },
);
if (row.state)
await this.database.query(
"UPDATE CronTriggers SET stop_requested=1 WHERE instance_id=$instanceId AND state='running'",
{ bind: { instanceId }, transaction },
);
// Root delivery failure rolls back. After successful root delivery, retain
// the stop marker even if some descendants still need recovery.
const error = signalTree();
return { targets: savedTargets, signalledAt, error };
},
);
if (result && 'ended' in result)
throw Object.assign(new Error('Instance already ended'), {
code: 'ESRCH',
});
if (result && 'error' in result && result.error instanceof Error)
throw result.error;
if (targets && result)
return { targets: result.targets, signalledAt: result.signalledAt };
}
async instanceStopRequested(instanceId: number, transaction?: Transaction) {
const [row] = await this.database.query<{ stop_requested: number | null }>(
'SELECT stop_requested FROM CronTriggers WHERE instance_id=$instanceId',
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
);
return row && Boolean(row.stop_requested);
}
async stopVerifiedInstance(
instanceId: number,
settleLegacy?: (transaction: Transaction) => Promise<boolean>,
) {
return this.database.transaction(async (transaction) => {
const [row] = await this.database.query<{
id: string;
owner: string | null;
command_identity: string | null;
reason: string | null;
state: TriggerState;
stop_exit_at: number | null;
exit_code: number | null;
exit_pending: number | null;
}>(
'SELECT id,owner,command_identity,reason,state,stop_exit_at,exit_code,exit_pending FROM CronTriggers WHERE instance_id=$instanceId',
{ transaction, bind: { instanceId }, type: QueryTypes.SELECT },
);
await this.database.query(
'DELETE FROM CronStopRequests WHERE instance_id=$instanceId',
{ transaction, bind: { instanceId } },
);
if (!row) return settleLegacy ? settleLegacy(transaction) : false;
if (row.state !== 'running') return row.state === 'stopped';
const legacyCrond =
row.owner?.startsWith('crond:') &&
(!row.command_identity || row.owner === row.command_identity);
// A live scheduler drains its log and reports the actual exit. If the
// callback already arrived or its owner is gone, settle in this transaction.
const exit = await this.evidence.exitBeforeStop(row.id);
if (
exit.published ||
exit.unreadable ||
row.exit_pending ||
row.stop_exit_at !== null ||
!row.owner ||
legacyCrond ||
row.reason === 'restart'
) {
await this.evidence.recoverScriptSample(row.id, transaction);
await this.evidence.completeCommandExit(
row.id,
'stopped',
'cancelled',
row.exit_code,
transaction,
exit.canonical,
row.stop_exit_at ?? undefined,
undefined,
exit.recovered,
);
}
return true;
});
}
async queueCounts() {
await this.recoverSystemOwners();
const [row] = await this.database.query<{
triggers: number;
tasks: number;
}>(
"SELECT COUNT(*) AS triggers, COUNT(DISTINCT cron_id) AS tasks FROM CronTriggers WHERE state='queued' AND dequeued_at IS NULL",
{ type: QueryTypes.SELECT },
);
return row;
}
async startSystem(
id: string,
cronId: number,
owner: string,
commandIdentity = owner,
wrapper?: { rule: string; at: number; dispatch?: number },
) {
// crond only tells us when the wrapper starts. It supplies no scheduled or queued time.
return this.database.transaction(async (transaction) => {
const [task] = await this.database.query<{
allow_multiple_instances: number;
status: number;
pid: number | null;
isDisabled: number;
}>(
'SELECT allow_multiple_instances, status, pid, isDisabled FROM Crontabs WHERE id=$cronId',
{ bind: { cronId }, type: QueryTypes.SELECT, transaction },
);
if (!task || (task.isDisabled && !wrapper?.dispatch)) return false;
const now = Date.now();
const inserted = await this.database.query(
`INSERT INTO CronTriggers(id,cron_id,source,state,owner,command_identity,observed_at,system_rule,system_dispatch_at)
VALUES ($id,$cronId,'system','queued',$owner,$commandIdentity,$observed,$rule,$dispatch) ON CONFLICT(id) DO NOTHING`,
{
bind: {
id,
cronId,
owner,
commandIdentity,
observed: wrapper?.at ?? now,
rule: wrapper?.rule ?? null,
dispatch: wrapper?.dispatch ?? null,
},
type: QueryTypes.BULKUPDATE,
transaction,
},
);
if (!inserted) return false;
if (task.isDisabled) {
await this.finish(id, 'skipped', 'changed', null, transaction);
return false;
}
const multiple = task.allow_multiple_instances === 1;
const claimed =
(multiple || !hasLiveCronProcess(task.status, task.pid)) &&
(await this.start(id, now, multiple, transaction));
if (claimed && wrapper)
await this.database.query(
'UPDATE CronTriggers SET command_started_at=$now WHERE id=$id',
{ transaction, bind: { id, now } },
);
if (claimed && owner.startsWith('crond:')) {
await this.registerCommandInstance(
id,
cronId,
Number(commandIdentity.split(':')[1]),
commandIdentity,
now,
undefined,
transaction,
);
}
if (!claimed)
await this.finish(id, 'skipped', 'overlap', null, transaction);
return claimed;
});
}
async recoverSystemOwners(
cronId?: number,
transaction?: Transaction,
instanceId?: number,
) {
// HTTP may restart while crond children keep running. Match process birth, including across reboots.
const active = await this.database.query<{ id: string; owner: string }>(
`SELECT id,CASE WHEN owner LIKE 'crond:%' THEN owner ELSE COALESCE(command_identity,process_identity) END AS owner FROM CronTriggers WHERE state='running' AND (owner LIKE 'crond:%' OR reason='restart')
AND NOT EXISTS (SELECT 1 FROM CronStopRequests s WHERE s.instance_id=CronTriggers.instance_id AND s.targets IS NOT NULL)
AND ($cronId IS NULL OR cron_id=$cronId) AND ($instanceId IS NULL OR instance_id=$instanceId)`,
{
transaction,
bind: { cronId: cronId ?? null, instanceId: instanceId ?? null },
type: QueryTypes.SELECT,
},
);
let reclaimed = false;
for (const row of active) {
const pid = Number(row.owner.split(':')[1]);
try {
if (systemOwner(pid) === row.owner) continue;
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== 'ENOENT' && code !== 'ESRCH') throw error;
}
const close = async (tx: Transaction) => {
const [current] = await this.database.query<{
stop_requested: number;
exit_code: number | null;
stop_exit_at: number | null;
}>(
`SELECT stop_requested,exit_code,stop_exit_at FROM CronTriggers WHERE id=$id AND state='running'
AND NOT EXISTS (SELECT 1 FROM CronStopRequests s WHERE s.instance_id=CronTriggers.instance_id AND s.targets IS NOT NULL)`,
{ transaction: tx, bind: { id: row.id }, type: QueryTypes.SELECT },
);
if (!current) return;
await this.evidence.recoverScriptSample(row.id, tx);
await this.evidence.completeCommandExit(
row.id,
current.stop_requested ? 'stopped' : 'unknown',
current.stop_requested ? 'cancelled' : 'restart',
current.exit_code,
tx,
undefined,
current.stop_exit_at ?? undefined,
);
};
if (transaction) await close(transaction);
else await this.database.transaction(close);
reclaimed = true;
}
return reclaimed;
}
async interrupt(owner: string) {
await this.database.transaction(async (transaction) => {
await this.evidence.replayPublishedExits(transaction);
if (owner === 'http')
await this.database.query(
`INSERT OR IGNORE INTO CronStopRequests(instance_id,cron_id,pid)
SELECT instance_id,cron_id,CAST(substr(process_identity,7) AS INTEGER) FROM CronTriggers
WHERE state='running' AND stop_requested=1 AND instance_id IS NOT NULL AND process_identity LIKE 'crond:%'`,
{ transaction },
);
// No process was bound and its launch gate closed when the worker exited.
await this.database.query(
`UPDATE CronTriggers SET state='stopped',reason='cancelled',started_at=NULL,finished_at=$now
WHERE owner=$owner AND state='running' AND stop_requested=1 AND instance_id IS NULL AND command_identity IS NULL`,
{ transaction, bind: { owner, now: Date.now() } },
);
await this.database.query(
`UPDATE CronTriggers SET reason='restart',
state=CASE WHEN state='queued' THEN 'skipped' WHEN COALESCE(command_identity,process_identity) IS NOT NULL THEN 'running' ELSE 'unknown' END,
finished_at=CASE WHEN state='running' AND COALESCE(command_identity,process_identity) IS NOT NULL THEN NULL ELSE $now END
WHERE (owner=$owner OR (source IN ('system','legacy','client') AND owner IS NULL AND $owner='http')) AND state IN ('queued','running')`,
{ transaction, bind: { owner, now: Date.now() } },
);
await this.recoverSystemOwners(undefined, transaction);
});
}
}
+473
View File
@@ -0,0 +1,473 @@
import { LegacyClientAdapter } from './compatibility/legacyClient';
import type { readExit } from './settlement/exitReceipt.cjs';
export { slotId } from './identity';
import type { Crontab } from '../data/cron';
export { systemOwner } from './execution/cronProcess';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import type {
TriggerSource,
TriggerState,
VerifiedSupervisorExit,
} from './types';
import { TriggerLifecycle } from './execution/triggerLifecycle';
import { TriggerSettlement } from './settlement/triggerSettlement';
export type { Trigger, TriggerSource, TriggerState } from './types';
import { TriggerQueries } from './queries/triggerQueries';
export { installTriggerHistory } from './schema';
export class TriggerHistory {
constructor(private database: Sequelize) {}
// Compatibility callers share the same lifecycle and settlement transaction paths.
private readonly settlement: TriggerSettlement = new TriggerSettlement(
this.database,
{
finish: (...args) => this.finish(...args),
shouldStop: (id, transaction) => this.shouldStop(id, transaction),
},
);
private readonly lifecycle: TriggerLifecycle = new TriggerLifecycle(
this.database,
{
exitBeforeStop: (id) => this.exitBeforeStop(id),
completeCommandExit: (...args) => this.completeCommandExit(...args),
recoverScriptSample: (id, transaction) =>
this.recoverScriptSample(id, transaction),
replayPublishedExits: (transaction) =>
this.replayPublishedExits(transaction),
},
);
private readonly clients: LegacyClientAdapter = new LegacyClientAdapter(
this.database,
this.lifecycle,
this.settlement,
);
// No command or instance exists before the scheduler claims the trigger.
// A cancelled or already claimed row must keep the outcome recorded by its owner.
async skipQueued(id: string, reason: string, finishedAt: number) {
return this.lifecycle.skipQueued(id, reason, finishedAt);
}
async enqueue(
id: string,
cronId: number,
source: TriggerSource,
scheduledAt: number | null,
now = Date.now(),
transaction?: Transaction,
) {
return this.lifecycle.enqueue(
id,
cronId,
source,
scheduledAt,
now,
transaction,
);
}
// Serialize admission with the receipt so simultaneous timers and recovered
// workers agree on which scheduled run owns the slot. Edits invalidate old waits.
async enqueueUnlessPending(
id: string,
cronId: number,
source: 'node' | 'recovery',
scheduledAt: number,
now: number,
revision = 0,
) {
return this.lifecycle.enqueueUnlessPending(
id,
cronId,
source,
scheduledAt,
now,
revision,
);
}
async start(
id: string,
now = Date.now(),
multiple = false,
transaction?: Transaction,
) {
return this.lifecycle.start(id, now, multiple, transaction);
}
async claimManual(
id: string,
snapshot: Crontab,
token: string,
independent: boolean,
) {
return this.lifecycle.claimManual(id, snapshot, token, independent);
}
async finish(
id: string,
state: TriggerState,
reason: string | null = null,
code: number | null = null,
transaction?: Transaction,
finishedAt?: number,
) {
return this.lifecycle.finish(
id,
state,
reason,
code,
transaction,
finishedAt,
);
}
// A child close is an independent receipt when either Shell callback is lost.
async complete(
id: string,
state: TriggerState,
reason: string | null,
code: number | null,
finishedAt?: number,
report?: VerifiedSupervisorExit | 'legacy',
) {
return this.settlement.complete(
id,
state,
reason,
code,
finishedAt,
report,
);
}
private async completeCommandExit(
id: string,
state: TriggerState,
reason: string | null,
code: number | null,
transaction: Transaction,
receipt?: Awaited<ReturnType<typeof readExit>>,
finishedAt?: number,
report?: VerifiedSupervisorExit | 'legacy',
recoveredCopies?: Awaited<ReturnType<typeof readExit>>[],
) {
return this.settlement.completeCommandExit(
id,
state,
reason,
code,
transaction,
receipt,
finishedAt,
report,
recoveredCopies,
);
}
async retryPendingExits() {
return this.settlement.retryPendingExits();
}
async replayPublishedExits(transaction: Transaction) {
return this.settlement.replayPublishedExits(transaction);
}
// Old shell-only executions publish status and statistics independently.
// Either final receipt can settle that execution if the other was lost.
async recordShellResult(
id: string,
cronId: number,
code: number,
elapsedMs: number,
now: number,
finishedAt?: number,
) {
return this.clients.recordShellResult(
id,
cronId,
code,
elapsedMs,
now,
finishedAt,
);
}
private async recoverScriptSample(id: string, transaction: Transaction) {
return this.settlement.recoverScriptSample(id, transaction);
}
async isRunning(cronId: number, transaction: Transaction) {
return this.lifecycle.isRunning(cronId, transaction);
}
async shellReport(
id: string,
cronId: number,
system: boolean,
running: boolean,
log: string,
seconds: number,
exitCode?: number,
stopped = false,
transaction?: Transaction,
elapsedMs?: number,
finishedAt?: number,
): Promise<void | false> {
return this.clients.shellReport(
id,
cronId,
system,
running,
log,
seconds,
exitCode,
stopped,
transaction,
elapsedMs,
finishedAt,
);
}
async reportLegacy(
cronId: number,
running: boolean,
pid: number,
log: string,
seconds: number,
elapsed: number,
code?: number,
) {
return this.clients.reportLegacy(
cronId,
running,
pid,
log,
seconds,
elapsed,
code,
);
}
// Link the Shell instance and its trigger in the same IMMEDIATE write transaction.
async reportInstance(
id: string,
cronId: number,
running: boolean,
pid: number,
log: string,
seconds: number,
elapsed: number | undefined,
code?: number,
stopped = false,
finishedAt?: number,
) {
return this.clients.reportInstance(
id,
cronId,
running,
pid,
log,
seconds,
elapsed,
code,
stopped,
finishedAt,
);
}
async cancelQueued(ids: number[]) {
return this.lifecycle.cancelQueued(ids);
}
async cancelQueuedInTransaction(ids: number[], transaction: Transaction) {
return this.lifecycle.cancelQueuedInTransaction(ids, transaction);
}
async queueInstanceStop(
instanceId: number,
cronId: number,
pid: number,
transaction?: Transaction,
identity?: string,
) {
return this.lifecycle.queueInstanceStop(
instanceId,
cronId,
pid,
transaction,
identity,
);
}
async pendingStop(instanceId: number, transaction?: Transaction) {
return this.lifecycle.pendingStop(instanceId, transaction);
}
async pendingStopBatches() {
return this.lifecycle.pendingStopBatches();
}
async pendingStops() {
return this.lifecycle.pendingStops();
}
async forgetStop(
instanceId: number,
onEnded?: (tx: Transaction) => Promise<void>,
) {
return this.lifecycle.forgetStop(instanceId, onEnded);
}
async shouldStop(id: string, transaction?: Transaction) {
return this.lifecycle.shouldStop(id, transaction);
}
// The outer command can outlive any of its task wrappers.
async recordCommandStart(id: string, at: number) {
return this.lifecycle.recordCommandStart(id, at);
}
async bindCommand(id: string, pid: number, log?: string) {
return this.lifecycle.bindCommand(id, pid, log);
}
async activeCommands(ids: number[], transaction?: Transaction) {
return this.lifecycle.activeCommands(ids, transaction);
}
async instanceIdentity(instanceId: number) {
return this.lifecycle.instanceIdentity(instanceId);
}
async requestInstanceStop(
instanceId: number,
pid: number,
signalTree: () => void | Error,
targets?: string[],
) {
return this.lifecycle.requestInstanceStop(
instanceId,
pid,
signalTree,
targets,
);
}
private async exitBeforeStop(id: string) {
return this.settlement.exitBeforeStop(id);
}
async instanceStopRequested(instanceId: number, transaction?: Transaction) {
return this.lifecycle.instanceStopRequested(instanceId, transaction);
}
async stopVerifiedInstance(
instanceId: number,
settleLegacy?: (transaction: Transaction) => Promise<boolean>,
) {
return this.lifecycle.stopVerifiedInstance(instanceId, settleLegacy);
}
async queueCounts() {
return this.lifecycle.queueCounts();
}
async startSystem(
id: string,
cronId: number,
owner: string,
commandIdentity = owner,
wrapper?: { rule: string; at: number; dispatch?: number },
) {
return this.lifecycle.startSystem(
id,
cronId,
owner,
commandIdentity,
wrapper,
);
}
async recoverSystemOwners(
cronId?: number,
transaction?: Transaction,
instanceId?: number,
) {
return this.lifecycle.recoverSystemOwners(cronId, transaction, instanceId);
}
async interrupt(owner: string) {
return this.lifecycle.interrupt(owner);
}
async reconcileInstances() {
return this.clients.reconcileInstances();
}
private static expired = `state NOT IN ('queued','running') AND exit_pending IS NOT 1 AND finished_at IS NOT NULL AND observed_at < $cutoff AND finished_at < $cutoff
AND NOT EXISTS (SELECT 1 FROM RunningInstances i WHERE i.id=CronTriggers.instance_id AND i.status=0)`;
async countExpired(cutoff: number) {
const [row] = await this.database.query<{ count: number }>(
`SELECT COUNT(*) AS count FROM CronTriggers WHERE ${TriggerHistory.expired}`,
{ bind: { cutoff }, type: QueryTypes.SELECT },
);
return row.count;
}
async deleteExpired(cutoff: number, transaction: Transaction) {
// Once both histories have expired, old packets must not recreate their rows.
await this.database.query(
`INSERT INTO CronHistoryRetention(id,cutoff) VALUES (1,$cutoff)
ON CONFLICT(id) DO UPDATE SET cutoff=MAX(cutoff,excluded.cutoff)`,
{ transaction, bind: { cutoff } },
);
// The visible histories can expire before statistics. Keep just enough to
// credit a verified receipt to its task without recreating either history.
await this.database.query(
`INSERT OR IGNORE INTO CronPrunedUnknownRuns(trigger_id,cron_id,source,started_at,last_possible_day)
SELECT id,cron_id,source,started_at,date(finished_at/1000,'unixepoch','localtime') FROM CronTriggers
WHERE ${TriggerHistory.expired} AND state='unknown' AND reason='restart' AND counted=0 AND owner IS NOT NULL
AND started_at IS NOT NULL AND EXISTS (SELECT 1 FROM Crontabs WHERE id=CronTriggers.cron_id)
AND NOT EXISTS (SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=CronTriggers.id)
AND NOT EXISTS (SELECT 1 FROM CronStatRetention WHERE first_day>date(finished_at/1000,'unixepoch','localtime'))`,
{ bind: { cutoff }, transaction },
);
return this.database.query(
`DELETE FROM CronTriggers WHERE ${TriggerHistory.expired}`,
{ bind: { cutoff }, transaction, type: QueryTypes.BULKDELETE },
);
}
// Compatibility entry points for existing scheduler, API and extension callers.
async visibleTriggers(cronId: number, ids: string[]) {
return new TriggerQueries(this.database).visibleTriggers(cronId, ids);
}
async recent(
cronId: number,
offset: number,
limit = 25,
before?: { time: number; id: string },
) {
return new TriggerQueries(this.database).recent(
cronId,
offset,
limit,
before,
);
}
async metrics(since: number) {
return new TriggerQueries(this.database).metrics(since);
}
}
export function triggerHistory(): TriggerHistory {
return new TriggerHistory(require('../data/index').sequelize);
}
+28
View File
@@ -0,0 +1,28 @@
import { createHash } from 'crypto';
// The original scheduled CLI wire format maps to its existing persisted trigger ID.
export const executionIdPattern =
/^(?:client-|legacy-system:\d{1,12}:)[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
export function executionTriggerId(id: string) {
return id.replace('legacy-system:', 'system-cli-').replace(':', '-');
}
// A header lets upgraded clients keep the same identified body on older panels.
export function receiptFinishTime(header?: string) {
if (header && /^\d{1,13}$/.test(header)) {
const time = Number(header);
if (time > 0 && time <= Date.now()) return time;
}
}
// A scheduled slot keeps the same identity across retries and diagnostics.
export function slotId(
task: string,
ruleIndex: number,
rule: string,
time: number,
) {
return createHash('sha256')
.update(JSON.stringify([task, ruleIndex, rule, time]))
.digest('hex');
}
+166
View File
@@ -0,0 +1,166 @@
import { FindOptions } from 'sequelize';
import { Crontab, CrontabModel, CrontabStatus } from '../../data/cron';
import {
RunningInstanceModel,
InstanceStatus,
} from '../../data/runningInstance';
import config from '../../config/index';
import { fileExist } from '../../shared/utils';
import fs from 'fs/promises';
import path from 'path';
import { logAttributes } from './cronViews';
import { TriggerQueries } from './triggerQueries';
import { resolveLogPath } from '../../shared/logPath';
import { LogChunk, LogReadOptions, readLogChunk } from '../../shared/logReader';
import { t } from '../../shared/i18n';
export type CronLogOptions = LogReadOptions & {
previousPath?: string;
triggerId?: string;
instanceId?: number;
};
export type CronLogResult = LogChunk & {
status: string;
logPath?: string;
triggerId?: string;
};
// The caller supplies its existing task lookup so missing-task behavior stays
// compatible. Trigger and instance reads are scoped to the requested task.
export class CronLogReader {
constructor(
private loadCron: (
id: number,
attributes?: FindOptions['attributes'],
) => Promise<Crontab>,
) {}
public async log(
id: number,
options: CronLogOptions = {},
): Promise<CronLogResult> {
let doc: Pick<Crontab, 'status' | 'log_path' | 'log_name'> & {
logTriggerId?: string;
};
if (options.instanceId !== undefined) {
const instance = await RunningInstanceModel.findOne({
where: { id: options.instanceId, cron_id: id },
attributes: ['status', 'log_path'],
raw: true,
});
doc = {
status:
instance?.status === InstanceStatus.running
? CrontabStatus.running
: CrontabStatus.idle,
log_path: instance?.log_path,
};
} else if (options.triggerId) {
const [trigger] = await new TriggerQueries(
CrontabModel.sequelize!,
).visibleTriggers(id, [options.triggerId]);
// A retained viewer must never fall back to a sibling if its receipt was removed.
doc = {
logTriggerId: options.triggerId,
log_path: trigger?.log_path ?? undefined,
status:
trigger?.state === 'running'
? CrontabStatus.running
: trigger?.state === 'queued'
? CrontabStatus.queued
: CrontabStatus.idle,
};
} else {
doc = await this.loadCron(id, logAttributes);
}
const triggerId = doc.logTriggerId ?? undefined;
if (doc.log_name === '/dev/null' || doc.log_path === '/dev/null') {
return {
content: t('日志设置为忽略'),
status: 'ignored',
triggerId,
offset: 0,
nextOffset: 0,
total: 0,
truncated: false,
};
}
if (typeof doc.status === 'number' && doc.status === CrontabStatus.queued) {
// The next run has reserved a slot but has not published its own path yet.
return {
triggerId,
content: '',
status: 'running',
offset: 0,
nextOffset: 0,
total: 0,
truncated: false,
};
}
const absolutePath = doc.log_path
? resolveLogPath(config.logPath, doc.log_path)
: '';
const logFileExist = doc.log_path && (await fileExist(absolutePath));
if (logFileExist) {
const changed =
options.previousPath !== undefined &&
options.previousPath !== doc.log_path;
const chunk = await readLogChunk(
absolutePath,
changed
? { ...options, cursor: undefined, offset: 0, tail: !options.follow }
: options,
);
const isRunning =
typeof doc.status === 'number' &&
[CrontabStatus.running, CrontabStatus.queued].includes(doc.status);
return {
...chunk,
triggerId,
logPath: doc.log_path,
status: isRunning ? 'running' : 'completed',
};
} else {
const status =
typeof doc.status === 'number' &&
[CrontabStatus.queued, CrontabStatus.running].includes(doc.status)
? 'running'
: 'notFound';
return {
triggerId,
content: status === 'running' ? t('运行中...') : t('日志不存在...'),
status,
offset: 0,
nextOffset: 0,
total: 0,
truncated: false,
};
}
}
public async logs(id: number) {
const doc = await this.loadCron(id);
if (!doc || !doc.log_path || doc.log_path === '/dev/null') {
return [];
}
const relativeDir = path.dirname(`${doc.log_path}`);
const dir = path.dirname(resolveLogPath(config.logPath, doc.log_path));
const dirExist = await fileExist(dir);
if (dirExist) {
let files = await fs.readdir(dir);
return (
await Promise.all(
files.map(async (x) => ({
filename: x,
directory: relativeDir.replace(config.logPath, ''),
time: (await fs.lstat(`${dir}/${x}`)).birthtimeMs,
})),
)
).sort((a, b) => b.time - a.time);
} else {
return [];
}
}
}
+53
View File
@@ -0,0 +1,53 @@
import { upcomingSlots } from '../scheduling/cronScheduler';
type Definition = {
schedule?: string;
extra_schedules?: { schedule: string }[];
isDisabled?: number;
saved?: boolean;
};
const cache = new Map<string, { after: number; times: number[] }>();
export function previewSchedule(
schedule: string,
count: number,
now: number,
): number[] {
const key = JSON.stringify([
Intl.DateTimeFormat().resolvedOptions().timeZone,
schedule,
]);
const cached = cache.get(key);
if (cached && now >= cached.after) {
const future = cached.times.filter((time) => time > now);
if (future.length >= count) return future.slice(0, count);
}
const times = upcomingSlots(schedule, now, count);
if (cache.size >= 512) cache.delete(cache.keys().next().value!);
cache.set(key, { after: now, times });
return times;
}
export function withNextRun<T extends Definition>(cron: T) {
let nextRunTime: number | null = null;
if (
cron.schedule &&
!cron.isDisabled &&
cron.saved !== false &&
!cron.schedule.startsWith('@once') &&
!cron.schedule.startsWith('@boot')
) {
try {
const now = Date.now();
nextRunTime = Math.min(
...[
cron.schedule,
...(cron.extra_schedules || []).map((x) => x.schedule),
].map((rule) => previewSchedule(rule, 1, now)[0]),
);
} catch {
// Legacy invalid rows remain visible and editable.
}
}
return { ...cron, nextRunTime };
}
+36
View File
@@ -0,0 +1,36 @@
import { literal, FindOptions } from 'sequelize';
// Queue membership belongs to the trigger. Expose it for list/detail reads
// without writing it into the manual-run reservation used by the scheduler.
export const visibleStatus = literal(`CASE
WHEN EXISTS (SELECT 1 FROM CronTriggers WHERE cron_id = "Crontab"."id" AND state = 'running') THEN 0
WHEN "Crontab"."status" = 1 AND EXISTS (
SELECT 1 FROM CronTriggers WHERE cron_id = "Crontab"."id" AND state = 'queued'
) THEN 3
ELSE "Crontab"."status" END`);
export const visibleAttributes: FindOptions['attributes'] = {
exclude: ['status'],
include: [[visibleStatus, 'status']],
};
// Resolve status and log ownership in one SQLite snapshot. A running trigger
// can be visible before its shell has published the file for this execution.
const activeLogTrigger = `FROM CronTriggers WHERE cron_id = "Crontab"."id"
AND state = 'running' ORDER BY started_at DESC, rowid DESC LIMIT 1`;
export const logAttributes: FindOptions['attributes'] = [
'log_name',
[visibleStatus, 'status'],
[
literal(`CASE WHEN EXISTS (SELECT 1 ${activeLogTrigger})
THEN (SELECT log_path ${activeLogTrigger}) ELSE "Crontab"."log_path" END`),
'log_path',
],
[
literal(`CASE WHEN allow_multiple_instances = 1 THEN COALESCE(
(SELECT id ${activeLogTrigger}),
(SELECT id FROM CronTriggers WHERE cron_id = "Crontab"."id" AND state = 'queued'
ORDER BY observed_at DESC, rowid DESC LIMIT 1)
) END`),
'logTriggerId',
],
];
+127
View File
@@ -0,0 +1,127 @@
import { QueryTypes, Sequelize } from 'sequelize';
type Occupant = { id?: string; name: string };
export type Admission = {
queue: 'manual' | 'scheduled';
limit: number;
occupied: number;
holders: Occupant[];
};
// Each object belongs to exactly one execution pool in its owning process.
export class QueueOccupants {
private active = new Set<Occupant>();
private waiting = new Map<string, Sequelize>();
private writing = false;
private changed = false;
constructor(
private queue: Admission['queue'],
private limit: () => number,
private warn: (error: Error) => void,
) {}
watch(id: string, db: Sequelize) {
this.waiting.set(id, db);
this.refresh();
}
forget(id?: string) {
if (id) this.waiting.delete(id);
}
refresh() {
if (!this.waiting.size) return;
this.changed = true;
if (this.writing) return;
this.writing = true;
// Coalesce synchronous PQueue handoffs and keep SQLite writes in observation order.
void Promise.resolve().then(async () => {
try {
while (this.changed) {
this.changed = false;
const context = JSON.stringify(this.snapshot(this.limit()));
const groups = new Map<Sequelize, string[]>();
for (const [id, db] of this.waiting) {
const ids = groups.get(db);
if (ids) ids.push(id);
else groups.set(db, [id]);
}
for (const [db, ids] of groups) {
await db
.query(
`UPDATE CronTriggers SET queue_live_context=$context
WHERE state='queued' AND dequeued_at IS NULL AND id IN (SELECT value FROM json_each($ids))`,
{ bind: { context, ids: JSON.stringify(ids) } },
)
.catch(this.warn);
}
}
} finally {
this.writing = false;
}
});
}
admission(limit: number): Admission | undefined {
return this.active.size >= limit ? this.snapshot(limit) : undefined;
}
private snapshot(limit: number): Admission {
return {
queue: this.queue,
limit,
occupied: this.active.size,
holders: [...this.active].slice(0, 8),
};
}
track<T>(job: () => Promise<T>, occupant: Occupant, db?: Sequelize) {
return async () => {
this.forget(occupant.id);
this.active.add(occupant);
this.refresh();
if (occupant.id && db) {
void db
.query(
'UPDATE CronTriggers SET dequeued_at=$at,queue_live_context=NULL WHERE id=$id AND queued_at <= $at AND dequeued_at IS NULL',
{ bind: { id: occupant.id, at: Date.now() } },
)
.catch(this.warn);
}
try {
return await job();
} finally {
this.active.delete(occupant);
this.refresh();
}
};
}
}
export function recordQueueAdmission(
db: Sequelize,
id: string,
admission: Admission,
) {
return db.query(
'UPDATE CronTriggers SET queue_context=$context WHERE id=$id AND queued_at <= $at AND queue_context IS NULL',
{ bind: { id, at: Date.now(), context: JSON.stringify(admission) } },
);
}
export function oldestQueued(db: Sequelize) {
return db.query<{
id: string;
name: string;
source: string;
queued_at: number;
queue_context: string | null;
queue_live_context: string | null;
}>(
`SELECT t.id, COALESCE(NULLIF(c.name,''), c.command, '#' || t.cron_id) AS name, t.source,t.queued_at,t.queue_context,t.queue_live_context
FROM CronTriggers t LEFT JOIN Crontabs c ON c.id=t.cron_id
WHERE t.state='queued' AND t.dequeued_at IS NULL AND t.queued_at IS NOT NULL ORDER BY t.queued_at,t.id LIMIT 25`,
{ type: QueryTypes.SELECT },
);
}
+52
View File
@@ -0,0 +1,52 @@
import { createHash } from 'crypto';
export type AnomalyKind = 'missing' | 'skipped' | 'unconfirmed';
export interface ScheduleAnomaly {
task: number;
name?: string;
rule: string | null;
time: number | null;
source: 'node' | 'recovery' | 'system';
trigger: string | null;
observed: number | null;
reason: string | null;
logPath: string | null;
ruleIndex?: number;
}
// Keep only the requested page and the first page. If late evidence changes
// the result between requests, return the new first page instead of mixing scans.
export class AnomalyPage {
private hash = createHash('sha256');
private total = 0;
private first: ScheduleAnomaly[] = [];
private selected: ScheduleAnomaly[] = [];
static readonly size = 25;
constructor(
readonly kind: AnomalyKind,
private page: number,
private previous?: string,
) {}
add(row: ScheduleAnomaly) {
this.hash.update(JSON.stringify(row)).update('\n');
const page = Math.floor(this.total++ / AnomalyPage.size) + 1;
if (page === 1) this.first.push(row);
if (page === this.page) this.selected.push(row);
}
result() {
const revision = this.hash.digest('hex');
const changed = !!this.previous && revision !== this.previous;
const reset = changed || (this.page > 1 && !this.selected.length);
return {
rows: reset ? this.first : this.selected,
total: this.total,
page: reset ? 1 : this.page,
pageSize: AnomalyPage.size,
revision,
changed,
};
}
}
+79
View File
@@ -0,0 +1,79 @@
import { QueryTypes, Sequelize } from 'sequelize';
import type { Trigger } from '../types';
import { auditSchedule } from '../scheduling/scheduleAudit';
import { systemScheduleAudit } from '../scheduling/systemScheduleAudit';
// Keep uncertain exits unresolved in every history view. These projections
// describe evidence; they never settle a run or book statistics.
const historyColumns = `id,cron_id,source,state,queue_context,queue_live_context,dequeued_at,scheduled_at,queued_at,started_at,command_started_at,script_started_at,
CASE WHEN exit_pending=1 OR (state='unknown' AND reason='restart') THEN NULL ELSE finished_at END AS finished_at,
CASE WHEN exit_pending=1 THEN CASE WHEN EXISTS (SELECT 1 FROM CronExitObservations
WHERE trigger_id=CronTriggers.id LIMIT 1 OFFSET 1) OR EXISTS (SELECT 1 FROM CronBoundExitConflicts
WHERE trigger_id=CronTriggers.id) THEN 'exit_conflict' ELSE 'exit_pending' END ELSE reason END AS reason,
EXISTS(SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=CronTriggers.id) AS legacy_exit_booking,
CASE WHEN exit_pending=1 OR (state='unknown' AND reason='restart') THEN NULL ELSE exit_code END AS exit_code,log_path,observed_at`;
// Read-only execution history and diagnostics, independent of lifecycle writes.
export class TriggerQueries {
constructor(private database: Sequelize) {}
async visibleTriggers(cronId: number, ids: string[]) {
return this.database.query<Trigger & { observed_at: number }>(
`SELECT ${historyColumns} FROM CronTriggers WHERE cron_id=:cronId AND id IN (:ids)`,
{ replacements: { cronId, ids }, type: QueryTypes.SELECT },
);
}
async recent(
cronId: number,
offset: number,
limit = 25,
before?: { time: number; id: string },
) {
return this.database.query<Trigger & { observed_at: number }>(
`SELECT ${historyColumns}
FROM CronTriggers WHERE cron_id=$cronId
${before ? 'AND (observed_at,id) < ($time,$id)' : ''}
ORDER BY observed_at DESC,id DESC LIMIT $limit OFFSET $offset`,
{ bind: { cronId, offset, limit, ...before }, type: QueryTypes.SELECT },
);
}
async metrics(since: number) {
const [row] = await this.database.query<{
observed: number;
skipped: number;
samples: number;
waitP95: number | null;
onTime: number;
planned: number;
triggerOnTime: number;
triggerDeviationP95: number | null;
scriptSamples: number;
scriptStartP95: number | null;
scriptOnTime: number;
}>(
`WITH today AS (SELECT * FROM CronTriggers WHERE observed_at >= $since),
triggers AS (SELECT ABS(observed_at - scheduled_at) AS deviation FROM today WHERE scheduled_at IS NOT NULL),
scripts AS (SELECT script_started_at - scheduled_at AS delay FROM today
WHERE scheduled_at IS NOT NULL AND script_started_at >= scheduled_at),
waits AS (SELECT COALESCE(dequeued_at,started_at) - queued_at AS delay FROM today WHERE COALESCE(dequeued_at,started_at) >= queued_at)
SELECT COUNT(*) AS observed, COUNT(CASE WHEN state='skipped' THEN 1 END) AS skipped,
COUNT(scheduled_at) AS planned, COUNT(CASE WHEN started_at <= scheduled_at + 5000 THEN 1 END) AS onTime,
(SELECT COUNT(*) FROM triggers WHERE deviation <= 5000) AS triggerOnTime,
(SELECT deviation FROM triggers ORDER BY deviation LIMIT 1 OFFSET (SELECT MAX(0,(95*COUNT(*)+99)/100-1) FROM triggers)) AS triggerDeviationP95,
(SELECT COUNT(*) FROM scripts) AS scriptSamples,
(SELECT COUNT(*) FROM scripts WHERE delay <= 5000) AS scriptOnTime,
(SELECT delay FROM scripts ORDER BY delay LIMIT 1 OFFSET (SELECT MAX(0,(95*COUNT(*)+99)/100-1) FROM scripts)) AS scriptStartP95,
(SELECT COUNT(*) FROM waits) AS samples,
(SELECT delay FROM waits ORDER BY delay LIMIT 1 OFFSET (SELECT MAX(0, (95*COUNT(*)+99)/100-1) FROM waits)) AS waitP95
FROM today`,
{ bind: { since }, type: QueryTypes.SELECT },
);
return {
...row,
audit: await auditSchedule(this.database, since),
systemAudit: await systemScheduleAudit(this.database, since),
};
}
}
+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,
};
}
+171
View File
@@ -0,0 +1,171 @@
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
export async function installTriggerHistory(
database: Sequelize,
transaction: Transaction,
) {
const conflictTable = `CREATE TABLE IF NOT EXISTS CronBoundExitConflicts (
trigger_id TEXT NOT NULL, outcome TEXT NOT NULL, finished_at INTEGER NOT NULL,
PRIMARY KEY(trigger_id,outcome,finished_at)) WITHOUT ROWID`;
const statements = [
`CREATE TABLE IF NOT EXISTS CronPlanSwitches (seq INTEGER PRIMARY KEY, token TEXT UNIQUE NOT NULL,
staged_at INTEGER NOT NULL, first_at INTEGER, last_at INTEGER)`,
'CREATE TABLE IF NOT EXISTS CronPlanCoverage (id INTEGER PRIMARY KEY CHECK(id=1), since INTEGER NOT NULL)',
`CREATE TABLE IF NOT EXISTS CronPlanRules (
cron_id TEXT NOT NULL, rule_index INTEGER NOT NULL, schedule TEXT NOT NULL, zone TEXT NOT NULL,
since INTEGER NOT NULL, until INTEGER)`,
'CREATE UNIQUE INDEX IF NOT EXISTS cron_plan_active ON CronPlanRules(cron_id,rule_index) WHERE until IS NULL',
`CREATE TABLE IF NOT EXISTS CronTriggers (
id TEXT PRIMARY KEY, cron_id INTEGER NOT NULL, source TEXT NOT NULL, state TEXT NOT NULL,
scheduled_at INTEGER, queued_at INTEGER, started_at INTEGER, finished_at INTEGER,
reason TEXT, exit_code INTEGER, log_path TEXT, counted INTEGER NOT NULL DEFAULT 0,
owner TEXT, observed_at INTEGER NOT NULL)`,
`CREATE TABLE IF NOT EXISTS CronShellBindings (
receipt TEXT PRIMARY KEY, trigger_id TEXT NOT NULL REFERENCES CronTriggers(id) ON DELETE CASCADE)`,
'CREATE INDEX IF NOT EXISTS cron_shell_binding_trigger ON CronShellBindings(trigger_id)',
`CREATE TABLE IF NOT EXISTS CronExitObservations (
trigger_id TEXT NOT NULL REFERENCES CronTriggers(id) ON DELETE CASCADE,
outcome TEXT NOT NULL, finished_at INTEGER NOT NULL,
PRIMARY KEY(trigger_id,outcome,finished_at)) WITHOUT ROWID`,
`CREATE TABLE IF NOT EXISTS CronLegacyExitBookings (
trigger_id TEXT PRIMARY KEY, cron_id INTEGER NOT NULL, source TEXT NOT NULL, started_at INTEGER NOT NULL,
finished_at INTEGER NOT NULL, outcome TEXT NOT NULL, day TEXT NOT NULL, stopped INTEGER NOT NULL DEFAULT 0,
stat_id INTEGER REFERENCES CrontabStats(id) ON DELETE SET NULL, disputed INTEGER NOT NULL DEFAULT 0)`,
`CREATE TABLE IF NOT EXISTS CronPrunedUnknownRuns (
trigger_id TEXT PRIMARY KEY, cron_id INTEGER NOT NULL REFERENCES Crontabs(id) ON DELETE CASCADE,
source TEXT NOT NULL, started_at INTEGER NOT NULL, last_possible_day TEXT NOT NULL) WITHOUT ROWID`,
'CREATE INDEX IF NOT EXISTS cron_pruned_unknown_day ON CronPrunedUnknownRuns(last_possible_day)',
`CREATE TABLE IF NOT EXISTS CronSystemPlans (id INTEGER PRIMARY KEY, staged INTEGER NOT NULL, confirmed INTEGER, zone TEXT NOT NULL, rules TEXT NOT NULL)`,
conflictTable,
`CREATE TABLE IF NOT EXISTS CronUnmatchedBoundExits (
trigger_id TEXT PRIMARY KEY, outcome TEXT NOT NULL, finished_at INTEGER NOT NULL) WITHOUT ROWID`,
'CREATE INDEX IF NOT EXISTS cron_legacy_booking_stat ON CronLegacyExitBookings(stat_id) WHERE stat_id IS NOT NULL',
'CREATE TABLE IF NOT EXISTS CronStatRetention (id INTEGER PRIMARY KEY CHECK(id=1), first_day TEXT NOT NULL)',
'CREATE TABLE IF NOT EXISTS CronHistoryRetention (id INTEGER PRIMARY KEY CHECK(id=1), cutoff INTEGER NOT NULL)',
`CREATE TABLE IF NOT EXISTS CronStopBatches (
request_id TEXT PRIMARY KEY, cron_ids TEXT NOT NULL, snapshot TEXT)`,
'CREATE INDEX IF NOT EXISTS cron_stop_batch_pending ON CronStopBatches(request_id) WHERE snapshot IS NOT NULL',
`CREATE TABLE IF NOT EXISTS CronStopRequests (
instance_id INTEGER PRIMARY KEY, cron_id INTEGER NOT NULL, pid INTEGER NOT NULL, targets TEXT, signalled INTEGER NOT NULL DEFAULT 0)`,
'CREATE INDEX IF NOT EXISTS cron_trigger_recent ON CronTriggers(cron_id, observed_at DESC)',
"CREATE INDEX IF NOT EXISTS cron_trigger_running_task ON CronTriggers(cron_id) WHERE state='running'",
"CREATE INDEX IF NOT EXISTS cron_trigger_queued_task ON CronTriggers(cron_id) WHERE state='queued'",
'CREATE INDEX IF NOT EXISTS cron_trigger_day ON CronTriggers(observed_at)',
'CREATE INDEX IF NOT EXISTS cron_trigger_slot ON CronTriggers(scheduled_at) WHERE scheduled_at IS NOT NULL',
'CREATE INDEX IF NOT EXISTS cron_trigger_active ON CronTriggers(source, state) WHERE finished_at IS NULL',
];
for (const sql of statements) await database.query(sql, { transaction });
const planFields = await database.query<{ name: string }>(
'PRAGMA table_info(CronPlanRules)',
{ transaction, type: QueryTypes.SELECT },
);
for (const column of ['opened_by', 'closed_by']) {
if (!planFields.some((field) => field.name === column))
await database.query(
`ALTER TABLE CronPlanRules ADD COLUMN ${column} TEXT`,
{ transaction },
);
}
const conflictFields = await database.query<{ name: string }>(
'PRAGMA table_info(CronBoundExitConflicts)',
{ transaction, type: QueryTypes.SELECT },
);
if (conflictFields.some((field) => field.name === 'other_outcome')) {
await database.query(
'ALTER TABLE CronBoundExitConflicts RENAME TO CronBoundExitConflictPairs',
{ transaction },
);
await database.query(conflictTable, { transaction });
await database.query(
`INSERT INTO CronBoundExitConflicts(trigger_id,outcome,finished_at)
SELECT trigger_id,outcome,finished_at FROM CronBoundExitConflictPairs UNION
SELECT trigger_id,other_outcome,other_finished_at FROM CronBoundExitConflictPairs`,
{ transaction },
);
await database.query('DROP TABLE CronBoundExitConflictPairs', {
transaction,
});
}
const bookingFields = await database.query<{ name: string }>(
'PRAGMA table_info(CronLegacyExitBookings)',
{ transaction, type: QueryTypes.SELECT },
);
if (!bookingFields.some((field) => field.name === 'bound'))
await database.query(
'ALTER TABLE CronLegacyExitBookings ADD COLUMN bound INTEGER NOT NULL DEFAULT 0',
{ transaction },
);
const batchFields = await database.query<{ name: string }>(
'PRAGMA table_info(CronStopBatches)',
{ transaction, type: QueryTypes.SELECT },
);
if (!batchFields.some((column) => column.name === 'status_code'))
await database.query(
'ALTER TABLE CronStopBatches ADD COLUMN status_code INTEGER NOT NULL DEFAULT 200',
{ transaction },
);
const stopFields = await database.query<{ name: string }>(
'PRAGMA table_info(CronStopRequests)',
{ transaction, type: QueryTypes.SELECT },
);
if (!stopFields.some((column) => column.name === 'signalled_at'))
await database.query(
'ALTER TABLE CronStopRequests ADD COLUMN signalled_at INTEGER',
{ transaction },
);
if (!stopFields.some((column) => column.name === 'root_identity'))
await database.query(
'ALTER TABLE CronStopRequests ADD COLUMN root_identity TEXT',
{ transaction },
);
if (!stopFields.some((column) => column.name === 'namespace_owner'))
await database.query(
'ALTER TABLE CronStopRequests ADD COLUMN namespace_owner TEXT',
{ transaction },
);
const fields = await database.query<{ name: string }>(
'PRAGMA table_info(CronTriggers)',
{ transaction, type: QueryTypes.SELECT },
);
for (const [column, type] of [
['queue_live_context', 'TEXT'],
['dequeued_at', 'INTEGER'],
['system_dispatch_at', 'INTEGER'],
['queue_context', 'TEXT'],
['system_rule', 'TEXT'],
['command_started_at', 'INTEGER'],
['instance_id', 'INTEGER'],
['script_started_at', 'INTEGER'],
['stop_requested', 'INTEGER'],
['process_identity', 'TEXT'],
['command_identity', 'TEXT'],
['stop_exit_at', 'INTEGER'],
['stop_exit_verified', 'INTEGER'],
['exit_pending', 'INTEGER'],
]) {
if (!fields.some((field) => field.name === column))
await database.query(
`ALTER TABLE CronTriggers ADD COLUMN ${column} ${type}`,
{ transaction },
);
}
await database.query(
`CREATE TRIGGER IF NOT EXISTS cron_exit_observations_settled AFTER UPDATE OF counted ON CronTriggers
WHEN OLD.exit_pending=1 AND OLD.counted=0 AND NEW.counted=1 BEGIN
DELETE FROM CronExitObservations WHERE trigger_id=NEW.id;
END`,
{ transaction },
);
await database.query(
"CREATE INDEX IF NOT EXISTS cron_system_dispatch ON CronTriggers(COALESCE(system_dispatch_at,observed_at)) WHERE source='system'",
{ transaction },
);
await database.query(
'CREATE INDEX IF NOT EXISTS cron_trigger_pending_exit ON CronTriggers(id) WHERE exit_pending=1',
{ transaction },
);
await database.query(
'CREATE UNIQUE INDEX IF NOT EXISTS cron_trigger_instance ON CronTriggers(instance_id) WHERE instance_id IS NOT NULL',
{ transaction },
);
}
+108
View File
@@ -0,0 +1,108 @@
import dayjs from 'dayjs';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
// Hold the receipt claim and the daily increment in the same write transaction.
export async function recordCronResult(
database: Sequelize,
cronId: number,
_code: number,
elapsedMs: number,
finishedAt: number,
triggerId: string,
transaction?: Transaction,
): Promise<void> {
if (!triggerId) throw new Error('Execution identity required');
if (!transaction) {
return database.transaction((tx) =>
recordCronResult(
database,
cronId,
_code,
elapsedMs,
finishedAt,
triggerId,
tx,
),
);
}
const bind = { ref: cronId, id: triggerId };
const claimed = await database.query(
"UPDATE CronTriggers SET counted=1,exit_pending=NULL WHERE cron_id=$ref AND id=$id AND counted=0 AND started_at IS NOT NULL AND state IN ('finished','failed','stopped')",
{ bind, type: QueryTypes.BULKUPDATE, transaction },
);
if (!claimed) {
const rows = await database.query(
'SELECT 1 FROM CronTriggers WHERE cron_id=$ref AND id=$id',
{ bind, type: QueryTypes.SELECT, transaction },
);
if (!rows.length) throw new Error('Unknown trigger');
return;
}
const [receipt] = await database.query<{
state: string;
finished_at: number;
reversible: number;
}>(
`SELECT state,finished_at,EXISTS(SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=$id) AS reversible
FROM CronTriggers WHERE cron_id=$ref AND id=$id`,
{ bind, type: QueryTypes.SELECT, transaction },
);
const day = dayjs(receipt.finished_at ?? finishedAt).format('YYYY-MM-DD');
await addDailyExit(
database,
cronId,
day,
receipt.state,
elapsedMs,
Boolean(receipt.reversible),
transaction,
);
if (receipt.reversible) {
await database.query(
`UPDATE CronLegacyExitBookings SET stopped=$stopped,
stat_id=(SELECT id FROM CrontabStats WHERE ref_id=$ref AND date=$day
AND NOT EXISTS (SELECT 1 FROM CronStatRetention WHERE id=1 AND first_day>$day))
WHERE trigger_id=$id`,
{
bind: { ...bind, day, stopped: Number(receipt.state === 'stopped') },
transaction,
},
);
}
}
export async function addDailyExit(
database: Sequelize,
cronId: number,
day: string,
state: string,
elapsedMs: number,
reversible: boolean,
transaction: Transaction,
) {
await database.query(
`INSERT INTO "CrontabStats"
(ref_id, date, run_count, success_count, fail_count, total_time, max_time, fixed_max_time, createdAt, updatedAt)
SELECT $id, $date, 1, $success, $fail, $elapsed, $elapsed, $fixedMax, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
WHERE NOT EXISTS (SELECT 1 FROM CronStatRetention WHERE id=1 AND first_day>$date)
ON CONFLICT(ref_id, date) DO UPDATE SET
run_count = COALESCE(run_count, 0) + 1,
success_count = COALESCE(success_count, 0) + excluded.success_count,
fail_count = COALESCE(fail_count, 0) + excluded.fail_count,
total_time = COALESCE(total_time, 0) + excluded.total_time,
max_time = MAX(COALESCE(max_time, 0), excluded.max_time),
fixed_max_time = MAX(COALESCE(fixed_max_time,max_time,0),excluded.fixed_max_time),
updatedAt = excluded.updatedAt`,
{
transaction,
bind: {
id: cronId,
date: day,
fixedMax: reversible ? 0 : elapsedMs,
success: Number(state === 'finished'),
fail: Number(state === 'failed'),
elapsed: elapsedMs,
},
},
);
}
+519
View File
@@ -0,0 +1,519 @@
// Keep the command's actual exit available until its SQLite transaction commits.
const fs = require('node:fs');
const path = require('node:path');
const { createHash, randomUUID } = require('node:crypto');
const idPattern = /^[a-z0-9-]{1,120}$/;
// A full data volume can still have room for a directory entry. In this format
// the empty file publishes the tuple atomically, including its execution-bound
// checksum. Keep the encoded name when moving it into a collector-private slot.
const metadataName =
/^\.pending\.([a-z0-9-]{1,120})\.full-(\d{1,3}|SIG[A-Z0-9]+)-(\d{1,16})-([0-9a-f]{64})-([a-zA-Z0-9_]+)$/;
// The digest only guards disposal of legacy bytes. It cannot establish an exit.
const legacyCapture =
/^\.pending\.([a-z0-9-]{1,120})\.l-([0-9a-f]{32})-[0-9a-f]{24}$/;
const claimName = /^\.claim(-bound)?\.([a-z0-9-]{1,120})\.[a-zA-Z0-9]{6}$/;
function metadataReceipt(file) {
const name = path.basename(file);
return metadataName.exec(
name === '.pending.claimed' ? path.basename(path.dirname(file)) : name,
);
}
function storageFull(error) {
const codes = [error?.code, error?.original?.code, error?.parent?.code];
if (codes.some((code) => ['ENOSPC', 'EDQUOT', 'SQLITE_FULL'].includes(code)))
return true;
const directory = receiptDirectory();
if (directory && codes.includes('SQLITE_CANTOPEN')) {
// SQLite maps a failed journal creation to CANTOPEN even when the kernel
// reported ENOSPC. Other open failures keep their normal error semantics.
try {
const capacity = fs.statfsSync(path.dirname(directory));
return (
capacity.bavail === 0 || (capacity.files > 0 && capacity.ffree === 0)
);
} catch {
return false;
}
}
return false;
}
function receiptDirectory() {
const data =
process.env.QL_DATA_DIR ||
(process.env.QL_DIR && path.join(process.env.QL_DIR, 'data'));
if (data) return path.join(data, 'db', 'cron-exits');
}
function receiptPath(id) {
const directory = receiptDirectory();
if (directory && typeof id === 'string' && idPattern.test(id))
return path.join(directory, id);
}
async function listReceiptFiles(directory, prefix) {
if (!directory) return [];
try {
const entries = await fs.promises.readdir(directory, {
withFileTypes: true,
});
const files = [];
for (const entry of entries) {
if (!entry.isFile() || !entry.name.startsWith(prefix)) continue;
const id = entry.name.slice(prefix.length);
if (idPattern.test(id))
files.push({ id, file: path.join(directory, entry.name) });
}
return files;
} catch (error) {
if (error.code === 'ENOENT') return [];
throw error;
}
}
async function publishedExits() {
return (await listReceiptFiles(receiptDirectory(), '')).map(
(entry) => entry.id,
);
}
// flock attaches to the open file description. The child inherits fd 3 and
// exits immediately. Closing the panel's handle (including on SIGKILL)
// releases the lock without leaving a lock file on a full volume.
async function lockClaim(handle, shared) {
const run = (program, args) =>
new Promise((resolve, reject) => {
const child = require('node:child_process').spawn(program, args, {
stdio: ['ignore', 'ignore', 'ignore', handle.fd],
});
child.once('error', reject);
child.once('exit', (code, signal) => {
if (code === 0 || code === 1) resolve(code === 0);
else
reject(
new Error(`Receipt directory lock failed (${signal || code})`),
);
});
});
try {
return await run('flock', ['-n', shared ? '-s' : '-x', '3']);
} catch (error) {
if (error.code !== 'ENOENT') throw error;
// Python is also shipped with the task supervisor on minimal Linux images.
const program =
'import fcntl,sys\ntry: fcntl.flock(3, fcntl.LOCK_NB | fcntl.LOCK_' +
(shared ? 'SH' : 'EX') +
')\nexcept BlockingIOError: sys.exit(1)';
return run('python3', ['-c', program]);
}
}
// Move the current directory entry to a fresh, recoverable name outside the
// reusable claim directory. A writer can replace that entry without flock.
// Only the bytes actually captured by this attempt authorize its final unlink.
/** @param {string} id @param {string} file @param {{outcome: string, time: number}} [booked] */
async function retireLegacyFile(id, file, booked) {
const directory = receiptDirectory();
const sourceDir = path.dirname(file);
const slot = path.basename(file);
const bound =
/^\.(pending|published)\./.test(slot) && !legacyCapture.test(slot);
const metadata = metadataReceipt(file);
const parent = claimName.exec(path.basename(sourceDir));
const privateSlot =
path.dirname(sourceDir) === directory &&
((parent?.[2] === id &&
slot === (parent[1] ? '.pending.claimed' : 'receipt')) ||
(metadata?.[1] === id && slot === '.pending.claimed'));
if (!directory || !idPattern.test(id)) return;
const dbDir = path.dirname(directory);
const localBin = path.join(directory, '.reclaim');
const fromBin = sourceDir === dbDir || sourceDir === localBin;
if (
sourceDir !== directory &&
!privateSlot &&
!(fromBin && captureId(slot) === id)
)
return;
const matches = (exit) =>
exit &&
!exit.namedExit &&
(exit.version === 1
? booked &&
exit.time === booked.time &&
(exit.signal ?? String(exit.code)) === booked.outcome
: !bound);
let handle, binHandle;
try {
if (
(privateSlot || sourceDir === localBin) &&
process.platform === 'linux'
) {
handle = await fs.promises.open(
sourceDir,
fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,
);
if (privateSlot && !(await lockClaim(handle, true))) return;
}
const source = handle ? `/proc/self/fd/${handle.fd}/${slot}` : file;
// A canonical publication may only be readable after the move. For a
// recovered copy, first avoid moving an unsettled witness on every scan.
const previous = await readExit(id, source, file);
if (slot !== id && !matches(previous)) return;
const nonce = randomUUID();
let name;
if (metadata) {
name =
metadata[0].slice(0, -metadata[5].length) +
'r_' +
nonce.replace(/-/g, '').slice(0, 16);
} else if (bound || !previous || previous.version === 1) {
name = `.pending.${id}.r-${nonce}`;
} else {
const digest = exitChecksum(
id,
previous.code,
previous.signal,
previous.time,
).slice(0, 32);
name = `.pending.${id}.l-${digest}-${nonce
.replace(/-/g, '')
.slice(0, 24)}`;
}
// The database directory is outside the writers' receipt namespace and
// already exists even at zero free inodes. A separately mounted journal
// requires a disposal directory on its own filesystem.
let bin = sourceDir === localBin ? localBin : dbDir;
const pinBin = async () => {
binHandle = await fs.promises.open(
localBin,
fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,
);
return process.platform === 'linux'
? `/proc/self/fd/${binHandle.fd}/${name}`
: path.join(localBin, name);
};
let captured = path.join(bin, name);
if (bin === localBin)
captured = handle
? path.join(path.dirname(source), name)
: await pinBin();
try {
await fs.promises.rename(source, captured);
} catch (error) {
if (error.code !== 'EXDEV' || bin === localBin) throw error;
await fs.promises.mkdir(localBin, { mode: 0o700, recursive: true });
bin = localBin;
captured = await pinBin();
await fs.promises.rename(source, captured);
}
const actual = await readExit(id, captured, path.join(bin, name));
// An unreadable source offers no authority to discard unbound bytes.
const sameExit =
previous &&
actual &&
actual.version === previous.version &&
actual.code === previous.code &&
actual.signal === previous.signal &&
actual.time === previous.time;
if (matches(actual) && (sameExit || (!previous && actual.version === 1))) {
await fs.promises.unlink(captured);
} else if (actual !== undefined) {
// A differing, torn or unreadable file is evidence for another pass.
// Persist its new directory entry before releasing the original directory.
if (binHandle) await binHandle.sync();
else if (bin !== sourceDir || !handle) syncDirectory(bin);
if (bin === localBin) syncDirectory(directory);
if (handle) await handle.sync();
else if (sourceDir !== bin) syncDirectory(sourceDir);
}
} catch (error) {
if (error.code !== 'ENOENT') throw error;
} finally {
if (binHandle) await binHandle.close();
if (handle) await handle.close();
if (privateSlot) await fs.promises.rmdir(sourceDir).catch(() => {});
}
}
function captureId(name) {
const marker = metadataName.exec(name);
if (marker && /^r_[0-9a-f]{16}$/.test(marker[5])) return marker[1];
const match =
legacyCapture.exec(name) ??
/^\.pending\.([a-z0-9-]{1,120})\.r-[0-9a-f-]{36}$/.exec(name);
return match?.[1];
}
async function receiptEntries(directory) {
try {
return await fs.promises.readdir(directory, { withFileTypes: true });
} catch (error) {
if (error.code === 'ENOENT') return [];
throw error;
}
}
async function retiringExits() {
const dir = receiptDirectory();
if (!dir) return [];
const files = [];
const bins = [path.dirname(dir)];
for (const entry of await receiptEntries(dir)) {
if (entry.isDirectory() && entry.name === '.reclaim') {
bins.push(path.join(dir, entry.name));
continue;
}
const claim = claimName.exec(entry.name);
const metadata = metadataName.exec(entry.name);
if ((claim || metadata) && entry.isDirectory()) {
const directory = path.join(dir, entry.name);
try {
await fs.promises.rmdir(directory);
continue;
} catch (error) {
if (error.code === 'ENOENT') continue;
}
files.push({
id: metadata ? metadata[1] : claim[2],
file: path.join(
directory,
metadata || claim[1] ? '.pending.claimed' : 'receipt',
),
});
continue;
}
const match =
metadata ??
/^\.(?:retiring|collecting)\.([a-z0-9-]{1,120})\.[0-9a-f-]{36}$/.exec(
entry.name,
) ??
/^\.pending\.([a-z0-9-]{1,120})\.[a-z0-9_-]{1,64}$/.exec(entry.name) ??
/^\.published\.([a-z0-9-]{1,120})\.[0-9a-f]{64}$/.exec(entry.name);
if (entry.isFile() && match)
files.push({ id: match[1], file: path.join(dir, entry.name) });
}
for (const bin of bins) {
for (const entry of await receiptEntries(bin)) {
const id = entry.isFile() && captureId(entry.name);
if (id) files.push({ id, file: path.join(bin, entry.name) });
}
}
return files;
}
async function publishedScriptStarts() {
const directory = process.env.QL_DIR && path.join(process.env.QL_DIR, '.tmp');
try {
return await listReceiptFiles(directory, 'cron-start-');
} catch {
// Optional entry instrumentation must not prevent exit recovery.
return [];
}
}
function validExit(code, signal, time) {
return (
Number.isSafeInteger(time) &&
time > 0 &&
Number.isFinite(new Date(time).getTime()) &&
((Number.isInteger(code) && code >= 0 && code <= 255 && signal === null) ||
(code === null &&
typeof signal === 'string' &&
/^SIG[A-Z0-9]+$/.test(signal)))
);
}
// The Python supervisor uses the same compact JSON array of ASCII values.
function exitChecksum(id, code, signal, time) {
return createHash('sha256')
.update(JSON.stringify([id, code, signal, time]))
.digest('hex');
}
function syncDirectory(directory) {
const fd = fs.openSync(
directory,
fs.constants.O_RDONLY | fs.constants.O_DIRECTORY,
);
try {
fs.fsyncSync(fd);
} finally {
fs.closeSync(fd);
}
}
function writeExit(id, code, signal, time) {
if (!validExit(code, signal, time))
throw new TypeError('Invalid command exit receipt');
const file = receiptPath(id);
if (!file) return;
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
const checksum = exitChecksum(id, code, signal, time);
const receipt = JSON.stringify({ code, signal, time, version: 1, checksum });
// Creation is the first durable observation. No data block is needed for
// this witness. Keep the regular JSON publication for earlier readers.
const directory = path.dirname(file);
const prefix = '.pending.' + id + '.';
const marker =
prefix + 'full-' + (signal ?? code) + '-' + time + '-' + checksum + '-';
const publish = (name, content) => {
for (;;) {
const target = path.join(
directory,
name + randomUUID().replace(/-/g, '').slice(0, 16),
);
try {
fs.writeFileSync(target, content, {
flag: 'wx',
mode: 0o600,
flush: Boolean(content),
});
return target;
} catch (error) {
if (error.code !== 'EEXIST') throw error;
}
}
};
publish(marker, '');
// ext4 journals the empty inode and directory entry together. Also fence the
// directory's own entry: another publisher may just have created it.
syncDirectory(directory);
syncDirectory(path.dirname(directory));
try {
if (fs.statfsSync(directory).bavail === 0) return;
const source = publish(marker, receipt);
try {
fs.linkSync(source, file);
} catch (error) {
if (error.code === 'ENOENT') return;
if (error.code !== 'EEXIST') throw error;
// A panel from before metadata receipts can still discover this retry.
for (;;) {
try {
fs.linkSync(source, path.join(directory, prefix + randomUUID()));
break;
} catch (linkError) {
if (linkError.code === 'ENOENT') break;
if (linkError.code !== 'EEXIST') throw linkError;
}
}
}
// Older panels find the JSON only through this newly created link.
syncDirectory(directory);
} catch (error) {
if (!storageFull(error)) throw error;
}
}
function parseExit(id, value) {
if (!value || !validExit(value.code, value.signal, value.time)) return null;
const { code, signal, time, checksum, version } = value;
if (version !== undefined || checksum !== undefined) {
if (version !== 1 || checksum !== exitChecksum(id, code, signal, time))
return null;
} else if (Object.keys(value).length !== 3) {
return null;
}
return { code, signal, time, version };
}
// undefined means no publication. null means a result cannot yet be trusted.
async function readExit(id, file = receiptPath(id), publication = file) {
if (!file) return;
try {
const handle = await fs.promises.open(
file,
fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW,
);
try {
// Bound CPU and memory even if the damaged file is growing.
const buffer = Buffer.alloc(1025);
let size = 0;
while (size < buffer.length) {
const { bytesRead } = await handle.read(
buffer,
size,
buffer.length - size,
null,
);
if (!bytesRead) break;
size += bytesRead;
}
if (size === buffer.length) return null;
const metadata = metadataReceipt(publication);
const bytes = buffer.toString('utf8', 0, size);
let namedExit;
if (metadata && metadata[1] === id && (await handle.stat()).isFile()) {
const [, , outcome, end, checksum] = metadata;
const signal = outcome.startsWith('SIG') ? outcome : null;
const value = {
code: signal ? null : Number(outcome),
signal,
time: Number(end),
version: 1,
checksum,
};
// Both current publishers serialize in this order. Accept a torn body
// only when every byte matches the tuple independently published by
// the filename. Validate replacement files on their own bytes below.
namedExit = parseExit(id, value);
const json = JSON.stringify(value);
if (json.startsWith(bytes)) {
return namedExit && { ...namedExit, file, namedExit: undefined };
}
}
const exit = parseExit(id, JSON.parse(bytes));
const guard = legacyCapture.exec(path.basename(publication));
if (
guard &&
exit &&
exit.version !== 1 &&
(guard[1] !== id ||
guard[2] !==
exitChecksum(id, exit.code, exit.signal, exit.time).slice(0, 32))
)
return null;
const conflictingName =
exit?.version === 1 &&
namedExit &&
(exit.time !== namedExit.time ||
exit.code !== namedExit.code ||
exit.signal !== namedExit.signal);
return (
exit && {
...exit,
file,
namedExit: conflictingName ? namedExit : undefined,
}
);
} finally {
await handle.close();
}
} catch (error) {
if (error.code === 'ENOENT') return;
if (error.code || error instanceof SyntaxError) return null;
throw error;
}
}
module.exports = {
parseExit,
isLegacyCapture: (file) => legacyCapture.test(path.basename(file)),
isMetadataReceipt: (file) => Boolean(metadataReceipt(file)),
receiptPath,
publishedExits,
publishedScriptStarts,
readExit,
writeExit,
validExit,
storageFull,
retireLegacyFile,
retiringExits,
};
@@ -0,0 +1,235 @@
import dayjs from 'dayjs';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
type DayCounts = {
cron_id: number;
day: string;
successes: number;
failures: number;
later_successes: number;
later_failures: number;
has_bookings: number;
saved_successes: number;
saved_failures: number;
};
// Process one outcome, newest day first. Same-day receipts can only cover
// eligible exits. Surplus becomes available to earlier days after this match.
function matchDailyCounts(
exits: number,
saved: number,
laterCredits: number,
afterLastBooking = 0,
) {
const localMatches = Math.min(saved, exits - afterLastBooking);
const deficit = exits - localMatches;
const borrowed = Math.min(deficit, laterCredits);
return {
missing: deficit - borrowed,
remaining: laterCredits - borrowed + saved - localMatches,
};
}
// A legacy terminal status needs a matching exit code. An identified supervisor
// also knows a child failed when the OS returns a signal instead of a code.
const confirmedResult = `t.started_at IS NOT NULL AND t.finished_at>=t.started_at
AND t.state IN ('finished','failed')
AND (t.source<>'legacy' OR (
((t.state='finished' AND t.exit_code=0) OR (t.state='failed' AND t.exit_code<>0))
AND NOT EXISTS (SELECT 1 FROM RunningInstances sibling
LEFT JOIN CronTriggers linked ON linked.instance_id=sibling.id
WHERE sibling.cron_id=i.cron_id AND sibling.pid=i.pid AND sibling.finished_at=i.finished_at
AND sibling.id<>i.id AND sibling.status IN (1,3)
AND (linked.id IS NULL OR (linked.source='legacy' AND linked.owner IS NULL))
AND (sibling.started_at<>i.started_at OR COALESCE(sibling.log_path,'')<>COALESCE(i.log_path,'')
OR sibling.status<>i.status OR sibling.exit_code IS NOT i.exit_code OR linked.id IS NOT NULL))))`;
export function readDailyResults(database: Sequelize, cronId: number) {
const today = dayjs().startOf('day');
const first = today.subtract(6, 'day');
const next = today.add(1, 'day');
return database.query<{
day: string;
exitSuccess: number;
exitFail: number;
bookedSuccess: number;
bookedFail: number;
supplement: number;
}>(
`WITH results AS (
SELECT date(t.finished_at/1000,'unixepoch','localtime') AS day,
SUM(t.state='finished') AS exitSuccess,SUM(t.state='failed') AS exitFail,
0 AS bookedSuccess,0 AS bookedFail,0 AS supplement
FROM CronTriggers t LEFT JOIN RunningInstances i ON i.id=t.instance_id
WHERE t.cron_id=$id AND t.finished_at >= $start AND t.finished_at < $end
AND t.reason IS NOT 'spawn' AND ${confirmedResult} GROUP BY day
UNION ALL
SELECT date,0,0,COALESCE(success_count,0),COALESCE(fail_count,0),untimed_count
FROM CrontabStats WHERE ref_id=$id AND date >= $first AND date < $next
) SELECT day,SUM(exitSuccess) AS exitSuccess,SUM(exitFail) AS exitFail,
SUM(bookedSuccess) AS bookedSuccess,SUM(bookedFail) AS bookedFail,SUM(supplement) AS supplement
FROM results GROUP BY day ORDER BY day DESC`,
{
type: QueryTypes.SELECT,
bind: {
id: cronId,
start: first.valueOf(),
end: next.valueOf(),
first: first.format('YYYY-MM-DD'),
next: next.format('YYYY-MM-DD'),
},
},
);
}
// Run under the schema migration's write lock, before accepting new receipts.
export async function repairLegacyDailyStatistics(
database: Sequelize,
transaction: Transaction,
priorVersion: 0 | 1 | 2,
) {
// Old panels updated every outstanding start with the reported PID. Identical
// copies of a start prove only one exit; conflicting rows cannot identify it.
const imported = await database.query(
`WITH exits AS (
SELECT MIN(i.id) AS instance FROM RunningInstances i
JOIN Crontabs c ON c.id=i.cron_id
LEFT JOIN CronTriggers linked ON linked.instance_id=i.id
WHERE (linked.id IS NULL OR (linked.source='legacy' AND linked.owner IS NULL))
AND i.status IN (1,3) AND i.pid>0 AND i.started_at>0 AND i.finished_at>=i.started_at
AND i.finished_at*1000>=COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)
GROUP BY i.cron_id,i.pid,i.finished_at
HAVING MIN(i.started_at)=MAX(i.started_at)
AND COUNT(DISTINCT COALESCE(i.log_path,''))=1 AND MIN(i.status)=MAX(i.status)
AND COUNT(i.exit_code)=COUNT(*) AND MIN(i.exit_code)=MAX(i.exit_code)
AND COUNT(linked.id)=0
)
INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,started_at,finished_at,instance_id,log_path,exit_code,counted)
SELECT 'legacy-db-' || i.id,i.cron_id,'legacy',CASE i.status WHEN 1 THEN 'finished' ELSE 'failed' END,
i.started_at*1000,i.started_at*1000,i.finished_at*1000,i.id,i.log_path,i.exit_code,1
FROM exits JOIN RunningInstances i ON i.id=exits.instance
WHERE (i.status=1 AND i.exit_code=0) OR (i.status=3 AND i.exit_code<>0)`,
{ transaction, type: QueryTypes.BULKUPDATE },
);
// A newly imported last run must have the same owner it would acquire through
// the normal handoff. An older exit must never replace a more recent start.
if (imported)
await database.query(
`WITH ranked AS (
SELECT cron_id,instance_id,started_at/1000 AS start,(finished_at-started_at)/1000 AS elapsed,
ROW_NUMBER() OVER (PARTITION BY cron_id ORDER BY started_at DESC,instance_id DESC) AS position
FROM CronTriggers WHERE source='legacy' AND id LIKE 'legacy-db-%'
)
UPDATE Crontabs AS c SET (last_instance_id,last_execution_time,last_running_time)=
(SELECT instance_id,start,elapsed FROM ranked WHERE cron_id=c.id AND position=1)
WHERE EXISTS (SELECT 1 FROM ranked r WHERE r.cron_id=c.id AND r.position=1 AND
(c.last_execution_time IS NULL OR c.last_execution_time<r.start OR
(c.last_execution_time=r.start AND (c.last_instance_id IS NULL OR c.last_instance_id<r.instance_id)))
AND NOT EXISTS (SELECT 1 FROM RunningInstances i WHERE i.cron_id=c.id AND
(i.started_at>r.start OR (i.started_at=r.start AND i.id>r.instance_id))))`,
{ transaction },
);
// Statistics retention removes whole dates across tasks. When the old panel
// retained no earlier totals, yesterday is the oldest date even a 1-day policy keeps.
const yesterday = dayjs().subtract(1, 'day').format('YYYY-MM-DD');
const days = await database.query<DayCounts>(
`WITH exits AS (
SELECT t.cron_id,t.state,date(t.finished_at/1000,'unixepoch','localtime') AS day,
t.started_at,i.createdAt,t.id
FROM CronTriggers t LEFT JOIN RunningInstances i ON i.id=t.instance_id
WHERE t.counted=1 AND ${confirmedResult}
), ordered AS (
SELECT e.*, CASE WHEN e.id LIKE 'legacy-db-%' AND s.untimed_count=0
AND date(s.updatedAt,'localtime')=e.day AND julianday(s.createdAt)<=julianday(s.updatedAt)
AND e.started_at/1000>CAST(strftime('%s',s.updatedAt) AS INTEGER)
AND julianday(e.createdAt)>julianday(s.updatedAt) THEN 1 ELSE 0 END AS later
FROM exits e LEFT JOIN CrontabStats s ON s.ref_id=e.cron_id AND s.date=e.day
), evidence AS (
SELECT cron_id,day,SUM(state='finished') AS successes,SUM(state='failed') AS failures,
SUM(later*(state='finished')) AS later_successes,SUM(later*(state='failed')) AS later_failures,
0 AS has_bookings,0 AS saved_successes,0 AS saved_failures FROM ordered GROUP BY cron_id,day
UNION ALL
SELECT ref_id,date,0,0,0,0,1,COALESCE(success_count,0),COALESCE(fail_count,0) FROM CrontabStats
)
SELECT cron_id,day,MAX(has_bookings) AS has_bookings,SUM(successes) AS successes,SUM(failures) AS failures,
SUM(later_successes) AS later_successes,SUM(later_failures) AS later_failures,
SUM(saved_successes) AS saved_successes,SUM(saved_failures) AS saved_failures
FROM evidence WHERE day>=MIN($yesterday,COALESCE((SELECT MIN(date) FROM CrontabStats),$yesterday))
AND day>=COALESCE((SELECT first_day FROM CronStatRetention WHERE id=1),'')
GROUP BY cron_id,day ORDER BY cron_id,day DESC`,
{ type: QueryTypes.SELECT, transaction, bind: { yesterday } },
);
// Anonymous receipts cannot identify a particular exit. Match nearest
// eligible days first; never move already booked counts or elapsed samples.
let task: number | undefined;
let successCredit = 0,
failureCredit = 0;
let priorSuccessCredit = 0,
priorFailureCredit = 0;
for (const day of days) {
if (day.cron_id !== task) {
task = day.cron_id;
successCredit =
failureCredit =
priorSuccessCredit =
priorFailureCredit =
0;
}
const successes = matchDailyCounts(
day.successes,
day.saved_successes,
successCredit,
day.later_successes,
);
const failures = matchDailyCounts(
day.failures,
day.saved_failures,
failureCredit,
day.later_failures,
);
successCredit = successes.remaining;
failureCredit = failures.remaining;
let success = successes.missing,
failure = failures.missing;
if (priorVersion === 2) {
// Replaying v2 on the current snapshot could resurrect a cleaned-up day.
// Only the extra lower bound established by v3 is new evidence.
const priorSuccess = matchDailyCounts(
day.successes,
day.saved_successes,
priorSuccessCredit,
);
const priorFailure = matchDailyCounts(
day.failures,
day.saved_failures,
priorFailureCredit,
);
priorSuccessCredit = priorSuccess.remaining;
priorFailureCredit = priorFailure.remaining;
success = Math.max(0, success - priorSuccess.missing);
failure = Math.max(0, failure - priorFailure.missing);
}
// Old repairs did not journal deletions. An absent task/day could have
// been cleared after a supplement. Preserve the gap on repeat upgrades.
if (priorVersion && !day.has_bookings) continue;
if (!success && !failure) continue;
// Anonymous elapsed samples have no execution identity. Preserve measured
// times; adding instance wall times here could count the same sample twice.
await database.query(
`INSERT INTO CrontabStats
(ref_id,date,run_count,success_count,fail_count,untimed_count,total_time,max_time,createdAt,updatedAt)
VALUES ($task,$day,$runs,$success,$failure,$runs,0,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)
ON CONFLICT(ref_id,date) DO UPDATE SET run_count=COALESCE(run_count,0)+excluded.run_count,
success_count=COALESCE(success_count,0)+excluded.success_count,
fail_count=COALESCE(fail_count,0)+excluded.fail_count,
untimed_count=untimed_count+excluded.untimed_count,updatedAt=CURRENT_TIMESTAMP`,
{
transaction,
bind: { task, day: day.day, runs: success + failure, success, failure },
},
);
}
}
File diff suppressed because it is too large. Load diff
+40
View File
@@ -0,0 +1,40 @@
export type TriggerSource =
| 'node'
| 'manual'
| 'boot'
| 'system'
| 'recovery'
| 'legacy'
| 'client';
export type TriggerState =
| 'queued'
| 'running'
| 'finished'
| 'failed'
| 'skipped'
| 'stopped'
| 'unknown';
export type Trigger = {
id: string;
cron_id: number;
source: TriggerSource;
state: TriggerState;
scheduled_at: number | null;
queued_at: number | null;
dequeued_at?: number | null;
started_at: number | null;
script_started_at: number | null;
command_started_at: number | null;
finished_at: number | null;
reason: string | null;
exit_code: number | null;
log_path: string | null;
};
export type VerifiedSupervisorExit = {
code: number | null;
signal: string | null;
time: number;
version: 1;
};