perf(cron): share global concurrency budget and streamline execution

Share durable permits across manual, scheduled and recovered runs, prioritize
short ready tasks with aging, and record global queue occupancy.

Reduce launch, log polling, dashboard and SQLite overhead while preserving
transactional receipts, cancellation, recovery and script hook compatibility.
Keep ordinary CRUD in ORM and bound SQL on measured execution hot paths.

Fix supervisor descendant tracking, asynchronous log draining, concurrent log
directory creation, Linux fallback launches and snapshot clock rollback.
Include regression coverage, SQL audits and evolution/review documentation.

Validation: five review rounds; local full suite 1478 passed, 28 platform skips;
dev suites 415 passed, no failures/skips; backend types and formatting passed.
This commit is contained in:
whyour committed 2026-11-25 00:54:41 +08:00
1 parent cddabbaf0e
commit 2f01f756d7
74 files changed
+6891 -837

No files matched your search

+38 -29
View File
@@ -1,4 +1,6 @@
import { executionModel } from '../data/executionModels';
import config from '../config';
import { dashboardSnapshot } from '../shared/dashboardSnapshot';
import { stat } from 'fs/promises';
import { resolveFileAccess } from '../shared/fileAccess';
import { AnomalyPage, AnomalyKind } from '../cron/queries/scheduleAnomalies';
@@ -15,7 +17,7 @@ import { containerResources } from '../shared/containerResources';
import { TriggerHistory } from '../cron/history';
import { Router, Request, Response, NextFunction } from 'express';
import { Container } from 'typedi';
import { fn, col, where, Op, QueryTypes } from 'sequelize';
import { fn, col, where, Op } from 'sequelize';
import { CrontabModel } from '../data/cron';
import { CrontabStatModel } from '../data/cronStats';
import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
@@ -96,26 +98,33 @@ export default (app: Router) => {
const day = dayjs(serverNow).startOf('day');
const today = day.format('YYYY-MM-DD');
const [total, enabled, disabled, stats, triggers] = await Promise.all([
CrontabModel.count(),
CrontabModel.count({ where: { isDisabled: 0 } }),
CrontabModel.count({ where: { isDisabled: 1 } }),
CrontabStatModel.findOne({
attributes: [
[fn('SUM', col('run_count')), 'total_runs'],
[fn('SUM', col('success_count')), 'total_success'],
[fn('SUM', col('fail_count')), 'total_fail'],
[fn('SUM', col('untimed_count')), 'untimed_count'],
[fn('SUM', col('total_time')), 'total_time'],
],
where: { date: today },
raw: true,
const snapshot = await dashboardSnapshot(
CrontabStatModel.sequelize!,
today,
async () => ({
sampledAt: Date.now(),
values: await Promise.all([
CrontabModel.count(),
CrontabModel.count({ where: { isDisabled: 0 } }),
CrontabModel.count({ where: { isDisabled: 1 } }),
CrontabStatModel.findOne({
attributes: [
[fn('SUM', col('run_count')), 'total_runs'],
[fn('SUM', col('success_count')), 'total_success'],
[fn('SUM', col('fail_count')), 'total_fail'],
[fn('SUM', col('untimed_count')), 'untimed_count'],
[fn('SUM', col('total_time')), 'total_time'],
],
where: { date: today },
raw: true,
}),
new TriggerHistory(CrontabStatModel.sequelize!).metrics(
day.valueOf(),
),
]),
}),
new TriggerHistory(CrontabStatModel.sequelize!).metrics(
day.valueOf(),
),
]);
);
const [total, enabled, disabled, stats, triggers] = snapshot.values;
const row = stats as any;
const totalRuns = Number(row?.total_runs) || 0;
const totalSuccess = Number(row?.total_success) || 0;
@@ -126,6 +135,7 @@ export default (app: Router) => {
code: 200,
data: {
serverNow,
sampledAt: snapshot.sampledAt,
expiresAt: day.add(1, 'day').valueOf(),
total,
enabled,
@@ -176,10 +186,10 @@ export default (app: Router) => {
)
return res.status(400).send({ code: 400 });
const [snapshotRetention] = live
? await CrontabStatModel.sequelize!.query<{ cutoff: number }>(
'SELECT cutoff FROM CronHistoryRetention WHERE id=1',
{ type: QueryTypes.SELECT },
)
? await executionModel(
CrontabStatModel.sequelize!,
'CronHistoryRetention',
).findAll({ attributes: ['cutoff'], where: { id: 1 }, raw: true })
: [];
const details = new AnomalyPage(
kind as AnomalyKind,
@@ -228,11 +238,10 @@ export default (app: Router) => {
// Log checks can yield after the audit transaction. Do not publish that
// snapshot if history cleanup has since removed part of its plan window.
if (live) {
const [retention] = await CrontabStatModel.sequelize!.query<{
cutoff: number;
}>('SELECT cutoff FROM CronHistoryRetention WHERE id=1', {
type: QueryTypes.SELECT,
});
const [retention] = await executionModel(
CrontabStatModel.sequelize!,
'CronHistoryRetention',
).findAll({ attributes: ['cutoff'], where: { id: 1 }, raw: true });
if (retention && retention.cutoff > (snapshotRetention?.cutoff ?? 0))
return res.send({ code: 200, data: { status: 'unavailable' } });
}
+39 -8
View File
@@ -1,8 +1,10 @@
import { executionModel } from '../data/executionModels';
import { storageFull, writeExit } from '../cron/settlement/exitReceipt.cjs';
import { QueryTypes } from 'sequelize';
import { randomUUID } from 'crypto';
import { sequelize } from '../data';
import { systemOwner, TriggerHistory } from '../cron/history';
import { globalCronBudget } from '../cron/execution/globalCronBudget';
async function receipt() {
const [action, task, pid, id, status, end] = process.argv.slice(2);
@@ -23,15 +25,35 @@ async function receipt() {
rule && Number.isSafeInteger(at) && at > 0 && at <= Date.now()
? { rule, at, dispatch }
: undefined;
const acquired = await history.startSystem(
triggerId,
Number(task),
owner,
command,
wrapper,
const queued = await sequelize.query(
`INSERT INTO CronTriggers(id,cron_id,source,state,owner,queued_at,observed_at)
VALUES ($id,$cronId,'system','queued',$owner,$now,$now) ON CONFLICT(id) DO NOTHING`,
{
bind: { id: triggerId, cronId: Number(task), owner, now: Date.now() },
type: QueryTypes.BULKUPDATE,
},
);
if (!acquired) process.exitCode = 75;
else if (!id) process.stdout.write(triggerId);
const budget = globalCronBudget(sequelize);
const token =
queued === 1 &&
(await budget.acquire(triggerId, {
owner,
commandIdentity: command,
current: () => systemOwner(Number(pid)) === owner,
}));
const acquired =
token &&
(await history.startSystem(
triggerId,
Number(task),
owner,
command,
wrapper,
));
if (!acquired) {
if (token) await budget.release(triggerId, token);
process.exitCode = 75;
} else if (!id) process.stdout.write(triggerId);
} else if (action === 'finish') {
// The live wrapper inherited both IDs from the start it just claimed. A
// standalone retry must match the registered system task before writing.
@@ -77,6 +99,15 @@ async function receipt() {
? undefined
: 'legacy',
);
const [lease] = await executionModel(
sequelize,
'CronConcurrencyLeases',
).findAll({
attributes: ['token'],
where: { trigger_id: id },
raw: true,
});
if (lease) await globalCronBudget(sequelize).release(id, lease.token);
} catch (error) {
if (!journaled || !storageFull(error)) throw error;
// The regular recovery pass will settle the receipt after space returns.
+19 -10
View File
@@ -43,17 +43,26 @@ async function probeUpgrade() {
try {
await loadDatabase();
// Exercise an actual on-disk transaction as well as schema initialization.
const { DataTypes } = await import('sequelize');
const probe = sequelize.define<
import('sequelize').Model<{ value: number }>
>(
'UpgradeProbe',
{ value: DataTypes.INTEGER },
{ tableName: 'upgrade_probe', timestamps: false },
);
probe.removeAttribute('id');
await sequelize.transaction(async (transaction) => {
await sequelize.query('CREATE TABLE upgrade_probe (value INTEGER)', {
transaction,
});
await sequelize.query('INSERT INTO upgrade_probe VALUES (42)', {
transaction,
});
const [rows] = await sequelize.query('SELECT value FROM upgrade_probe', {
transaction,
});
if ((rows[0] as { value: number })?.value !== 42)
await sequelize
.getQueryInterface()
.createTable(
'upgrade_probe',
{ value: DataTypes.INTEGER },
{ transaction },
);
await probe.create({ value: 42 }, { transaction });
const row = await probe.findOne({ attributes: ['value'], transaction });
if (row?.get('value') !== 42)
throw new Error('Upgrade database readback failed');
});
inject();
+205 -114
View File
@@ -1,4 +1,16 @@
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import {
executionModel,
executionAssociation,
} from '../../data/executionModels';
import {
QueryTypes,
Sequelize,
Transaction,
Op,
literal,
fn,
col,
} from 'sequelize';
import { createHash } from 'crypto';
import { executionIdPattern } from '../identity';
import {
@@ -113,17 +125,27 @@ export class LegacyClientAdapter {
},
);
}
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 } },
await executionModel(this.database, 'CronTriggers').update(
{ log_path: fn('COALESCE', col('log_path'), log) },
{
where: { id, cron_id: cronId },
transaction,
hooks: false,
validate: false,
},
);
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 } },
);
const [legacy] = await executionModel(
this.database,
'CronTriggers',
).findAll({
attributes: ['id'],
where: { id, cron_id: cronId, owner: null },
transaction,
raw: true,
});
if (legacy) {
const state = stopped
? 'stopped'
@@ -185,13 +207,59 @@ export class LegacyClientAdapter {
.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 } },
);
const [bound] = await executionModel(
this.database,
'CronShellBindings',
).findAll({
attributes: ['receipt'],
where: { receipt },
transaction,
raw: true,
});
if (bound) return;
const rows = await this.database.query<{
const rows = (await executionModel(
this.database,
'RunningInstances',
).findAll({
attributes: [
[col('RunningInstance.id'), 'instance'],
'status',
'finished_at',
'exit_code',
'log_path',
[col('trigger.id'), 'id'],
[col('trigger.source'), 'source'],
],
include: [
{
association: executionAssociation(this.database, 'instanceTrigger'),
attributes: [],
required: false,
},
],
where: {
cron_id: cronId,
pid,
started_at: seconds,
[Op.and]: [
{
[Op.or]: [
{ '$trigger.id$': null },
{ '$trigger.source$': 'legacy' },
{ '$trigger.owner$': { [Op.not]: null } },
],
},
...(log
? [{ [Op.or]: [{ log_path: log }, { log_path: null }] }]
: []),
],
},
limit: 2,
subQuery: false,
transaction,
raw: true,
})) as unknown as Array<{
instance: number;
status: number;
finished_at: number | null;
@@ -199,29 +267,20 @@ export class LegacyClientAdapter {
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 },
},
);
const [expired] = await executionModel(
this.database,
'CronHistoryRetention',
).findAll({
attributes: ['id'],
where: { cutoff: { [Op.gt]: (old.finished_at ?? seconds) * 1000 } },
transaction,
raw: true,
});
if (expired) return;
}
if (old.status !== 0 && old.status !== 4) {
@@ -285,21 +344,22 @@ export class LegacyClientAdapter {
);
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`,
const roots = await executionModel(this.database, 'CronTriggers').findAll(
{
attributes: ['id', 'command_identity'],
where: {
cron_id: cronId,
state: 'running',
command_identity: { [Op.not]: null },
started_at: { [Op.lt]: start + 1000 },
},
transaction,
type: QueryTypes.SELECT,
bind: { cronId, end: start + 1000 },
raw: true,
},
);
for (const root of roots) {
if (!identity) break;
const parent = Number(root.command_identity.split(':')[1]);
const parent = Number(root.command_identity!.split(':')[1]);
try {
if (
!isProcessDescendant(pid, parent) ||
@@ -313,9 +373,9 @@ export class LegacyClientAdapter {
continue;
throw error;
}
await this.database.query(
'INSERT INTO CronShellBindings(receipt,trigger_id) VALUES ($receipt,$id)',
{ transaction, bind: { receipt, id: root.id } },
await executionModel(this.database, 'CronShellBindings').create(
{ receipt, trigger_id: root.id },
{ transaction, silent: true, hooks: false, validate: false },
);
if (running)
await this.attachShellLog(root.id, cronId, log, transaction);
@@ -326,19 +386,30 @@ export class LegacyClientAdapter {
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 },
const others = (await executionModel(
this.database,
'RunningInstances',
).findAll({
attributes: [[col('trigger.id'), 'id'], 'started_at'],
include: [
{
association: executionAssociation(this.database, 'instanceTrigger'),
attributes: [],
required: false,
},
],
where: {
cron_id: cronId,
pid,
started_at: { [Op.ne]: seconds },
[Op.or]: [
{ started_at: { [Op.gt]: seconds } },
{ status: 0, '$trigger.source$': 'legacy' },
],
},
);
transaction,
raw: true,
})) as unknown as Array<{ id: string | null; started_at: number }>;
if (running && old) identity = legacyProcessOwner(pid, seconds);
const historical =
!running ||
@@ -347,46 +418,42 @@ export class LegacyClientAdapter {
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,
[instance] = await executionModel(this.database, 'RunningInstances')
.create(
{
cron_id: cronId,
pid,
log: log || null,
seconds,
log_path: log || null,
started_at: seconds,
status: historical ? 4 : 0,
finished: historical ? Math.floor(Date.now() / 1000) : null,
finished_at: historical ? Math.floor(Date.now() / 1000) : null,
createdAt: literal('CURRENT_TIMESTAMP'),
updatedAt: literal('CURRENT_TIMESTAMP'),
},
},
);
{ transaction, silent: true, hooks: false, validate: false },
)
.then((row) => [row.id] as const);
}
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)`,
await executionModel(this.database, 'CronTriggers').create(
{
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,
},
id,
cron_id: cronId,
source: 'legacy',
state: unknown ? 'unknown' : 'running',
observed_at: start,
started_at: start,
finished_at: unknown
? old?.finished_at
? old.finished_at * 1000
: Date.now()
: null,
instance_id: instance,
log_path: old?.log_path ?? (log || null),
process_identity: !unknown && running ? identity ?? null : null,
reason: old && running && !unknown ? 'restart' : null,
},
{ transaction, silent: true, hooks: false, validate: false },
);
await this.lifecycle.claimSummary(
cronId,
@@ -398,7 +465,7 @@ export class LegacyClientAdapter {
for (const other of others) {
if (other.started_at < seconds)
await this.settlement.completeInTransaction(
other.id,
other.id!,
'unknown',
null,
null,
@@ -441,9 +508,9 @@ export class LegacyClientAdapter {
{ 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 executionModel(this.database, 'CronTriggers').update(
{ log_path: fn('COALESCE', col('log_path'), log) },
{ where: { id }, transaction, hooks: false, validate: false },
);
await this.database.query(
`UPDATE Crontabs SET log_path=$log WHERE id=$cronId AND status=0 AND pid=(
@@ -484,15 +551,19 @@ export class LegacyClientAdapter {
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 },
const [row] = await executionModel(this.database, 'CronTriggers').findAll(
{
attributes: [
'state',
'started_at',
'instance_id',
'command_identity',
'owner',
],
where: { id, cron_id: cronId },
transaction,
raw: true,
},
);
if (!row) return;
const startSeconds =
@@ -520,9 +591,15 @@ export class LegacyClientAdapter {
},
);
if (instance) {
await this.database.query(
'UPDATE CronTriggers SET instance_id=$instance WHERE id=$id',
{ transaction, bind: { instance, id } },
await executionModel(this.database, 'CronTriggers').update(
{ instance_id: instance },
{
where: { id },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
await this.lifecycle.claimSummary(
cronId,
@@ -547,19 +624,33 @@ export class LegacyClientAdapter {
/* 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)`,
const [instance] = await executionModel(
this.database,
'RunningInstances',
)
.create(
{
cron_id: cronId,
pid,
log_path: log,
started_at: startSeconds,
status: 0,
createdAt: literal('CURRENT_TIMESTAMP'),
updatedAt: literal('CURRENT_TIMESTAMP'),
},
{ transaction, silent: true, hooks: false, validate: false },
)
.then((row) => [row.id] as const);
await executionModel(this.database, 'CronTriggers').update(
{ instance_id: instance, process_identity: identity },
{
where: { id },
transaction,
type: QueryTypes.INSERT,
bind: { cronId, pid, log, seconds: startSeconds },
silent: true,
hooks: false,
validate: false,
},
);
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,
+6 -1
View File
@@ -31,7 +31,12 @@ export function spawnCronCommand(
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 },
env: {
...process.env,
QL_TRIGGER_ID: triggerId,
QL_SUPERVISOR_RECEIPT: '1',
QL_SUPERVISOR_LOG_BOUND: outputPath ? '1' : '',
},
stdio: onCommandStart ? ['pipe', 'pipe', 'pipe', 'pipe'] : 'pipe',
}) as ChildProcessWithoutNullStreams;
if (onCommandStart && child.stdio[3]) {
+105 -46
View File
@@ -1,20 +1,36 @@
import type { Logger } from 'winston';
import { randomUUID } from 'crypto';
import dayjs from 'dayjs';
import fs from 'fs/promises';
import path from 'path';
import {
Op,
where,
col as colFn,
FindOptions,
QueryTypes,
Op,
Transaction,
col,
col as colFn,
where,
} from 'sequelize';
import type { Logger } from 'winston';
import config from '../../config/index';
import { getUniqPath, killTask } from '../../config/util';
import { Crontab, CrontabModel, CrontabStatus } from '../../data/cron';
import {
RunningInstanceModel,
executionAssociation,
executionModel,
} from '../../data/executionModels';
import {
InstanceStatus,
RunningInstanceModel,
} from '../../data/runningInstance';
import { asError, observeChildProcess } from '../../shared/childProcess';
import { resolveFileAccess } from '../../shared/fileAccess';
import { t } from '../../shared/i18n';
import { resolveLogPath } from '../../shared/logPath';
import { logStreamManager } from '../../shared/logStreamManager';
import { TriggerHistory, TriggerState } from '../history';
import { shellValue } from '../scheduling/cronScheduling';
import { releaseCronCommand, spawnCronCommand } from './cronCommandProcess';
import taskLimit from './cronLimit';
import {
finishStoppedTree,
hasLiveCronProcess,
@@ -22,18 +38,6 @@ import {
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<
@@ -120,6 +124,17 @@ export class CronExecution {
});
} else {
accepted.push(row.get({ plain: true }));
await database.query(
'INSERT INTO CronManualSubmissions(trigger_id,token,snapshot) VALUES ($id,$token,$snapshot)',
{
transaction,
bind: {
id: trigger,
token,
snapshot: JSON.stringify(row.get({ plain: true })),
},
},
);
triggers.push({
taskId: id,
triggerId: trigger,
@@ -146,6 +161,40 @@ export class CronExecution {
return submission.triggers;
}
public async recoverQueued() {
const rows = await executionModel(
CrontabModel.sequelize!,
'CronManualSubmissions',
).findAll({
attributes: ['trigger_id', 'token', 'snapshot'],
include: [
{
association: executionAssociation(
CrontabModel.sequelize!,
'submissionTrigger',
),
attributes: [],
required: true,
where: {
state: 'queued',
[Op.or]: [{ stop_requested: null }, { stop_requested: 0 }],
},
},
],
order: [
[col('trigger.queued_at'), 'ASC'],
[col('trigger.id'), 'ASC'],
],
raw: true,
});
for (const row of rows) {
const snapshot: Crontab = JSON.parse(row.snapshot);
void this.host
.runSingle(snapshot.id!, row.token, row.trigger_id, snapshot)
.catch((error) => this.logger.error(String(error)));
}
}
private readonly stoppingBatches = new Map<string, Promise<void>>();
public async stop(ids: number[], requestId?: string) {
@@ -171,14 +220,15 @@ export class CronExecution {
{ 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 },
);
const [existing] = await executionModel(
database,
'CronStopBatches',
).findAll({
attributes: ['cron_ids', 'snapshot', 'status_code'],
where: { request_id: requestId },
transaction,
raw: true,
});
if (existing) {
if (existing.cron_ids !== cronIds)
throw Object.assign(
@@ -254,12 +304,13 @@ export class CronExecution {
identityConflict,
};
if (requestId) {
await database.query(
'INSERT INTO CronStopBatches(request_id,cron_ids,snapshot) VALUES ($requestId,$cronIds,$snapshot)',
await executionModel(database, 'CronStopBatches').create(
{
transaction,
bind: { requestId, cronIds, snapshot: JSON.stringify(batch) },
request_id: requestId,
cron_ids: cronIds,
snapshot: JSON.stringify(batch),
},
{ transaction, silent: true, hooks: false, validate: false },
);
}
return batch;
@@ -328,9 +379,14 @@ export class CronExecution {
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 } },
await executionModel(database, 'CronStopBatches').update(
{ snapshot: null, status_code: identityConflict ? 409 : 200 },
{
where: { request_id: requestId, snapshot: { [Op.not]: null } },
silent: true,
hooks: false,
validate: false,
},
);
if (identityConflict)
throw Object.assign(new Error(t('实例不存在或已停止')), { status: 409 });
@@ -378,16 +434,16 @@ export class CronExecution {
});
}
for (const command of commands) {
const pid = Number(command.command_identity.split(':')[1]);
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,
identity: command.command_identity!,
started: Math.floor(command.started_at! / 1000),
log: command.log_path ?? undefined,
});
}
let identityConflict = false;
@@ -424,11 +480,14 @@ export class CronExecution {
{ transaction },
);
if (target.trigger)
await CrontabModel.sequelize!.query(
"UPDATE CronTriggers SET instance_id=$id,process_identity=$identity WHERE id=$trigger AND state='running'",
await executionModel(CrontabModel.sequelize!, 'CronTriggers').update(
{ instance_id: row.id, process_identity: identity },
{
where: { id: target.trigger, state: 'running' },
transaction,
bind: { id: row.id, identity, trigger: target.trigger },
silent: true,
hooks: false,
validate: false,
},
);
await history.queueInstanceStop(
@@ -506,9 +565,8 @@ export class CronExecution {
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 } },
await executionModel(CrontabModel.sequelize!, 'CronStopRequests').destroy(
{ where: { instance_id: instanceId, cron_id: cronId }, hooks: false },
);
return { code: 404, message: t('实例不存在或已停止') };
}
@@ -736,9 +794,10 @@ export class CronExecution {
)
: await getUniqPath(command, `${id}`);
const logTime = dayjs().format('YYYY-MM-DD-HH-mm-ss-SSS');
logPath = `${uniqPath}/${logTime}${
independent ? '-' + expectedToken : ''
}.log`;
// Different tasks can share a script/log directory and start in
// the same millisecond. Every launch needs its own log identity.
// The submission token can also be shared by different tasks.
logPath = `${uniqPath}/${logTime}-${randomUUID()}.log`;
absolutePath = resolveFileAccess(config.logPath, [logPath]);
if (!absolutePath)
throw new Error('Log path is outside the log directory');
+55 -36
View File
@@ -2,10 +2,7 @@ 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 { QueueOccupants } from '../queries/queueDiagnostics';
import { CronWaitQueue, CronQueueOptions } from './cronWaitQueue';
import { AuthDataType, SystemModel } from '../../data/system';
import Logger from '../../loaders/logger';
@@ -15,6 +12,7 @@ import config from '../../config';
import { credentials } from '@grpc/grpc-js';
import { ApiClient } from '../../protos/api';
import { getGrpcCerts } from '../../config/grpcCerts';
import { globalCronBudget } from './globalCronBudget';
// One scheduler/manual queue owner per process; services and execution share it.
class CronLimit {
@@ -192,43 +190,62 @@ class CronLimit {
return;
}
this.queuedCrons.set(cron.id, result);
const dispatch = (job: () => Promise<T | void>) => {
if (!waitingSignal) return this.cronLimit.add(job, options);
return new Promise<T | void>((resolve, reject) => {
this.cronLimit
.add(job, {
...options,
waitingSignal,
onRemoved: () => {
this.scheduledOccupants.forget(triggerId);
resolve();
},
})
.then(resolve, reject);
});
};
const run = this.trackAdmission(
this.scheduledOccupants,
this.cronLimit.concurrency,
fn,
{ id: triggerId, name: cron.name || cron.id },
db,
isCurrent,
waitingSignal,
triggerId && db ? dispatch : undefined,
);
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);
});
// Durable requests are scheduled together by the global budget. A local
// FIFO in front of it hides short jobs behind long-running tasks.
if (triggerId && db) return run();
return dispatch(run);
}
private trackAdmission<T>(
pool: QueueOccupants,
limit: number,
fn: () => Promise<T>,
occupant: { id?: string; name: string },
db?: Sequelize,
current?: () => boolean,
signal?: EventEmitter,
dispatch?: (job: () => Promise<T>) => Promise<T | void>,
) {
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);
// Durable wait diagnostics come from the shared budget, before local
// dispatch. Local occupancy cannot see other workers or a fresh batch.
const tracked = pool.track(fn, occupant, db);
return async () => {
try {
return occupant.id && db
? await globalCronBudget(db).run(
occupant.id,
() => (dispatch ? dispatch(tracked) : tracked()),
current,
signal,
)
: await tracked();
} finally {
pool.forget(occupant.id);
}
};
}
public async manualRunWithCronLimit<T>(
@@ -237,16 +254,18 @@ class CronLimit {
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,
const run = this.trackAdmission(
this.manualOccupants,
fn,
occupant,
db,
undefined,
undefined,
occupant.id && db
? (job) => this.manualCronoLimit.add(job, options)
: undefined,
);
return occupant.id && db ? run() : this.manualCronoLimit.add(run, options);
}
}
+460
View File
@@ -0,0 +1,460 @@
import { randomUUID } from 'crypto';
import { EventEmitter } from 'events';
import os from 'os';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { systemOwner } from './cronProcess';
import { GlobalQueueDiagnostics } from '../queries/queueDiagnostics';
type Lease = {
trigger_id: string;
token: string;
owner: string;
command_identity: string | null;
targets?: string | null;
name?: string;
at?: number;
};
const leaseQuery = `SELECT l.*,s.targets,COALESCE(NULLIF(c.name,''),c.command,l.trigger_id) AS name,
COALESCE(t.started_at,t.queued_at,t.observed_at) AS at FROM CronConcurrencyLeases l
LEFT JOIN CronTriggers t ON t.id=l.trigger_id LEFT JOIN CronStopRequests s ON s.instance_id=t.instance_id
LEFT JOIN Crontabs c ON c.id=t.cron_id`;
function liveLease(lease: Lease) {
return (
budgetOwnerAlive(lease.command_identity || lease.owner) ||
Boolean(
lease.targets &&
(JSON.parse(lease.targets) as string[]).some(budgetOwnerAlive),
)
);
}
type Waiter = {
id: string;
token: string;
owner: string;
commandIdentity?: string;
registered?: boolean;
current: () => boolean;
resolve: (acquired: boolean) => void;
reject: (error: unknown) => void;
};
// Birth identities include the boot ID and start ticks; a reused PID is not a
// surviving execution. Permission/I/O failures fail closed, never free a slot.
export function budgetOwnerAlive(identity: string) {
try {
return systemOwner(Number(identity.split(':')[1])) === identity;
} catch (error) {
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!))
return false;
throw error;
}
}
const budgets = new WeakMap<Sequelize, GlobalCronBudget>();
export function globalCronBudget(db: Sequelize) {
let budget = budgets.get(db);
if (!budget) budgets.set(db, (budget = new GlobalCronBudget(db)));
return budget;
}
// Admission polling and handoff use bound SQL: model query construction here
// repeats for each ready task and extends the single-writer critical section.
// Ordinary management queries remain ORM; see docs/SQL_ORM_AUDIT.txt.
// Only admissions use a write transaction. A saturated queue shares one read
// poll per worker, independent of its backlog size; idle workers do no polling.
export class GlobalCronBudget {
private waiting = new Set<Waiter>();
private pumping = false;
private scheduled = false;
private wakePending = false;
private heldTokens = new Set<string>();
private timer?: NodeJS.Timeout;
private diagnostics = new GlobalQueueDiagnostics(this.db);
constructor(private db: Sequelize) {}
async acquire(
id: string,
options: {
current?: () => boolean;
signal?: EventEmitter;
owner?: string;
commandIdentity?: string;
} = {},
) {
let expired = false;
const expire = () => {
expired = true;
this.wake();
};
options.signal?.once('expired', expire);
const token = randomUUID();
let acquired = false;
try {
acquired = await new Promise<boolean>((resolve, reject) => {
this.waiting.add({
id,
token,
owner: options.owner ?? systemOwner(process.pid),
commandIdentity: options.commandIdentity,
current: () => !expired && (options.current?.() ?? true),
resolve,
reject,
});
this.wake();
});
if (acquired) this.heldTokens.add(token);
return acquired ? token : undefined;
} finally {
options.signal?.off('expired', expire);
// Successful admission removes the wait in the same transaction as its
// lease. A later cleanup error must never hide an acquired permit.
if (!acquired)
await this.db.query(
'DELETE FROM CronConcurrencyWaiters WHERE trigger_id=$id AND token=$token',
{ bind: { id, token } },
);
}
}
async run<T>(
id: string,
fn: () => Promise<T>,
current?: () => boolean,
signal?: EventEmitter,
) {
const token = await this.acquire(id, { current, signal });
if (!token) return;
try {
return await fn();
} finally {
await this.release(id, token);
}
}
async release(id: string, token: string) {
// Once the callback returns, a still-live command needs normal recovery
// polling: there is no longer a local completion that can wake us.
this.heldTokens.delete(token);
const [lease] = await this.db.query<Lease>(
leaseQuery + ' WHERE l.trigger_id=$id AND l.token=$token',
{ bind: { id, token }, type: QueryTypes.SELECT },
);
// A failed callback or a stop request is not proof that its child exited.
if (lease && (!lease.command_identity || !liveLease(lease))) {
await this.db.query(
'DELETE FROM CronConcurrencyLeases WHERE trigger_id=$id AND token=$token',
{ bind: { id, token } },
);
}
this.wake();
}
private wake() {
if (!this.waiting.size) return;
if (this.pumping) {
this.wakePending = true;
return;
}
clearTimeout(this.timer);
this.timer = undefined;
if (this.scheduled) return;
// A batch submission calls acquire synchronously for each accepted task.
// Publish the whole batch before choosing its first permit, so the first
// long task cannot bypass the same batch's shorter ready tasks.
this.scheduled = true;
queueMicrotask(() => {
this.scheduled = false;
if (this.waiting.size) void this.pump();
});
}
private async snapshot(transaction?: Transaction) {
// An upgrade can restart workers while supervisors from the previous
// version are still alive. Their existing birth identities also consume
// capacity, even though that version did not create budget reservations.
const leases = await this.db.query<Lease>(
leaseQuery +
`
UNION ALL SELECT t.id,'inherited',COALESCE(t.command_identity,t.process_identity),
COALESCE(t.command_identity,t.process_identity),s.targets,
COALESCE(NULLIF(c.name,''),c.command,t.id),COALESCE(t.started_at,t.queued_at,t.observed_at)
FROM CronTriggers t LEFT JOIN CronStopRequests s ON s.instance_id=t.instance_id
LEFT JOIN Crontabs c ON c.id=t.cron_id
WHERE t.state='running' AND COALESCE(t.command_identity,t.process_identity) IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM CronConcurrencyLeases l WHERE l.trigger_id=t.id)`,
{
type: QueryTypes.SELECT,
transaction,
},
);
const [config] = await this.db.query<{ info: string }>(
"SELECT info FROM Auths WHERE type='systemConfig' LIMIT 1",
{ type: QueryTypes.SELECT, transaction },
);
const configured = config?.info && JSON.parse(config.info).cronConcurrency;
const limit =
Number.isSafeInteger(configured) && configured > 0
? configured
: Math.max(os.cpus().length, 4);
const stale = leases.filter((lease) => !liveLease(lease));
return {
leases,
stale,
limit,
free: Math.max(0, limit - leases.length + stale.length),
};
}
private async pump() {
this.pumping = true;
this.wakePending = false;
const batch = [...this.waiting];
const results = new Map<Waiter, boolean>();
let pollInterval = 100;
try {
// Publish all ready requests, including those behind long local jobs.
// Tokens prevent a duplicate submitter from deleting the original wait.
const fresh = batch.filter((waiter) => !waiter.registered);
if (fresh.length) {
await this.db.transaction(
{ type: Transaction.TYPES.IMMEDIATE },
async (transaction) => {
const owners = await this.db.query<{
trigger_id: string;
token: string;
owner: string;
}>(
'SELECT * FROM CronConcurrencyWaiters WHERE trigger_id IN (:ids)',
{
replacements: { ids: fresh.map((w) => w.id) },
transaction,
type: QueryTypes.SELECT,
},
);
for (const owner of owners)
if (!budgetOwnerAlive(owner.owner)) {
await this.db.query(
'DELETE FROM CronConcurrencyWaiters WHERE trigger_id=$id AND token=$token',
{
bind: { id: owner.trigger_id, token: owner.token },
transaction,
},
);
}
// Keep a burst in the same transaction, but avoid one SQLite
// round trip per waiter. Three binds per row stay below even
// SQLite's older 999-variable limit; values never enter SQL text.
for (let offset = 0; offset < fresh.length; offset += 200) {
const chunk = fresh.slice(offset, offset + 200);
const bind: string[] = [];
const values = chunk.map((waiter) => {
const start = bind.length;
bind.push(waiter.id, waiter.token, waiter.owner);
return `($${start + 1},$${start + 2},$${start + 3})`;
});
await this.db.query(
`WITH incoming(trigger_id,token,owner) AS (VALUES ${values.join(
',',
)})
INSERT INTO CronConcurrencyWaiters(trigger_id,token,owner)
SELECT i.trigger_id,i.token,i.owner FROM incoming i
JOIN CronTriggers t ON t.id=i.trigger_id WHERE t.state='queued'
ON CONFLICT(trigger_id) DO NOTHING`,
{
bind,
transaction,
},
);
}
},
);
for (const waiter of fresh) waiter.registered = true;
}
const queued = await this.db.query<{ id: string; token: string }>(
"SELECT t.id,w.token FROM CronTriggers t JOIN CronConcurrencyWaiters w ON w.trigger_id=t.id WHERE t.id IN (:ids) AND t.state='queued' AND COALESCE(t.stop_requested,0)=0",
{
replacements: { ids: batch.map((w) => w.id) },
type: QueryTypes.SELECT,
},
);
const ids = new Set(queued.map((row) => row.token));
for (const waiter of batch)
if (!waiter.current() || !ids.has(waiter.token))
results.set(waiter, false);
const view = await this.snapshot();
// Local callbacks wake the budget immediately on completion. While all
// slots are held by this exact budget instance, avoid scanning SQLite
// ten times per second for changes those callbacks will report anyway.
// Foreign/inherited permits and released-but-live descendants retain
// the short recovery poll; runtime limit changes remain bounded at 500 ms.
if (
!view.free &&
!view.stale.length &&
view.leases.length &&
view.leases.every((lease) => this.heldTokens.has(lease.token))
)
pollInterval = 500;
for (const waiter of batch) {
if (
view.leases.some(
(lease) =>
lease.trigger_id === waiter.id && !view.stale.includes(lease),
)
)
results.set(waiter, false);
}
if (view.free || view.stale.length) {
await this.db.transaction(
{ type: Transaction.TYPES.IMMEDIATE },
async (transaction) => {
const { leases, stale, free } = await this.snapshot(transaction);
for (const lease of stale)
await this.db.query(
'DELETE FROM CronConcurrencyLeases WHERE trigger_id=$id AND token=$token',
{
bind: { id: lease.trigger_id, token: lease.token },
transaction,
},
);
// Only live, ready owners take part in ordering. A dead worker's
// request must not block recovery or unrelated tasks.
const ready = await this.db.query<{
trigger_id: string;
token: string;
owner: string;
}>(
`
SELECT w.* FROM CronConcurrencyWaiters w JOIN CronTriggers t ON t.id=w.trigger_id
LEFT JOIN Crontabs c ON c.id=t.cron_id
WHERE t.state='queued' AND COALESCE(t.stop_requested,0)=0
AND NOT EXISTS(SELECT 1 FROM CronConcurrencyLeases l WHERE l.trigger_id=w.trigger_id)
ORDER BY CASE WHEN t.queued_at <= $aged THEN 0 ELSE 1 END,
CASE WHEN t.queued_at <= $aged THEN t.queued_at
ELSE CASE WHEN c.last_execution_time > 0 AND c.last_running_time IS NOT NULL
THEN MAX(0,c.last_running_time)*1000 ELSE 10000 END END,
t.queued_at,t.observed_at,t.id`,
{
bind: { aged: Date.now() - 30000 },
transaction,
type: QueryTypes.SELECT,
},
);
const selected = new Set<string>();
for (const request of ready) {
if (!budgetOwnerAlive(request.owner)) {
await this.db.query(
'DELETE FROM CronConcurrencyWaiters WHERE trigger_id=$id AND token=$token',
{
bind: { id: request.trigger_id, token: request.token },
transaction,
},
);
} else if (selected.size < free) selected.add(request.token);
}
// Resolve local permits in the same order as the shared ranking.
// Set membership alone would start a long task first again when
// both it and a short task fit into the remaining free slots.
const priority = new Map(
[...selected].map((token, index) => [token, index]),
);
batch.sort(
(a, b) =>
(priority.get(a.token) ?? selected.size) -
(priority.get(b.token) ?? selected.size),
);
let available = free;
for (const waiter of batch) {
if (results.has(waiter)) continue;
if (
!waiter.current() ||
leases.some(
(lease) =>
lease.trigger_id === waiter.id && !stale.includes(lease),
)
) {
results.set(waiter, false);
continue;
}
if (!available) break;
if (!selected.has(waiter.token)) continue;
const inserted = await this.db.query(
`INSERT INTO CronConcurrencyLeases(trigger_id,token,owner,command_identity)
SELECT $id,$token,$owner,$command FROM CronTriggers WHERE id=$id AND state='queued' AND COALESCE(stop_requested,0)=0
ON CONFLICT(trigger_id) DO NOTHING`,
{
bind: {
id: waiter.id,
token: waiter.token,
owner: waiter.owner,
command: waiter.commandIdentity ?? null,
},
transaction,
type: QueryTypes.BULKUPDATE,
},
);
results.set(waiter, inserted === 1);
if (inserted) {
await this.db.query(
'DELETE FROM CronConcurrencyWaiters WHERE trigger_id=$id AND token=$token',
{
bind: { id: waiter.id, token: waiter.token },
transaction,
},
);
available--;
}
}
},
);
}
const occupied = view.leases.filter(
(lease) => !view.stale.includes(lease),
);
this.diagnostics.observe(
batch
.filter((waiter) => !results.has(waiter))
.map((waiter) => waiter.id),
!view.free && occupied.length
? {
queue: 'global',
limit: view.limit,
occupied: occupied.length,
holders: occupied
.sort(
(a, b) =>
(a.at ?? 0) - (b.at ?? 0) ||
a.trigger_id.localeCompare(b.trigger_id),
)
.slice(0, 8)
.map((lease) => ({
id: lease.trigger_id,
name: lease.name || lease.trigger_id,
})),
}
: undefined,
);
for (const [waiter, acquired] of results) {
this.waiting.delete(waiter);
waiter.resolve(acquired);
}
} catch (error) {
this.diagnostics.observe([]);
for (const waiter of batch) {
this.waiting.delete(waiter);
waiter.reject(error);
}
} finally {
this.pumping = false;
if (this.waiting.size) {
// An arrival, expiration or release while a query was pending must not
// lose its wakeup and wait for the saturated-queue polling interval.
if (this.wakePending) this.wake();
else
this.timer = setTimeout(() => {
this.timer = undefined;
this.wake();
}, pollInterval);
}
}
}
}
+7 -2
View File
@@ -27,10 +27,15 @@ export async function runCron(
cmd: string,
cron: ICron,
isCurrent: () => boolean = () => true,
trigger?: { id: string; time: number; source: 'node' | 'recovery' },
trigger?: {
id: string;
time: number;
source: 'node' | 'recovery';
queuedAt?: number;
},
): Promise<number | void> {
const history = trigger && triggerHistory();
const queuedAt = Date.now();
const queuedAt = trigger?.queuedAt ?? Date.now();
if (trigger && history) {
const cronId = Number(cron.id);
const admitted = await historyWrites.add(() =>
+315 -139
View File
@@ -1,11 +1,15 @@
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { Op, QueryTypes, Sequelize, Transaction, col, fn } from 'sequelize';
import type { Crontab } from '../../data/cron';
import {
executionAssociation,
executionModel,
} from '../../data/executionModels';
import type { readExit } from '../settlement/exitReceipt.cjs';
import type {
TriggerSource,
TriggerState,
VerifiedSupervisorExit,
} from '../types';
import type { readExit } from '../settlement/exitReceipt.cjs';
import {
hasLiveCronProcess,
pidNamespaceOwner,
@@ -38,6 +42,8 @@ export interface TriggerLifecycleEvidence {
replayPublishedExits(transaction: Transaction): Promise<void>;
}
// Launch/command binding uses bound SQL to keep write transactions short.
// Preserve the state predicates and caller transaction when changing a query.
// 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 {
@@ -48,11 +54,22 @@ export class TriggerLifecycle {
// 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 },
);
await executionModel(this.database, 'CronTriggers')
.update(
{ state: 'skipped', reason, finished_at: finishedAt },
{
where: {
id,
source: { [Op.in]: ['node', 'recovery'] },
state: 'queued',
started_at: null,
},
silent: true,
hooks: false,
validate: false,
},
)
.then(([changed]) => changed);
}
async enqueue(
@@ -69,7 +86,7 @@ export class TriggerLifecycle {
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
source=excluded.source, owner=excluded.owner, resume_pending=NULL
WHERE excluded.source='recovery' AND state='skipped' AND reason='restart' AND started_at IS NULL`,
{
bind: {
@@ -102,16 +119,24 @@ export class TriggerLifecycle {
)
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,
const pending = await executionModel(
this.database,
'CronTriggers',
).findAll({
attributes: ['id'],
where: {
cron_id: cronId,
id: { [Op.ne]: id },
source: { [Op.in]: ['node', 'recovery', 'system'] },
[Op.or]: [
{ state: 'running' },
{ state: 'queued', queued_at: { [Op.gte]: revision } },
],
},
);
limit: 1,
transaction,
raw: true,
});
if (!pending.length) return true;
await this.finish(id, 'skipped', 'pending', null, transaction);
return false;
@@ -137,10 +162,14 @@ export class TriggerLifecycle {
);
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 },
);
const [task] = await executionModel(
this.database,
'CronTriggers',
).findAll({
attributes: ['cron_id'],
where: { id, state: 'queued' },
raw: true,
});
if (task && (await this.recoverSystemOwners(task.cron_id)))
changed = await claim();
}
@@ -258,18 +287,63 @@ export class TriggerLifecycle {
}
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 },
await executionModel(this.database, 'CronTriggers').update(
{ stop_requested: 1 },
{
where: {
cron_id: { [Op.in]: ids },
state: 'running',
command_identity: null,
instance_id: null,
},
transaction,
silent: true,
hooks: false,
validate: false,
},
);
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 },
const rows = await executionModel(this.database, 'CronTriggers').findAll({
attributes: ['id'],
where: {
cron_id: { [Op.in]: ids },
[Op.or]: [
{ state: 'queued' },
{
state: 'skipped',
reason: 'restart',
resume_pending: 1,
started_at: null,
},
],
},
transaction,
raw: true,
});
await executionModel(this.database, 'CronTriggers').update(
{
state: 'stopped',
reason: 'cancelled',
finished_at: Date.now(),
resume_pending: null,
},
{
where: {
cron_id: { [Op.in]: ids },
[Op.or]: [
{ state: 'queued' },
{
state: 'skipped',
reason: 'restart',
resume_pending: 1,
started_at: null,
},
],
},
transaction,
silent: true,
hooks: false,
validate: false,
},
);
return rows.map((r) => r.id);
}
@@ -300,36 +374,38 @@ export class TriggerLifecycle {
}
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 },
);
const [row] = await executionModel(
this.database,
'CronStopRequests',
).findAll({
attributes: [
'targets',
'signalled',
'signalled_at',
'root_identity',
'namespace_owner',
],
where: { instance_id: instanceId },
transaction,
raw: true,
});
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 },
);
return executionModel(this.database, 'CronStopBatches').findAll({
attributes: ['request_id', 'cron_ids'],
where: { snapshot: { [Op.not]: null } },
raw: true,
});
}
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 },
);
return executionModel(this.database, 'CronStopRequests').findAll({
attributes: ['instance_id', 'cron_id', 'pid', 'targets'],
order: [['instance_id', 'ASC']],
raw: true,
});
}
async forgetStop(
@@ -337,10 +413,11 @@ export class TriggerLifecycle {
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 } },
);
await executionModel(this.database, 'CronStopRequests').destroy({
where: { instance_id: instanceId, signalled: 0 },
transaction,
hooks: false,
});
const claimed = await this.pendingStop(instanceId, transaction);
if (!claimed && onEnded) await onEnded(transaction);
return claimed;
@@ -357,10 +434,14 @@ export class TriggerLifecycle {
// 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 } },
await executionModel(this.database, 'CronTriggers').update(
{ command_started_at: at },
{
where: { id, command_started_at: null, started_at: { [Op.not]: null } },
silent: true,
hooks: false,
validate: false,
},
);
}
@@ -383,6 +464,10 @@ export class TriggerLifecycle {
{ transaction, bind: { id }, type: QueryTypes.SELECT },
);
if (!row) return false;
await this.database.query(
'UPDATE CronConcurrencyLeases SET command_identity=$identity WHERE trigger_id=$id',
{ transaction, bind: { identity, id } },
);
await this.database.query(
'UPDATE CronTriggers SET command_identity=$identity WHERE id=$id',
{ transaction, bind: { identity, id } },
@@ -448,25 +533,31 @@ export class TriggerLifecycle {
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 },
);
return executionModel(this.database, 'CronTriggers').findAll({
attributes: [
'id',
'cron_id',
'command_identity',
'started_at',
'log_path',
],
where: {
cron_id: { [Op.in]: ids },
state: 'running',
instance_id: null,
command_identity: { [Op.not]: null },
},
transaction,
raw: true,
});
}
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 },
);
const [row] = await executionModel(this.database, 'CronTriggers').findAll({
attributes: ['process_identity'],
where: { instance_id: instanceId },
raw: true,
});
return row?.process_identity;
}
@@ -490,17 +581,37 @@ export class TriggerLifecycle {
const result = await this.database.transaction(
{ type: Transaction.TYPES.IMMEDIATE },
async (transaction) => {
const [row] = await this.database.query<{
const [row] = (await executionModel(
this.database,
'RunningInstances',
).findAll({
attributes: [
[col('trigger.id'), 'id'],
'pid',
'status',
[col('trigger.state'), 'state'],
[col('trigger.stop_requested'), 'stop_requested'],
],
where: { id: instanceId },
include: [
{
association: executionAssociation(
this.database,
'instanceTrigger',
),
attributes: [],
required: false,
},
],
transaction,
raw: true,
})) as unknown as Array<{
id: string | null;
pid: number;
status: number;
state: TriggerState | null;
state: string | 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 ||
@@ -554,14 +665,26 @@ export class TriggerLifecycle {
);
}
const signalledAt = Date.now();
await this.database.query(
'UPDATE CronStopRequests SET signalled=1,signalled_at=$signalledAt WHERE instance_id=$instanceId',
{ transaction, bind: { instanceId, signalledAt } },
await executionModel(this.database, 'CronStopRequests').update(
{ signalled: 1, signalled_at: signalledAt },
{
where: { instance_id: instanceId },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
if (row.state)
await this.database.query(
"UPDATE CronTriggers SET stop_requested=1 WHERE instance_id=$instanceId AND state='running'",
{ bind: { instanceId }, transaction },
await executionModel(this.database, 'CronTriggers').update(
{ stop_requested: 1 },
{
where: { instance_id: instanceId, state: 'running' },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
// Root delivery failure rolls back. After successful root delivery, retain
// the stop marker even if some descendants still need recovery.
@@ -580,10 +703,12 @@ export class TriggerLifecycle {
}
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 },
);
const [row] = await executionModel(this.database, 'CronTriggers').findAll({
attributes: ['stop_requested'],
where: { instance_id: instanceId },
transaction,
raw: true,
});
return row && Boolean(row.stop_requested);
}
@@ -592,23 +717,28 @@ export class TriggerLifecycle {
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 } },
const [row] = await executionModel(this.database, 'CronTriggers').findAll(
{
attributes: [
'id',
'owner',
'command_identity',
'reason',
'state',
'stop_exit_at',
'exit_code',
'exit_pending',
],
where: { instance_id: instanceId },
transaction,
raw: true,
},
);
await executionModel(this.database, 'CronStopRequests').destroy({
where: { instance_id: instanceId },
transaction,
hooks: false,
});
if (!row) return settleLegacy ? settleLegacy(transaction) : false;
if (row.state !== 'running') return row.state === 'stopped';
const legacyCrond =
@@ -645,13 +775,14 @@ export class TriggerLifecycle {
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 },
);
const [row] = (await executionModel(this.database, 'CronTriggers').findAll({
attributes: [
[fn('COUNT', col('id')), 'triggers'],
[fn('COUNT', fn('DISTINCT', col('cron_id'))), 'tasks'],
],
where: { state: 'queued', dequeued_at: null },
raw: true,
})) as unknown as Array<{ triggers: number; tasks: number }>;
return row;
}
@@ -664,20 +795,21 @@ export class TriggerLifecycle {
) {
// 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 },
);
const [task] = await executionModel(this.database, 'Crontabs').findAll({
attributes: ['allow_multiple_instances', 'status', 'pid', 'isDisabled'],
where: { id: cronId },
transaction,
raw: true,
});
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`,
VALUES ($id,$cronId,'system','queued',$owner,$commandIdentity,$observed,$rule,$dispatch)
ON CONFLICT(id) DO UPDATE SET command_identity=excluded.command_identity,
system_rule=excluded.system_rule,system_dispatch_at=excluded.system_dispatch_at
WHERE state='queued' AND source='system' AND owner=$owner
AND EXISTS (SELECT 1 FROM CronConcurrencyLeases WHERE trigger_id=$id AND command_identity=$commandIdentity)`,
{
bind: {
id,
@@ -699,12 +831,22 @@ export class TriggerLifecycle {
}
const multiple = task.allow_multiple_instances === 1;
const claimed =
(multiple || !hasLiveCronProcess(task.status, task.pid)) &&
(multiple ||
!hasLiveCronProcess(
task.status ?? undefined,
task.pid ?? undefined,
)) &&
(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 } },
await executionModel(this.database, 'CronTriggers').update(
{ command_started_at: now },
{
where: { id },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
if (claimed && owner.startsWith('crond:')) {
await this.registerCommandInstance(
@@ -729,8 +871,12 @@ export class TriggerLifecycle {
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')
const active = await this.database.query<{
id: string;
owner: string;
state: string;
}>(
`SELECT id,state,CASE WHEN owner LIKE 'crond:%' THEN owner ELSE COALESCE(command_identity,process_identity) END AS owner FROM CronTriggers WHERE (state='running' OR (state='queued' AND source='system' AND owner LIKE 'crond:%')) 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)`,
{
@@ -749,6 +895,10 @@ export class TriggerLifecycle {
if (code !== 'ENOENT' && code !== 'ESRCH') throw error;
}
const close = async (tx: Transaction) => {
if (row.state === 'queued') {
await this.finish(row.id, 'skipped', 'restart', null, tx);
return;
}
const [current] = await this.database.query<{
stop_requested: number;
exit_code: number | null;
@@ -788,16 +938,42 @@ export class TriggerLifecycle {
{ transaction },
);
// No process was bound and its launch gate closed when the worker exited.
await executionModel(this.database, 'CronTriggers').update(
{
state: 'stopped',
reason: 'cancelled',
started_at: null,
finished_at: Date.now(),
},
{
where: {
owner,
state: 'running',
stop_requested: 1,
instance_id: null,
command_identity: null,
},
transaction,
silent: true,
hooks: false,
validate: false,
},
);
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() } },
`UPDATE CronTriggers SET state='queued',started_at=NULL,reason=NULL
WHERE owner=$owner AND state='running' AND COALESCE(stop_requested,0)=0
AND command_identity IS NULL AND process_identity IS NULL AND instance_id IS NULL
AND (EXISTS (SELECT 1 FROM CronManualSubmissions WHERE trigger_id=CronTriggers.id)
OR EXISTS (SELECT 1 FROM CronConcurrencyLeases WHERE trigger_id=CronTriggers.id AND command_identity IS NULL))`,
{ transaction, bind: { owner } },
);
await this.database.query(
`UPDATE CronTriggers SET reason='restart',
resume_pending=CASE WHEN state='queued' AND source IN ('node','recovery') THEN 1 ELSE resume_pending END,
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')`,
WHERE (owner=$owner OR (source IN ('system','legacy','client') AND owner IS NULL AND $owner='http')) AND state IN ('queued','running')
AND NOT (state='queued' AND EXISTS (SELECT 1 FROM CronManualSubmissions WHERE trigger_id=CronTriggers.id))`,
{ transaction, bind: { owner, now: Date.now() } },
);
await this.recoverSystemOwners(undefined, transaction);
+203 -46
View File
@@ -1,8 +1,14 @@
import { QueryTypes, Sequelize } from 'sequelize';
import { Op, Sequelize, col, fn } from 'sequelize';
import {
executionAssociation,
executionModel,
} from '../../data/executionModels';
type Occupant = { id?: string; name: string };
type WaitingSample = { db: Sequelize; context?: string };
const LIVE_SAMPLE_INTERVAL_MS = 250;
export type Admission = {
queue: 'manual' | 'scheduled';
queue: 'manual' | 'scheduled' | 'global';
limit: number;
occupied: number;
holders: Occupant[];
@@ -11,9 +17,10 @@ export type Admission = {
// 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 waiting = new Map<string, WaitingSample>();
private writing = false;
private changed = false;
private timer?: NodeJS.Timeout;
constructor(
private queue: Admission['queue'],
@@ -22,45 +29,74 @@ export class QueueOccupants {
) {}
watch(id: string, db: Sequelize) {
this.waiting.set(id, db);
this.waiting.set(id, { db });
this.refresh();
}
forget(id?: string) {
if (id) this.waiting.delete(id);
if (!this.waiting.size) {
clearTimeout(this.timer);
this.timer = undefined;
this.changed = false;
}
}
refresh() {
if (!this.waiting.size) return;
this.changed = true;
if (this.writing) return;
if (this.writing || this.timer) return;
// Bound diagnostic write frequency across asynchronous admissions/handoffs.
// Execution and its durable admission/dequeue records never wait for this timer.
this.timer = setTimeout(() => {
this.timer = undefined;
void this.flush();
}, LIVE_SAMPLE_INTERVAL_MS);
this.timer.unref();
}
private async flush() {
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;
this.changed = false;
try {
const context = JSON.stringify(this.snapshot(this.limit()));
const groups = new Map<Sequelize, Map<string, WaitingSample>>();
for (const [id, sample] of this.waiting) {
if (sample.context === context) continue;
let group = groups.get(sample.db);
if (!group) groups.set(sample.db, (group = new Map()));
group.set(id, sample);
}
});
for (const [db, samples] of groups) {
try {
await executionModel(db, 'CronTriggers').update(
{ queue_live_context: context },
{
where: {
state: 'queued',
dequeued_at: null,
[Op.or]: [
{ queue_live_context: null },
{ queue_live_context: { [Op.ne]: context } },
],
id: { [Op.in]: [...samples.keys()] },
},
hooks: false,
validate: false,
},
);
for (const [id, sample] of samples) {
// A removed/re-admitted ID belongs to a different observation.
if (this.waiting.get(id) === sample) sample.context = context;
}
} catch (error) {
this.warn(error as Error);
}
}
} finally {
this.writing = false;
if (this.changed) this.refresh();
}
}
admission(limit: number): Admission | undefined {
@@ -104,24 +140,145 @@ export function recordQueueAdmission(
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) } },
return executionModel(db, 'CronTriggers').update(
{ queue_context: JSON.stringify(admission) },
{
where: { id, queued_at: { [Op.lte]: Date.now() }, queue_context: null },
silent: true,
hooks: false,
validate: false,
},
);
}
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 },
);
return executionModel(db, 'CronTriggers').findAll({
attributes: [
'id',
[
fn(
'COALESCE',
fn('NULLIF', col('task.name'), ''),
col('task.command'),
fn('printf', '#%s', col('CronTriggers.cron_id')),
),
'name',
],
'source',
'queued_at',
'queue_context',
'queue_live_context',
],
where: {
state: 'queued',
dequeued_at: null,
queued_at: { [Op.not]: null },
},
include: [
{
association: executionAssociation(db, 'triggerTask'),
attributes: [],
required: false,
},
],
order: [
['queued_at', 'ASC'],
['id', 'ASC'],
],
limit: 25,
raw: true,
}) as unknown as Promise<
Array<{
id: string;
name: string;
source: string;
queued_at: number;
queue_context: string | null;
queue_live_context: string | null;
}>
>;
}
// The shared budget supplies its existing occupancy snapshot, including foreign
// workers. Diagnostics never open a transaction on the admission critical path.
export class GlobalQueueDiagnostics {
private pending = new Map<string, string>();
private sampled = new Map<string, string>();
private timer?: NodeJS.Timeout;
private writing = false;
constructor(private db: Sequelize) {}
observe(ids: string[], admission?: Admission) {
const context = admission && JSON.stringify(admission);
this.pending = new Map(
ids.map((id) => [id, context ?? this.pending.get(id) ?? '']),
);
for (const id of this.sampled.keys())
if (!this.pending.has(id)) this.sampled.delete(id);
if (!ids.length) {
clearTimeout(this.timer);
this.timer = undefined;
} else this.schedule();
}
private schedule() {
if (
this.timer ||
this.writing ||
![...this.pending].some(
([id, value]) => value && this.sampled.get(id) !== value,
)
)
return;
this.timer = setTimeout(() => {
this.timer = undefined;
void this.flush();
}, LIVE_SAMPLE_INTERVAL_MS);
this.timer.unref();
}
private async flush() {
this.writing = true;
const groups = new Map<string, string[]>();
for (const [id, context] of this.pending) {
if (!context || this.sampled.get(id) === context) continue;
const group = groups.get(context) ?? [];
group.push(id);
groups.set(context, group);
}
try {
for (const [context, ids] of groups) {
await executionModel(this.db, 'CronTriggers').update(
{
queue_context: fn('COALESCE', col('queue_context'), context),
queue_live_context: context,
},
{
where: {
id: { [Op.in]: ids },
state: 'queued',
dequeued_at: null,
[Op.or]: [
{ queue_live_context: null },
{ queue_live_context: { [Op.ne]: context } },
],
},
hooks: false,
validate: false,
},
);
for (const id of ids)
if (this.pending.get(id) === context) this.sampled.set(id, context);
}
} catch (error) {
console.warn('[queue] Could not save global occupancy:', error);
// A later observation retries a failed sample, without a timer that can
// outlive the budget/database after the last waiter has left.
return;
} finally {
this.writing = false;
}
this.schedule();
}
}
+5 -1
View File
@@ -53,7 +53,11 @@ export class TriggerQueries {
scriptStartP95: number | null;
scriptOnTime: number;
}>(
`WITH today AS (SELECT * FROM CronTriggers WHERE observed_at >= $since),
// Reuse a narrow snapshot: inlining this CTE makes each count/percentile
// revisit the wide trigger rows, including their queue diagnostics.
`WITH today AS MATERIALIZED (
SELECT state,observed_at,scheduled_at,started_at,script_started_at,dequeued_at,queued_at
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),
@@ -0,0 +1,51 @@
import { executionModel } from '../../data/executionModels';
import { Op } from 'sequelize';
import type { ICron } from '../../protos/cron';
import { CrontabModel } from '../../data/cron';
import { slotId } from '../identity';
import { runCron } from '../execution/runCron';
// Accepted work is distinct from catching up timers missed while offline.
// Keep its identity and original queue deadline; never replay a bound command.
export async function resumeAcceptedCrons(item: ICron, current: () => boolean) {
const rows = await executionModel(
CrontabModel.sequelize!,
'CronTriggers',
).findAll({
attributes: ['id', 'scheduled_at', 'queued_at'],
where: {
cron_id: Number(item.id),
source: { [Op.in]: ['node', 'recovery'] },
state: 'skipped',
reason: 'restart',
resume_pending: 1,
started_at: null,
queued_at: { [Op.gte]: item.recovery_from || 0 },
},
order: [
['queued_at', 'ASC'],
['id', 'ASC'],
],
raw: true,
});
const rules = [
item.schedule,
...(item.extra_schedules || []).map((s) => s.schedule),
];
await Promise.all(
rows
.filter((row) =>
rules.some(
(rule, i) => slotId(item.id, i, rule, row.scheduled_at!) === row.id,
),
)
.map((row) =>
runCron(item.command, item, current, {
id: row.id,
time: row.scheduled_at!,
queuedAt: row.queued_at!,
source: 'recovery',
}),
),
);
}
+16 -10
View File
@@ -1,3 +1,4 @@
import { executionModel } from '../../data/executionModels';
import { AnomalyPage } from '../queries/scheduleAnomalies';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { AddCronRequest, DeleteCronRequest } from '../../protos/cron';
@@ -61,14 +62,14 @@ export async function saveSchedulePlan(
token: token ?? null,
};
if (token)
await db.query(
'INSERT INTO CronPlanSwitches(token,staged_at) VALUES($token,$now)',
{ transaction, bind: { token, now } },
await executionModel(db, 'CronPlanSwitches').create(
{ token, staged_at: now },
{ transaction, silent: true, hooks: false, validate: false },
);
if (replace)
await db.query(
'INSERT OR IGNORE INTO CronPlanCoverage(id,since) VALUES(1,$now)',
{ transaction, bind: { now } },
await executionModel(db, 'CronPlanCoverage').bulkCreate(
[{ id: 1, since: now }],
{ transaction, ignoreDuplicates: true, hooks: false },
);
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))`;
@@ -105,10 +106,15 @@ export async function confirmSchedulePlan(
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 } },
await executionModel(db, 'CronPlanSwitches').update(
{ first_at: first, last_at: last },
{
where: { token, last_at: null },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
if (replace) {
// After a crash the former worker's switch time is unknowable. A complete
+39 -19
View File
@@ -1,3 +1,4 @@
import { executionModel } from '../../data/executionModels';
import { AnomalyPage } from '../queries/scheduleAnomalies';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { blockSize, blockSlots } from './scheduleAudit';
@@ -35,20 +36,29 @@ export async function stageSystemPlan(
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 },
const [pending] = await executionModel(db, 'CronSystemPlans')
.findAll({
attributes: ['id', 'confirmed', 'zone', 'rules'],
order: [['id', 'DESC']],
limit: 1,
transaction,
type: QueryTypes.SELECT,
},
);
raw: true,
})
.then((rows) =>
rows.filter(
(row) =>
row.confirmed === null &&
row.zone === bind.zone &&
row.rules === bind.rules,
),
);
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 },
);
const [id] = await executionModel(db, 'CronSystemPlans')
.create(
{ staged: bind.at, zone: bind.zone, rules: bind.rules },
{ transaction, silent: true, hooks: false, validate: false },
)
.then((row) => [row.id] as const);
return id;
},
);
@@ -70,9 +80,15 @@ export async function confirmSystemPlan(
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 } },
await executionModel(db, 'CronSystemPlans').update(
{ confirmed: at },
{
where: { id, confirmed: null },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
// Keep the effective snapshot preceding the retention window.
await db.query(
@@ -94,10 +110,14 @@ export async function systemScheduleAudit(
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 [retention] = await executionModel(db, 'CronHistoryRetention')
.findAll({
attributes: ['cutoff'],
where: { id: 1 },
transaction,
raw: true,
})
.then(([row]) => [{ since: Math.max(dayStart, row?.cutoff ?? 0) }]);
const since = retention.since;
const installs = await db.query<Install>(
`SELECT * FROM CronSystemPlans WHERE id >= COALESCE((SELECT MAX(id) FROM CronSystemPlans
+201 -59
View File
@@ -1,4 +1,10 @@
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import {
QueryTypes,
Sequelize,
Transaction,
DataTypes,
ModelAttributes,
} from 'sequelize';
export async function installTriggerHistory(
database: Sequelize,
@@ -7,46 +13,143 @@ export async function installTriggerHistory(
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)`,
const statements: Array<
string | { table: string; attributes: ModelAttributes }
> = [
`CREATE TABLE IF NOT EXISTS CronConcurrencyLeases (
trigger_id TEXT PRIMARY KEY, token TEXT NOT NULL, owner TEXT NOT NULL,
command_identity TEXT) WITHOUT ROWID`,
`CREATE TABLE IF NOT EXISTS CronConcurrencyWaiters (
trigger_id TEXT PRIMARY KEY REFERENCES CronTriggers(id) ON DELETE CASCADE,
token TEXT NOT NULL, owner TEXT NOT NULL) WITHOUT ROWID`,
{
table: 'CronPlanSwitches',
attributes: {
seq: { type: DataTypes.INTEGER, primaryKey: true },
token: { type: DataTypes.TEXT, allowNull: false, unique: true },
staged_at: { type: DataTypes.INTEGER, allowNull: false },
first_at: { type: DataTypes.INTEGER },
last_at: { type: DataTypes.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)`,
{
table: 'CronPlanRules',
attributes: {
cron_id: { type: DataTypes.TEXT, allowNull: false },
rule_index: { type: DataTypes.INTEGER, allowNull: false },
schedule: { type: DataTypes.TEXT, allowNull: false },
zone: { type: DataTypes.TEXT, allowNull: false },
since: { type: DataTypes.INTEGER, allowNull: false },
until: { type: DataTypes.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)`,
{
table: 'CronTriggers',
attributes: {
id: { type: DataTypes.TEXT, primaryKey: true },
cron_id: { type: DataTypes.INTEGER, allowNull: false },
source: { type: DataTypes.TEXT, allowNull: false },
state: { type: DataTypes.TEXT, allowNull: false },
scheduled_at: { type: DataTypes.INTEGER },
queued_at: { type: DataTypes.INTEGER },
started_at: { type: DataTypes.INTEGER },
finished_at: { type: DataTypes.INTEGER },
reason: { type: DataTypes.TEXT },
exit_code: { type: DataTypes.INTEGER },
log_path: { type: DataTypes.TEXT },
counted: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },
owner: { type: DataTypes.TEXT },
observed_at: { type: DataTypes.INTEGER, allowNull: false },
},
},
`CREATE TABLE IF NOT EXISTS CronManualSubmissions (
trigger_id TEXT PRIMARY KEY REFERENCES CronTriggers(id) ON DELETE CASCADE,
token TEXT NOT NULL, snapshot TEXT NOT NULL) WITHOUT ROWID`,
{
table: 'CronShellBindings',
attributes: {
receipt: { type: DataTypes.TEXT, primaryKey: true },
trigger_id: {
type: DataTypes.TEXT,
allowNull: false,
references: { model: 'CronTriggers', key: 'id' },
onDelete: '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)`,
{
table: 'CronLegacyExitBookings',
attributes: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
cron_id: { type: DataTypes.INTEGER, allowNull: false },
source: { type: DataTypes.TEXT, allowNull: false },
started_at: { type: DataTypes.INTEGER, allowNull: false },
finished_at: { type: DataTypes.INTEGER, allowNull: false },
outcome: { type: DataTypes.TEXT, allowNull: false },
day: { type: DataTypes.TEXT, allowNull: false },
stopped: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },
stat_id: {
type: DataTypes.INTEGER,
references: { model: 'CrontabStats', key: 'id' },
onDelete: 'SET NULL',
},
disputed: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 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)`,
{
table: 'CronSystemPlans',
attributes: {
id: { type: DataTypes.INTEGER, primaryKey: true },
staged: { type: DataTypes.INTEGER, allowNull: false },
confirmed: { type: DataTypes.INTEGER },
zone: { type: DataTypes.TEXT, allowNull: false },
rules: { type: DataTypes.TEXT, allowNull: false },
},
},
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)`,
{
table: 'CronStopBatches',
attributes: {
request_id: { type: DataTypes.TEXT, primaryKey: true },
cron_ids: { type: DataTypes.TEXT, allowNull: false },
snapshot: { type: DataTypes.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)`,
{
table: 'CronStopRequests',
attributes: {
instance_id: { type: DataTypes.INTEGER, primaryKey: true },
cron_id: { type: DataTypes.INTEGER, allowNull: false },
pid: { type: DataTypes.INTEGER, allowNull: false },
targets: { type: DataTypes.TEXT },
signalled: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 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'",
@@ -54,27 +157,41 @@ export async function installTriggerHistory(
'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 });
for (const statement of statements) {
if (typeof statement === 'string')
await database.query(statement, { transaction });
else
await database
.getQueryInterface()
.createTable(statement.table, statement.attributes, { transaction });
}
// Sequelize 6 describeTable cannot inspect expression indexes (the indexed
// column name is null). Keep PRAGMA introspection for upgrade compatibility.
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 },
);
await database
.getQueryInterface()
.addColumn(
'CronPlanRules',
column,
{ type: DataTypes.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
.getQueryInterface()
.renameTable('CronBoundExitConflicts', 'CronBoundExitConflictPairs', {
transaction,
});
await database.query(conflictTable, { transaction });
await database.query(
`INSERT INTO CronBoundExitConflicts(trigger_id,outcome,finished_at)
@@ -82,47 +199,67 @@ export async function installTriggerHistory(
SELECT trigger_id,other_outcome,other_finished_at FROM CronBoundExitConflictPairs`,
{ transaction },
);
await database.query('DROP TABLE CronBoundExitConflictPairs', {
transaction,
});
await database
.getQueryInterface()
.dropTable('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 },
);
await database
.getQueryInterface()
.addColumn(
'CronLegacyExitBookings',
'bound',
{ type: DataTypes.INTEGER, allowNull: false, defaultValue: 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 },
);
await database
.getQueryInterface()
.addColumn(
'CronStopBatches',
'status_code',
{ type: DataTypes.INTEGER, allowNull: false, defaultValue: 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 },
);
await database
.getQueryInterface()
.addColumn(
'CronStopRequests',
'signalled_at',
{ type: DataTypes.INTEGER },
{ transaction },
);
if (!stopFields.some((column) => column.name === 'root_identity'))
await database.query(
'ALTER TABLE CronStopRequests ADD COLUMN root_identity TEXT',
{ transaction },
);
await database
.getQueryInterface()
.addColumn(
'CronStopRequests',
'root_identity',
{ type: DataTypes.TEXT },
{ transaction },
);
if (!stopFields.some((column) => column.name === 'namespace_owner'))
await database.query(
'ALTER TABLE CronStopRequests ADD COLUMN namespace_owner TEXT',
{ transaction },
);
await database
.getQueryInterface()
.addColumn(
'CronStopRequests',
'namespace_owner',
{ type: DataTypes.TEXT },
{ transaction },
);
const fields = await database.query<{ name: string }>(
'PRAGMA table_info(CronTriggers)',
{ transaction, type: QueryTypes.SELECT },
@@ -137,6 +274,7 @@ export async function installTriggerHistory(
['instance_id', 'INTEGER'],
['script_started_at', 'INTEGER'],
['stop_requested', 'INTEGER'],
['resume_pending', 'INTEGER'],
['process_identity', 'TEXT'],
['command_identity', 'TEXT'],
['stop_exit_at', 'INTEGER'],
@@ -144,10 +282,14 @@ export async function installTriggerHistory(
['exit_pending', 'INTEGER'],
]) {
if (!fields.some((field) => field.name === column))
await database.query(
`ALTER TABLE CronTriggers ADD COLUMN ${column} ${type}`,
{ transaction },
);
await database
.getQueryInterface()
.addColumn(
'CronTriggers',
column,
{ type: type === 'TEXT' ? DataTypes.TEXT : DataTypes.INTEGER },
{ transaction },
);
}
await database.query(
`CREATE TRIGGER IF NOT EXISTS cron_exit_observations_settled AFTER UPDATE OF counted ON CronTriggers
+1
View File
@@ -1,6 +1,7 @@
import dayjs from 'dayjs';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
// This per-exit claim stays bound SQL; its affected-row count gates the increment.
// Hold the receipt claim and the daily increment in the same write transaction.
export async function recordCronResult(
database: Sequelize,
+183 -104
View File
@@ -1,3 +1,28 @@
import dayjs from 'dayjs';
import { promises as fs } from 'fs';
import { basename, join } from 'path';
import {
Op,
QueryTypes,
Sequelize,
Transaction,
col,
fn,
literal,
where,
} from 'sequelize';
import { executionModel } from '../../data/executionModels';
import type {
TriggerLifecycle,
TriggerLifecycleEvidence,
} from '../execution/triggerLifecycle';
import type {
Trigger,
TriggerSource,
TriggerState,
VerifiedSupervisorExit,
} from '../types';
import { addDailyExit, recordCronResult } from './cronStatistics';
import {
isLegacyCapture,
isMetadataReceipt,
@@ -9,21 +34,6 @@ import {
retiringExits,
validExit,
} from './exitReceipt.cjs';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import dayjs from 'dayjs';
import { addDailyExit, recordCronResult } from './cronStatistics';
import { promises as fs } from 'fs';
import { basename, join } from 'path';
import type {
Trigger,
TriggerSource,
TriggerState,
VerifiedSupervisorExit,
} from '../types';
import type {
TriggerLifecycle,
TriggerLifecycleEvidence,
} from '../execution/triggerLifecycle';
// The lifecycle owns transition guards; settlement must use its caller's transaction.
export type TriggerSettlementLifecycle = Pick<
@@ -56,6 +66,8 @@ function isBoundPublication(file: string) {
);
}
// High-frequency receipt/instance updates use bound SQL to avoid model query
// construction while the writer is held. Infrequent recovery reads stay ORM.
// Receipt verification, disputes and statistics are one transactional unit.
// Durable evidence is retired only after the committed outcome is checked again.
export class TriggerSettlement implements TriggerLifecycleEvidence {
@@ -402,22 +414,24 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
transaction,
},
);
await this.database.query(
'DELETE FROM CrontabStats WHERE id=$stat AND run_count=0',
{ bind: { stat }, transaction },
);
await executionModel(this.database, 'CrontabStats').destroy({
where: { id: stat, run_count: 0 },
transaction,
hooks: false,
});
}
}
private async invalidateBookedTrigger(id: string, transaction: Transaction) {
const [trigger] = await this.database.query<{
instance_id: number | null;
state: TriggerState;
cron_id: number;
}>(
'SELECT instance_id,state,cron_id FROM CronTriggers WHERE id=$id AND started_at IS NOT NULL',
{ bind: { id }, type: QueryTypes.SELECT, transaction },
);
const [trigger] = await executionModel(
this.database,
'CronTriggers',
).findAll({
attributes: ['instance_id', 'state', 'cron_id'],
where: { id, started_at: { [Op.not]: null } },
transaction,
raw: true,
});
if (!trigger) return false;
const ref = trigger.cron_id;
await this.database.query(
@@ -426,13 +440,25 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
{ bind: { id }, transaction },
);
if (trigger.instance_id !== null && trigger.state !== 'running') {
await this.database.query(
'UPDATE RunningInstances SET status=4,exit_code=NULL,updatedAt=CURRENT_TIMESTAMP WHERE id=$instance AND cron_id=$ref',
{ bind: { instance: trigger.instance_id, ref }, transaction },
await executionModel(this.database, 'RunningInstances').update(
{ status: 4, exit_code: null, updatedAt: literal('CURRENT_TIMESTAMP') },
{
where: { id: trigger.instance_id, cron_id: ref },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
await this.database.query(
'UPDATE Crontabs SET last_running_time=NULL WHERE id=$ref AND last_instance_id=$instance',
{ bind: { ref, instance: trigger.instance_id }, transaction },
await executionModel(this.database, 'Crontabs').update(
{ last_running_time: null },
{
where: { id: ref, last_instance_id: trigger.instance_id },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
}
return true;
@@ -444,10 +470,13 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
transaction: Transaction,
) {
if (!tuples.length) return;
await this.database.query(
`INSERT OR IGNORE INTO CronBoundExitConflicts(trigger_id,outcome,finished_at)
SELECT $id,json_extract(value,'$.outcome'),json_extract(value,'$.time') FROM json_each($tuples)`,
{ bind: { id, tuples: JSON.stringify(tuples) }, transaction },
await executionModel(this.database, 'CronBoundExitConflicts').bulkCreate(
tuples.map((tuple) => ({
trigger_id: id,
outcome: tuple.outcome,
finished_at: tuple.time,
})),
{ transaction, ignoreDuplicates: true, hooks: false },
);
}
@@ -502,9 +531,15 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
const retained = await this.invalidateBookedTrigger(id, transaction);
if (!retained) {
if (!bound) {
await this.database.query(
'UPDATE CronLegacyExitBookings SET disputed=1,stat_id=NULL WHERE trigger_id=$id',
{ bind: { id }, transaction },
await executionModel(this.database, 'CronLegacyExitBookings').update(
{ disputed: 1, stat_id: null },
{
where: { trigger_id: id },
transaction,
silent: true,
hooks: false,
validate: false,
},
);
} else {
await this.bookPrunedExit(
@@ -516,18 +551,21 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
}
return false;
}
await this.database.query(
'DELETE FROM CronLegacyExitBookings WHERE trigger_id=$id',
{ bind: { id }, transaction },
);
await executionModel(this.database, 'CronLegacyExitBookings').destroy({
where: { trigger_id: id },
transaction,
hooks: false,
});
if (!bound)
await this.database.query(
`INSERT OR IGNORE INTO CronExitObservations(trigger_id,outcome,finished_at)
VALUES($id,$outcome,$time)`,
{
bind: { id, outcome: booking.outcome, time: booking.finished_at },
transaction,
},
await executionModel(this.database, 'CronExitObservations').bulkCreate(
[
{
trigger_id: id,
outcome: booking.outcome,
finished_at: booking.finished_at,
},
],
{ transaction, ignoreDuplicates: true, hooks: false },
);
return true;
}
@@ -575,13 +613,15 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
// Sequelize also invokes this hook after a failed COMMIT. Verify the
// specific tuple in a separate snapshot, including on an existing dispute.
try {
const rows = await this.database.query<{
outcome: string;
finished_at: number;
}>(
'SELECT outcome,finished_at FROM CronBoundExitConflicts WHERE trigger_id=$id',
{ bind: { id }, transaction: null, type: QueryTypes.SELECT },
);
const rows = await executionModel(
this.database,
'CronBoundExitConflicts',
).findAll({
attributes: ['outcome', 'finished_at'],
where: { trigger_id: id },
transaction: null,
raw: true,
});
const committed = new Set(
rows.map((row) => JSON.stringify([row.outcome, row.finished_at])),
);
@@ -699,11 +739,21 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
if (unreadable.size) {
// Retention runs this scan before deletion. Keep unresolved history for
// later repair without ending a live process solely on damaged bytes.
await this.database.query(
`UPDATE CronTriggers SET exit_pending=1 WHERE counted=0 AND state='unknown'
AND exit_pending IS NOT 1 AND owner IS NOT NULL AND started_at IS NOT NULL
AND id IN (SELECT value FROM json_each($ids))`,
{ transaction, bind: { ids: JSON.stringify([...unreadable]) } },
await executionModel(this.database, 'CronTriggers').update(
{ exit_pending: 1 },
{
where: {
counted: 0,
state: 'unknown',
owner: { [Op.not]: null },
started_at: { [Op.not]: null },
id: { [Op.in]: [...unreadable] },
[Op.or]: [{ exit_pending: null }, { exit_pending: { [Op.ne]: 1 } }],
},
transaction,
hooks: false,
validate: false,
},
);
}
for (const [id, copies] of byId) {
@@ -753,11 +803,23 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
exit: ExitObservation,
transaction?: Transaction,
) {
const [match] = await this.database.query(
`SELECT 1 FROM CronExitObservations WHERE trigger_id=$id GROUP BY trigger_id
HAVING COUNT(*)=1 AND MAX(outcome)=$outcome AND MAX(finished_at)=$time`,
{ bind: observationKey(id, exit), type: QueryTypes.SELECT, transaction },
);
const [match] = await executionModel(
this.database,
'CronExitObservations',
).findAll({
attributes: ['trigger_id'],
where: { trigger_id: id },
group: ['trigger_id'],
having: {
[Op.and]: [
where(fn('COUNT', col('trigger_id')), 1),
where(fn('MAX', col('outcome')), observationKey(id, exit).outcome),
where(fn('MAX', col('finished_at')), observationKey(id, exit).time),
],
},
transaction,
raw: true,
});
return Boolean(match);
}
@@ -782,9 +844,18 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
) {
if (observation)
await this.saveExitObservation(id, observation, transaction);
await this.database.query(
'UPDATE CronTriggers SET exit_pending=1 WHERE id=$id AND exit_pending IS NOT 1',
{ bind: { id }, transaction },
await executionModel(this.database, 'CronTriggers').update(
{ exit_pending: 1 },
{
where: {
id,
[Op.or]: [{ exit_pending: { [Op.ne]: 1 } }, { exit_pending: null }],
},
transaction,
silent: true,
hooks: false,
validate: false,
},
);
// A signalled stop remains running until all of its descendants are gone.
await this.database.query(
@@ -850,18 +921,15 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
if (!files.length) return;
// Only probe existing executions. Keep live markers in place so another
// instrumented command in the same execution cannot replace the first sample.
const rows = await this.database.query<{
id: string;
counted: number;
script_started_at: number | null;
}>(
`SELECT id,counted,script_started_at FROM CronTriggers WHERE id IN (SELECT value FROM json_each($ids))
AND started_at IS NOT NULL AND (script_started_at IS NULL OR counted=1)`,
{
bind: { ids: JSON.stringify(files.map(({ id }) => id)) },
type: QueryTypes.SELECT,
const rows = await executionModel(this.database, 'CronTriggers').findAll({
attributes: ['id', 'counted', 'script_started_at'],
where: {
id: { [Op.in]: files.map(({ id }) => id) },
started_at: { [Op.not]: null },
[Op.or]: [{ script_started_at: null }, { counted: 1 }],
},
);
raw: true,
});
for (const row of rows) {
const sample = await this.readScriptSample(row.id);
if (!sample) continue;
@@ -885,14 +953,14 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
// exit file was already deleted. An unregistered entry may still be live.
const exits = new Set(await publishedExits());
for (const { id, file } of await publishedScriptStarts()) {
const [row] = await this.database.query<{
counted: number;
script_started_at: number | null;
}>('SELECT counted,script_started_at FROM CronTriggers WHERE id=$id', {
bind: { id },
transaction,
type: QueryTypes.SELECT,
});
const [row] = await executionModel(this.database, 'CronTriggers').findAll(
{
attributes: ['counted', 'script_started_at'],
where: { id },
transaction,
raw: true,
},
);
// After pruning the trigger, a matching supervisor exit still identifies
// this panel's retired run. A start file alone cannot establish that.
if (row ? row.counted && row.script_started_at !== null : exits.has(id)) {
@@ -1018,10 +1086,15 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
}
async hasBoundConflict(id: string, transaction: Transaction) {
const [conflict] = await this.database.query(
'SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=$id',
{ bind: { id }, transaction, type: QueryTypes.SELECT },
);
const [conflict] = await executionModel(
this.database,
'CronBoundExitConflicts',
).findAll({
attributes: ['trigger_id'],
where: { trigger_id: id },
transaction,
raw: true,
});
return Boolean(conflict);
}
@@ -1037,19 +1110,25 @@ export class TriggerSettlement implements TriggerLifecycleEvidence {
) {
return this.database.transaction(async (transaction) => {
if (await this.hasBoundConflict(id, transaction)) return;
const [row] = await this.database.query<{
owner: string | null;
state: TriggerState;
}>(
'SELECT owner,state FROM CronTriggers WHERE id=$id AND cron_id=$cronId',
{ transaction, type: QueryTypes.SELECT, bind: { id, cronId } },
const [row] = await executionModel(this.database, 'CronTriggers').findAll(
{
attributes: ['owner', 'state'],
where: { id, cron_id: cronId },
transaction,
raw: true,
},
);
if (!row) {
if (finishedAt && finishedAt <= now) {
const [pruned] = await this.database.query(
'SELECT 1 FROM CronHistoryRetention WHERE id=1 AND cutoff>$end',
{ transaction, type: QueryTypes.SELECT, bind: { end: finishedAt } },
);
const [pruned] = await executionModel(
this.database,
'CronHistoryRetention',
).findAll({
attributes: ['id'],
where: { id: 1, cutoff: { [Op.gt]: finishedAt } },
transaction,
raw: true,
});
if (pruned) return;
}
throw new Error('Unknown trigger');
+3 -39
View File
@@ -1,5 +1,6 @@
import { defineCrontabModel } from './executionModelDefinitions';
import { sequelize } from '.';
import { DataTypes, Model, ModelDefined } from 'sequelize';
import { Model } from 'sequelize';
export class Crontab {
name?: string;
@@ -72,41 +73,4 @@ export enum CrontabStatus {
}
export interface CronInstance extends Model<Crontab, Crontab>, Crontab {}
export const CrontabModel = sequelize.define<CronInstance>('Crontab', {
name: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
command: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
schedule: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
timestamp: DataTypes.STRING,
saved: DataTypes.BOOLEAN,
status: DataTypes.NUMBER,
isSystem: DataTypes.NUMBER,
pid: DataTypes.NUMBER,
isDisabled: DataTypes.NUMBER,
isPinned: DataTypes.NUMBER,
log_path: DataTypes.STRING,
queued_token: DataTypes.STRING,
labels: DataTypes.JSON,
last_instance_id: DataTypes.INTEGER,
last_running_time: DataTypes.NUMBER,
last_execution_time: DataTypes.NUMBER,
sub_id: { type: DataTypes.NUMBER, allowNull: true },
extra_schedules: DataTypes.JSON,
task_before: DataTypes.STRING,
task_after: DataTypes.STRING,
log_name: DataTypes.STRING,
allow_multiple_instances: DataTypes.NUMBER,
skip_if_pending: DataTypes.BOOLEAN,
max_queue_wait: DataTypes.INTEGER,
catchup_seconds: DataTypes.INTEGER,
recovery_from: DataTypes.BIGINT,
work_dir: DataTypes.STRING,
});
export const CrontabModel = defineCrontabModel(sequelize);
+3 -51
View File
@@ -1,4 +1,5 @@
import { DataTypes, Model } from 'sequelize';
import { defineCrontabStatModel } from './executionModelDefinitions';
import { Model } from 'sequelize';
import { sequelize } from '.';
export class CrontabStat {
@@ -30,53 +31,4 @@ export interface CrontabStatInstance
extends Model<CrontabStat, CrontabStat>,
CrontabStat {}
export const CrontabStatModel = sequelize.define<CrontabStatInstance>(
'CrontabStat',
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
ref_id: {
type: DataTypes.NUMBER,
allowNull: false,
},
date: {
type: DataTypes.STRING,
allowNull: false,
},
run_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
success_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
fail_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
untimed_count: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
total_time: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
fixed_max_time: { type: DataTypes.NUMBER, allowNull: true },
max_time: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
},
{
indexes: [
{ unique: true, fields: ['ref_id', 'date'] },
{ fields: ['date'] },
],
},
);
export const CrontabStatModel = defineCrontabStatModel(sequelize);
+160
View File
@@ -0,0 +1,160 @@
import { DataTypes, Sequelize } from 'sequelize';
import type { CronInstance } from './cron';
import type { RunningInstanceModel } from './runningInstance';
import type { CrontabStatInstance } from './cronStats';
import type { SystemInstance } from './system';
export function defineCrontabModel(database: Sequelize) {
return database.define<CronInstance>('Crontab', {
name: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
command: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
schedule: {
unique: 'compositeIndex',
type: DataTypes.STRING,
},
timestamp: DataTypes.STRING,
saved: DataTypes.BOOLEAN,
status: DataTypes.NUMBER,
isSystem: DataTypes.NUMBER,
pid: DataTypes.NUMBER,
isDisabled: DataTypes.NUMBER,
isPinned: DataTypes.NUMBER,
log_path: DataTypes.STRING,
queued_token: DataTypes.STRING,
labels: DataTypes.JSON,
last_instance_id: DataTypes.INTEGER,
last_running_time: DataTypes.NUMBER,
last_execution_time: DataTypes.NUMBER,
sub_id: { type: DataTypes.NUMBER, allowNull: true },
extra_schedules: DataTypes.JSON,
task_before: DataTypes.STRING,
task_after: DataTypes.STRING,
log_name: DataTypes.STRING,
allow_multiple_instances: DataTypes.NUMBER,
skip_if_pending: DataTypes.BOOLEAN,
max_queue_wait: DataTypes.INTEGER,
catchup_seconds: DataTypes.INTEGER,
recovery_from: DataTypes.BIGINT,
work_dir: DataTypes.STRING,
});
}
export function defineRunningInstanceModel(database: Sequelize) {
return database.define<RunningInstanceModel>(
'RunningInstance',
{
cron_id: {
type: DataTypes.NUMBER,
allowNull: false,
},
pid: {
type: DataTypes.NUMBER,
allowNull: true,
},
log_path: {
type: DataTypes.STRING,
allowNull: true,
},
started_at: {
type: DataTypes.NUMBER,
allowNull: false,
},
finished_at: {
type: DataTypes.NUMBER,
allowNull: true,
},
status: {
type: DataTypes.NUMBER,
allowNull: false,
defaultValue: 0,
},
exit_code: {
type: DataTypes.NUMBER,
allowNull: true,
},
},
{
indexes: [
{ fields: ['cron_id', 'pid', 'started_at'] },
{ fields: ['cron_id', 'id'] },
// Settlement looks for live siblings while holding the writer transaction.
// Finished history must not make that lookup scan every past execution.
{
name: 'running_instances_active_cron_id',
fields: ['cron_id', 'id'],
where: { status: 0 },
},
],
},
);
}
export function defineCrontabStatModel(database: Sequelize) {
return database.define<CrontabStatInstance>(
'CrontabStat',
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
ref_id: {
type: DataTypes.NUMBER,
allowNull: false,
},
date: {
type: DataTypes.STRING,
allowNull: false,
},
run_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
success_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
fail_count: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
untimed_count: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
},
total_time: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
fixed_max_time: { type: DataTypes.NUMBER, allowNull: true },
max_time: {
type: DataTypes.NUMBER,
defaultValue: 0,
},
},
{
indexes: [
{ unique: true, fields: ['ref_id', 'date'] },
{ fields: ['date'] },
],
},
);
}
export function defineSystemModel(database: Sequelize) {
return database.define<SystemInstance>('Auth', {
ip: DataTypes.STRING,
type: DataTypes.STRING,
info: {
type: DataTypes.JSON,
allowNull: true,
},
});
}
+390
View File
@@ -0,0 +1,390 @@
import {
defineCrontabModel,
defineRunningInstanceModel,
defineCrontabStatModel,
defineSystemModel,
} from './executionModelDefinitions';
import {
DataTypes,
Model,
ModelStatic,
Sequelize,
ModelAttributes,
} from 'sequelize';
import type { Literal, Fn, Col } from 'sequelize/types/utils';
import type { CronInstance } from './cron';
import type { RunningInstanceModel } from './runningInstance';
import type { CrontabStatInstance } from './cronStats';
import type { SystemInstance } from './system';
import type { TriggerSource, TriggerState } from '../cron/types';
// Ledger tables are installed by versioned migrations, not Model.sync().
// Bind each mapping to its caller's connection: workers and test databases must
// never share the application's singleton or silently open another transaction.
interface LedgerRows {
CronPlanCoverage: { id: number; since: number };
CronTriggers: {
id: string;
source: TriggerSource;
state: TriggerState;
reason: string | null;
log_path: string | null;
owner: string | null;
queue_context: string | null;
queue_live_context: string | null;
system_rule: string | null;
process_identity: string | null;
command_identity: string | null;
cron_id: number;
scheduled_at: number | null;
queued_at: number | null;
started_at: number | null;
finished_at: number | null;
exit_code: number | null;
counted: number;
observed_at: number;
dequeued_at: number | null;
system_dispatch_at: number | null;
command_started_at: number | null;
instance_id: number | null;
script_started_at: number | null;
stop_requested: number | null;
resume_pending: number | null;
stop_exit_at: number | null;
stop_exit_verified: number | null;
exit_pending: number | null;
};
CronConcurrencyLeases: {
trigger_id: string;
token: string;
owner: string;
command_identity: string | null;
};
CronConcurrencyWaiters: {
trigger_id: string;
token: string;
owner: string;
};
CronStopRequests: {
targets: string | null;
root_identity: string | null;
namespace_owner: string | null;
instance_id: number;
cron_id: number;
pid: number | null;
signalled: number;
signalled_at: number | null;
};
CronStopBatches: {
request_id: string;
cron_ids: string;
snapshot: string | null;
status_code: number;
};
CronManualSubmissions: {
trigger_id: string;
token: string;
snapshot: string;
};
CronShellBindings: {
receipt: string;
trigger_id: string | null;
};
CronExitObservations: {
trigger_id: string;
outcome: string;
finished_at: number;
};
CronBoundExitConflicts: {
trigger_id: string;
outcome: string;
finished_at: number;
};
CronUnmatchedBoundExits: {
trigger_id: string;
outcome: string | null;
finished_at: number | null;
};
CronLegacyExitBookings: {
trigger_id: string;
source: TriggerSource;
outcome: string | null;
day: string | null;
cron_id: number;
started_at: number | null;
finished_at: number | null;
stopped: number | null;
stat_id: number | null;
disputed: number | null;
bound: number | null;
};
CronPrunedUnknownRuns: {
trigger_id: string;
source: TriggerSource;
last_possible_day: string;
cron_id: number;
started_at: number;
};
CronHistoryRetention: {
id: number;
cutoff: number;
};
CronPlanSwitches: {
token: string;
seq: number;
staged_at: number | null;
first_at: number | null;
last_at: number | null;
};
CronSystemPlans: {
zone: string;
rules: string;
id: number;
staged: number;
confirmed: number | null;
};
SchemaMigrations: {
id: string;
applied_at: string;
};
}
type Persisted<T> = {
[K in keyof T]-?: undefined extends T[K]
? Exclude<T[K], undefined> | null
: T[K];
} & { id: number; createdAt: Date; updatedAt: Date };
type ExistingRows = {
Crontabs: Persisted<CronInstance['_attributes']>;
RunningInstances: Persisted<RunningInstanceModel['_attributes']>;
CrontabStats: Persisted<CrontabStatInstance['_attributes']>;
Auths: Persisted<SystemInstance['_attributes']>;
};
type Rows = LedgerRows & ExistingRows;
type Creation<T> = { [K in keyof T]?: T[K] | Literal | Fn | Col };
type RowModel<T extends object> = Model<T, Creation<T>> & T;
const definitions: {
[K in keyof LedgerRows]: ModelAttributes<RowModel<LedgerRows[K]>>;
} = {
CronPlanCoverage: {
id: { type: DataTypes.INTEGER, primaryKey: true },
since: DataTypes.BIGINT,
},
CronTriggers: {
id: { type: DataTypes.TEXT, primaryKey: true },
source: DataTypes.TEXT,
state: DataTypes.TEXT,
reason: DataTypes.TEXT,
log_path: DataTypes.TEXT,
owner: DataTypes.TEXT,
queue_context: DataTypes.TEXT,
queue_live_context: DataTypes.TEXT,
system_rule: DataTypes.TEXT,
process_identity: DataTypes.TEXT,
command_identity: DataTypes.TEXT,
cron_id: DataTypes.BIGINT,
scheduled_at: DataTypes.BIGINT,
queued_at: DataTypes.BIGINT,
started_at: DataTypes.BIGINT,
finished_at: DataTypes.BIGINT,
exit_code: DataTypes.BIGINT,
counted: DataTypes.BIGINT,
observed_at: DataTypes.BIGINT,
dequeued_at: DataTypes.BIGINT,
system_dispatch_at: DataTypes.BIGINT,
command_started_at: DataTypes.BIGINT,
instance_id: DataTypes.BIGINT,
script_started_at: DataTypes.BIGINT,
stop_requested: DataTypes.BIGINT,
resume_pending: DataTypes.BIGINT,
stop_exit_at: DataTypes.BIGINT,
stop_exit_verified: DataTypes.BIGINT,
exit_pending: DataTypes.BIGINT,
},
CronConcurrencyLeases: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
token: DataTypes.TEXT,
owner: DataTypes.TEXT,
command_identity: DataTypes.TEXT,
},
CronConcurrencyWaiters: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
token: DataTypes.TEXT,
owner: DataTypes.TEXT,
},
CronStopRequests: {
targets: DataTypes.TEXT,
root_identity: DataTypes.TEXT,
namespace_owner: DataTypes.TEXT,
instance_id: { type: DataTypes.INTEGER, primaryKey: true },
cron_id: DataTypes.BIGINT,
pid: DataTypes.BIGINT,
signalled: DataTypes.BIGINT,
signalled_at: DataTypes.BIGINT,
},
CronStopBatches: {
request_id: { type: DataTypes.TEXT, primaryKey: true },
cron_ids: DataTypes.TEXT,
snapshot: DataTypes.TEXT,
status_code: DataTypes.BIGINT,
},
CronManualSubmissions: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
token: DataTypes.TEXT,
snapshot: DataTypes.TEXT,
},
CronShellBindings: {
receipt: { type: DataTypes.TEXT, primaryKey: true },
trigger_id: DataTypes.TEXT,
},
CronExitObservations: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
outcome: { type: DataTypes.TEXT, primaryKey: true },
finished_at: { type: DataTypes.INTEGER, primaryKey: true },
},
CronBoundExitConflicts: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
outcome: { type: DataTypes.TEXT, primaryKey: true },
finished_at: { type: DataTypes.INTEGER, primaryKey: true },
},
CronUnmatchedBoundExits: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
outcome: DataTypes.TEXT,
finished_at: DataTypes.BIGINT,
},
CronLegacyExitBookings: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
source: DataTypes.TEXT,
outcome: DataTypes.TEXT,
day: DataTypes.TEXT,
cron_id: DataTypes.BIGINT,
started_at: DataTypes.BIGINT,
finished_at: DataTypes.BIGINT,
stopped: DataTypes.BIGINT,
stat_id: DataTypes.BIGINT,
disputed: DataTypes.BIGINT,
bound: DataTypes.BIGINT,
},
CronPrunedUnknownRuns: {
trigger_id: { type: DataTypes.TEXT, primaryKey: true },
source: DataTypes.TEXT,
last_possible_day: DataTypes.TEXT,
cron_id: DataTypes.BIGINT,
started_at: DataTypes.BIGINT,
},
CronHistoryRetention: {
id: { type: DataTypes.INTEGER, primaryKey: true },
cutoff: DataTypes.BIGINT,
},
CronPlanSwitches: {
token: DataTypes.TEXT,
seq: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
staged_at: DataTypes.BIGINT,
first_at: DataTypes.BIGINT,
last_at: DataTypes.BIGINT,
},
CronSystemPlans: {
zone: DataTypes.TEXT,
rules: DataTypes.TEXT,
id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
staged: DataTypes.BIGINT,
confirmed: DataTypes.BIGINT,
},
SchemaMigrations: {
id: { type: DataTypes.TEXT, primaryKey: true },
applied_at: DataTypes.TEXT,
},
};
const existingNames: Record<keyof ExistingRows, string> = {
Crontabs: 'Crontab',
RunningInstances: 'RunningInstance',
CrontabStats: 'CrontabStat',
Auths: 'Auth',
};
export function executionModel<K extends keyof Rows>(
database: Sequelize,
table: K,
): ModelStatic<RowModel<Rows[K]>> {
const name =
table in existingNames ? existingNames[table as keyof ExistingRows] : table;
if (!database.isDefined(name)) {
if (table === 'Crontabs') defineCrontabModel(database);
else if (table === 'RunningInstances') defineRunningInstanceModel(database);
else if (table === 'CrontabStats') defineCrontabStatModel(database);
else if (table === 'Auths') defineSystemModel(database);
else
database.define(
name,
definitions[table as keyof LedgerRows] as ModelAttributes,
{ tableName: table, timestamps: false, freezeTableName: true },
);
}
return database.model(name) as ModelStatic<RowModel<Rows[K]>>;
}
const relationships = {
leaseTrigger: [
'CronConcurrencyLeases',
'CronTriggers',
'trigger',
'trigger_id',
'id',
],
waiterTrigger: [
'CronConcurrencyWaiters',
'CronTriggers',
'trigger',
'trigger_id',
'id',
],
submissionTrigger: [
'CronManualSubmissions',
'CronTriggers',
'trigger',
'trigger_id',
'id',
],
triggerStop: [
'CronTriggers',
'CronStopRequests',
'stop',
'instance_id',
'instance_id',
],
triggerTask: ['CronTriggers', 'Crontabs', 'task', 'cron_id', 'id'],
instanceTrigger: [
'RunningInstances',
'CronTriggers',
'trigger',
'instance_id',
'id',
],
} as const;
// Associations describe existing joins only; migrations own foreign keys.
export function executionAssociation(
database: Sequelize,
relation: keyof typeof relationships,
) {
const [from, to, as, foreignKey, key] = relationships[relation];
const source: ModelStatic<Model> = executionModel(database, from);
if (!source.associations[as]) {
const target: ModelStatic<Model> = executionModel(database, to);
if (relation === 'instanceTrigger')
source.hasOne(target, {
as,
foreignKey,
sourceKey: key,
constraints: false,
});
else
source.belongsTo(target, {
as,
foreignKey,
targetKey: key,
constraints: false,
});
}
return source.associations[as];
}
+9 -1
View File
@@ -8,7 +8,11 @@ export const sequelize = new Sequelize({
storage: join(config.dbPath, 'database.sqlite'),
logging: false,
retry: {
max: 10,
// Keep a bounded 15-second wait in JS. Constant delays let a burst of
// writers make progress without exponential retries stretching the queue.
max: 301,
backoffBase: 50,
backoffExponent: 1,
match: ['SQLITE_BUSY: database is locked'],
},
pool: {
@@ -29,6 +33,10 @@ sequelize.addHook('beforeQuery', async (_options, query) => {
let ready = initialized.get(connection);
if (!ready) {
ready = new Promise<void>((resolve, reject) => {
// Native busy waits occupy libuv workers. Concurrent BEGINs can exhaust
// that pool and prevent the lock holder's next query or COMMIT from
// running. Let Sequelize's asynchronous SQLITE_BUSY retries wait instead.
connection.configure('busyTimeout', 0);
connection.run('PRAGMA synchronous=EXTRA', (error) =>
error ? reject(error) : resolve(),
);
+3 -41
View File
@@ -1,5 +1,6 @@
import { defineRunningInstanceModel } from './executionModelDefinitions';
import { sequelize } from '.';
import { DataTypes, Model } from 'sequelize';
import { Model } from 'sequelize';
export enum InstanceStatus {
'running' = 0,
@@ -46,43 +47,4 @@ export interface RunningInstanceModel
extends Model<RunningInstanceAttributes, RunningInstanceAttributes>,
RunningInstanceAttributes {}
export const RunningInstanceModel = sequelize.define<RunningInstanceModel>(
'RunningInstance',
{
cron_id: {
type: DataTypes.NUMBER,
allowNull: false,
},
pid: {
type: DataTypes.NUMBER,
allowNull: true,
},
log_path: {
type: DataTypes.STRING,
allowNull: true,
},
started_at: {
type: DataTypes.NUMBER,
allowNull: false,
},
finished_at: {
type: DataTypes.NUMBER,
allowNull: true,
},
status: {
type: DataTypes.NUMBER,
allowNull: false,
defaultValue: InstanceStatus.running,
},
exit_code: {
type: DataTypes.NUMBER,
allowNull: true,
},
},
{
indexes: [
{ fields: ['cron_id', 'pid', 'started_at'] },
{ fields: ['cron_id', 'id'] },
],
},
);
export const RunningInstanceModel = defineRunningInstanceModel(sequelize);
+38 -25
View File
@@ -1,7 +1,8 @@
import { executionModel } from './executionModels';
import dayjs from 'dayjs';
import { installTriggerHistory } from '../cron/schema';
import { repairLegacyDailyStatistics } from '../cron/settlement/legacyDailyStatistics';
import { QueryTypes, Sequelize } from 'sequelize';
import { QueryTypes, Sequelize, literal, DataTypes } from 'sequelize';
export const prunedExitMigrationId = 'preserve-pruned-bound-exits-v1';
@@ -45,15 +46,20 @@ const columns = [
export async function migrateSchema(database: Sequelize): Promise<void> {
await database.transaction(async (transaction) => {
await database.query(
'CREATE TABLE IF NOT EXISTS "SchemaMigrations" ("id" TEXT PRIMARY KEY, "applied_at" TEXT NOT NULL)',
await database.getQueryInterface().createTable(
'SchemaMigrations',
{
id: { type: DataTypes.TEXT, primaryKey: true },
applied_at: { type: DataTypes.TEXT, allowNull: false },
},
{ transaction },
);
await installTriggerHistory(database, transaction);
const applied = await database.query<{ id: string }>(
'SELECT "id" FROM "SchemaMigrations"',
{ type: QueryTypes.SELECT, transaction },
);
const applied = await executionModel(database, 'SchemaMigrations').findAll({
attributes: ['id'],
transaction,
raw: true,
});
const appliedIds = new Set(applied.map(({ id }) => id));
for (const { table, column, type } of columns) {
const id = `add-${table}-${column}`;
@@ -68,18 +74,22 @@ export async function migrateSchema(database: Sequelize): Promise<void> {
throw new Error(`Migration table is missing: ${table}`);
if (!fields.some((field) => field.name === column)) {
// table/column/type come only from the static migration manifest above.
await database.query(
`ALTER TABLE "${table}" ADD COLUMN "${column}" ${type}`,
await database.getQueryInterface().addColumn(
table,
column,
{
type: type.replace(' NOT NULL DEFAULT 0', ''),
...(type.includes('NOT NULL')
? { allowNull: false, defaultValue: 0 }
: {}),
},
{ transaction },
);
}
if (!appliedIds.has(id)) {
await database.query(
'INSERT INTO "SchemaMigrations" ("id", "applied_at") VALUES (:id, :appliedAt)',
{
replacements: { id, appliedAt: new Date().toISOString() },
transaction,
},
await executionModel(database, 'SchemaMigrations').create(
{ id, applied_at: new Date().toISOString() },
{ transaction, silent: true, hooks: false, validate: false },
);
}
}
@@ -107,19 +117,22 @@ export async function migrateSchema(database: Sequelize): Promise<void> {
},
);
}
await database.query(
'INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
{ bind: { id: retentionId }, transaction },
await executionModel(database, 'SchemaMigrations').create(
{ id: retentionId, applied_at: literal('CURRENT_TIMESTAMP') },
{ transaction, silent: true, hooks: false, validate: false },
);
}
if (!appliedIds.has(repairId)) {
await repairLegacyDailyStatistics(database, transaction, prior);
// This reconciliation includes v1 and v2. Record all on fresh installations
// so rolling back and upgrading again cannot replay the superseded repair.
await database.query(
`INSERT OR IGNORE INTO SchemaMigrations(id,applied_at)
VALUES ('repair-legacy-daily-statistics-v1',CURRENT_TIMESTAMP),('repair-legacy-daily-statistics-v2',CURRENT_TIMESTAMP),($id,CURRENT_TIMESTAMP)`,
{ transaction, bind: { id: repairId } },
await executionModel(database, 'SchemaMigrations').bulkCreate(
[
'repair-legacy-daily-statistics-v1',
'repair-legacy-daily-statistics-v2',
repairId,
].map((id) => ({ id, applied_at: literal('CURRENT_TIMESTAMP') })),
{ transaction, ignoreDuplicates: true, hooks: false },
);
}
@@ -133,9 +146,9 @@ export async function migrateSchema(database: Sequelize): Promise<void> {
AND NOT EXISTS (SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=b.trigger_id)`,
{ transaction },
);
await database.query(
'INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
{ bind: { id: prunedExitMigrationId }, transaction },
await executionModel(database, 'SchemaMigrations').create(
{ id: prunedExitMigrationId, applied_at: literal('CURRENT_TIMESTAMP') },
{ transaction, silent: true, hooks: false, validate: false },
);
}
+3 -9
View File
@@ -1,5 +1,6 @@
import { defineSystemModel } from './executionModelDefinitions';
import { sequelize } from '.';
import { DataTypes, Model, ModelDefined } from 'sequelize';
import { Model } from 'sequelize';
import { NotificationInfo } from './notify';
export class SystemInfo {
@@ -109,11 +110,4 @@ export type SystemModelInfo = SystemConfigInfo &
export interface SystemInstance
extends Model<SystemInfo, SystemInfo>,
SystemInfo {}
export const SystemModel = sequelize.define<SystemInstance>('Auth', {
ip: DataTypes.STRING,
type: DataTypes.STRING,
info: {
type: DataTypes.JSON,
allowNull: true,
},
});
export const SystemModel = defineSystemModel(sequelize);
+1
View File
@@ -225,6 +225,7 @@ export default async () => {
await systemService.restoreCronConcurrency();
});
await cronClient.readiness.recover();
await cronService.recoverQueuedTasks();
const authInfo = await userService.getAuthInfo();
await shareStore.updateAuthInfo(authInfo);
+6
View File
@@ -8,6 +8,7 @@ import { slotId } from '../cron/history';
import { runCron } from '../cron/execution/runCron';
import Logger from '../loaders/logger';
import { t, tf } from '../shared/i18n';
import { resumeAcceptedCrons } from '../cron/scheduling/resumeAcceptedCrons';
// Validate the entire batch before replacing any existing jobs.
const isValidCronField = (cron: string): boolean => {
@@ -77,6 +78,11 @@ const addCron = (
const jobs: CronJob[] = [];
definitions.set(jobs, signature);
prepared.set(item.id, jobs);
if (call.request.replace && savePlan) {
recoveries.push(() =>
resumeAcceptedCrons(item, () => scheduleStacks.get(item.id) === jobs),
);
}
for (const [ruleIndex, schedule] of [
item.schedule,
...(item.extra_schedules || []).map((x) => x.schedule),
+25
View File
@@ -0,0 +1,25 @@
import type {
UntypedServiceImplementation,
sendUnaryData,
} from '@grpc/grpc-js';
import { ApiService } from '../protos/api';
// Registration/health never need the script API's HTTP-oriented services.
// Keep their dependency graph out of an ordinary scheduler's resident heap.
// Dynamic import shares initialization across simultaneous first calls; the
// normal handlers retain validation, callback errors and service singletons.
export function lazyApiHandlers(): UntypedServiceImplementation {
return Object.fromEntries(
Object.keys(ApiService).map((method) => [
method,
(call: unknown, callback: sendUnaryData<unknown>) => {
void import('./api')
.then((handlers) => {
const handler = handlers[method as keyof typeof ApiService];
return handler(call as never, callback);
})
.catch(callback);
},
]),
);
}
+4
View File
@@ -907,4 +907,8 @@ export default class CronService {
);
}
}
public async recoverQueuedTasks() {
await this.execution.recoverQueued();
}
}
+3 -3
View File
@@ -1,5 +1,6 @@
import { sequelize } from '../data';
import groupBy from 'lodash/groupBy';
import { FindOptions, Op } from 'sequelize';
import { FindOptions, Op, fn, col } from 'sequelize';
import { Inject, Service } from 'typedi';
import winston from 'winston';
import config from '../config';
@@ -13,7 +14,6 @@ import {
stepPosition,
} from '../data/env';
import { writeFileWithLock } from '../shared/utils';
import { sequelize } from '../data';
import {
assertAllowedTaskEnvName,
isAllowedTaskEnvName,
@@ -153,7 +153,7 @@ export default class EnvService {
}
try {
const result = await this.find(condition, [
[sequelize.literal('COALESCE(`isPinned`, 0)'), 'DESC'],
[fn('COALESCE', col('isPinned'), 0), 'DESC'],
['position', 'DESC'],
['createdAt', 'ASC'],
]);
+2 -2
View File
@@ -5,7 +5,7 @@ import { ApiService } from '../protos/api';
import { registeredAdd, registeredDelete } from '../schedule/registeredPlans';
import { setConcurrency } from '../schedule/setConcurrency';
import { check } from '../schedule/health';
import * as Api from '../schedule/api';
import { lazyApiHandlers } from '../schedule/lazyApiHandlers';
import Logger from '../loaders/logger';
import { promisify } from 'util';
import config from '../config';
@@ -32,7 +32,7 @@ export class GrpcServerService {
delCron: registeredDelete,
setConcurrency,
});
this.server.addService(ApiService, Api);
this.server.addService(ApiService, lazyApiHandlers());
const tlsConfig = await initGrpcCerts();
const credentials = ServerCredentials.createSsl(
+35
View File
@@ -0,0 +1,35 @@
import type { Sequelize } from 'sequelize';
import { performance } from 'perf_hooks';
// Per database and day: concurrent viewers share one computation. Rejections
// are never cached; a new day cannot reuse yesterday's summary. Runtime/task
// control endpoints remain live and never read this display-only snapshot.
const snapshots = new WeakMap<
Sequelize,
{ key: string; until: number; value: Promise<unknown> }
>();
export function dashboardSnapshot<T>(
db: Sequelize,
key: string,
compute: () => Promise<T>,
): Promise<T> {
const existing = snapshots.get(db);
if (existing?.key === key && performance.now() < existing.until)
return existing.value as Promise<T>;
const entry = {
key,
until: Infinity,
value: Promise.resolve().then(compute),
};
snapshots.set(db, entry);
entry.value.then(
() => {
// Wall-clock corrections must not stretch a one-second cache for minutes.
entry.until = performance.now() + 1000;
},
() => {
if (snapshots.get(db) === entry) snapshots.delete(db);
},
);
return entry.value;
}
+6 -2
View File
@@ -39,8 +39,12 @@ export function resolveFileAccess(
while (!fs.existsSync(existing)) {
// existsSync is false for a dangling symlink; never treat one as absent.
try {
fs.lstatSync(existing);
return '';
const entry = fs.lstatSync(existing);
if (entry.isSymbolicLink()) return '';
// Another task may have created this directory after existsSync.
// Canonicalize the now-existing entry below, with the same root and
// blacklist checks, rather than rejecting a legitimate concurrent run.
break;
} catch (error: any) {
if (error.code !== 'ENOENT') return '';
}
+73
View File
@@ -1,5 +1,6 @@
import fs from 'fs/promises';
import { createHash } from 'crypto';
import type { BigIntStats } from 'fs';
export const DEFAULT_LOG_CHUNK_BYTES = 256 * 1024;
export const MAX_LOG_CHUNK_BYTES = 1024 * 1024;
@@ -7,6 +8,37 @@ export const MAX_LOG_CHUNK_BYTES = 1024 * 1024;
// The viewer retains at most one Mi UTF-16 code units.
const CURSOR_WINDOW_BYTES = 4 * MAX_LOG_CHUNK_BYTES;
// Cache only a server-verified EOF, never client-supplied file metadata or log
// contents. Bound both the number of viewers retained and verification lifetime.
const EOF_CACHE_LIMIT = 256;
const EOF_CACHE_TTL_MS = 30_000;
const EOF_CACHE_SETTLE_MS = 2_000;
const verifiedEnds = new Map<
string,
{ version: string; cursor: string; offset: number; verifiedAt: number }
>();
function fileVersion(stat: BigIntStats) {
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.birthtimeNs}`;
}
function rememberEnd(
filePath: string,
version: string,
cursor: string,
offset: number,
) {
verifiedEnds.delete(filePath);
verifiedEnds.set(filePath, {
version,
cursor,
offset,
verifiedAt: Date.now(),
});
if (verifiedEnds.size > EOF_CACHE_LIMIT)
verifiedEnds.delete(verifiedEnds.keys().next().value!);
}
export interface LogReadOptions {
offset?: number;
limit?: number;
@@ -68,6 +100,15 @@ export async function readLogChunk(
const stat = await handle.stat({ bigint: true });
const total = Number(stat.size);
const identity = `${stat.dev}:${stat.ino}`;
const version = fileVersion(stat);
const observedAt = Date.now();
// Even nanosecond stat fields can repeat across writes within a filesystem
// clock tick. Never cache content read while that timestamp is still fresh.
const metadataSettled =
Number(stat.mtimeMs) > 0 &&
Number(stat.ctimeMs) > 0 &&
observedAt - Number(stat.mtimeMs) >= EOF_CACHE_SETTLE_MS &&
observedAt - Number(stat.ctimeMs) >= EOF_CACHE_SETTLE_MS;
const limit = normalizeLimit(options.limit);
const requestedOffset = Number.isFinite(options.offset)
? Math.max(0, Math.trunc(options.offset!))
@@ -78,6 +119,30 @@ export async function readLogChunk(
: Math.min(requestedOffset, total);
const resume =
options.cursor && !options.tail && requestedOffset !== undefined;
const verified = verifiedEnds.get(filePath);
if (
resume &&
verified?.version === version &&
verified.cursor === options.cursor &&
verified.offset === requestedOffset &&
requestedOffset === total &&
observedAt >= verified.verifiedAt &&
observedAt - verified.verifiedAt < EOF_CACHE_TTL_MS
) {
// A cache hit does not extend the deadline: even an unchanged file is
// periodically verified again. Keep the entry recent without retaining bytes.
verifiedEnds.delete(filePath);
verifiedEnds.set(filePath, verified);
return {
content: '',
offset: total,
nextOffset: total,
total,
truncated: total > 0,
cursor: options.cursor,
reset: false,
};
}
const [fromText, digest] = resume ? options.cursor!.split('.') : [];
let from = resume ? Number(fromText) : start;
let reset = Boolean(
@@ -136,6 +201,13 @@ export async function readLogChunk(
)}`;
}
if (cursor && nextOffset === total && metadataSettled) {
// Do not trust an EOF read that raced with append, truncate or overwrite.
// ctime also detects rewrites that restore mtime; inode detects replacement.
if (fileVersion(await handle.stat({ bigint: true })) === version)
rememberEnd(filePath, version, cursor, nextOffset);
}
return {
...(cursor && { cursor, reset }),
content: buffer.subarray(leadingBytes, contentEnd).toString('utf8'),
@@ -146,6 +218,7 @@ export async function readLogChunk(
};
} catch (error: any) {
if (error?.code === 'ENOENT') {
verifiedEnds.delete(filePath);
return {
content: '',
offset: 0,