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

+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),
};
}
}