mirror of
https://github.com/whyour/qinglong.git
synced 2026-12-01 09:45:36 +08:00
feat(cron): expose run receipts and modularize execution
Return committed trigger IDs and add CLI wait and trigger-specific logs while preserving API, CLI, transaction, deduplication and unknown-result semantics. Move scheduling, lifecycle, settlement, queries and legacy adapters into back/cron; remove obsolete internal import paths and circular dependencies. Apply project formatting across the repository, cover CJS/MJS in formatting hooks, add prettier:check and require formatting checks in AGENTS.md. Validation: backend build; 1398 backend/frontend tests passed (17 platform skips); 327 CLI tests passed (6 platform skips); 670 files pass format checks.
This commit is contained in:
1 parent
77ece406ac
commit
c5458596c8
346 files changed
+32133
-11556
No files matched your search
@@ -0,0 +1,108 @@
|
||||
import dayjs from 'dayjs';
|
||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||
|
||||
// Hold the receipt claim and the daily increment in the same write transaction.
|
||||
export async function recordCronResult(
|
||||
database: Sequelize,
|
||||
cronId: number,
|
||||
_code: number,
|
||||
elapsedMs: number,
|
||||
finishedAt: number,
|
||||
triggerId: string,
|
||||
transaction?: Transaction,
|
||||
): Promise<void> {
|
||||
if (!triggerId) throw new Error('Execution identity required');
|
||||
if (!transaction) {
|
||||
return database.transaction((tx) =>
|
||||
recordCronResult(
|
||||
database,
|
||||
cronId,
|
||||
_code,
|
||||
elapsedMs,
|
||||
finishedAt,
|
||||
triggerId,
|
||||
tx,
|
||||
),
|
||||
);
|
||||
}
|
||||
const bind = { ref: cronId, id: triggerId };
|
||||
const claimed = await database.query(
|
||||
"UPDATE CronTriggers SET counted=1,exit_pending=NULL WHERE cron_id=$ref AND id=$id AND counted=0 AND started_at IS NOT NULL AND state IN ('finished','failed','stopped')",
|
||||
{ bind, type: QueryTypes.BULKUPDATE, transaction },
|
||||
);
|
||||
if (!claimed) {
|
||||
const rows = await database.query(
|
||||
'SELECT 1 FROM CronTriggers WHERE cron_id=$ref AND id=$id',
|
||||
{ bind, type: QueryTypes.SELECT, transaction },
|
||||
);
|
||||
if (!rows.length) throw new Error('Unknown trigger');
|
||||
return;
|
||||
}
|
||||
const [receipt] = await database.query<{
|
||||
state: string;
|
||||
finished_at: number;
|
||||
reversible: number;
|
||||
}>(
|
||||
`SELECT state,finished_at,EXISTS(SELECT 1 FROM CronLegacyExitBookings WHERE trigger_id=$id) AS reversible
|
||||
FROM CronTriggers WHERE cron_id=$ref AND id=$id`,
|
||||
{ bind, type: QueryTypes.SELECT, transaction },
|
||||
);
|
||||
const day = dayjs(receipt.finished_at ?? finishedAt).format('YYYY-MM-DD');
|
||||
await addDailyExit(
|
||||
database,
|
||||
cronId,
|
||||
day,
|
||||
receipt.state,
|
||||
elapsedMs,
|
||||
Boolean(receipt.reversible),
|
||||
transaction,
|
||||
);
|
||||
if (receipt.reversible) {
|
||||
await database.query(
|
||||
`UPDATE CronLegacyExitBookings SET stopped=$stopped,
|
||||
stat_id=(SELECT id FROM CrontabStats WHERE ref_id=$ref AND date=$day
|
||||
AND NOT EXISTS (SELECT 1 FROM CronStatRetention WHERE id=1 AND first_day>$day))
|
||||
WHERE trigger_id=$id`,
|
||||
{
|
||||
bind: { ...bind, day, stopped: Number(receipt.state === 'stopped') },
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function addDailyExit(
|
||||
database: Sequelize,
|
||||
cronId: number,
|
||||
day: string,
|
||||
state: string,
|
||||
elapsedMs: number,
|
||||
reversible: boolean,
|
||||
transaction: Transaction,
|
||||
) {
|
||||
await database.query(
|
||||
`INSERT INTO "CrontabStats"
|
||||
(ref_id, date, run_count, success_count, fail_count, total_time, max_time, fixed_max_time, createdAt, updatedAt)
|
||||
SELECT $id, $date, 1, $success, $fail, $elapsed, $elapsed, $fixedMax, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
WHERE NOT EXISTS (SELECT 1 FROM CronStatRetention WHERE id=1 AND first_day>$date)
|
||||
ON CONFLICT(ref_id, date) DO UPDATE SET
|
||||
run_count = COALESCE(run_count, 0) + 1,
|
||||
success_count = COALESCE(success_count, 0) + excluded.success_count,
|
||||
fail_count = COALESCE(fail_count, 0) + excluded.fail_count,
|
||||
total_time = COALESCE(total_time, 0) + excluded.total_time,
|
||||
max_time = MAX(COALESCE(max_time, 0), excluded.max_time),
|
||||
fixed_max_time = MAX(COALESCE(fixed_max_time,max_time,0),excluded.fixed_max_time),
|
||||
updatedAt = excluded.updatedAt`,
|
||||
{
|
||||
transaction,
|
||||
bind: {
|
||||
id: cronId,
|
||||
date: day,
|
||||
fixedMax: reversible ? 0 : elapsedMs,
|
||||
success: Number(state === 'finished'),
|
||||
fail: Number(state === 'failed'),
|
||||
elapsed: elapsedMs,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
// Keep the command's actual exit available until its SQLite transaction commits.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { createHash, randomUUID } = require('node:crypto');
|
||||
|
||||
const idPattern = /^[a-z0-9-]{1,120}$/;
|
||||
|
||||
// A full data volume can still have room for a directory entry. In this format
|
||||
// the empty file publishes the tuple atomically, including its execution-bound
|
||||
// checksum. Keep the encoded name when moving it into a collector-private slot.
|
||||
const metadataName =
|
||||
/^\.pending\.([a-z0-9-]{1,120})\.full-(\d{1,3}|SIG[A-Z0-9]+)-(\d{1,16})-([0-9a-f]{64})-([a-zA-Z0-9_]+)$/;
|
||||
|
||||
// The digest only guards disposal of legacy bytes. It cannot establish an exit.
|
||||
const legacyCapture =
|
||||
/^\.pending\.([a-z0-9-]{1,120})\.l-([0-9a-f]{32})-[0-9a-f]{24}$/;
|
||||
const claimName = /^\.claim(-bound)?\.([a-z0-9-]{1,120})\.[a-zA-Z0-9]{6}$/;
|
||||
|
||||
function metadataReceipt(file) {
|
||||
const name = path.basename(file);
|
||||
return metadataName.exec(
|
||||
name === '.pending.claimed' ? path.basename(path.dirname(file)) : name,
|
||||
);
|
||||
}
|
||||
|
||||
function storageFull(error) {
|
||||
const codes = [error?.code, error?.original?.code, error?.parent?.code];
|
||||
if (codes.some((code) => ['ENOSPC', 'EDQUOT', 'SQLITE_FULL'].includes(code)))
|
||||
return true;
|
||||
const directory = receiptDirectory();
|
||||
if (directory && codes.includes('SQLITE_CANTOPEN')) {
|
||||
// SQLite maps a failed journal creation to CANTOPEN even when the kernel
|
||||
// reported ENOSPC. Other open failures keep their normal error semantics.
|
||||
try {
|
||||
const capacity = fs.statfsSync(path.dirname(directory));
|
||||
return (
|
||||
capacity.bavail === 0 || (capacity.files > 0 && capacity.ffree === 0)
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function receiptDirectory() {
|
||||
const data =
|
||||
process.env.QL_DATA_DIR ||
|
||||
(process.env.QL_DIR && path.join(process.env.QL_DIR, 'data'));
|
||||
if (data) return path.join(data, 'db', 'cron-exits');
|
||||
}
|
||||
|
||||
function receiptPath(id) {
|
||||
const directory = receiptDirectory();
|
||||
if (directory && typeof id === 'string' && idPattern.test(id))
|
||||
return path.join(directory, id);
|
||||
}
|
||||
|
||||
async function listReceiptFiles(directory, prefix) {
|
||||
if (!directory) return [];
|
||||
try {
|
||||
const entries = await fs.promises.readdir(directory, {
|
||||
withFileTypes: true,
|
||||
});
|
||||
const files = [];
|
||||
for (const entry of entries) {
|
||||
if (!entry.isFile() || !entry.name.startsWith(prefix)) continue;
|
||||
const id = entry.name.slice(prefix.length);
|
||||
if (idPattern.test(id))
|
||||
files.push({ id, file: path.join(directory, entry.name) });
|
||||
}
|
||||
return files;
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function publishedExits() {
|
||||
return (await listReceiptFiles(receiptDirectory(), '')).map(
|
||||
(entry) => entry.id,
|
||||
);
|
||||
}
|
||||
|
||||
// flock attaches to the open file description. The child inherits fd 3 and
|
||||
// exits immediately. Closing the panel's handle (including on SIGKILL)
|
||||
// releases the lock without leaving a lock file on a full volume.
|
||||
async function lockClaim(handle, shared) {
|
||||
const run = (program, args) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const child = require('node:child_process').spawn(program, args, {
|
||||
stdio: ['ignore', 'ignore', 'ignore', handle.fd],
|
||||
});
|
||||
child.once('error', reject);
|
||||
child.once('exit', (code, signal) => {
|
||||
if (code === 0 || code === 1) resolve(code === 0);
|
||||
else
|
||||
reject(
|
||||
new Error(`Receipt directory lock failed (${signal || code})`),
|
||||
);
|
||||
});
|
||||
});
|
||||
try {
|
||||
return await run('flock', ['-n', shared ? '-s' : '-x', '3']);
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
// Python is also shipped with the task supervisor on minimal Linux images.
|
||||
const program =
|
||||
'import fcntl,sys\ntry: fcntl.flock(3, fcntl.LOCK_NB | fcntl.LOCK_' +
|
||||
(shared ? 'SH' : 'EX') +
|
||||
')\nexcept BlockingIOError: sys.exit(1)';
|
||||
return run('python3', ['-c', program]);
|
||||
}
|
||||
}
|
||||
|
||||
// Move the current directory entry to a fresh, recoverable name outside the
|
||||
// reusable claim directory. A writer can replace that entry without flock.
|
||||
// Only the bytes actually captured by this attempt authorize its final unlink.
|
||||
/** @param {string} id @param {string} file @param {{outcome: string, time: number}} [booked] */
|
||||
async function retireLegacyFile(id, file, booked) {
|
||||
const directory = receiptDirectory();
|
||||
const sourceDir = path.dirname(file);
|
||||
const slot = path.basename(file);
|
||||
const bound =
|
||||
/^\.(pending|published)\./.test(slot) && !legacyCapture.test(slot);
|
||||
const metadata = metadataReceipt(file);
|
||||
const parent = claimName.exec(path.basename(sourceDir));
|
||||
const privateSlot =
|
||||
path.dirname(sourceDir) === directory &&
|
||||
((parent?.[2] === id &&
|
||||
slot === (parent[1] ? '.pending.claimed' : 'receipt')) ||
|
||||
(metadata?.[1] === id && slot === '.pending.claimed'));
|
||||
if (!directory || !idPattern.test(id)) return;
|
||||
const dbDir = path.dirname(directory);
|
||||
const localBin = path.join(directory, '.reclaim');
|
||||
const fromBin = sourceDir === dbDir || sourceDir === localBin;
|
||||
if (
|
||||
sourceDir !== directory &&
|
||||
!privateSlot &&
|
||||
!(fromBin && captureId(slot) === id)
|
||||
)
|
||||
return;
|
||||
|
||||
const matches = (exit) =>
|
||||
exit &&
|
||||
!exit.namedExit &&
|
||||
(exit.version === 1
|
||||
? booked &&
|
||||
exit.time === booked.time &&
|
||||
(exit.signal ?? String(exit.code)) === booked.outcome
|
||||
: !bound);
|
||||
let handle, binHandle;
|
||||
try {
|
||||
if (
|
||||
(privateSlot || sourceDir === localBin) &&
|
||||
process.platform === 'linux'
|
||||
) {
|
||||
handle = await fs.promises.open(
|
||||
sourceDir,
|
||||
fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,
|
||||
);
|
||||
if (privateSlot && !(await lockClaim(handle, true))) return;
|
||||
}
|
||||
const source = handle ? `/proc/self/fd/${handle.fd}/${slot}` : file;
|
||||
// A canonical publication may only be readable after the move. For a
|
||||
// recovered copy, first avoid moving an unsettled witness on every scan.
|
||||
const previous = await readExit(id, source, file);
|
||||
if (slot !== id && !matches(previous)) return;
|
||||
const nonce = randomUUID();
|
||||
let name;
|
||||
if (metadata) {
|
||||
name =
|
||||
metadata[0].slice(0, -metadata[5].length) +
|
||||
'r_' +
|
||||
nonce.replace(/-/g, '').slice(0, 16);
|
||||
} else if (bound || !previous || previous.version === 1) {
|
||||
name = `.pending.${id}.r-${nonce}`;
|
||||
} else {
|
||||
const digest = exitChecksum(
|
||||
id,
|
||||
previous.code,
|
||||
previous.signal,
|
||||
previous.time,
|
||||
).slice(0, 32);
|
||||
name = `.pending.${id}.l-${digest}-${nonce
|
||||
.replace(/-/g, '')
|
||||
.slice(0, 24)}`;
|
||||
}
|
||||
// The database directory is outside the writers' receipt namespace and
|
||||
// already exists even at zero free inodes. A separately mounted journal
|
||||
// requires a disposal directory on its own filesystem.
|
||||
let bin = sourceDir === localBin ? localBin : dbDir;
|
||||
const pinBin = async () => {
|
||||
binHandle = await fs.promises.open(
|
||||
localBin,
|
||||
fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,
|
||||
);
|
||||
return process.platform === 'linux'
|
||||
? `/proc/self/fd/${binHandle.fd}/${name}`
|
||||
: path.join(localBin, name);
|
||||
};
|
||||
let captured = path.join(bin, name);
|
||||
if (bin === localBin)
|
||||
captured = handle
|
||||
? path.join(path.dirname(source), name)
|
||||
: await pinBin();
|
||||
try {
|
||||
await fs.promises.rename(source, captured);
|
||||
} catch (error) {
|
||||
if (error.code !== 'EXDEV' || bin === localBin) throw error;
|
||||
await fs.promises.mkdir(localBin, { mode: 0o700, recursive: true });
|
||||
bin = localBin;
|
||||
captured = await pinBin();
|
||||
await fs.promises.rename(source, captured);
|
||||
}
|
||||
const actual = await readExit(id, captured, path.join(bin, name));
|
||||
// An unreadable source offers no authority to discard unbound bytes.
|
||||
const sameExit =
|
||||
previous &&
|
||||
actual &&
|
||||
actual.version === previous.version &&
|
||||
actual.code === previous.code &&
|
||||
actual.signal === previous.signal &&
|
||||
actual.time === previous.time;
|
||||
if (matches(actual) && (sameExit || (!previous && actual.version === 1))) {
|
||||
await fs.promises.unlink(captured);
|
||||
} else if (actual !== undefined) {
|
||||
// A differing, torn or unreadable file is evidence for another pass.
|
||||
// Persist its new directory entry before releasing the original directory.
|
||||
if (binHandle) await binHandle.sync();
|
||||
else if (bin !== sourceDir || !handle) syncDirectory(bin);
|
||||
if (bin === localBin) syncDirectory(directory);
|
||||
if (handle) await handle.sync();
|
||||
else if (sourceDir !== bin) syncDirectory(sourceDir);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
} finally {
|
||||
if (binHandle) await binHandle.close();
|
||||
if (handle) await handle.close();
|
||||
if (privateSlot) await fs.promises.rmdir(sourceDir).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
function captureId(name) {
|
||||
const marker = metadataName.exec(name);
|
||||
if (marker && /^r_[0-9a-f]{16}$/.test(marker[5])) return marker[1];
|
||||
const match =
|
||||
legacyCapture.exec(name) ??
|
||||
/^\.pending\.([a-z0-9-]{1,120})\.r-[0-9a-f-]{36}$/.exec(name);
|
||||
return match?.[1];
|
||||
}
|
||||
|
||||
async function receiptEntries(directory) {
|
||||
try {
|
||||
return await fs.promises.readdir(directory, { withFileTypes: true });
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function retiringExits() {
|
||||
const dir = receiptDirectory();
|
||||
if (!dir) return [];
|
||||
const files = [];
|
||||
const bins = [path.dirname(dir)];
|
||||
for (const entry of await receiptEntries(dir)) {
|
||||
if (entry.isDirectory() && entry.name === '.reclaim') {
|
||||
bins.push(path.join(dir, entry.name));
|
||||
continue;
|
||||
}
|
||||
const claim = claimName.exec(entry.name);
|
||||
const metadata = metadataName.exec(entry.name);
|
||||
if ((claim || metadata) && entry.isDirectory()) {
|
||||
const directory = path.join(dir, entry.name);
|
||||
try {
|
||||
await fs.promises.rmdir(directory);
|
||||
continue;
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') continue;
|
||||
}
|
||||
files.push({
|
||||
id: metadata ? metadata[1] : claim[2],
|
||||
file: path.join(
|
||||
directory,
|
||||
metadata || claim[1] ? '.pending.claimed' : 'receipt',
|
||||
),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const match =
|
||||
metadata ??
|
||||
/^\.(?:retiring|collecting)\.([a-z0-9-]{1,120})\.[0-9a-f-]{36}$/.exec(
|
||||
entry.name,
|
||||
) ??
|
||||
/^\.pending\.([a-z0-9-]{1,120})\.[a-z0-9_-]{1,64}$/.exec(entry.name) ??
|
||||
/^\.published\.([a-z0-9-]{1,120})\.[0-9a-f]{64}$/.exec(entry.name);
|
||||
if (entry.isFile() && match)
|
||||
files.push({ id: match[1], file: path.join(dir, entry.name) });
|
||||
}
|
||||
for (const bin of bins) {
|
||||
for (const entry of await receiptEntries(bin)) {
|
||||
const id = entry.isFile() && captureId(entry.name);
|
||||
if (id) files.push({ id, file: path.join(bin, entry.name) });
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
async function publishedScriptStarts() {
|
||||
const directory = process.env.QL_DIR && path.join(process.env.QL_DIR, '.tmp');
|
||||
try {
|
||||
return await listReceiptFiles(directory, 'cron-start-');
|
||||
} catch {
|
||||
// Optional entry instrumentation must not prevent exit recovery.
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function validExit(code, signal, time) {
|
||||
return (
|
||||
Number.isSafeInteger(time) &&
|
||||
time > 0 &&
|
||||
Number.isFinite(new Date(time).getTime()) &&
|
||||
((Number.isInteger(code) && code >= 0 && code <= 255 && signal === null) ||
|
||||
(code === null &&
|
||||
typeof signal === 'string' &&
|
||||
/^SIG[A-Z0-9]+$/.test(signal)))
|
||||
);
|
||||
}
|
||||
|
||||
// The Python supervisor uses the same compact JSON array of ASCII values.
|
||||
function exitChecksum(id, code, signal, time) {
|
||||
return createHash('sha256')
|
||||
.update(JSON.stringify([id, code, signal, time]))
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
function syncDirectory(directory) {
|
||||
const fd = fs.openSync(
|
||||
directory,
|
||||
fs.constants.O_RDONLY | fs.constants.O_DIRECTORY,
|
||||
);
|
||||
try {
|
||||
fs.fsyncSync(fd);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
function writeExit(id, code, signal, time) {
|
||||
if (!validExit(code, signal, time))
|
||||
throw new TypeError('Invalid command exit receipt');
|
||||
const file = receiptPath(id);
|
||||
if (!file) return;
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
||||
const checksum = exitChecksum(id, code, signal, time);
|
||||
const receipt = JSON.stringify({ code, signal, time, version: 1, checksum });
|
||||
// Creation is the first durable observation. No data block is needed for
|
||||
// this witness. Keep the regular JSON publication for earlier readers.
|
||||
const directory = path.dirname(file);
|
||||
const prefix = '.pending.' + id + '.';
|
||||
const marker =
|
||||
prefix + 'full-' + (signal ?? code) + '-' + time + '-' + checksum + '-';
|
||||
const publish = (name, content) => {
|
||||
for (;;) {
|
||||
const target = path.join(
|
||||
directory,
|
||||
name + randomUUID().replace(/-/g, '').slice(0, 16),
|
||||
);
|
||||
try {
|
||||
fs.writeFileSync(target, content, {
|
||||
flag: 'wx',
|
||||
mode: 0o600,
|
||||
flush: Boolean(content),
|
||||
});
|
||||
return target;
|
||||
} catch (error) {
|
||||
if (error.code !== 'EEXIST') throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
publish(marker, '');
|
||||
// ext4 journals the empty inode and directory entry together. Also fence the
|
||||
// directory's own entry: another publisher may just have created it.
|
||||
syncDirectory(directory);
|
||||
syncDirectory(path.dirname(directory));
|
||||
try {
|
||||
if (fs.statfsSync(directory).bavail === 0) return;
|
||||
const source = publish(marker, receipt);
|
||||
try {
|
||||
fs.linkSync(source, file);
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return;
|
||||
if (error.code !== 'EEXIST') throw error;
|
||||
// A panel from before metadata receipts can still discover this retry.
|
||||
for (;;) {
|
||||
try {
|
||||
fs.linkSync(source, path.join(directory, prefix + randomUUID()));
|
||||
break;
|
||||
} catch (linkError) {
|
||||
if (linkError.code === 'ENOENT') break;
|
||||
if (linkError.code !== 'EEXIST') throw linkError;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Older panels find the JSON only through this newly created link.
|
||||
syncDirectory(directory);
|
||||
} catch (error) {
|
||||
if (!storageFull(error)) throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function parseExit(id, value) {
|
||||
if (!value || !validExit(value.code, value.signal, value.time)) return null;
|
||||
const { code, signal, time, checksum, version } = value;
|
||||
if (version !== undefined || checksum !== undefined) {
|
||||
if (version !== 1 || checksum !== exitChecksum(id, code, signal, time))
|
||||
return null;
|
||||
} else if (Object.keys(value).length !== 3) {
|
||||
return null;
|
||||
}
|
||||
return { code, signal, time, version };
|
||||
}
|
||||
|
||||
// undefined means no publication. null means a result cannot yet be trusted.
|
||||
async function readExit(id, file = receiptPath(id), publication = file) {
|
||||
if (!file) return;
|
||||
try {
|
||||
const handle = await fs.promises.open(
|
||||
file,
|
||||
fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | fs.constants.O_NOFOLLOW,
|
||||
);
|
||||
try {
|
||||
// Bound CPU and memory even if the damaged file is growing.
|
||||
const buffer = Buffer.alloc(1025);
|
||||
let size = 0;
|
||||
while (size < buffer.length) {
|
||||
const { bytesRead } = await handle.read(
|
||||
buffer,
|
||||
size,
|
||||
buffer.length - size,
|
||||
null,
|
||||
);
|
||||
if (!bytesRead) break;
|
||||
size += bytesRead;
|
||||
}
|
||||
if (size === buffer.length) return null;
|
||||
const metadata = metadataReceipt(publication);
|
||||
const bytes = buffer.toString('utf8', 0, size);
|
||||
let namedExit;
|
||||
if (metadata && metadata[1] === id && (await handle.stat()).isFile()) {
|
||||
const [, , outcome, end, checksum] = metadata;
|
||||
const signal = outcome.startsWith('SIG') ? outcome : null;
|
||||
const value = {
|
||||
code: signal ? null : Number(outcome),
|
||||
signal,
|
||||
time: Number(end),
|
||||
version: 1,
|
||||
checksum,
|
||||
};
|
||||
// Both current publishers serialize in this order. Accept a torn body
|
||||
// only when every byte matches the tuple independently published by
|
||||
// the filename. Validate replacement files on their own bytes below.
|
||||
namedExit = parseExit(id, value);
|
||||
const json = JSON.stringify(value);
|
||||
if (json.startsWith(bytes)) {
|
||||
return namedExit && { ...namedExit, file, namedExit: undefined };
|
||||
}
|
||||
}
|
||||
const exit = parseExit(id, JSON.parse(bytes));
|
||||
const guard = legacyCapture.exec(path.basename(publication));
|
||||
if (
|
||||
guard &&
|
||||
exit &&
|
||||
exit.version !== 1 &&
|
||||
(guard[1] !== id ||
|
||||
guard[2] !==
|
||||
exitChecksum(id, exit.code, exit.signal, exit.time).slice(0, 32))
|
||||
)
|
||||
return null;
|
||||
const conflictingName =
|
||||
exit?.version === 1 &&
|
||||
namedExit &&
|
||||
(exit.time !== namedExit.time ||
|
||||
exit.code !== namedExit.code ||
|
||||
exit.signal !== namedExit.signal);
|
||||
return (
|
||||
exit && {
|
||||
...exit,
|
||||
file,
|
||||
namedExit: conflictingName ? namedExit : undefined,
|
||||
}
|
||||
);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return;
|
||||
if (error.code || error instanceof SyntaxError) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
parseExit,
|
||||
isLegacyCapture: (file) => legacyCapture.test(path.basename(file)),
|
||||
isMetadataReceipt: (file) => Boolean(metadataReceipt(file)),
|
||||
receiptPath,
|
||||
publishedExits,
|
||||
publishedScriptStarts,
|
||||
readExit,
|
||||
writeExit,
|
||||
validExit,
|
||||
storageFull,
|
||||
retireLegacyFile,
|
||||
retiringExits,
|
||||
};
|
||||
@@ -0,0 +1,235 @@
|
||||
import dayjs from 'dayjs';
|
||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||
|
||||
type DayCounts = {
|
||||
cron_id: number;
|
||||
day: string;
|
||||
successes: number;
|
||||
failures: number;
|
||||
later_successes: number;
|
||||
later_failures: number;
|
||||
has_bookings: number;
|
||||
saved_successes: number;
|
||||
saved_failures: number;
|
||||
};
|
||||
|
||||
// Process one outcome, newest day first. Same-day receipts can only cover
|
||||
// eligible exits. Surplus becomes available to earlier days after this match.
|
||||
function matchDailyCounts(
|
||||
exits: number,
|
||||
saved: number,
|
||||
laterCredits: number,
|
||||
afterLastBooking = 0,
|
||||
) {
|
||||
const localMatches = Math.min(saved, exits - afterLastBooking);
|
||||
const deficit = exits - localMatches;
|
||||
const borrowed = Math.min(deficit, laterCredits);
|
||||
return {
|
||||
missing: deficit - borrowed,
|
||||
remaining: laterCredits - borrowed + saved - localMatches,
|
||||
};
|
||||
}
|
||||
|
||||
// A legacy terminal status needs a matching exit code. An identified supervisor
|
||||
// also knows a child failed when the OS returns a signal instead of a code.
|
||||
const confirmedResult = `t.started_at IS NOT NULL AND t.finished_at>=t.started_at
|
||||
AND t.state IN ('finished','failed')
|
||||
AND (t.source<>'legacy' OR (
|
||||
((t.state='finished' AND t.exit_code=0) OR (t.state='failed' AND t.exit_code<>0))
|
||||
AND NOT EXISTS (SELECT 1 FROM RunningInstances sibling
|
||||
LEFT JOIN CronTriggers linked ON linked.instance_id=sibling.id
|
||||
WHERE sibling.cron_id=i.cron_id AND sibling.pid=i.pid AND sibling.finished_at=i.finished_at
|
||||
AND sibling.id<>i.id AND sibling.status IN (1,3)
|
||||
AND (linked.id IS NULL OR (linked.source='legacy' AND linked.owner IS NULL))
|
||||
AND (sibling.started_at<>i.started_at OR COALESCE(sibling.log_path,'')<>COALESCE(i.log_path,'')
|
||||
OR sibling.status<>i.status OR sibling.exit_code IS NOT i.exit_code OR linked.id IS NOT NULL))))`;
|
||||
|
||||
export function readDailyResults(database: Sequelize, cronId: number) {
|
||||
const today = dayjs().startOf('day');
|
||||
const first = today.subtract(6, 'day');
|
||||
const next = today.add(1, 'day');
|
||||
return database.query<{
|
||||
day: string;
|
||||
exitSuccess: number;
|
||||
exitFail: number;
|
||||
bookedSuccess: number;
|
||||
bookedFail: number;
|
||||
supplement: number;
|
||||
}>(
|
||||
`WITH results AS (
|
||||
SELECT date(t.finished_at/1000,'unixepoch','localtime') AS day,
|
||||
SUM(t.state='finished') AS exitSuccess,SUM(t.state='failed') AS exitFail,
|
||||
0 AS bookedSuccess,0 AS bookedFail,0 AS supplement
|
||||
FROM CronTriggers t LEFT JOIN RunningInstances i ON i.id=t.instance_id
|
||||
WHERE t.cron_id=$id AND t.finished_at >= $start AND t.finished_at < $end
|
||||
AND t.reason IS NOT 'spawn' AND ${confirmedResult} GROUP BY day
|
||||
UNION ALL
|
||||
SELECT date,0,0,COALESCE(success_count,0),COALESCE(fail_count,0),untimed_count
|
||||
FROM CrontabStats WHERE ref_id=$id AND date >= $first AND date < $next
|
||||
) SELECT day,SUM(exitSuccess) AS exitSuccess,SUM(exitFail) AS exitFail,
|
||||
SUM(bookedSuccess) AS bookedSuccess,SUM(bookedFail) AS bookedFail,SUM(supplement) AS supplement
|
||||
FROM results GROUP BY day ORDER BY day DESC`,
|
||||
{
|
||||
type: QueryTypes.SELECT,
|
||||
bind: {
|
||||
id: cronId,
|
||||
start: first.valueOf(),
|
||||
end: next.valueOf(),
|
||||
first: first.format('YYYY-MM-DD'),
|
||||
next: next.format('YYYY-MM-DD'),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Run under the schema migration's write lock, before accepting new receipts.
|
||||
export async function repairLegacyDailyStatistics(
|
||||
database: Sequelize,
|
||||
transaction: Transaction,
|
||||
priorVersion: 0 | 1 | 2,
|
||||
) {
|
||||
// Old panels updated every outstanding start with the reported PID. Identical
|
||||
// copies of a start prove only one exit; conflicting rows cannot identify it.
|
||||
const imported = await database.query(
|
||||
`WITH exits AS (
|
||||
SELECT MIN(i.id) AS instance FROM RunningInstances i
|
||||
JOIN Crontabs c ON c.id=i.cron_id
|
||||
LEFT JOIN CronTriggers linked ON linked.instance_id=i.id
|
||||
WHERE (linked.id IS NULL OR (linked.source='legacy' AND linked.owner IS NULL))
|
||||
AND i.status IN (1,3) AND i.pid>0 AND i.started_at>0 AND i.finished_at>=i.started_at
|
||||
AND i.finished_at*1000>=COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)
|
||||
GROUP BY i.cron_id,i.pid,i.finished_at
|
||||
HAVING MIN(i.started_at)=MAX(i.started_at)
|
||||
AND COUNT(DISTINCT COALESCE(i.log_path,''))=1 AND MIN(i.status)=MAX(i.status)
|
||||
AND COUNT(i.exit_code)=COUNT(*) AND MIN(i.exit_code)=MAX(i.exit_code)
|
||||
AND COUNT(linked.id)=0
|
||||
)
|
||||
INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,started_at,finished_at,instance_id,log_path,exit_code,counted)
|
||||
SELECT 'legacy-db-' || i.id,i.cron_id,'legacy',CASE i.status WHEN 1 THEN 'finished' ELSE 'failed' END,
|
||||
i.started_at*1000,i.started_at*1000,i.finished_at*1000,i.id,i.log_path,i.exit_code,1
|
||||
FROM exits JOIN RunningInstances i ON i.id=exits.instance
|
||||
WHERE (i.status=1 AND i.exit_code=0) OR (i.status=3 AND i.exit_code<>0)`,
|
||||
{ transaction, type: QueryTypes.BULKUPDATE },
|
||||
);
|
||||
|
||||
// A newly imported last run must have the same owner it would acquire through
|
||||
// the normal handoff. An older exit must never replace a more recent start.
|
||||
if (imported)
|
||||
await database.query(
|
||||
`WITH ranked AS (
|
||||
SELECT cron_id,instance_id,started_at/1000 AS start,(finished_at-started_at)/1000 AS elapsed,
|
||||
ROW_NUMBER() OVER (PARTITION BY cron_id ORDER BY started_at DESC,instance_id DESC) AS position
|
||||
FROM CronTriggers WHERE source='legacy' AND id LIKE 'legacy-db-%'
|
||||
)
|
||||
UPDATE Crontabs AS c SET (last_instance_id,last_execution_time,last_running_time)=
|
||||
(SELECT instance_id,start,elapsed FROM ranked WHERE cron_id=c.id AND position=1)
|
||||
WHERE EXISTS (SELECT 1 FROM ranked r WHERE r.cron_id=c.id AND r.position=1 AND
|
||||
(c.last_execution_time IS NULL OR c.last_execution_time<r.start OR
|
||||
(c.last_execution_time=r.start AND (c.last_instance_id IS NULL OR c.last_instance_id<r.instance_id)))
|
||||
AND NOT EXISTS (SELECT 1 FROM RunningInstances i WHERE i.cron_id=c.id AND
|
||||
(i.started_at>r.start OR (i.started_at=r.start AND i.id>r.instance_id))))`,
|
||||
{ transaction },
|
||||
);
|
||||
|
||||
// Statistics retention removes whole dates across tasks. When the old panel
|
||||
// retained no earlier totals, yesterday is the oldest date even a 1-day policy keeps.
|
||||
const yesterday = dayjs().subtract(1, 'day').format('YYYY-MM-DD');
|
||||
const days = await database.query<DayCounts>(
|
||||
`WITH exits AS (
|
||||
SELECT t.cron_id,t.state,date(t.finished_at/1000,'unixepoch','localtime') AS day,
|
||||
t.started_at,i.createdAt,t.id
|
||||
FROM CronTriggers t LEFT JOIN RunningInstances i ON i.id=t.instance_id
|
||||
WHERE t.counted=1 AND ${confirmedResult}
|
||||
), ordered AS (
|
||||
SELECT e.*, CASE WHEN e.id LIKE 'legacy-db-%' AND s.untimed_count=0
|
||||
AND date(s.updatedAt,'localtime')=e.day AND julianday(s.createdAt)<=julianday(s.updatedAt)
|
||||
AND e.started_at/1000>CAST(strftime('%s',s.updatedAt) AS INTEGER)
|
||||
AND julianday(e.createdAt)>julianday(s.updatedAt) THEN 1 ELSE 0 END AS later
|
||||
FROM exits e LEFT JOIN CrontabStats s ON s.ref_id=e.cron_id AND s.date=e.day
|
||||
), evidence AS (
|
||||
SELECT cron_id,day,SUM(state='finished') AS successes,SUM(state='failed') AS failures,
|
||||
SUM(later*(state='finished')) AS later_successes,SUM(later*(state='failed')) AS later_failures,
|
||||
0 AS has_bookings,0 AS saved_successes,0 AS saved_failures FROM ordered GROUP BY cron_id,day
|
||||
UNION ALL
|
||||
SELECT ref_id,date,0,0,0,0,1,COALESCE(success_count,0),COALESCE(fail_count,0) FROM CrontabStats
|
||||
)
|
||||
SELECT cron_id,day,MAX(has_bookings) AS has_bookings,SUM(successes) AS successes,SUM(failures) AS failures,
|
||||
SUM(later_successes) AS later_successes,SUM(later_failures) AS later_failures,
|
||||
SUM(saved_successes) AS saved_successes,SUM(saved_failures) AS saved_failures
|
||||
FROM evidence WHERE day>=MIN($yesterday,COALESCE((SELECT MIN(date) FROM CrontabStats),$yesterday))
|
||||
AND day>=COALESCE((SELECT first_day FROM CronStatRetention WHERE id=1),'')
|
||||
GROUP BY cron_id,day ORDER BY cron_id,day DESC`,
|
||||
{ type: QueryTypes.SELECT, transaction, bind: { yesterday } },
|
||||
);
|
||||
|
||||
// Anonymous receipts cannot identify a particular exit. Match nearest
|
||||
// eligible days first; never move already booked counts or elapsed samples.
|
||||
let task: number | undefined;
|
||||
let successCredit = 0,
|
||||
failureCredit = 0;
|
||||
let priorSuccessCredit = 0,
|
||||
priorFailureCredit = 0;
|
||||
for (const day of days) {
|
||||
if (day.cron_id !== task) {
|
||||
task = day.cron_id;
|
||||
successCredit =
|
||||
failureCredit =
|
||||
priorSuccessCredit =
|
||||
priorFailureCredit =
|
||||
0;
|
||||
}
|
||||
const successes = matchDailyCounts(
|
||||
day.successes,
|
||||
day.saved_successes,
|
||||
successCredit,
|
||||
day.later_successes,
|
||||
);
|
||||
const failures = matchDailyCounts(
|
||||
day.failures,
|
||||
day.saved_failures,
|
||||
failureCredit,
|
||||
day.later_failures,
|
||||
);
|
||||
successCredit = successes.remaining;
|
||||
failureCredit = failures.remaining;
|
||||
let success = successes.missing,
|
||||
failure = failures.missing;
|
||||
if (priorVersion === 2) {
|
||||
// Replaying v2 on the current snapshot could resurrect a cleaned-up day.
|
||||
// Only the extra lower bound established by v3 is new evidence.
|
||||
const priorSuccess = matchDailyCounts(
|
||||
day.successes,
|
||||
day.saved_successes,
|
||||
priorSuccessCredit,
|
||||
);
|
||||
const priorFailure = matchDailyCounts(
|
||||
day.failures,
|
||||
day.saved_failures,
|
||||
priorFailureCredit,
|
||||
);
|
||||
priorSuccessCredit = priorSuccess.remaining;
|
||||
priorFailureCredit = priorFailure.remaining;
|
||||
success = Math.max(0, success - priorSuccess.missing);
|
||||
failure = Math.max(0, failure - priorFailure.missing);
|
||||
}
|
||||
// Old repairs did not journal deletions. An absent task/day could have
|
||||
// been cleared after a supplement. Preserve the gap on repeat upgrades.
|
||||
if (priorVersion && !day.has_bookings) continue;
|
||||
if (!success && !failure) continue;
|
||||
// Anonymous elapsed samples have no execution identity. Preserve measured
|
||||
// times; adding instance wall times here could count the same sample twice.
|
||||
await database.query(
|
||||
`INSERT INTO CrontabStats
|
||||
(ref_id,date,run_count,success_count,fail_count,untimed_count,total_time,max_time,createdAt,updatedAt)
|
||||
VALUES ($task,$day,$runs,$success,$failure,$runs,0,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(ref_id,date) DO UPDATE SET run_count=COALESCE(run_count,0)+excluded.run_count,
|
||||
success_count=COALESCE(success_count,0)+excluded.success_count,
|
||||
fail_count=COALESCE(fail_count,0)+excluded.fail_count,
|
||||
untimed_count=untimed_count+excluded.untimed_count,updatedAt=CURRENT_TIMESTAMP`,
|
||||
{
|
||||
transaction,
|
||||
bind: { task, day: day.day, runs: success + failure, success, failure },
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user