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

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

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

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

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

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
import type { Sequelize } from 'sequelize';
import { performance } from 'perf_hooks';
// Per database and day: concurrent viewers share one computation. Rejections
// are never cached; a new day cannot reuse yesterday's summary. Runtime/task
// control endpoints remain live and never read this display-only snapshot.
const snapshots = new WeakMap<
Sequelize,
{ key: string; until: number; value: Promise<unknown> }
>();
export function dashboardSnapshot<T>(
db: Sequelize,
key: string,
compute: () => Promise<T>,
): Promise<T> {
const existing = snapshots.get(db);
if (existing?.key === key && performance.now() < existing.until)
return existing.value as Promise<T>;
const entry = {
key,
until: Infinity,
value: Promise.resolve().then(compute),
};
snapshots.set(db, entry);
entry.value.then(
() => {
// Wall-clock corrections must not stretch a one-second cache for minutes.
entry.until = performance.now() + 1000;
},
() => {
if (snapshots.get(db) === entry) snapshots.delete(db);
},
);
return entry.value;
}
+6 -2
View File
@@ -39,8 +39,12 @@ export function resolveFileAccess(
while (!fs.existsSync(existing)) {
// existsSync is false for a dangling symlink; never treat one as absent.
try {
fs.lstatSync(existing);
return '';
const entry = fs.lstatSync(existing);
if (entry.isSymbolicLink()) return '';
// Another task may have created this directory after existsSync.
// Canonicalize the now-existing entry below, with the same root and
// blacklist checks, rather than rejecting a legitimate concurrent run.
break;
} catch (error: any) {
if (error.code !== 'ENOENT') return '';
}
+73
View File
@@ -1,5 +1,6 @@
import fs from 'fs/promises';
import { createHash } from 'crypto';
import type { BigIntStats } from 'fs';
export const DEFAULT_LOG_CHUNK_BYTES = 256 * 1024;
export const MAX_LOG_CHUNK_BYTES = 1024 * 1024;
@@ -7,6 +8,37 @@ export const MAX_LOG_CHUNK_BYTES = 1024 * 1024;
// The viewer retains at most one Mi UTF-16 code units.
const CURSOR_WINDOW_BYTES = 4 * MAX_LOG_CHUNK_BYTES;
// Cache only a server-verified EOF, never client-supplied file metadata or log
// contents. Bound both the number of viewers retained and verification lifetime.
const EOF_CACHE_LIMIT = 256;
const EOF_CACHE_TTL_MS = 30_000;
const EOF_CACHE_SETTLE_MS = 2_000;
const verifiedEnds = new Map<
string,
{ version: string; cursor: string; offset: number; verifiedAt: number }
>();
function fileVersion(stat: BigIntStats) {
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}:${stat.birthtimeNs}`;
}
function rememberEnd(
filePath: string,
version: string,
cursor: string,
offset: number,
) {
verifiedEnds.delete(filePath);
verifiedEnds.set(filePath, {
version,
cursor,
offset,
verifiedAt: Date.now(),
});
if (verifiedEnds.size > EOF_CACHE_LIMIT)
verifiedEnds.delete(verifiedEnds.keys().next().value!);
}
export interface LogReadOptions {
offset?: number;
limit?: number;
@@ -68,6 +100,15 @@ export async function readLogChunk(
const stat = await handle.stat({ bigint: true });
const total = Number(stat.size);
const identity = `${stat.dev}:${stat.ino}`;
const version = fileVersion(stat);
const observedAt = Date.now();
// Even nanosecond stat fields can repeat across writes within a filesystem
// clock tick. Never cache content read while that timestamp is still fresh.
const metadataSettled =
Number(stat.mtimeMs) > 0 &&
Number(stat.ctimeMs) > 0 &&
observedAt - Number(stat.mtimeMs) >= EOF_CACHE_SETTLE_MS &&
observedAt - Number(stat.ctimeMs) >= EOF_CACHE_SETTLE_MS;
const limit = normalizeLimit(options.limit);
const requestedOffset = Number.isFinite(options.offset)
? Math.max(0, Math.trunc(options.offset!))
@@ -78,6 +119,30 @@ export async function readLogChunk(
: Math.min(requestedOffset, total);
const resume =
options.cursor && !options.tail && requestedOffset !== undefined;
const verified = verifiedEnds.get(filePath);
if (
resume &&
verified?.version === version &&
verified.cursor === options.cursor &&
verified.offset === requestedOffset &&
requestedOffset === total &&
observedAt >= verified.verifiedAt &&
observedAt - verified.verifiedAt < EOF_CACHE_TTL_MS
) {
// A cache hit does not extend the deadline: even an unchanged file is
// periodically verified again. Keep the entry recent without retaining bytes.
verifiedEnds.delete(filePath);
verifiedEnds.set(filePath, verified);
return {
content: '',
offset: total,
nextOffset: total,
total,
truncated: total > 0,
cursor: options.cursor,
reset: false,
};
}
const [fromText, digest] = resume ? options.cursor!.split('.') : [];
let from = resume ? Number(fromText) : start;
let reset = Boolean(
@@ -136,6 +201,13 @@ export async function readLogChunk(
)}`;
}
if (cursor && nextOffset === total && metadataSettled) {
// Do not trust an EOF read that raced with append, truncate or overwrite.
// ctime also detects rewrites that restore mtime; inode detects replacement.
if (fileVersion(await handle.stat({ bigint: true })) === version)
rememberEnd(filePath, version, cursor, nextOffset);
}
return {
...(cursor && { cursor, reset }),
content: buffer.subarray(leadingBytes, contentEnd).toString('utf8'),
@@ -146,6 +218,7 @@ export async function readLogChunk(
};
} catch (error: any) {
if (error?.code === 'ENOENT') {
verifiedEnds.delete(filePath);
return {
content: '',
offset: 0,