mirror of
https://github.com/whyour/qinglong.git
synced 2026-12-01 09:45:36 +08:00
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:
1 parent
cddabbaf0e
commit
2f01f756d7
74 files changed
+6891
-837
No files matched your search
@@ -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]) {
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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(() =>
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user