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
@@ -3,11 +3,18 @@ import { readFileSync } from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
function read(file: string): string {
|
||||
try { return readFileSync(file, 'utf8').trim(); } catch { return ''; }
|
||||
try {
|
||||
return readFileSync(file, 'utf8').trim();
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
// Walk ancestors too: a nested cgroup can inherit a tighter parent quota.
|
||||
export function containerResources(readValue = read, platform = process.platform) {
|
||||
export function containerResources(
|
||||
readValue = read,
|
||||
platform = process.platform,
|
||||
) {
|
||||
const hostCpus = os.cpus().length;
|
||||
const hostMemory = os.totalmem();
|
||||
let cpus = hostCpus;
|
||||
@@ -22,17 +29,25 @@ export function containerResources(readValue = read, platform = process.platform
|
||||
const unified = !match[1];
|
||||
for (const kind of ['cpu', 'memory', 'cpuset']) {
|
||||
if (!unified && !controllers.includes(kind)) continue;
|
||||
const roots = unified ? ['/sys/fs/cgroup'] : [...new Set([kind, match[1]].map(k => '/sys/fs/cgroup/' + k))];
|
||||
const roots = unified
|
||||
? ['/sys/fs/cgroup']
|
||||
: [...new Set([kind, match[1]].map((k) => '/sys/fs/cgroup/' + k))];
|
||||
for (const root of roots) {
|
||||
let dir = path.join(root, path.normalize(match[2]));
|
||||
while (dir === root || dir.startsWith(root + '/')) {
|
||||
const value = (file: string) => readValue(path.join(dir, file));
|
||||
if (kind === 'cpu') {
|
||||
const [quota, period] = (unified ? value('cpu.max').split(/\s+/) :
|
||||
[value('cpu.cfs_quota_us'), value('cpu.cfs_period_us')]).map(Number);
|
||||
if (quota > 0 && period > 0) cpus = Math.min(cpus, quota / period);
|
||||
const [quota, period] = (
|
||||
unified
|
||||
? value('cpu.max').split(/\s+/)
|
||||
: [value('cpu.cfs_quota_us'), value('cpu.cfs_period_us')]
|
||||
).map(Number);
|
||||
if (quota > 0 && period > 0)
|
||||
cpus = Math.min(cpus, quota / period);
|
||||
} else if (kind === 'cpuset') {
|
||||
const set = value(unified ? 'cpuset.cpus.effective' : 'cpuset.cpus');
|
||||
const set = value(
|
||||
unified ? 'cpuset.cpus.effective' : 'cpuset.cpus',
|
||||
);
|
||||
if (/^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$/.test(set)) {
|
||||
const count = set.split(',').reduce((n, range) => {
|
||||
const [lo, hi] = range.split('-').map(Number);
|
||||
@@ -41,9 +56,13 @@ export function containerResources(readValue = read, platform = process.platform
|
||||
if (count > 0) cpus = Math.min(cpus, count);
|
||||
}
|
||||
} else {
|
||||
const limit = Number(value(unified ? 'memory.max' : 'memory.limit_in_bytes'));
|
||||
const limit = Number(
|
||||
value(unified ? 'memory.max' : 'memory.limit_in_bytes'),
|
||||
);
|
||||
if (limit > 0 && limit <= memTotal) {
|
||||
const usage = value(unified ? 'memory.current' : 'memory.usage_in_bytes');
|
||||
const usage = value(
|
||||
unified ? 'memory.current' : 'memory.usage_in_bytes',
|
||||
);
|
||||
if (usage && Number.isFinite(Number(usage))) {
|
||||
memTotal = limit;
|
||||
memFree = Math.max(0, limit - Number(usage));
|
||||
@@ -57,6 +76,12 @@ export function containerResources(readValue = read, platform = process.platform
|
||||
}
|
||||
}
|
||||
}
|
||||
return { cpus, memTotal, memFree, hostCpus, hostMemory,
|
||||
memUsagePercent: ((1 - memFree / memTotal) * 100).toFixed(1) };
|
||||
return {
|
||||
cpus,
|
||||
memTotal,
|
||||
memFree,
|
||||
hostCpus,
|
||||
hostMemory,
|
||||
memUsagePercent: ((1 - memFree / memTotal) * 100).toFixed(1),
|
||||
};
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
// Match command text literally: looking up a task must never execute its input.
|
||||
export function findCronId(crontab: string, command: string): string {
|
||||
if (!command) return '';
|
||||
for (const line of crontab.split('\n')) {
|
||||
const id = /\bID=(\d+)\s/.exec(line);
|
||||
if (id && line.includes(command, id.index + id[0].length)) {
|
||||
return id[1];
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { join } from 'path';
|
||||
import { existsSync } from 'fs';
|
||||
import { receiptPath } from './managedExit.cjs';
|
||||
import { spawn } from 'cross-spawn';
|
||||
import type { ChildProcessWithoutNullStreams } from 'child_process';
|
||||
import type { Readable } from 'stream';
|
||||
|
||||
// A managed command waits on its parent's pipe. EOF before authorization exits
|
||||
// without interpreting the command, even when the worker is killed by SIGKILL.
|
||||
export function spawnCronCommand(command: string, triggerId?: string, onCommandStart?: (at: number) => void, outputPath?: string) {
|
||||
if (!triggerId) return spawn(command, { shell: '/bin/bash' });
|
||||
const sourceScript = join(__dirname, '../../shell/cron-command.py');
|
||||
const supervisor = existsSync(sourceScript) ? sourceScript : join(process.env.QL_DIR!, 'shell/cron-command.py');
|
||||
const args = ['-I', '-S', supervisor, command, String(process.pid),
|
||||
receiptPath(triggerId) || '', process.execPath, join(__dirname, 'managedExit.cjs'),
|
||||
];
|
||||
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 },
|
||||
stdio: onCommandStart ? ['pipe', 'pipe', 'pipe', 'pipe'] : 'pipe' }) as ChildProcessWithoutNullStreams;
|
||||
if (onCommandStart && child.stdio[3]) {
|
||||
const timing = child.stdio[3] as Readable;
|
||||
let stamp = '';
|
||||
timing.setEncoding('ascii').on('data', chunk => { stamp += chunk; });
|
||||
timing.once('end', () => { if (/^\d{13}$/.test(stamp)) onCommandStart(Number(stamp)); });
|
||||
timing.on('error', () => {}); // Missing telemetry must not change the command result.
|
||||
}
|
||||
// A concurrent stop can close the pipe before the authorization write.
|
||||
child.stdin.on('error', () => {});
|
||||
return child;
|
||||
}
|
||||
|
||||
export function releaseCronCommand(child: ChildProcessWithoutNullStreams): Promise<void> {
|
||||
return new Promise((resolve, reject) =>
|
||||
child.stdin.end('run\n', (error?: Error) => error ? reject(error) : resolve()));
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
// Read literal shell words only. Never expand or execute a command to derive a
|
||||
// path. Adjacent quoted/unquoted fragments belong to the same argument.
|
||||
function words(command: string): string[] {
|
||||
const result: string[] = [];
|
||||
let value = '', quote = '', active = false;
|
||||
for (let i = 0; i < command.length; i++) {
|
||||
const c = command[i];
|
||||
if (quote && c === quote) { quote = ''; continue; }
|
||||
if (!quote && (c === "'" || c === '"')) { quote = c; active = true; continue; }
|
||||
if (c === '\\' && quote !== "'") {
|
||||
const next = command[++i];
|
||||
if (next === undefined) return [];
|
||||
if (quote === '"' && !/[$`"\\\n]/.test(next)) value += '\\';
|
||||
if (next !== '\n') { value += next; active = true; }
|
||||
continue;
|
||||
}
|
||||
if (!quote && /[;&|<>()\n]/.test(c)) break;
|
||||
if (!quote && /\s/.test(c)) {
|
||||
if (active) result.push(value);
|
||||
value = ''; active = false; continue;
|
||||
}
|
||||
if (!active && !quote && c === '#') break;
|
||||
value += c; active = true;
|
||||
}
|
||||
if (quote) return [];
|
||||
if (active) result.push(value);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function cronOperand(command: string, taskOnly = false): string | undefined {
|
||||
const args = words(command.trim());
|
||||
if (args[0] === 'task') args.shift();
|
||||
else if (taskOnly && args[0] === 'ql') return;
|
||||
while (args[0] === '-l' || args[0] === '-m') {
|
||||
if (args.shift() === '-m') args.shift();
|
||||
}
|
||||
if (args.length > 1 && /^(?:.*\/)?(?:node|python3?|bash|sh|ts-node(?:-transpile-only)?)$/.test(args[0])) args.shift();
|
||||
return args[0];
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import { upcomingSlots } from './cronScheduler';
|
||||
|
||||
type Definition = {
|
||||
schedule?: string;
|
||||
extra_schedules?: { schedule: string }[];
|
||||
isDisabled?: number;
|
||||
saved?: boolean;
|
||||
};
|
||||
const cache = new Map<string, { after: number; times: number[] }>();
|
||||
|
||||
export function previewSchedule(
|
||||
schedule: string,
|
||||
count: number,
|
||||
now: number,
|
||||
): number[] {
|
||||
const key = JSON.stringify([
|
||||
Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
schedule,
|
||||
]);
|
||||
const cached = cache.get(key);
|
||||
if (cached && now >= cached.after) {
|
||||
const future = cached.times.filter((time) => time > now);
|
||||
if (future.length >= count) return future.slice(0, count);
|
||||
}
|
||||
const times = upcomingSlots(schedule, now, count);
|
||||
if (cache.size >= 512) cache.delete(cache.keys().next().value!);
|
||||
cache.set(key, { after: now, times });
|
||||
return times;
|
||||
}
|
||||
|
||||
export function withNextRun<T extends Definition>(cron: T) {
|
||||
let nextRunTime: number | null = null;
|
||||
if (
|
||||
cron.schedule &&
|
||||
!cron.isDisabled &&
|
||||
cron.saved !== false &&
|
||||
!cron.schedule.startsWith('@once') &&
|
||||
!cron.schedule.startsWith('@boot')
|
||||
) {
|
||||
try {
|
||||
const now = Date.now();
|
||||
nextRunTime = Math.min(
|
||||
...[
|
||||
cron.schedule,
|
||||
...(cron.extra_schedules || []).map((x) => x.schedule),
|
||||
].map((rule) => previewSchedule(rule, 1, now)[0]),
|
||||
);
|
||||
} catch {
|
||||
// Legacy invalid rows remain visible and editable.
|
||||
}
|
||||
}
|
||||
return { ...cron, nextRunTime };
|
||||
}
|
||||
@@ -1,172 +0,0 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { execFileSync, spawnSync } from 'child_process';
|
||||
|
||||
// Legacy runs can outlive a scheduler restart without an active trigger receipt.
|
||||
export function hasLiveCronProcess(status?: number, pid?: number | null) {
|
||||
if (status !== 0 || !pid || pid < 0) return false; // CrontabStatus.running
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === 'ESRCH') return false;
|
||||
if (code === 'EPERM') return true;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function readBsdProcessField(pid: number, field: 'lstart' | 'ppid') {
|
||||
const result = spawnSync('ps', ['-p', String(pid), '-o', field + '='], {
|
||||
encoding: 'utf8', env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
|
||||
});
|
||||
// ENOENT from spawning ps refers to the executable, not the target PID.
|
||||
if (result.error) throw new Error('Cannot run ps: ' + result.error.message, { cause: result.error });
|
||||
const value = result.stdout.trim();
|
||||
if (result.status === 0 && value) return value;
|
||||
// BSD ps exits 1 without output when the selected PID has already exited.
|
||||
if (result.status === 1 && !value && !result.stderr.trim())
|
||||
throw Object.assign(new Error('Process has exited'), { code: 'ESRCH' });
|
||||
throw new Error(`Cannot read ${field} for PID ${pid}: ${result.stderr.trim() || result.signal || 'ps status ' + result.status}`);
|
||||
}
|
||||
|
||||
export function systemOwner(pid: number) {
|
||||
if (process.platform !== 'linux') {
|
||||
// BSD crontab installations have no procfs. ps exposes the process birth time.
|
||||
process.kill(pid, 0);
|
||||
const birth = readBsdProcessField(pid, 'lstart');
|
||||
return `crond:${pid}:${birth}`;
|
||||
}
|
||||
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
||||
const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
|
||||
if (['Z', 'X', 'x'].includes(fields[0])) throw Object.assign(new Error('Process has exited'), { code: 'ESRCH' });
|
||||
const startTicks = fields[19];
|
||||
const boot = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
|
||||
return `crond:${pid}:${startTicks}:${boot}`;
|
||||
}
|
||||
|
||||
let linuxClockTicks: number | undefined;
|
||||
|
||||
// A start packet may arrive after its PID was recycled, before the replacement reports.
|
||||
export function legacyProcessOwner(pid: number, started: number): string | undefined {
|
||||
try {
|
||||
const identity = systemOwner(pid);
|
||||
const birth = identity.slice(`crond:${pid}:`.length);
|
||||
let bornAt: number;
|
||||
if (process.platform === 'linux') {
|
||||
linuxClockTicks ??= Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' }));
|
||||
const boot = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
|
||||
if (!boot || !(linuxClockTicks > 0)) throw new Error('Cannot read process birth time');
|
||||
bornAt = Number(boot[1]) + Number(birth.split(':')[0]) / linuxClockTicks;
|
||||
} else {
|
||||
bornAt = Date.parse(birth + ' UTC') / 1000;
|
||||
}
|
||||
// Both the callback and Linux boot time have one-second precision.
|
||||
return Math.floor(bornAt) <= started + 1 ? identity : undefined;
|
||||
} catch (error) {
|
||||
if (['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)) return undefined;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// PID 1 survives worker restarts, but changes when a container or Linux host restarts.
|
||||
export function pidNamespaceOwner() {
|
||||
return process.platform === 'linux' ? systemOwner(1) : null;
|
||||
}
|
||||
|
||||
// psTree enumerates asynchronously. Reject a PID already reparented or recycled
|
||||
// between enumeration and the birth-token snapshot.
|
||||
export function isProcessDescendant(pid: number, root: number) {
|
||||
const seen = new Set<number>();
|
||||
while (pid > 1 && !seen.has(pid)) {
|
||||
if (pid === root) return true;
|
||||
seen.add(pid);
|
||||
if (process.platform === 'linux') {
|
||||
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
||||
pid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
|
||||
} else {
|
||||
pid = Number(readBsdProcessField(pid, 'ppid'));
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// For an individual legacy instance the task ID alone also matches its siblings.
|
||||
export function verifyCronProcess(pid: number, cronId: number, identity?: string | null, started?: number,
|
||||
instance?: { logPath?: string }) {
|
||||
const conflict = () => Object.assign(new Error('Task process identity could not be verified'), { status: 409 });
|
||||
if (!Number.isInteger(pid) || pid <= 1) throw conflict();
|
||||
if (identity) {
|
||||
// A birth token for this PID proves the original process is gone if the
|
||||
// kernel now reports a different birth. Access errors remain retryable.
|
||||
if (!identity.startsWith(`crond:${pid}:`)) throw conflict();
|
||||
let current: string;
|
||||
try { current = systemOwner(pid); }
|
||||
catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT')
|
||||
throw Object.assign(new Error('Command already exited'), { code: 'ESRCH' });
|
||||
throw error;
|
||||
}
|
||||
if (current !== identity) throw Object.assign(new Error('Command PID was reused'), { code: 'PID_REUSED', status: 409 });
|
||||
return current;
|
||||
}
|
||||
try {
|
||||
if (process.platform === 'linux') {
|
||||
const env = readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0');
|
||||
if (instance && (!instance.logPath || instance.logPath === '/dev/null' ||
|
||||
!env.includes('real_log_path=' + instance.logPath))) throw conflict();
|
||||
if (env.includes('ID=' + cronId) && started) {
|
||||
const boot = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
|
||||
const birth = systemOwner(pid);
|
||||
const ticks = Number(birth.split(':')[2]);
|
||||
const hz = Number(execFileSync('getconf', ['CLK_TCK'], { encoding: 'utf8' }));
|
||||
if (boot && hz > 0 && Math.floor(Number(boot[1]) + ticks / hz) <= started + 1) return birth;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (['ENOENT', 'ESRCH'].includes((error as NodeJS.ErrnoException).code!)) {
|
||||
// Distinguish a completed child whose receipt is still being written
|
||||
// from a live PID with an unverifiable identity.
|
||||
try { systemOwner(pid); } catch (probe) {
|
||||
if (['ENOENT', 'ESRCH'].includes((probe as NodeJS.ErrnoException).code!))
|
||||
throw Object.assign(new Error('Command already exited'), { code: 'ESRCH' });
|
||||
}
|
||||
}
|
||||
}
|
||||
throw conflict();
|
||||
}
|
||||
|
||||
// After a stop worker exits, descendants may already have been adopted by PID 1.
|
||||
// A saved birth identity still identifies them; walking the dead root no longer can.
|
||||
export async function finishStoppedTree(identities: string[], signalledAt?: number | null) {
|
||||
const surviving = () => identities.flatMap(identity => {
|
||||
const pid = Number(identity.split(':')[1]);
|
||||
if (!Number.isSafeInteger(pid) || pid <= 1) throw new Error('Invalid saved process identity');
|
||||
try { return systemOwner(pid) === identity ? [pid] : []; }
|
||||
catch (error) {
|
||||
if (['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)) return [];
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
const remainingGrace = Math.min(1000, Math.max(0, (signalledAt ?? Date.now()) + 1000 - Date.now()));
|
||||
const graceDeadline = Date.now() + remainingGrace;
|
||||
while (surviving().length) {
|
||||
const remaining = graceDeadline - Date.now();
|
||||
if (remaining <= 0) break;
|
||||
await new Promise(resolve => setTimeout(resolve, Math.min(20, remaining)));
|
||||
}
|
||||
if (!surviving().length) return;
|
||||
// Revalidate each PID immediately before signalling, including after the grace period.
|
||||
for (const identity of identities) {
|
||||
const pid = Number(identity.split(':')[1]);
|
||||
try {
|
||||
if (systemOwner(pid) === identity) process.kill(pid, 'SIGKILL');
|
||||
} catch (error) {
|
||||
if (!['ESRCH', 'ENOENT'].includes((error as NodeJS.ErrnoException).code!)) throw error;
|
||||
}
|
||||
}
|
||||
const deadline = Date.now() + 1000;
|
||||
while (surviving().length) {
|
||||
if (Date.now() >= deadline) throw new Error('Stopped process tree did not exit');
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { upcomingSlots } from './cronScheduler';
|
||||
|
||||
// Find only the latest eligible slot even for a second-level rule after hours
|
||||
// offline. Search by time, so cost is logarithmic in the configured window.
|
||||
export function latestMissedSlot(
|
||||
schedule: string,
|
||||
since: number,
|
||||
until: number,
|
||||
): number | null {
|
||||
let low = Math.floor(since / 1000);
|
||||
let high = Math.floor(until / 1000);
|
||||
let latest: number | null = null;
|
||||
while (low < high) {
|
||||
const middle = Math.floor((low + high) / 2);
|
||||
const [next] = upcomingSlots(schedule, middle * 1000);
|
||||
if (next > until) high = middle;
|
||||
else {
|
||||
latest = next;
|
||||
low = next / 1000;
|
||||
}
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
import CronExpressionParser from 'cron-parser';
|
||||
import { validate } from 'node-cron';
|
||||
import { ScheduleType } from '../interface/schedule';
|
||||
|
||||
const aliases: Record<string, string> = {
|
||||
'@yearly': '0 0 0 1 1 *',
|
||||
'@annually': '0 0 0 1 1 *',
|
||||
'@monthly': '0 0 0 1 * *',
|
||||
'@weekly': '0 0 0 * * 0',
|
||||
'@daily': '0 0 0 * * *',
|
||||
'@midnight': '0 0 0 * * *',
|
||||
'@hourly': '0 0 * * * *',
|
||||
'@minutely': '0 * * * * *',
|
||||
};
|
||||
|
||||
export interface CronSchedule {
|
||||
patterns: string[];
|
||||
dayCount: number;
|
||||
nthDay: number;
|
||||
}
|
||||
|
||||
// Validation and registration repeatedly see identical rules in large snapshots.
|
||||
// Cache only immutable syntax, never dates or running tasks, and bound user input.
|
||||
const scheduleCache = new Map<string, CronSchedule>();
|
||||
const daysInMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
|
||||
// Canonicalize legacy shorthand, aliases, names and numeric-start steps before
|
||||
// node-cron sees them. Extend legacy aliases explicitly; reject H and bare /N.
|
||||
export function parseCronSchedule(schedule: unknown): CronSchedule {
|
||||
if (typeof schedule !== 'string' || !schedule.trim()) {
|
||||
throw new Error('Invalid cron schedule');
|
||||
}
|
||||
let source = schedule.trim();
|
||||
const cacheKey = source;
|
||||
const cached = scheduleCache.get(cacheKey);
|
||||
if (cached) return cached;
|
||||
if (source.startsWith('@')) {
|
||||
if (!Object.hasOwn(aliases, source)) throw new Error('Invalid cron alias');
|
||||
source = aliases[source];
|
||||
}
|
||||
let parts = source.split(/\s+/);
|
||||
if (
|
||||
parts.length > 6 ||
|
||||
parts.some((part) => /(^|,)\//.test(part) || /H(?:\(|\/|$)/i.test(part))
|
||||
) {
|
||||
throw new Error('Unsupported cron syntax');
|
||||
}
|
||||
parts = [
|
||||
...['0', '*', '*', '*', '*', '*'].slice(0, 6 - parts.length),
|
||||
...parts,
|
||||
];
|
||||
if (
|
||||
parts.some(
|
||||
(part, index) => index !== 3 && index !== 5 && part.includes('?'),
|
||||
)
|
||||
) {
|
||||
throw new Error('Question mark is only valid in day fields');
|
||||
}
|
||||
const expression = CronExpressionParser.parse(parts.join(' '));
|
||||
if (!expression.hasNext())
|
||||
throw new Error('Cron schedule has no next execution');
|
||||
let normalized = parts.map((part) => part.replace(/\?/g, '*'));
|
||||
// cron-parser includes Sunday in stepped ranges ending in 7 even when the
|
||||
// step does not land on 7. node-cron accepts those ranges with different days.
|
||||
if (/(^|,)(?:\d+|[a-z]{3})-0*7\/\d+(?=,|$)/i.test(normalized[5])) {
|
||||
normalized[5] = expression.fields.dayOfWeek.values.join(',');
|
||||
}
|
||||
// Most rules are already supported; only inspect individual fields on failure.
|
||||
if (!validate(normalized.join(' '))) {
|
||||
const fields = [
|
||||
expression.fields.second,
|
||||
expression.fields.minute,
|
||||
expression.fields.hour,
|
||||
expression.fields.dayOfMonth,
|
||||
expression.fields.month,
|
||||
expression.fields.dayOfWeek,
|
||||
];
|
||||
normalized = normalized.map((value, index) => {
|
||||
// Preserve supported lists, ranges and names. Expand only fields node-cron
|
||||
// cannot consume, such as numeric/name-start steps; never compress them.
|
||||
const probe = ['0', '0', '0', '*', '*', '*'];
|
||||
probe[index] = value;
|
||||
if (validate(probe.join(' '))) return value;
|
||||
const values = fields[index].values;
|
||||
if (index === 5 && expression.fields.dayOfWeek.nthDay) {
|
||||
// The legacy normalizer treated *#N / ?#N as an unrestricted weekday.
|
||||
if (values.length === 8) return '*';
|
||||
// # applies to a single weekday; normalize its numeric spelling only.
|
||||
return values.length === 1
|
||||
? `${values[0]}#${expression.fields.dayOfWeek.nthDay}`
|
||||
: value;
|
||||
}
|
||||
return values.join(',');
|
||||
});
|
||||
}
|
||||
const months = expression.fields.month.values;
|
||||
// cron-parser 4 clipped dates outside a single selected month's maximum
|
||||
// before deciding whether the day field covered the whole month.
|
||||
const dayCount = expression.fields.dayOfMonth.values.filter(
|
||||
(day) =>
|
||||
months.length !== 1 ||
|
||||
typeof day !== 'number' ||
|
||||
day <= daysInMonth[months[0] - 1],
|
||||
).length;
|
||||
const weekCount = expression.fields.dayOfWeek.values.length;
|
||||
// Preserve the legacy count-based wildcard rules, including repeated Sunday
|
||||
// and L tokens: an ignored day field must not remain an AND constraint.
|
||||
const weekdayPattern = [
|
||||
...normalized.slice(0, 3),
|
||||
'*',
|
||||
...normalized.slice(4),
|
||||
].join(' ');
|
||||
const patterns =
|
||||
weekCount === 8
|
||||
? [[...normalized.slice(0, 5), '*'].join(' ')]
|
||||
: dayCount < 31
|
||||
? [[...normalized.slice(0, 5), '*'].join(' '), weekdayPattern]
|
||||
: [weekdayPattern];
|
||||
const valid = patterns.map((pattern) => validate(pattern));
|
||||
if (patterns.length === 2 && !valid[0] && valid[1]) {
|
||||
// A date branch can be impossible for all chosen months while the weekday
|
||||
// branch still runs. Drop it only if its syntax is valid with any month.
|
||||
if (validate([...normalized.slice(0, 4), '*', '*'].join(' '))) {
|
||||
patterns.shift();
|
||||
valid.shift();
|
||||
}
|
||||
}
|
||||
if (!valid.every(Boolean)) {
|
||||
throw new Error('Unsupported cron schedule');
|
||||
}
|
||||
const parsed = {
|
||||
patterns,
|
||||
dayCount,
|
||||
nthDay: expression.fields.dayOfWeek.nthDay,
|
||||
};
|
||||
Object.freeze(patterns);
|
||||
Object.freeze(parsed);
|
||||
if (scheduleCache.size >= 512)
|
||||
scheduleCache.delete(scheduleCache.keys().next().value);
|
||||
scheduleCache.set(cacheKey, parsed);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export function isValidCronSchedule(schedule: unknown): schedule is string {
|
||||
try {
|
||||
parseCronSchedule(schedule);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function getInvalidCronSchedules(cron: {
|
||||
schedule?: string;
|
||||
extra_schedules?: Array<{ schedule: string }>;
|
||||
}): unknown[] {
|
||||
if (
|
||||
cron.schedule?.startsWith(ScheduleType.ONCE) ||
|
||||
cron.schedule?.startsWith(ScheduleType.BOOT)
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
cron.schedule,
|
||||
...(cron.extra_schedules || []).map((x) => x.schedule),
|
||||
].filter((schedule) => !isValidCronSchedule(schedule));
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
import { t } from './i18n';
|
||||
import { createTask, ScheduledTask } from 'node-cron';
|
||||
import { parseCronSchedule } from './cronSchedule';
|
||||
|
||||
interface SchedulerLogger {
|
||||
warn(message: string, ...args: unknown[]): unknown;
|
||||
error(message: string, ...args: unknown[]): unknown;
|
||||
}
|
||||
|
||||
export interface CronJob {
|
||||
start(): void;
|
||||
cancel(): void;
|
||||
}
|
||||
|
||||
function acceptsSlot(parsed: ReturnType<typeof parseCronSchedule>, tasks: ScheduledTask[], index: number, date: Date) {
|
||||
if (tasks.length === 1) return true;
|
||||
// Preserve cron-parser 4's day/weekday OR semantics, including its
|
||||
// month-dependent full-day range and the global nth-week constraint.
|
||||
if (parsed.nthDay && Math.ceil(date.getDate() / 7) !== parsed.nthDay)
|
||||
return false;
|
||||
if (index === 1) return !tasks[0].match(date);
|
||||
const monthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
return parsed.dayCount < monthDays[date.getMonth()] || tasks[1].match(date);
|
||||
}
|
||||
|
||||
// node-cron owns timers and calendar calculation; Qinglong owns execution
|
||||
// concurrency and process lifetime. Missed in-process slots join that same queue.
|
||||
export function createCronJob(
|
||||
schedule: string,
|
||||
callback: (date: Date) => unknown | Promise<unknown>,
|
||||
options: { name: string; logger: SchedulerLogger; start?: boolean },
|
||||
): CronJob {
|
||||
const parsed = parseCronSchedule(schedule);
|
||||
const tasks: ScheduledTask[] = [];
|
||||
let cancelled = false;
|
||||
let started = false;
|
||||
const dispatch = async (index: number, date: Date, missed: boolean) => {
|
||||
if (cancelled || !started || !acceptsSlot(parsed, tasks, index, date)) return;
|
||||
if (missed) {
|
||||
options.logger.warn(
|
||||
t('[schedule][补执行迟到任务] 任务: %s, 计划时间: %s'),
|
||||
options.name,
|
||||
date.toISOString(),
|
||||
);
|
||||
}
|
||||
try {
|
||||
await callback(date);
|
||||
} catch (error) {
|
||||
options.logger.error(
|
||||
t('[schedule][定时回调失败] 任务: %s, 错误: %s'),
|
||||
options.name,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
}
|
||||
};
|
||||
try {
|
||||
for (const [index, pattern] of parsed.patterns.entries()) {
|
||||
const task = createTask(
|
||||
pattern,
|
||||
(context) => dispatch(index, context.date, false),
|
||||
{
|
||||
noOverlap: false,
|
||||
missedExecutionTolerance: 5000,
|
||||
},
|
||||
);
|
||||
tasks.push(task);
|
||||
task.on('execution:missed', (context) =>
|
||||
dispatch(index, context.date, true),
|
||||
);
|
||||
// Fail before an existing schedule is cancelled, including impossible dates.
|
||||
task.getNextRuns(1);
|
||||
}
|
||||
} catch (error) {
|
||||
tasks.forEach((task) => task.destroy());
|
||||
throw error;
|
||||
}
|
||||
const job: CronJob = {
|
||||
start() {
|
||||
if (started || cancelled) return;
|
||||
started = true;
|
||||
tasks.forEach((task) => task.start());
|
||||
},
|
||||
cancel() {
|
||||
if (cancelled) return;
|
||||
cancelled = true;
|
||||
tasks.forEach((task) => task.destroy());
|
||||
},
|
||||
};
|
||||
if (options.start !== false) job.start();
|
||||
return job;
|
||||
}
|
||||
|
||||
|
||||
// node-cron 4.6.0 exposes getNextRuns only from the wall clock. Its pinned
|
||||
// inline matcher also accepts an explicit cursor, needed for previews and recovery.
|
||||
export function upcomingSlots(schedule: string, after: number, count = 1, through?: number): number[] {
|
||||
const parsed = parseCronSchedule(schedule);
|
||||
const tasks: ScheduledTask[] = [];
|
||||
try {
|
||||
const matchers = parsed.patterns.map((pattern) => {
|
||||
const task = createTask(pattern, () => {});
|
||||
tasks.push(task);
|
||||
return (task as ScheduledTask & {
|
||||
timeMatcher: { getNextMatch(date: Date): Date; expressions: number[][] };
|
||||
}).timeMatcher;
|
||||
});
|
||||
const next = matchers.map((matcher) => matcher.getNextMatch(new Date(after)));
|
||||
// All calendar branches share their clock fields. For bounded audit ranges,
|
||||
// resolve each matching minute once, including the matcher's DST choice.
|
||||
const seconds = through == null ? [] : [...new Set(matchers[0].expressions[0])].sort((a,b) => a-b);
|
||||
const slots: number[] = [];
|
||||
let horizon = after + 366 * 100 * 86400000;
|
||||
while (slots.length < count) {
|
||||
const time = Math.min(...next.map(Number));
|
||||
if (through != null && time > through) break;
|
||||
if (!Number.isFinite(time) || time > horizon) throw new Error('No matching calendar date');
|
||||
let accepted = false;
|
||||
next.forEach((date, index) => {
|
||||
if (+date !== time) return;
|
||||
const valid = acceptsSlot(parsed, tasks, index, date);
|
||||
accepted ||= valid;
|
||||
// Both branches share the clock fields. Rejection applies to the
|
||||
// entire local day, including schedules that fire every second.
|
||||
const cursor = new Date(time);
|
||||
if (!valid) cursor.setHours(23, 59, 59, 999);
|
||||
else if (through != null) cursor.setTime(time - time % 60000 + 59999);
|
||||
next[index] = matchers[index].getNextMatch(cursor);
|
||||
});
|
||||
if (accepted) {
|
||||
if (through == null) slots.push(time);
|
||||
else for (const second of seconds) {
|
||||
const slot = time - time % 60000 + second * 1000;
|
||||
if (slot >= time && slot <= through && slots.length < count) slots.push(slot);
|
||||
}
|
||||
horizon = time + 366 * 100 * 86400000;
|
||||
}
|
||||
}
|
||||
return slots;
|
||||
} finally {
|
||||
tasks.forEach((task) => task.destroy());
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
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 } },
|
||||
);
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import { QueueAddOptions } from 'p-queue-cjs';
|
||||
|
||||
type Job = () => Promise<unknown>;
|
||||
export interface CronQueueOptions extends QueueAddOptions {
|
||||
waitingSignal?: EventEmitter;
|
||||
onRemoved?: () => void;
|
||||
}
|
||||
|
||||
// p-queue checks its signal only after dequeue. Remove expired waits while the
|
||||
// execution slots are still occupied, without aborting a running child.
|
||||
export class CronWaitQueue {
|
||||
private entries: { run: Job; priority: number; detach: () => void }[] = [];
|
||||
|
||||
get size() { return this.entries.length; }
|
||||
|
||||
enqueue(run: Job, options: Partial<CronQueueOptions> = {}) {
|
||||
const { priority = 0, waitingSignal, onRemoved } = options;
|
||||
const remove = () => {
|
||||
const index = this.entries.indexOf(entry);
|
||||
if (index < 0) return;
|
||||
this.entries.splice(index, 1);
|
||||
onRemoved?.();
|
||||
};
|
||||
const entry = { run, priority, detach: () => waitingSignal?.off('expired', remove) };
|
||||
const last = this.entries[this.size - 1];
|
||||
if (!last || last.priority >= priority) this.entries.push(entry);
|
||||
else this.entries.splice(this.entries.findIndex((job) => job.priority < priority), 0, entry);
|
||||
waitingSignal?.once('expired', remove);
|
||||
}
|
||||
|
||||
dequeue() {
|
||||
const next = this.entries.shift();
|
||||
next?.detach();
|
||||
return next?.run;
|
||||
}
|
||||
|
||||
filter(options: Partial<CronQueueOptions>) {
|
||||
return this.entries.filter((entry) => entry.priority === options.priority).map((entry) => entry.run);
|
||||
}
|
||||
}
|
||||
@@ -9,37 +9,60 @@ function isGone(error: unknown) {
|
||||
return code === 'ENOENT' || code === 'ENOTDIR';
|
||||
}
|
||||
|
||||
async function directoryVersion(root: string, parent: string, blacklist: string[]) {
|
||||
async function directoryVersion(
|
||||
root: string,
|
||||
parent: string,
|
||||
blacklist: string[],
|
||||
) {
|
||||
const dir = parent ? resolveFileAccess(root, [parent], blacklist) : root;
|
||||
const denied = () => Object.assign(new Error('Invalid directory'), { status: 403 });
|
||||
const denied = () =>
|
||||
Object.assign(new Error('Invalid directory'), { status: 403 });
|
||||
if (!dir) throw denied();
|
||||
try {
|
||||
if (await fs.realpath(dir) !== path.join(root, parent)) throw denied();
|
||||
if ((await fs.realpath(dir)) !== path.join(root, parent)) throw denied();
|
||||
const stat = await fs.lstat(dir, { bigint: true });
|
||||
return stat.isDirectory() ? [stat.dev, stat.ino, stat.mtimeNs, stat.ctimeNs].join(':') : null;
|
||||
return stat.isDirectory()
|
||||
? [stat.dev, stat.ino, stat.mtimeNs, stat.ctimeNs].join(':')
|
||||
: null;
|
||||
} catch (error) {
|
||||
if (isGone(error)) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkDirectoryVersions(root: string, blacklist: string[], versions: DirectoryVersion[]) {
|
||||
export async function checkDirectoryVersions(
|
||||
root: string,
|
||||
blacklist: string[],
|
||||
versions: DirectoryVersion[],
|
||||
) {
|
||||
const realRoot = await fs.realpath(root);
|
||||
const matches = await Promise.all(versions.map(async ([parent, expected]) => {
|
||||
try {
|
||||
return await directoryVersion(realRoot, parent, blacklist) === expected;
|
||||
} catch (error) {
|
||||
// A formerly accessible directory may now be a symlink outside the root.
|
||||
if ((error as { status?: number }).status === 403) return false;
|
||||
throw error;
|
||||
}
|
||||
}));
|
||||
const matches = await Promise.all(
|
||||
versions.map(async ([parent, expected]) => {
|
||||
try {
|
||||
return (
|
||||
(await directoryVersion(realRoot, parent, blacklist)) === expected
|
||||
);
|
||||
} catch (error) {
|
||||
// A formerly accessible directory may now be a symlink outside the root.
|
||||
if ((error as { status?: number }).status === 403) return false;
|
||||
throw error;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return matches.every(Boolean);
|
||||
}
|
||||
|
||||
export async function readDirectoryPage(root: string, blacklist: string[], directory: string, after: string,
|
||||
search: string, foldersOnly: boolean, newestFirst: boolean, limit = 50) {
|
||||
const blocked = new Set(blacklist.map(name => name.toLowerCase()));
|
||||
export async function readDirectoryPage(
|
||||
root: string,
|
||||
blacklist: string[],
|
||||
directory: string,
|
||||
after: string,
|
||||
search: string,
|
||||
foldersOnly: boolean,
|
||||
newestFirst: boolean,
|
||||
limit = 50,
|
||||
) {
|
||||
const blocked = new Set(blacklist.map((name) => name.toLowerCase()));
|
||||
const realRoot = await fs.realpath(root);
|
||||
const versions: DirectoryVersion[] = [];
|
||||
async function entries(parent: string) {
|
||||
@@ -47,36 +70,63 @@ export async function readDirectoryPage(root: string, blacklist: string[], direc
|
||||
versions.push([parent, version]);
|
||||
if (version === null) return [];
|
||||
try {
|
||||
return (await fs.readdir(path.join(realRoot, parent), { withFileTypes: true })).filter(e =>
|
||||
!blocked.has(e.name.toLowerCase()) && (e.isDirectory() || (!foldersOnly && e.isFile())));
|
||||
return (
|
||||
await fs.readdir(path.join(realRoot, parent), { withFileTypes: true })
|
||||
).filter(
|
||||
(e) =>
|
||||
!blocked.has(e.name.toLowerCase()) &&
|
||||
(e.isDirectory() || (!foldersOnly && e.isFile())),
|
||||
);
|
||||
} catch (error) {
|
||||
if (isGone(error)) return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const compare = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
|
||||
const compare = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
|
||||
const rows = [];
|
||||
let next: string | null = null;
|
||||
async function row(parent: string, title: string, directory: boolean) {
|
||||
const key = path.join(parent, title);
|
||||
if (directory) return { title, parent, key, type: 'directory', isLeaf: false };
|
||||
if (directory)
|
||||
return { title, parent, key, type: 'directory', isLeaf: false };
|
||||
try {
|
||||
const stat = await fs.lstat(path.join(root, key));
|
||||
if (stat.isFile()) return { title, parent, key, type: 'file', isLeaf: true, size: stat.size };
|
||||
} catch (error) { if (!isGone(error)) throw error; }
|
||||
if (stat.isFile())
|
||||
return {
|
||||
title,
|
||||
parent,
|
||||
key,
|
||||
type: 'file',
|
||||
isLeaf: true,
|
||||
size: stat.size,
|
||||
};
|
||||
} catch (error) {
|
||||
if (!isGone(error)) throw error;
|
||||
}
|
||||
}
|
||||
if (!search) {
|
||||
const sorted = (await entries(directory)).sort((a,b) =>
|
||||
Number(b.isDirectory()) - Number(a.isDirectory()) ||
|
||||
compare(a.name, b.name) * (newestFirst && !a.isDirectory() ? -1 : 1));
|
||||
const selected = sorted.filter(e => {
|
||||
const sorted = (await entries(directory)).sort(
|
||||
(a, b) =>
|
||||
Number(b.isDirectory()) - Number(a.isDirectory()) ||
|
||||
compare(a.name, b.name) * (newestFirst && !a.isDirectory() ? -1 : 1),
|
||||
);
|
||||
const selected = sorted.filter((e) => {
|
||||
if (!after) return true;
|
||||
const group = e.isDirectory() ? '0' : '1';
|
||||
return group > after[0] || (group === after[0] &&
|
||||
compare(e.name, after.slice(1)) * (newestFirst && !e.isDirectory() ? -1 : 1) > 0);
|
||||
return (
|
||||
group > after[0] ||
|
||||
(group === after[0] &&
|
||||
compare(e.name, after.slice(1)) *
|
||||
(newestFirst && !e.isDirectory() ? -1 : 1) >
|
||||
0)
|
||||
);
|
||||
});
|
||||
const page = selected.slice(0, limit);
|
||||
const data = (await Promise.all(page.map(e => row(directory, e.name, e.isDirectory())))).filter(Boolean);
|
||||
const data = (
|
||||
await Promise.all(
|
||||
page.map((e) => row(directory, e.name, e.isDirectory())),
|
||||
)
|
||||
).filter(Boolean);
|
||||
if (selected.length > limit) {
|
||||
const last = page[page.length - 1];
|
||||
next = (last.isDirectory() ? '0' : '1') + last.name;
|
||||
@@ -84,16 +134,26 @@ export async function readDirectoryPage(root: string, blacklist: string[], direc
|
||||
return { data, next, versions };
|
||||
}
|
||||
// Resume a depth-first search at the last visited entry, including on pages with zero matches.
|
||||
async function* walk(parent: string, resume: string[]): AsyncGenerator<{ parent: string; name: string; dir: boolean }> {
|
||||
const items = (await entries(parent)).sort((a,b) => compare(a.name,b.name));
|
||||
async function* walk(
|
||||
parent: string,
|
||||
resume: string[],
|
||||
): AsyncGenerator<{ parent: string; name: string; dir: boolean }> {
|
||||
const items = (await entries(parent)).sort((a, b) =>
|
||||
compare(a.name, b.name),
|
||||
);
|
||||
for (const item of items) {
|
||||
if (resume.length && item.name < resume[0]) continue;
|
||||
const same = item.name === resume[0];
|
||||
if (!same) yield { parent, name: item.name, dir: item.isDirectory() };
|
||||
if (item.isDirectory()) {
|
||||
try { yield* walk(path.join(parent, item.name), same ? resume.slice(1) : []); }
|
||||
catch (error) {
|
||||
if (!isGone(error) && (error as { status?: number }).status !== 403) throw error;
|
||||
try {
|
||||
yield* walk(
|
||||
path.join(parent, item.name),
|
||||
same ? resume.slice(1) : [],
|
||||
);
|
||||
} catch (error) {
|
||||
if (!isGone(error) && (error as { status?: number }).status !== 403)
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -105,7 +165,10 @@ export async function readDirectoryPage(root: string, blacklist: string[], direc
|
||||
const item = await row(entry.parent, entry.name, entry.dir);
|
||||
if (item) rows.push(item);
|
||||
}
|
||||
if (++visited >= 512 || rows.length === limit) { next = key; break; }
|
||||
if (++visited >= 512 || rows.length === limit) {
|
||||
next = key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { data: rows, next, versions };
|
||||
}
|
||||
@@ -4,31 +4,66 @@ import { checkDirectoryVersions, readDirectoryPage } from './directoryPage';
|
||||
|
||||
export function directoryCheckHandler(root: () => string, blacklist: string[]) {
|
||||
return [
|
||||
celebrate({ body: Joi.array().items(Joi.array().ordered(
|
||||
Joi.string().allow('').max(4096).required(), Joi.string().max(128).allow(null).required(),
|
||||
).length(2)).min(1).max(128).required() }),
|
||||
celebrate({
|
||||
body: Joi.array()
|
||||
.items(
|
||||
Joi.array()
|
||||
.ordered(
|
||||
Joi.string().allow('').max(4096).required(),
|
||||
Joi.string().max(128).allow(null).required(),
|
||||
)
|
||||
.length(2),
|
||||
)
|
||||
.min(1)
|
||||
.max(128)
|
||||
.required(),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const current = await checkDirectoryVersions(root(), blacklist, req.body);
|
||||
const current = await checkDirectoryVersions(
|
||||
root(),
|
||||
blacklist,
|
||||
req.body,
|
||||
);
|
||||
res.send({ code: 200, current });
|
||||
} catch (error) { next(error); }
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function directoryPageHandler(root: () => string, blacklist: string[], newestFirst: boolean) {
|
||||
export function directoryPageHandler(
|
||||
root: () => string,
|
||||
blacklist: string[],
|
||||
newestFirst: boolean,
|
||||
) {
|
||||
return [
|
||||
celebrate({ query: Joi.object({
|
||||
path: Joi.string().allow(''), after: Joi.string().allow(''), search: Joi.string().allow(''),
|
||||
folders: Joi.boolean(), t: Joi.string(),
|
||||
}) }),
|
||||
celebrate({
|
||||
query: Joi.object({
|
||||
path: Joi.string().allow(''),
|
||||
after: Joi.string().allow(''),
|
||||
search: Joi.string().allow(''),
|
||||
folders: Joi.boolean(),
|
||||
t: Joi.string(),
|
||||
}),
|
||||
}),
|
||||
async (req: Request, res: Response, next: NextFunction) => {
|
||||
try {
|
||||
const { path = '', after = '', search = '', folders } = req.query;
|
||||
const page = await readDirectoryPage(root(), blacklist, String(path), String(after),
|
||||
String(search), String(folders) === 'true', newestFirst);
|
||||
const page = await readDirectoryPage(
|
||||
root(),
|
||||
blacklist,
|
||||
String(path),
|
||||
String(after),
|
||||
String(search),
|
||||
String(folders) === 'true',
|
||||
newestFirst,
|
||||
);
|
||||
res.send({ code: 200, ...page });
|
||||
} catch (error) { next(error); }
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
// The original scheduled CLI wire format maps to its existing persisted trigger ID.
|
||||
export const executionIdPattern = /^(?:client-|legacy-system:\d{1,12}:)[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/;
|
||||
export function executionTriggerId(id: string) {
|
||||
return id.replace('legacy-system:', 'system-cli-').replace(':', '-');
|
||||
}
|
||||
|
||||
// A header lets upgraded clients keep the same identified body on older panels.
|
||||
export function receiptFinishTime(header?: string) {
|
||||
if (header && /^\d{1,13}$/.test(header)) {
|
||||
const time = Number(header);
|
||||
if (time > 0 && time <= Date.now()) return time;
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,9 @@ export function resolveFileAccess(
|
||||
// of the same entry. Check every protected name without case sensitivity.
|
||||
const blockedNames = new Set(blacklist.map((part) => part.toLowerCase()));
|
||||
const isBlocked = (relative: string) =>
|
||||
relative.split(path.sep).some((part) => blockedNames.has(part.toLowerCase()));
|
||||
relative
|
||||
.split(path.sep)
|
||||
.some((part) => blockedNames.has(part.toLowerCase()));
|
||||
if (isBlocked(path.relative(resolvedRoot, target))) return '';
|
||||
try {
|
||||
const realRoot = fs.realpathSync(resolvedRoot);
|
||||
|
||||
+5
-3
@@ -1,8 +1,9 @@
|
||||
const messages: Record<string, Record<string, string>> = {
|
||||
zh: {},
|
||||
en: {
|
||||
'系统定时规则安装失败,旧规则可能仍在运行,正在重试': 'System crontab installation failed. The previous rules may still run. Retrying.',
|
||||
'Cron表达式格式有误': 'Invalid cron expression',
|
||||
'系统定时规则安装失败,旧规则可能仍在运行,正在重试':
|
||||
'System crontab installation failed. The previous rules may still run. Retrying.',
|
||||
Cron表达式格式有误: 'Invalid cron expression',
|
||||
'升级任务启动失败,请检查日志后重试':
|
||||
'Failed to start the update. Check the logs and try again.',
|
||||
'[schedule][停止已运行任务] 任务ID: %s, PID: %s':
|
||||
@@ -264,7 +265,8 @@ const messages: Record<string, Record<string, string>> = {
|
||||
'执行after命令...': 'Execute after command...',
|
||||
'## 执行结束... %s 耗时 %s 秒':
|
||||
'## Execution finished... %s elapsed %s seconds',
|
||||
'原调度未能恢复,正在重试': 'Could not restore the previous schedule. Retrying.',
|
||||
'原调度未能恢复,正在重试':
|
||||
'Could not restore the previous schedule. Retrying.',
|
||||
'任务已修改,请刷新后重试': 'The task has changed. Refresh and try again.',
|
||||
'调度器注册失败,任务创建已回滚':
|
||||
'Scheduler registration failed, task creation rolled back',
|
||||
|
||||
@@ -1,172 +0,0 @@
|
||||
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 } });
|
||||
}
|
||||
}
|
||||
+31
-19
@@ -47,18 +47,15 @@ function completeUtf8End(buffer: Buffer, start: number, end: number) {
|
||||
|
||||
const firstByte = buffer[sequenceStart];
|
||||
const expectedLength =
|
||||
firstByte < 0x80
|
||||
? 1
|
||||
: firstByte < 0xe0
|
||||
? 2
|
||||
: firstByte < 0xf0
|
||||
? 3
|
||||
: 4;
|
||||
firstByte < 0x80 ? 1 : firstByte < 0xe0 ? 2 : firstByte < 0xf0 ? 3 : 4;
|
||||
return end - sequenceStart < expectedLength ? sequenceStart : end;
|
||||
}
|
||||
|
||||
function logDigest(identity: string, from: number, bytes: Buffer) {
|
||||
return createHash('sha256').update(`${identity}:${from}:`).update(bytes).digest('hex');
|
||||
return createHash('sha256')
|
||||
.update(`${identity}:${from}:`)
|
||||
.update(bytes)
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
export async function readLogChunk(
|
||||
@@ -75,16 +72,22 @@ export async function readLogChunk(
|
||||
const requestedOffset = Number.isFinite(options.offset)
|
||||
? Math.max(0, Math.trunc(options.offset!))
|
||||
: undefined;
|
||||
let start = options.tail || requestedOffset === undefined
|
||||
? Math.max(total - limit, 0)
|
||||
: Math.min(requestedOffset, total);
|
||||
const resume = options.cursor && !options.tail && requestedOffset !== undefined;
|
||||
let start =
|
||||
options.tail || requestedOffset === undefined
|
||||
? Math.max(total - limit, 0)
|
||||
: Math.min(requestedOffset, total);
|
||||
const resume =
|
||||
options.cursor && !options.tail && requestedOffset !== undefined;
|
||||
const [fromText, digest] = resume ? options.cursor!.split('.') : [];
|
||||
let from = resume ? Number(fromText) : start;
|
||||
let reset = Boolean(resume && (
|
||||
requestedOffset !== start || !Number.isSafeInteger(from) ||
|
||||
from < 0 || from > start || start - from > CURSOR_WINDOW_BYTES
|
||||
));
|
||||
let reset = Boolean(
|
||||
resume &&
|
||||
(requestedOffset !== start ||
|
||||
!Number.isSafeInteger(from) ||
|
||||
from < 0 ||
|
||||
from > start ||
|
||||
start - from > CURSOR_WINDOW_BYTES),
|
||||
);
|
||||
if (reset) from = start = 0;
|
||||
|
||||
// Read the previously displayed bytes and their continuation together.
|
||||
@@ -97,7 +100,10 @@ export async function readLogChunk(
|
||||
let window = await readWindow(from, start + limit + 3);
|
||||
if (resume && !reset) {
|
||||
const prefix = window.subarray(0, start - from);
|
||||
if (prefix.length !== start - from || logDigest(identity, from, prefix) !== digest) {
|
||||
if (
|
||||
prefix.length !== start - from ||
|
||||
logDigest(identity, from, prefix) !== digest
|
||||
) {
|
||||
reset = true;
|
||||
start = from = 0;
|
||||
window = await readWindow(0, limit + 3);
|
||||
@@ -120,8 +126,14 @@ export async function readLogChunk(
|
||||
let cursor: string | undefined;
|
||||
if (options.follow || options.cursor) {
|
||||
const retainedFrom = Math.max(from, nextOffset - CURSOR_WINDOW_BYTES);
|
||||
cursor = resume && !reset && nextOffset === start ? options.cursor :
|
||||
`${retainedFrom}.${logDigest(identity, retainedFrom, window.subarray(retainedFrom - from, nextOffset - from))}`;
|
||||
cursor =
|
||||
resume && !reset && nextOffset === start
|
||||
? options.cursor
|
||||
: `${retainedFrom}.${logDigest(
|
||||
identity,
|
||||
retainedFrom,
|
||||
window.subarray(retainedFrom - from, nextOffset - from),
|
||||
)}`;
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
+32
-371
@@ -1,390 +1,51 @@
|
||||
// Keep the command's actual exit available until its SQLite transaction commits.
|
||||
// Stable supervisor entry point. Receipt storage is a separate, service-free module.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { createHash, randomUUID } = require('node:crypto');
|
||||
|
||||
const {
|
||||
parseExit,
|
||||
writeExit,
|
||||
receiptPath,
|
||||
storageFull,
|
||||
} = require('../cron/settlement/exitReceipt.cjs');
|
||||
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 = { isLegacyCapture: file => legacyCapture.test(path.basename(file)), isMetadataReceipt: file => Boolean(metadataReceipt(file)), receiptPath, publishedExits, publishedScriptStarts, readExit, writeExit, validExit, storageFull, retireLegacyFile, retiringExits };
|
||||
|
||||
if (require.main === module) {
|
||||
const id = process.env.QL_TRIGGER_ID;
|
||||
const exit = parseExit(id, JSON.parse(process.argv[2]));
|
||||
if (!idPattern.test(id || '') || !exit) throw new Error('Invalid supervisor exit receipt');
|
||||
if (!idPattern.test(id || '') || !exit)
|
||||
throw new Error('Invalid supervisor exit receipt');
|
||||
const { code, signal, time } = exit;
|
||||
// An older supervisor may only have delivered this tuple in its message.
|
||||
// Journal it before waiting for the SQLite writer or loading the panel.
|
||||
let journaled = false;
|
||||
if (exit.version === 1) {
|
||||
try { writeExit(id, code, signal, time); journaled = Boolean(receiptPath(id)); }
|
||||
catch (error) { console.error('[scheduler] Could not journal supervisor message:', error); }
|
||||
try {
|
||||
writeExit(id, code, signal, time);
|
||||
journaled = Boolean(receiptPath(id));
|
||||
} catch (error) {
|
||||
console.error('[scheduler] Could not journal supervisor message:', error);
|
||||
}
|
||||
}
|
||||
// Development workers run TypeScript directly. Released panels load the
|
||||
// compiled module without starting another runtime on ordinary exits.
|
||||
if (!fs.existsSync(path.join(__dirname, 'triggerHistory.js'))) {
|
||||
if (!fs.existsSync(path.join(__dirname, '../cron/history.js'))) {
|
||||
process.env.TS_NODE_PROJECT = path.join(__dirname, '../tsconfig.json');
|
||||
require('ts-node/register/transpile-only');
|
||||
}
|
||||
const { triggerHistory } = require('./triggerHistory');
|
||||
triggerHistory().complete(id, signal || code !== 0 ? 'failed' : 'finished',
|
||||
signal, code, time, exit.version === 1 ? exit : 'legacy').catch(error => {
|
||||
if (journaled && storageFull(error)) return;
|
||||
console.error('[scheduler] Failed to settle orphaned command:', error);
|
||||
process.exitCode = storageFull(error) ? 75 : 1;
|
||||
}).finally(() => require('../data').sequelize.close());
|
||||
const { triggerHistory } = require('../cron/history');
|
||||
triggerHistory()
|
||||
.complete(
|
||||
id,
|
||||
signal || code !== 0 ? 'failed' : 'finished',
|
||||
signal,
|
||||
code,
|
||||
time,
|
||||
exit.version === 1 ? exit : 'legacy',
|
||||
)
|
||||
.catch((error) => {
|
||||
if (journaled && storageFull(error)) return;
|
||||
console.error('[scheduler] Failed to settle orphaned command:', error);
|
||||
process.exitCode = storageFull(error) ? 75 : 1;
|
||||
})
|
||||
.finally(() => require('../data').sequelize.close());
|
||||
}
|
||||
+2
-213
@@ -1,42 +1,12 @@
|
||||
import { EventEmitter } from 'events';
|
||||
import PQueue, { QueueAddOptions } from 'p-queue-cjs';
|
||||
import os from 'os';
|
||||
import type { Sequelize } from 'sequelize';
|
||||
import { QueueOccupants, recordQueueAdmission } from './queueDiagnostics';
|
||||
import { CronWaitQueue, CronQueueOptions } from './cronWaitQueue';
|
||||
import { AuthDataType, SystemModel } from '../data/system';
|
||||
import Logger from '../loaders/logger';
|
||||
import { Dependence } from '../data/dependence';
|
||||
import NotificationService from '../services/notify';
|
||||
import { t, tf } from '../shared/i18n';
|
||||
import {
|
||||
ICronFn,
|
||||
IDependencyFn,
|
||||
ISchedule,
|
||||
IScheduleFn,
|
||||
TCron,
|
||||
} from './interface';
|
||||
import config from '../config';
|
||||
import { credentials } from '@grpc/grpc-js';
|
||||
import { ApiClient } from '../protos/api';
|
||||
import { getGrpcCerts } from '../config/grpcCerts';
|
||||
import type { Dependence } from '../data/dependence';
|
||||
import type { IDependencyFn, ISchedule, IScheduleFn, TCron } from './interface';
|
||||
|
||||
class TaskLimit {
|
||||
private dependenyLimit = new PQueue({ concurrency: 1 });
|
||||
private queuedDependencyIds = new Set<number>([]);
|
||||
private queuedCrons = new Map<string, ICronFn<any>[]>();
|
||||
private repeatCronNotifyMap = new Map<string, number>();
|
||||
private updateLogLimit = new PQueue({ concurrency: 1 });
|
||||
private warnSampling = (error: Error) => Logger.warn('[queue] Could not save occupancy: %s', error.message);
|
||||
private scheduledOccupants = new QueueOccupants('scheduled', () => this.cronLimit.concurrency, this.warnSampling);
|
||||
private manualOccupants = new QueueOccupants('manual', () => this.manualCronoLimit.concurrency, this.warnSampling);
|
||||
private cronLimit = new PQueue<CronWaitQueue, CronQueueOptions>({
|
||||
queueClass: CronWaitQueue,
|
||||
concurrency: Math.max(os.cpus().length, 4),
|
||||
});
|
||||
private manualCronoLimit = new PQueue({
|
||||
concurrency: Math.max(os.cpus().length, 4),
|
||||
});
|
||||
private subscriptionLimit = new PQueue({
|
||||
concurrency: Math.max(os.cpus().length, 4),
|
||||
});
|
||||
@@ -46,198 +16,17 @@ class TaskLimit {
|
||||
private systemLimit = new PQueue({
|
||||
concurrency: Math.max(os.cpus().length, 4),
|
||||
});
|
||||
private _client: ApiClient | null = null;
|
||||
|
||||
private get client(): ApiClient {
|
||||
if (!this._client) {
|
||||
const tlsConfig = getGrpcCerts();
|
||||
const creds = tlsConfig
|
||||
? credentials.createSsl(
|
||||
Buffer.from(tlsConfig.caCert),
|
||||
Buffer.from(tlsConfig.clientKey),
|
||||
Buffer.from(tlsConfig.clientCert),
|
||||
)
|
||||
: credentials.createInsecure();
|
||||
this._client = new ApiClient(`localhost:${config.grpcPort}`, creds, {
|
||||
'grpc.enable_http_proxy': 0,
|
||||
});
|
||||
}
|
||||
return this._client;
|
||||
}
|
||||
|
||||
get cronLimitActiveCount() {
|
||||
return this.cronLimit.pending;
|
||||
}
|
||||
|
||||
get cronLimitPendingCount() {
|
||||
return this.cronLimit.size;
|
||||
}
|
||||
|
||||
get firstDependencyId() {
|
||||
return [...this.queuedDependencyIds.values()][0];
|
||||
}
|
||||
|
||||
private notificationService: NotificationService = new NotificationService();
|
||||
|
||||
constructor() {
|
||||
this.setCustomLimit();
|
||||
this.handleEvents();
|
||||
}
|
||||
|
||||
private handleEvents() {
|
||||
this.cronLimit.on('add', () => {
|
||||
Logger.info(
|
||||
t('[schedule][任务加入队列] 运行中任务数: %s, 等待中任务数: %s'),
|
||||
this.cronLimitActiveCount,
|
||||
this.cronLimitPendingCount,
|
||||
);
|
||||
});
|
||||
this.cronLimit.on('active', () => {
|
||||
Logger.info(
|
||||
t('[schedule][开始处理任务] 运行中任务数: %s, 等待中任务数: %s'),
|
||||
this.cronLimitActiveCount + 1,
|
||||
this.cronLimitPendingCount,
|
||||
);
|
||||
});
|
||||
this.cronLimit.on('completed', (param) => {
|
||||
Logger.info(t('[schedule][任务处理成功] 参数 %s'), JSON.stringify(param));
|
||||
});
|
||||
this.cronLimit.on('error', (error) => {
|
||||
Logger.error(
|
||||
t('[schedule][任务处理错误] 参数 %s'),
|
||||
JSON.stringify(error),
|
||||
);
|
||||
});
|
||||
this.cronLimit.on('next', () => {
|
||||
Logger.info(
|
||||
t('[schedule][任务处理结束] 运行中任务数: %s, 等待中任务数: %s'),
|
||||
this.cronLimitActiveCount,
|
||||
this.cronLimitPendingCount,
|
||||
);
|
||||
});
|
||||
this.cronLimit.on('idle', () => {
|
||||
Logger.info(t(`[schedule][任务队列] 空闲中...`));
|
||||
});
|
||||
}
|
||||
|
||||
public removeQueuedDependency(dependency: Dependence) {
|
||||
if (this.queuedDependencyIds.has(dependency.id!)) {
|
||||
this.queuedDependencyIds.delete(dependency.id!);
|
||||
}
|
||||
}
|
||||
|
||||
public removeQueuedCron(id: string, completed?: ICronFn<any>) {
|
||||
if (this.queuedCrons.has(id)) {
|
||||
const runs = this.queuedCrons.get(id);
|
||||
if (runs && runs.length > 0) {
|
||||
const remaining = completed
|
||||
? runs.filter((run) => run !== completed)
|
||||
: runs.slice(0, -1);
|
||||
if (remaining.length) this.queuedCrons.set(id, remaining);
|
||||
else this.queuedCrons.delete(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public get cronConcurrency() {
|
||||
return this.manualCronoLimit.concurrency;
|
||||
}
|
||||
|
||||
public async setCustomLimit(limit?: number) {
|
||||
if (limit) {
|
||||
this.cronLimit.concurrency = limit;
|
||||
this.manualCronoLimit.concurrency = limit;
|
||||
this.scheduledOccupants.refresh();
|
||||
this.manualOccupants.refresh();
|
||||
return;
|
||||
}
|
||||
await SystemModel.sync();
|
||||
const doc = await SystemModel.findOne({
|
||||
where: { type: AuthDataType.systemConfig },
|
||||
});
|
||||
if (doc?.info?.cronConcurrency) {
|
||||
await this.setCustomLimit(doc.info.cronConcurrency);
|
||||
}
|
||||
}
|
||||
|
||||
public async runWithCronLimit<T>(
|
||||
cron: TCron,
|
||||
fn: ICronFn<T>,
|
||||
options?: Partial<QueueAddOptions>,
|
||||
isCurrent: () => boolean = () => true,
|
||||
onPending?: () => void,
|
||||
waitingSignal?: EventEmitter,
|
||||
triggerId?: string,
|
||||
db?: Sequelize,
|
||||
): Promise<T | void> {
|
||||
if (!isCurrent()) return;
|
||||
fn.cron = cron;
|
||||
fn.isCurrent = isCurrent;
|
||||
// Invalidated snapshots must not consume the new revision's repeat budget.
|
||||
const runs = this.queuedCrons
|
||||
.get(cron.id)
|
||||
?.filter((run) => run.isCurrent?.() !== false);
|
||||
if (cron.skip_if_pending && runs?.length) {
|
||||
onPending?.();
|
||||
return;
|
||||
}
|
||||
const result = runs?.length ? [...runs, fn] : [fn];
|
||||
const repeatTimes = this.repeatCronNotifyMap.get(cron.id) || 0;
|
||||
if (result?.length > 5) {
|
||||
if (repeatTimes < 3) {
|
||||
this.repeatCronNotifyMap.set(cron.id, repeatTimes + 1);
|
||||
this.client.systemNotify(
|
||||
{
|
||||
title: t('任务重复运行'),
|
||||
content: tf(
|
||||
'任务:%s,命令:%s,定时:%s,处于运行中的超过 %d 个,请检查定时设置',
|
||||
cron.name || '',
|
||||
cron.command || '',
|
||||
cron.schedule || '',
|
||||
5,
|
||||
),
|
||||
},
|
||||
(err, res) => {
|
||||
if (err) {
|
||||
Logger.error(
|
||||
t('[schedule][任务重复运行] 通知失败 %s'),
|
||||
JSON.stringify(err),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
Logger.warn(t('[schedule][任务重复运行] 参数 %s'), JSON.stringify(cron));
|
||||
return;
|
||||
}
|
||||
this.queuedCrons.set(cron.id, result);
|
||||
const run = this.trackAdmission(this.scheduledOccupants, this.cronLimit.concurrency, fn,
|
||||
{ id: triggerId, name: cron.name || cron.id }, db);
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
private trackAdmission<T>(pool: QueueOccupants, limit: number, fn: () => Promise<T>, occupant: { id?: string; name: string }, db?: Sequelize) {
|
||||
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);
|
||||
}
|
||||
|
||||
public async manualRunWithCronLimit<T>(
|
||||
fn: () => Promise<T>,
|
||||
options?: Partial<QueueAddOptions>,
|
||||
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);
|
||||
}
|
||||
|
||||
public async runWithSubscriptionLimit<T>(
|
||||
schedule: TCron,
|
||||
fn: IScheduleFn<T>,
|
||||
|
||||
@@ -1,127 +0,0 @@
|
||||
import { QueryTypes, Sequelize } from 'sequelize';
|
||||
|
||||
type Occupant = { id?: string; name: string };
|
||||
export type Admission = {
|
||||
queue: 'manual' | 'scheduled';
|
||||
limit: number;
|
||||
occupied: number;
|
||||
holders: Occupant[];
|
||||
};
|
||||
|
||||
// Each object belongs to exactly one execution pool in its owning process.
|
||||
export class QueueOccupants {
|
||||
private active = new Set<Occupant>();
|
||||
private waiting = new Map<string, Sequelize>();
|
||||
private writing = false;
|
||||
private changed = false;
|
||||
|
||||
constructor(
|
||||
private queue: Admission['queue'],
|
||||
private limit: () => number,
|
||||
private warn: (error: Error) => void,
|
||||
) {}
|
||||
|
||||
watch(id: string, db: Sequelize) {
|
||||
this.waiting.set(id, db);
|
||||
this.refresh();
|
||||
}
|
||||
|
||||
forget(id?: string) {
|
||||
if (id) this.waiting.delete(id);
|
||||
}
|
||||
|
||||
refresh() {
|
||||
if (!this.waiting.size) return;
|
||||
this.changed = true;
|
||||
if (this.writing) return;
|
||||
this.writing = true;
|
||||
// Coalesce synchronous PQueue handoffs and keep SQLite writes in observation order.
|
||||
void Promise.resolve().then(async () => {
|
||||
try {
|
||||
while (this.changed) {
|
||||
this.changed = false;
|
||||
const context = JSON.stringify(this.snapshot(this.limit()));
|
||||
const groups = new Map<Sequelize, string[]>();
|
||||
for (const [id, db] of this.waiting) {
|
||||
const ids = groups.get(db);
|
||||
if (ids) ids.push(id);
|
||||
else groups.set(db, [id]);
|
||||
}
|
||||
for (const [db, ids] of groups) {
|
||||
await db
|
||||
.query(
|
||||
`UPDATE CronTriggers SET queue_live_context=$context
|
||||
WHERE state='queued' AND dequeued_at IS NULL AND id IN (SELECT value FROM json_each($ids))`,
|
||||
{ bind: { context, ids: JSON.stringify(ids) } },
|
||||
)
|
||||
.catch(this.warn);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.writing = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
admission(limit: number): Admission | undefined {
|
||||
return this.active.size >= limit ? this.snapshot(limit) : undefined;
|
||||
}
|
||||
|
||||
private snapshot(limit: number): Admission {
|
||||
return {
|
||||
queue: this.queue,
|
||||
limit,
|
||||
occupied: this.active.size,
|
||||
holders: [...this.active].slice(0, 8),
|
||||
};
|
||||
}
|
||||
|
||||
track<T>(job: () => Promise<T>, occupant: Occupant, db?: Sequelize) {
|
||||
return async () => {
|
||||
this.forget(occupant.id);
|
||||
this.active.add(occupant);
|
||||
this.refresh();
|
||||
if (occupant.id && db) {
|
||||
void db
|
||||
.query(
|
||||
'UPDATE CronTriggers SET dequeued_at=$at,queue_live_context=NULL WHERE id=$id AND queued_at <= $at AND dequeued_at IS NULL',
|
||||
{ bind: { id: occupant.id, at: Date.now() } },
|
||||
)
|
||||
.catch(this.warn);
|
||||
}
|
||||
try {
|
||||
return await job();
|
||||
} finally {
|
||||
this.active.delete(occupant);
|
||||
this.refresh();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function recordQueueAdmission(
|
||||
db: Sequelize,
|
||||
id: string,
|
||||
admission: Admission,
|
||||
) {
|
||||
return db.query(
|
||||
'UPDATE CronTriggers SET queue_context=$context WHERE id=$id AND queued_at <= $at AND queue_context IS NULL',
|
||||
{ bind: { id, at: Date.now(), context: JSON.stringify(admission) } },
|
||||
);
|
||||
}
|
||||
|
||||
export function oldestQueued(db: Sequelize) {
|
||||
return db.query<{
|
||||
id: string;
|
||||
name: string;
|
||||
source: string;
|
||||
queued_at: number;
|
||||
queue_context: string | null;
|
||||
queue_live_context: string | null;
|
||||
}>(
|
||||
`SELECT t.id, COALESCE(NULLIF(c.name,''), c.command, '#' || t.cron_id) AS name, t.source,t.queued_at,t.queue_context,t.queue_live_context
|
||||
FROM CronTriggers t LEFT JOIN Crontabs c ON c.id=t.cron_id
|
||||
WHERE t.state='queued' AND t.dequeued_at IS NULL AND t.queued_at IS NOT NULL ORDER BY t.queued_at,t.id LIMIT 25`,
|
||||
{ type: QueryTypes.SELECT },
|
||||
);
|
||||
}
|
||||
@@ -1,262 +0,0 @@
|
||||
import { hasLiveCronProcess } from './cronProcess';
|
||||
import { EventEmitter } from 'events';
|
||||
import PQueue from 'p-queue-cjs';
|
||||
import { triggerHistory, TriggerState } from './triggerHistory';
|
||||
import { t } from './i18n';
|
||||
import { spawnCronCommand, releaseCronCommand } from './cronCommandProcess';
|
||||
import taskLimit from './pLimit';
|
||||
import Logger from '../loaders/logger';
|
||||
import { ICron } from '../protos/cron';
|
||||
import { CrontabModel, CrontabStatus } from '../data/cron';
|
||||
import { RunningInstanceModel, InstanceStatus } from '../data/runningInstance';
|
||||
import dayjs from 'dayjs';
|
||||
import { observeChildProcess, asError } from './childProcess';
|
||||
|
||||
const waiting = new Map<string, () => void>();
|
||||
// A backlog of missed timers can otherwise open hundreds of competing SQLite
|
||||
// writer transactions on wake. Only serialize history writes, never commands.
|
||||
const historyWrites = new PQueue({ concurrency: 1 });
|
||||
export function cancelWaitingTriggers(ids: string[]) {
|
||||
for (const id of ids) waiting.get(id)?.();
|
||||
}
|
||||
|
||||
export async function runCron(
|
||||
cmd: string,
|
||||
cron: ICron,
|
||||
isCurrent: () => boolean = () => true,
|
||||
trigger?: { id: string; time: number; source: 'node' | 'recovery' },
|
||||
): Promise<number | void> {
|
||||
const history = trigger && triggerHistory();
|
||||
const queuedAt = Date.now();
|
||||
if (trigger && history) {
|
||||
const cronId = Number(cron.id);
|
||||
const admitted = await historyWrites.add(() => cron.skip_if_pending
|
||||
? history.enqueueUnlessPending(trigger.id, cronId, trigger.source, trigger.time, queuedAt, cron.recovery_from)
|
||||
: history.enqueue(trigger.id, cronId, trigger.source, trigger.time, queuedAt));
|
||||
if (!admitted) return;
|
||||
}
|
||||
let reason = 'capacity';
|
||||
let state: TriggerState = 'skipped';
|
||||
let exitCode: number | null = null;
|
||||
let claimed = false;
|
||||
const deadline = cron.max_queue_wait ? queuedAt + cron.max_queue_wait * 1000 : Infinity;
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const expiry = trigger ? new EventEmitter() : undefined;
|
||||
const alive = () => isCurrent() && Date.now() < deadline;
|
||||
if (trigger && expiry && Number.isFinite(deadline)) {
|
||||
timer = setTimeout(() => {
|
||||
reason = 'queue_timeout';
|
||||
taskLimit.removeQueuedCron(cron.id, execute);
|
||||
expiry.emit('expired');
|
||||
}, Math.max(0, deadline - Date.now()));
|
||||
timer.unref();
|
||||
}
|
||||
const execute = async () => {
|
||||
if (trigger) waiting.delete(trigger.id);
|
||||
reason = 'changed';
|
||||
try {
|
||||
if (!alive()) { reason = isCurrent() ? 'queue_timeout' : 'changed'; return; }
|
||||
let multiple = false;
|
||||
// A single-instance trigger must not interrupt work already in progress.
|
||||
try {
|
||||
const existingCron = await CrontabModel.findOne({
|
||||
where: { id: Number(cron.id) },
|
||||
});
|
||||
|
||||
// A mutation may commit while this queued run is reading the database.
|
||||
if (!isCurrent() || !existingCron || existingCron.isDisabled) return;
|
||||
|
||||
// Default to single instance mode (0) for backward compatibility
|
||||
multiple = existingCron.allow_multiple_instances === 1;
|
||||
|
||||
if (!multiple) {
|
||||
// A queued manual run is an active reservation, even if its stored PID
|
||||
// belongs to a previous execution.
|
||||
if (
|
||||
existingCron.status === CrontabStatus.queued &&
|
||||
existingCron.pid
|
||||
) {
|
||||
Logger.info(
|
||||
'[schedule][Skip queued single-instance task] Task ID: %s, PID: %s',
|
||||
cron.id,
|
||||
existingCron.pid,
|
||||
);
|
||||
reason = 'overlap';
|
||||
return;
|
||||
}
|
||||
if (
|
||||
existingCron.status === CrontabStatus.running &&
|
||||
existingCron.pid
|
||||
) {
|
||||
if (hasLiveCronProcess(existingCron.status, existingCron.pid)) {
|
||||
Logger.info(
|
||||
'[schedule][Skip active single-instance task] Task ID: %s, PID: %s',
|
||||
cron.id,
|
||||
existingCron.pid,
|
||||
);
|
||||
reason = 'overlap';
|
||||
return;
|
||||
}
|
||||
|
||||
// Capture old instance IDs before releasing the stale cron state so
|
||||
// a concurrent replacement cannot have its instance marked stopped.
|
||||
const staleInstances = await RunningInstanceModel.findAll({
|
||||
attributes: ['id'],
|
||||
where: {
|
||||
cron_id: Number(cron.id),
|
||||
pid: existingCron.pid,
|
||||
status: InstanceStatus.running,
|
||||
},
|
||||
});
|
||||
if (!isCurrent()) return;
|
||||
const [recovered] = await CrontabModel.update(
|
||||
{
|
||||
status: CrontabStatus.idle,
|
||||
pid: null,
|
||||
queued_token: null,
|
||||
} as any,
|
||||
{
|
||||
where: {
|
||||
id: Number(cron.id),
|
||||
pid: existingCron.pid,
|
||||
status: CrontabStatus.running,
|
||||
...(existingCron.log_path !== undefined
|
||||
? { log_path: existingCron.log_path }
|
||||
: {}),
|
||||
...(existingCron.queued_token !== undefined
|
||||
? { queued_token: existingCron.queued_token }
|
||||
: {}),
|
||||
...(existingCron.last_execution_time !== undefined
|
||||
? { last_execution_time: existingCron.last_execution_time }
|
||||
: {}),
|
||||
...(existingCron.isDisabled !== undefined
|
||||
? { isDisabled: existingCron.isDisabled }
|
||||
: {}),
|
||||
allow_multiple_instances: 0,
|
||||
},
|
||||
},
|
||||
);
|
||||
if (recovered !== 1) return;
|
||||
const staleIds = staleInstances.map((instance) => instance.id!);
|
||||
if (staleIds.length) {
|
||||
await RunningInstanceModel.update(
|
||||
{ status: InstanceStatus.stopped, finished_at: dayjs().unix() },
|
||||
{ where: { id: staleIds, status: InstanceStatus.running } },
|
||||
);
|
||||
}
|
||||
Logger.info(
|
||||
'[schedule][Recovered stale single-instance task] Task ID: %s, PID: %s',
|
||||
cron.id,
|
||||
existingCron.pid,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
Logger.error(
|
||||
t('[schedule][检查已运行任务失败] 任务ID: %s, 错误: %s'),
|
||||
cron.id,
|
||||
error,
|
||||
);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Invalidation can happen during the asynchronous database check.
|
||||
if (!isCurrent()) return;
|
||||
Logger.info(
|
||||
t('[schedule][开始执行任务] 参数 %s'),
|
||||
JSON.stringify({
|
||||
...cron,
|
||||
command: cmd,
|
||||
}),
|
||||
);
|
||||
clearTimeout(timer);
|
||||
if (Date.now() >= deadline) {
|
||||
reason = 'queue_timeout';
|
||||
return;
|
||||
}
|
||||
if (trigger) {
|
||||
claimed = await history!.start(trigger.id, Date.now(), multiple);
|
||||
if (!claimed) { reason = 'overlap'; return; }
|
||||
}
|
||||
if (!isCurrent() || Date.now() >= deadline) {
|
||||
reason = isCurrent() ? 'queue_timeout' : 'changed';
|
||||
return;
|
||||
}
|
||||
let saveStart: Promise<void> | undefined;
|
||||
const cp = spawnCronCommand(cmd, trigger?.id, trigger && history ? at => {
|
||||
saveStart = history.recordCommandStart(trigger.id, at).catch(error => {
|
||||
Logger.warn('[schedule] Could not record command start: %s', asError(error).message);
|
||||
});
|
||||
} : undefined);
|
||||
|
||||
let denied: string | undefined;
|
||||
const { completed } = observeChildProcess(cp, {
|
||||
onStart: async () => {
|
||||
if (!trigger) return;
|
||||
try {
|
||||
if (await history!.bindCommand(trigger.id, cp.pid!) && !await history!.shouldStop(trigger.id)) {
|
||||
if (!alive()) denied = isCurrent() ? 'queue_timeout' : 'changed';
|
||||
else await releaseCronCommand(cp);
|
||||
}
|
||||
} finally {
|
||||
cp.stdin.end();
|
||||
}
|
||||
},
|
||||
onStderr: async (message) => {
|
||||
Logger.info(
|
||||
t('[schedule][任务标准错误] 命令: %s, 信息: %s'),
|
||||
cmd,
|
||||
message,
|
||||
);
|
||||
},
|
||||
});
|
||||
const result = await completed;
|
||||
await saveStart;
|
||||
if (denied) { reason = denied; return; }
|
||||
state = result.signal ? 'stopped' : result.error || result.code !== 0 ? 'failed' : 'finished';
|
||||
reason = result.error ? 'spawn' : result.signal || '';
|
||||
exitCode = result.code;
|
||||
if (result.error) {
|
||||
Logger.error(
|
||||
t('[schedule][执行任务失败] 命令: %s, 错误: %s'),
|
||||
cmd,
|
||||
result.error.message,
|
||||
);
|
||||
}
|
||||
Logger.info(
|
||||
t('[schedule][执行任务结束] 任务ID: %s, 退出码: %j'),
|
||||
cron.id,
|
||||
result.code,
|
||||
);
|
||||
return { ...cron, command: cmd, pid: cp.pid, ...result } as any;
|
||||
} catch (error) {
|
||||
state = 'failed';
|
||||
reason = 'spawn';
|
||||
Logger.error(
|
||||
t('[schedule][创建任务失败] 命令: %s, 错误: %s'),
|
||||
cmd,
|
||||
asError(error).message,
|
||||
);
|
||||
} finally {
|
||||
taskLimit.removeQueuedCron(cron.id, execute);
|
||||
}
|
||||
};
|
||||
try {
|
||||
if (trigger && expiry) waiting.set(trigger.id, () => {
|
||||
taskLimit.removeQueuedCron(cron.id, execute);
|
||||
expiry.emit('expired');
|
||||
});
|
||||
return await taskLimit.runWithCronLimit(cron, execute, undefined, isCurrent, () => { reason = 'pending'; }, expiry, trigger?.id, CrontabModel.sequelize);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
if (trigger) waiting.delete(trigger.id);
|
||||
if (trigger && history) {
|
||||
const outcomeReason = state === 'skipped' && !isCurrent() ? 'changed' : reason;
|
||||
const finishedAt = Date.now();
|
||||
await historyWrites.add(() => state === 'skipped' && !claimed
|
||||
? history.skipQueued(trigger.id, outcomeReason, finishedAt)
|
||||
: history.complete(trigger.id, state, outcomeReason || null, exitCode, finishedAt),
|
||||
{ priority: 1 });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,9 @@ const backend = read(path.resolve(__dirname, '../app.js'));
|
||||
const root = process.env.QL_DIR || path.resolve(__dirname, '../../..');
|
||||
const version = read(path.join(root, 'version.yaml'))
|
||||
?.toString()
|
||||
.match(/^\uFEFF?version:\s*["']?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)/m)?.[1];
|
||||
.match(
|
||||
/^\uFEFF?version:\s*["']?(\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?)/m,
|
||||
)?.[1];
|
||||
|
||||
export const runtimeBuild = Object.freeze({
|
||||
instanceId: randomUUID(),
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
export type AnomalyKind = 'missing' | 'skipped' | 'unconfirmed';
|
||||
export interface ScheduleAnomaly {
|
||||
task: number;
|
||||
name?: string;
|
||||
rule: string | null;
|
||||
time: number | null;
|
||||
source: 'node' | 'recovery' | 'system';
|
||||
trigger: string | null;
|
||||
observed: number | null;
|
||||
reason: string | null;
|
||||
logPath: string | null;
|
||||
ruleIndex?: number;
|
||||
}
|
||||
|
||||
// Keep only the requested page and the first page. If late evidence changes
|
||||
// the result between requests, return the new first page instead of mixing scans.
|
||||
export class AnomalyPage {
|
||||
private hash = createHash('sha256');
|
||||
private total = 0;
|
||||
private first: ScheduleAnomaly[] = [];
|
||||
private selected: ScheduleAnomaly[] = [];
|
||||
static readonly size = 25;
|
||||
|
||||
constructor(readonly kind: AnomalyKind, private page: number, private previous?: string) {}
|
||||
|
||||
add(row: ScheduleAnomaly) {
|
||||
this.hash.update(JSON.stringify(row)).update('\n');
|
||||
const page = Math.floor(this.total++ / AnomalyPage.size) + 1;
|
||||
if (page === 1) this.first.push(row);
|
||||
if (page === this.page) this.selected.push(row);
|
||||
}
|
||||
|
||||
result() {
|
||||
const revision = this.hash.digest('hex');
|
||||
const changed = !!this.previous && revision !== this.previous;
|
||||
const reset = changed || (this.page > 1 && !this.selected.length);
|
||||
return { rows: reset ? this.first : this.selected, total: this.total,
|
||||
page: reset ? 1 : this.page, pageSize: AnomalyPage.size, revision, changed };
|
||||
}
|
||||
}
|
||||
@@ -1,311 +0,0 @@
|
||||
import { AnomalyPage } from './scheduleAnomalies';
|
||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||
import { AddCronRequest, DeleteCronRequest } from '../protos/cron';
|
||||
import { upcomingSlots } from './cronScheduler';
|
||||
import { slotId } from './triggerHistory';
|
||||
|
||||
type Rule = {
|
||||
cron_id: string;
|
||||
rule_index: number;
|
||||
schedule: string;
|
||||
zone: string;
|
||||
since: number;
|
||||
until: number | null;
|
||||
open_latest: number;
|
||||
close_latest: number;
|
||||
};
|
||||
type Receipt = {
|
||||
id: string;
|
||||
cron_id: number;
|
||||
scheduled_at: number;
|
||||
observed_at: number;
|
||||
state: string;
|
||||
reason: string | null;
|
||||
log_path: string | null;
|
||||
source: 'node' | 'recovery';
|
||||
command_started_at: number | null;
|
||||
verified_exit: number;
|
||||
script_started_at: number | null;
|
||||
queued_at: number | null;
|
||||
started_at: number | null;
|
||||
};
|
||||
|
||||
export async function saveSchedulePlan(
|
||||
db: Sequelize,
|
||||
change: AddCronRequest | DeleteCronRequest,
|
||||
at?: number,
|
||||
token?: string,
|
||||
) {
|
||||
const rules =
|
||||
'crons' in change
|
||||
? [
|
||||
...new Map(change.crons.map((task) => [task.id, task])).values(),
|
||||
].flatMap((task) =>
|
||||
[
|
||||
task.schedule,
|
||||
...(task.extra_schedules || []).map((extra) => extra.schedule),
|
||||
].map((schedule, index) => ({ task: task.id, index, schedule })),
|
||||
)
|
||||
: [];
|
||||
const ids =
|
||||
'crons' in change ? change.crons.map((task) => task.id) : change.ids;
|
||||
const replace = 'replace' in change && change.replace;
|
||||
await db.transaction(async (transaction) => {
|
||||
const now = at ?? Date.now();
|
||||
const bind = {
|
||||
rules: JSON.stringify(rules),
|
||||
ids: JSON.stringify(ids),
|
||||
replace: Number(replace),
|
||||
zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
now,
|
||||
token: token ?? null,
|
||||
};
|
||||
if (token)
|
||||
await db.query(
|
||||
'INSERT INTO CronPlanSwitches(token,staged_at) VALUES($token,$now)',
|
||||
{ transaction, bind: { token, now } },
|
||||
);
|
||||
if (replace)
|
||||
await db.query(
|
||||
'INSERT OR IGNORE INTO CronPlanCoverage(id,since) VALUES(1,$now)',
|
||||
{ transaction, bind: { now } },
|
||||
);
|
||||
const desired = `WITH desired AS (SELECT json_extract(value,'$.task') AS task, json_extract(value,'$.index') AS idx,
|
||||
json_extract(value,'$.schedule') AS schedule FROM json_each($rules))`;
|
||||
await db.query(
|
||||
`${desired} UPDATE CronPlanRules SET until=$now,closed_by=$token WHERE until IS NULL
|
||||
AND ($replace OR cron_id IN (SELECT value FROM json_each($ids)))
|
||||
AND (cron_id,rule_index,schedule,zone) NOT IN (SELECT task,idx,schedule,$zone FROM desired)`,
|
||||
{ transaction, bind },
|
||||
);
|
||||
await db.query(
|
||||
`${desired} INSERT OR IGNORE INTO CronPlanRules(cron_id,rule_index,schedule,zone,since,opened_by)
|
||||
SELECT task,idx,schedule,$zone,$now,$token FROM desired`,
|
||||
{
|
||||
transaction,
|
||||
bind: { rules: bind.rules, zone: bind.zone, now, token: bind.token },
|
||||
},
|
||||
);
|
||||
// Only the current local day is displayed. Keep an extra day for zone changes.
|
||||
await db.query(
|
||||
`DELETE FROM CronPlanRules WHERE until < $now - 3*86400000 AND
|
||||
(closed_by IS NULL OR closed_by IN (SELECT token FROM CronPlanSwitches WHERE last_at < $now - 3*86400000))`,
|
||||
{ transaction, bind: { now } },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Persisting intent and installing timers are separated by an asynchronous
|
||||
// SQLite commit. Only the synchronous timer swap defines the effective edges.
|
||||
export async function confirmSchedulePlan(
|
||||
db: Sequelize,
|
||||
token: string,
|
||||
first: number,
|
||||
last: number,
|
||||
replace: boolean,
|
||||
) {
|
||||
await db.transaction(async (transaction) => {
|
||||
await db.query(
|
||||
`UPDATE CronPlanSwitches SET first_at=$first,last_at=$last
|
||||
WHERE token=$token AND last_at IS NULL`,
|
||||
{ transaction, bind: { token, first, last } },
|
||||
);
|
||||
if (replace) {
|
||||
// After a crash the former worker's switch time is unknowable. A complete
|
||||
// replacement establishes the latest possible edge for older requests.
|
||||
await db.query(
|
||||
`UPDATE CronPlanSwitches SET first_at=staged_at,last_at=$last
|
||||
WHERE last_at IS NULL AND seq<(SELECT seq FROM CronPlanSwitches WHERE token=$token)`,
|
||||
{ transaction, bind: { token, last } },
|
||||
);
|
||||
}
|
||||
await db.query(
|
||||
`DELETE FROM CronPlanSwitches WHERE last_at < $last - 3*86400000
|
||||
AND token NOT IN (SELECT opened_by FROM CronPlanRules WHERE opened_by IS NOT NULL)
|
||||
AND token NOT IN (SELECT closed_by FROM CronPlanRules WHERE closed_by IS NOT NULL)`,
|
||||
{ transaction, bind: { last } },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export const blockSize = 15 * 60000;
|
||||
const calendar = new Map<string, number[]>();
|
||||
export function blockSlots(schedule: string, zone: string, block: number) {
|
||||
const key = JSON.stringify([zone, schedule, block]);
|
||||
let times = calendar.get(key);
|
||||
if (!times) {
|
||||
times = upcomingSlots(schedule, block - 1, Infinity, block + blockSize - 1);
|
||||
if (calendar.size >= 2048) calendar.delete(calendar.keys().next().value!);
|
||||
calendar.set(key, times);
|
||||
}
|
||||
return times;
|
||||
}
|
||||
|
||||
function lowerBound(times: number[], time: number) {
|
||||
let lo = 0,
|
||||
hi = times.length;
|
||||
while (lo < hi) {
|
||||
const mid = Math.floor((lo + hi) / 2);
|
||||
if (times[mid] < time) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
function p95(values: number[]) {
|
||||
return values.length
|
||||
? values.sort((a, b) => a - b)[Math.ceil(values.length * 0.95) - 1]
|
||||
: null;
|
||||
}
|
||||
|
||||
export async function auditSchedule(
|
||||
db: Sequelize,
|
||||
dayStart: number,
|
||||
now = Date.now(),
|
||||
details?: AnomalyPage,
|
||||
) {
|
||||
// All counts use the same settled plan window and the same committed snapshot.
|
||||
const nextDay = new Date(dayStart);
|
||||
nextDay.setHours(24, 0, 0, 0);
|
||||
const through = Math.min(now - 5000, nextDay.getTime() - 1);
|
||||
const snapshot = await db.transaction(
|
||||
{ type: Transaction.TYPES.DEFERRED },
|
||||
async (transaction) => {
|
||||
const [coverage] = await db.query<{ since: number }>(
|
||||
`SELECT MAX(since,$dayStart,
|
||||
COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)) AS since FROM CronPlanCoverage WHERE id=1`,
|
||||
{ transaction, bind: { dayStart }, type: QueryTypes.SELECT },
|
||||
);
|
||||
if (!coverage || coverage.since > through) return;
|
||||
const bind = { since: coverage.since, through };
|
||||
const rules = await db.query<Rule>(
|
||||
`SELECT r.cron_id,r.rule_index,r.schedule,r.zone,COALESCE(o.first_at,r.since) AS since,
|
||||
CASE WHEN o.token IS NULL THEN r.since ELSE COALESCE(o.last_at,$through) END AS open_latest,
|
||||
COALESCE(c.first_at,r.until) AS until,
|
||||
CASE WHEN c.token IS NULL THEN COALESCE(r.until,$through) ELSE COALESCE(c.last_at,$through) END AS close_latest
|
||||
FROM CronPlanRules r LEFT JOIN CronPlanSwitches o ON o.token=r.opened_by
|
||||
LEFT JOIN CronPlanSwitches c ON c.token=r.closed_by
|
||||
WHERE r.since < $through AND close_latest >= $since ORDER BY r.cron_id,r.rule_index,r.since,r.rowid`,
|
||||
{ transaction, bind, type: QueryTypes.SELECT },
|
||||
);
|
||||
const receipts = await db.query<Receipt>(
|
||||
`SELECT id,cron_id,scheduled_at,observed_at,state,${details ? 'source,reason,log_path,' : ''}
|
||||
command_started_at,script_started_at,queued_at,COALESCE(dequeued_at,started_at) AS started_at,
|
||||
EXISTS(SELECT 1 FROM CronLegacyExitBookings b WHERE b.trigger_id=CronTriggers.id AND b.bound=1) AS verified_exit FROM CronTriggers
|
||||
WHERE scheduled_at BETWEEN $since AND $through AND source IN ('node','recovery') ${details ? 'ORDER BY cron_id,scheduled_at,id' : ''}`,
|
||||
{ transaction, bind, type: QueryTypes.SELECT },
|
||||
);
|
||||
return { since: coverage.since, rules, receipts };
|
||||
},
|
||||
);
|
||||
if (!snapshot) return null;
|
||||
const byTaskBlock = new Map<string, Receipt[]>();
|
||||
for (const row of snapshot.receipts) {
|
||||
const block = row.scheduled_at - (row.scheduled_at % blockSize);
|
||||
const key = row.cron_id + '/' + block;
|
||||
const group = byTaskBlock.get(key);
|
||||
if (group) group.push(row);
|
||||
else byTaskBlock.set(key, [row]);
|
||||
}
|
||||
const deviations: number[] = [],
|
||||
starts: number[] = [],
|
||||
entries: number[] = [],
|
||||
waits: number[] = [];
|
||||
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
let partial = false;
|
||||
let expected = 0,
|
||||
onTime = 0,
|
||||
skipped = 0,
|
||||
queued = 0,
|
||||
dispatched = 0;
|
||||
for (const rule of snapshot.rules) {
|
||||
const first = Math.max(snapshot.since, rule.since + 1);
|
||||
const last = Math.min(through, rule.close_latest);
|
||||
const certainFirst = Math.max(first, rule.open_latest + 1);
|
||||
const certainLast = Math.min(last, rule.until ?? last);
|
||||
if (first > last) continue;
|
||||
// A wall clock rule registered in another time zone cannot be replayed
|
||||
// against the current local calendar.
|
||||
if (rule.zone !== zone) return null;
|
||||
for (
|
||||
let block = first - (first % blockSize);
|
||||
block <= last;
|
||||
block += blockSize
|
||||
) {
|
||||
const times = blockSlots(rule.schedule, zone, block);
|
||||
const possible = lowerBound(times, last + 1) - lowerBound(times, first);
|
||||
const certain = Math.max(
|
||||
0,
|
||||
lowerBound(times, certainLast + 1) - lowerBound(times, certainFirst),
|
||||
);
|
||||
if (certain < possible) partial = true;
|
||||
expected += certain;
|
||||
const received = details?.kind === 'missing' && certain ? new Set<number>() : null;
|
||||
for (const row of byTaskBlock.get(rule.cron_id + '/' + block) ?? []) {
|
||||
const time = row.scheduled_at;
|
||||
if (
|
||||
time < certainFirst ||
|
||||
time > certainLast ||
|
||||
times[lowerBound(times, time)] !== time ||
|
||||
row.id !== slotId(rule.cron_id, rule.rule_index, rule.schedule, time)
|
||||
)
|
||||
continue;
|
||||
received?.add(time);
|
||||
const deviation = Math.abs(row.observed_at - time);
|
||||
deviations.push(deviation);
|
||||
if (deviation <= 5000) onTime++;
|
||||
if (
|
||||
row.command_started_at != null ||
|
||||
row.script_started_at != null ||
|
||||
row.verified_exit
|
||||
) {
|
||||
dispatched++;
|
||||
if (row.command_started_at != null && row.command_started_at >= time)
|
||||
starts.push(row.command_started_at - time);
|
||||
} else if (row.state === 'queued') {
|
||||
queued++;
|
||||
} else {
|
||||
const kind = row.state === 'skipped' ? 'skipped' : 'unconfirmed';
|
||||
if (kind === 'skipped') skipped++;
|
||||
if (details?.kind === kind) details.add({
|
||||
task: row.cron_id, rule: rule.schedule, ruleIndex: rule.rule_index, time, source: row.source,
|
||||
trigger: row.id, observed: row.observed_at, reason: row.reason, logPath: row.log_path,
|
||||
});
|
||||
}
|
||||
if (row.script_started_at != null && row.script_started_at >= time)
|
||||
entries.push(row.script_started_at - time);
|
||||
if (row.started_at != null && row.queued_at != null && row.started_at >= row.queued_at)
|
||||
waits.push(row.started_at - row.queued_at);
|
||||
}
|
||||
if (details && received && received.size < certain) {
|
||||
for (let i = lowerBound(times, certainFirst); i < times.length && times[i] <= certainLast; i++) {
|
||||
if (!received.has(times[i])) details.add({ task: Number(rule.cron_id), rule: rule.schedule,
|
||||
ruleIndex: rule.rule_index, time: times[i], source: 'node', trigger: null,
|
||||
observed: null, reason: null, logPath: null });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const observed = deviations.length;
|
||||
return {
|
||||
since: snapshot.since,
|
||||
through,
|
||||
zone,
|
||||
partial,
|
||||
expected,
|
||||
observed,
|
||||
missing: expected - observed,
|
||||
onTime,
|
||||
skipped,
|
||||
queued,
|
||||
dispatched,
|
||||
commandSamples: starts.length,
|
||||
unconfirmed: observed - dispatched - skipped - queued,
|
||||
triggerDeviationP95: p95(deviations),
|
||||
waitP95: p95(waits),
|
||||
waitSamples: waits.length,
|
||||
commandStartP95: p95(starts),
|
||||
scriptStartP95: p95(entries),
|
||||
scriptSamples: entries.length,
|
||||
};
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import lockfile from 'proper-lockfile';
|
||||
import config from '../config';
|
||||
|
||||
// HTTP and gRPC both mutate cron definitions. Hold one shared lock from the
|
||||
// initial DB read/write through scheduler registration (including rollback).
|
||||
// Recovery takes the same lock before reading its replacement snapshot.
|
||||
export async function withSchedulerMutation<T>(
|
||||
operation: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
let release: () => Promise<void>;
|
||||
try {
|
||||
// proper-lockfile indexes held locks by target, not lockfilePath. Keep
|
||||
// this identity separate from nested writeFileWithLock(crontabFile).
|
||||
release = await lockfile.lock(`${config.crontabFile}.scheduler`, {
|
||||
realpath: false,
|
||||
lockfilePath: `${config.crontabFile}.scheduler.lock`,
|
||||
stale: 30000,
|
||||
update: 10000,
|
||||
retries: { retries: 50, factor: 1, minTimeout: 100, maxTimeout: 100 },
|
||||
});
|
||||
} catch (cause) {
|
||||
throw Object.assign(
|
||||
new Error('Scheduler configuration is busy', { cause }),
|
||||
{
|
||||
status: 503,
|
||||
},
|
||||
);
|
||||
}
|
||||
try {
|
||||
return await operation();
|
||||
} finally {
|
||||
await release();
|
||||
}
|
||||
}
|
||||
|
||||
export function schedulerRegistrationError(message: string, cause: any): Error {
|
||||
return Object.assign(new Error(message, { cause }), {
|
||||
status: cause?.status === 503 ? 503 : 500,
|
||||
});
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
// Recovery is single-flight and retried only while unavailable, never at idle.
|
||||
export class SchedulerReadiness {
|
||||
private ready = false;
|
||||
private generation = 0;
|
||||
private restore?: () => Promise<void>;
|
||||
private pending?: Promise<boolean>;
|
||||
private retry?: NodeJS.Timeout;
|
||||
|
||||
constructor(private probe: () => Promise<void>, private retryMs = 1000) {}
|
||||
|
||||
configure(restore: () => Promise<void>) {
|
||||
this.restore = restore;
|
||||
}
|
||||
|
||||
invalidate() {
|
||||
this.ready = false;
|
||||
this.generation++;
|
||||
void this.recover();
|
||||
}
|
||||
|
||||
recover(): Promise<boolean> {
|
||||
if (this.pending) return this.pending;
|
||||
if (!this.restore) return Promise.resolve(false);
|
||||
clearTimeout(this.retry);
|
||||
const generation = this.generation;
|
||||
this.ready = false;
|
||||
this.pending = (async () => {
|
||||
try {
|
||||
await this.probe();
|
||||
await this.restore!();
|
||||
await this.probe();
|
||||
this.ready = generation === this.generation;
|
||||
} catch {
|
||||
this.ready = false;
|
||||
}
|
||||
return this.ready;
|
||||
})().finally(() => {
|
||||
this.pending = undefined;
|
||||
if (!this.ready) {
|
||||
this.retry = setTimeout(() => void this.recover(), this.retryMs);
|
||||
this.retry.unref();
|
||||
}
|
||||
});
|
||||
return this.pending;
|
||||
}
|
||||
|
||||
async check(): Promise<boolean> {
|
||||
if (!this.ready) return false;
|
||||
const generation = this.generation;
|
||||
try {
|
||||
await this.probe();
|
||||
return this.ready && generation === this.generation;
|
||||
} catch {
|
||||
this.invalidate();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async ensureReady(timeoutMs = 2000): Promise<void> {
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
try {
|
||||
const available = await Promise.race([
|
||||
(async () => (await this.check()) || (await this.recover()))(),
|
||||
new Promise<boolean>((resolve) => {
|
||||
timer = setTimeout(() => resolve(false), timeoutMs);
|
||||
}),
|
||||
]);
|
||||
if (!available) {
|
||||
throw Object.assign(new Error('Scheduler is recovering; try again later'), {
|
||||
status: 503,
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
import dayjs from 'dayjs';
|
||||
import { installTriggerHistory } from './triggerHistory';
|
||||
import { repairLegacyDailyStatistics } from './legacyDailyStatistics';
|
||||
import { QueryTypes, Sequelize } from 'sequelize';
|
||||
|
||||
export const prunedExitMigrationId = 'preserve-pruned-bound-exits-v1';
|
||||
|
||||
// Append new entries; IDs are persisted and must not be renumbered or reused.
|
||||
const columns = [
|
||||
{
|
||||
table: 'CrontabViews',
|
||||
column: 'filterRelation',
|
||||
type: 'VARCHAR(255)',
|
||||
},
|
||||
{ table: 'Subscriptions', column: 'proxy', type: 'VARCHAR(255)' },
|
||||
{ table: 'CrontabViews', column: 'type', type: 'NUMBER' },
|
||||
{ table: 'Subscriptions', column: 'autoAddCron', type: 'NUMBER' },
|
||||
{ table: 'Subscriptions', column: 'autoDelCron', type: 'NUMBER' },
|
||||
{ table: 'Crontabs', column: 'sub_id', type: 'NUMBER' },
|
||||
{ table: 'Crontabs', column: 'extra_schedules', type: 'JSON' },
|
||||
{ table: 'Crontabs', column: 'task_before', type: 'TEXT' },
|
||||
{ table: 'Crontabs', column: 'task_after', type: 'TEXT' },
|
||||
{ table: 'Crontabs', column: 'log_name', type: 'VARCHAR(255)' },
|
||||
{
|
||||
table: 'Crontabs',
|
||||
column: 'allow_multiple_instances',
|
||||
type: 'NUMBER',
|
||||
},
|
||||
{ table: 'Crontabs', column: 'work_dir', type: 'VARCHAR(255)' },
|
||||
{ table: 'Envs', column: 'isPinned', type: 'NUMBER' },
|
||||
{ table: 'Envs', column: 'labels', type: 'JSON' },
|
||||
{ table: 'Crontabs', column: 'queued_token', type: 'VARCHAR(255)' },
|
||||
{ table: 'Crontabs', column: 'max_queue_wait', type: 'INTEGER' },
|
||||
{ table: 'Crontabs', column: 'catchup_seconds', type: 'INTEGER' },
|
||||
{ table: 'Crontabs', column: 'skip_if_pending', type: 'BOOLEAN' },
|
||||
{ table: 'Crontabs', column: 'recovery_from', type: 'BIGINT' },
|
||||
{ table: 'Crontabs', column: 'last_instance_id', type: 'INTEGER' },
|
||||
{ table: 'CrontabStats', column: 'untimed_count', type: 'INTEGER NOT NULL DEFAULT 0' },
|
||||
{ table: 'CrontabStats', column: 'fixed_max_time', type: 'NUMBER' },
|
||||
];
|
||||
|
||||
export async function migrateSchema(database: Sequelize): Promise<void> {
|
||||
await database.transaction(async (transaction) => {
|
||||
await database.query(
|
||||
'CREATE TABLE IF NOT EXISTS "SchemaMigrations" ("id" TEXT PRIMARY KEY, "applied_at" TEXT NOT NULL)',
|
||||
{ transaction },
|
||||
);
|
||||
await installTriggerHistory(database, transaction);
|
||||
const applied = await database.query<{ id: string }>(
|
||||
'SELECT "id" FROM "SchemaMigrations"',
|
||||
{ type: QueryTypes.SELECT, transaction },
|
||||
);
|
||||
const appliedIds = new Set(applied.map(({ id }) => id));
|
||||
for (const { table, column, type } of columns) {
|
||||
const id = `add-${table}-${column}`;
|
||||
const fields = await database.query<{ name: string }>(
|
||||
`PRAGMA table_info("${table}")`,
|
||||
{
|
||||
type: QueryTypes.SELECT,
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
if (fields.length === 0)
|
||||
throw new Error(`Migration table is missing: ${table}`);
|
||||
if (!fields.some((field) => field.name === column)) {
|
||||
// table/column/type come only from the static migration manifest above.
|
||||
await database.query(
|
||||
`ALTER TABLE "${table}" ADD COLUMN "${column}" ${type}`,
|
||||
{ transaction },
|
||||
);
|
||||
}
|
||||
if (!appliedIds.has(id)) {
|
||||
await database.query(
|
||||
'INSERT INTO "SchemaMigrations" ("id", "applied_at") VALUES (:id, :appliedAt)',
|
||||
{
|
||||
replacements: { id, appliedAt: new Date().toISOString() },
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const repairId = 'repair-legacy-daily-statistics-v3';
|
||||
const prior = appliedIds.has('repair-legacy-daily-statistics-v2') ? 2
|
||||
: appliedIds.has('repair-legacy-daily-statistics-v1') ? 1 : 0;
|
||||
const retentionId = 'preserve-cron-stat-retention-v1';
|
||||
if (!appliedIds.has(retentionId)) {
|
||||
if (prior || appliedIds.has(repairId)) {
|
||||
// Old cleanup removed complete date prefixes but kept no cutoff. Every
|
||||
// surviving date and yesterday (the minimum supported retention) is
|
||||
// safe to keep. Older empty dates cannot be distinguished from deletions.
|
||||
await database.query(`INSERT OR IGNORE INTO CronStatRetention(id,first_day)
|
||||
SELECT 1, MIN(COALESCE(MIN(date),$yesterday),$yesterday) FROM CrontabStats`,
|
||||
{ bind: { yesterday: dayjs().subtract(1,'day').format('YYYY-MM-DD') }, transaction });
|
||||
}
|
||||
await database.query('INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
|
||||
{ bind: { id: retentionId }, transaction });
|
||||
}
|
||||
if (!appliedIds.has(repairId)) {
|
||||
await repairLegacyDailyStatistics(database, transaction, prior);
|
||||
// This reconciliation includes v1 and v2. Record all on fresh installations
|
||||
// so rolling back and upgrading again cannot replay the superseded repair.
|
||||
await database.query(`INSERT OR IGNORE INTO SchemaMigrations(id,applied_at)
|
||||
VALUES ('repair-legacy-daily-statistics-v1',CURRENT_TIMESTAMP),('repair-legacy-daily-statistics-v2',CURRENT_TIMESTAMP),($id,CURRENT_TIMESTAMP)`,
|
||||
{ transaction, bind: { id: repairId } });
|
||||
}
|
||||
|
||||
if (!appliedIds.has(prunedExitMigrationId)) {
|
||||
// Earlier versions could reclaim the last file before upgrading. The
|
||||
// surviving bound booking still identifies the original exit exactly.
|
||||
await database.query(`INSERT OR IGNORE INTO CronUnmatchedBoundExits(trigger_id,outcome,finished_at)
|
||||
SELECT b.trigger_id,b.outcome,b.finished_at FROM CronLegacyExitBookings b
|
||||
WHERE b.bound=1 AND NOT EXISTS (SELECT 1 FROM CronTriggers WHERE id=b.trigger_id)
|
||||
AND NOT EXISTS (SELECT 1 FROM CronBoundExitConflicts WHERE trigger_id=b.trigger_id)`, { transaction });
|
||||
await database.query('INSERT INTO SchemaMigrations(id,applied_at) VALUES ($id,CURRENT_TIMESTAMP)',
|
||||
{ bind: { id: prunedExitMigrationId }, transaction });
|
||||
}
|
||||
|
||||
// Older databases can contain non-JSON values in Envs.labels. Sequelize
|
||||
// parses this column on every environment read, including HTTP startup.
|
||||
await database.query(
|
||||
`UPDATE "Envs" SET "labels" = '[]'
|
||||
WHERE CASE WHEN json_valid("labels")
|
||||
THEN json_type("labels") <> 'array'
|
||||
ELSE 1
|
||||
END`,
|
||||
{ transaction },
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1,13 +1,20 @@
|
||||
import Logger from '../loaders/logger';
|
||||
import { performance } from 'perf_hooks';
|
||||
|
||||
export async function startupStage<T>(name: string, operation: () => Promise<T>): Promise<T> {
|
||||
export async function startupStage<T>(
|
||||
name: string,
|
||||
operation: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
if (process.env.QL_STARTUP_TIMING !== '1') return operation();
|
||||
const started = performance.now();
|
||||
try {
|
||||
return await operation();
|
||||
} finally {
|
||||
const role = process.env.SERVICE_TYPE || 'primary';
|
||||
Logger.info(`[boot:timing] ${role}:${name} ${Math.round(performance.now() - started)}ms (PID: ${process.pid})`);
|
||||
Logger.info(
|
||||
`[boot:timing] ${role}:${name} ${Math.round(
|
||||
performance.now() - started,
|
||||
)}ms (PID: ${process.pid})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,340 +0,0 @@
|
||||
import { AnomalyPage } from './scheduleAnomalies';
|
||||
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
|
||||
import { blockSize, blockSlots } from './scheduleAudit';
|
||||
|
||||
export type SystemRule = { id: number; schedule: string; name?: string };
|
||||
type Install = {
|
||||
id: number;
|
||||
staged: number;
|
||||
confirmed: number | null;
|
||||
zone: string;
|
||||
rules: string;
|
||||
};
|
||||
type Receipt = {
|
||||
id: string;
|
||||
cron_id: number;
|
||||
system_rule: string | null;
|
||||
observed_at: number;
|
||||
system_dispatch_at: number | null;
|
||||
reason: string | null;
|
||||
log_path: string | null;
|
||||
launched: number;
|
||||
state: string;
|
||||
};
|
||||
|
||||
export async function stageSystemPlan(
|
||||
db: Sequelize,
|
||||
rules: SystemRule[],
|
||||
at = Date.now(),
|
||||
) {
|
||||
const bind = {
|
||||
at,
|
||||
zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
||||
rules: JSON.stringify([...rules].sort((a, b) => a.id - b.id)),
|
||||
};
|
||||
return db.transaction(
|
||||
{ type: Transaction.TYPES.IMMEDIATE },
|
||||
async (transaction) => {
|
||||
const [pending] = await db.query<{ id: number }>(
|
||||
`SELECT id FROM (SELECT * FROM CronSystemPlans ORDER BY id DESC LIMIT 1)
|
||||
WHERE confirmed IS NULL AND zone=$zone AND rules=$rules`,
|
||||
{
|
||||
bind: { zone: bind.zone, rules: bind.rules },
|
||||
transaction,
|
||||
type: QueryTypes.SELECT,
|
||||
},
|
||||
);
|
||||
if (pending) return pending.id;
|
||||
const [id] = await db.query(
|
||||
'INSERT INTO CronSystemPlans(staged,zone,rules) VALUES ($at,$zone,$rules)',
|
||||
{ bind, transaction, type: QueryTypes.INSERT },
|
||||
);
|
||||
return id;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// On a switch to Node the service can no longer attest the installed daemon rules.
|
||||
export async function suspendSystemPlan(db: Sequelize) {
|
||||
await db.query(
|
||||
`INSERT INTO CronSystemPlans(staged,zone,rules)
|
||||
SELECT $now,zone,'[]' FROM (SELECT zone,confirmed FROM CronSystemPlans ORDER BY id DESC LIMIT 1)
|
||||
WHERE confirmed IS NOT NULL`,
|
||||
{ bind: { now: Date.now() } },
|
||||
);
|
||||
}
|
||||
|
||||
export async function confirmSystemPlan(
|
||||
db: Sequelize,
|
||||
id: number,
|
||||
at = Date.now(),
|
||||
) {
|
||||
await db.transaction(async (transaction) => {
|
||||
await db.query(
|
||||
'UPDATE CronSystemPlans SET confirmed=$at WHERE id=$id AND confirmed IS NULL',
|
||||
{ transaction, bind: { id, at } },
|
||||
);
|
||||
// Keep the effective snapshot preceding the retention window.
|
||||
await db.query(
|
||||
'DELETE FROM CronSystemPlans WHERE id < (SELECT MAX(id) FROM CronSystemPlans WHERE staged < $cutoff AND confirmed IS NOT NULL)',
|
||||
{ transaction, bind: { cutoff: at - 3 * 86400000 } },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export async function systemScheduleAudit(
|
||||
db: Sequelize,
|
||||
dayStart: number,
|
||||
now = Date.now(),
|
||||
details?: AnomalyPage,
|
||||
) {
|
||||
const next = new Date(dayStart);
|
||||
next.setHours(24, 0, 0, 0);
|
||||
const through = Math.min(now - 5000, +next - 1);
|
||||
const { since, installs, receipts } = await db.transaction(
|
||||
{ type: Transaction.TYPES.DEFERRED },
|
||||
async (transaction) => {
|
||||
const [retention] = await db.query<{ since: number }>(
|
||||
'SELECT MAX($dayStart,COALESCE((SELECT cutoff FROM CronHistoryRetention WHERE id=1),0)) AS since',
|
||||
{ transaction, bind: { dayStart }, type: QueryTypes.SELECT },
|
||||
);
|
||||
const since = retention.since;
|
||||
const installs = await db.query<Install>(
|
||||
`SELECT * FROM CronSystemPlans WHERE id >= COALESCE((SELECT MAX(id) FROM CronSystemPlans
|
||||
WHERE confirmed < $since - 60000),0) AND staged <= $now ORDER BY id`,
|
||||
{ transaction, bind: { since, now }, type: QueryTypes.SELECT },
|
||||
);
|
||||
const receipts = await db.query<Receipt>(
|
||||
`SELECT id,cron_id,system_rule,system_dispatch_at,observed_at,state,${details ? 'reason,log_path,' : ''}
|
||||
(command_started_at IS NOT NULL OR script_started_at IS NOT NULL OR
|
||||
(started_at IS NOT NULL AND EXISTS (SELECT 1 FROM CronLegacyExitBookings b
|
||||
WHERE b.trigger_id=CronTriggers.id AND b.bound=1 AND b.disputed=0))) AS launched
|
||||
FROM CronTriggers
|
||||
WHERE source='system' AND COALESCE(system_dispatch_at,observed_at) >= $since
|
||||
AND COALESCE(system_dispatch_at,observed_at) < $end ORDER BY observed_at,id`,
|
||||
{
|
||||
transaction,
|
||||
bind: {
|
||||
since,
|
||||
end: Math.min(
|
||||
+next,
|
||||
Math.floor(through / 60000) * 60000 + 60000,
|
||||
now + 1,
|
||||
),
|
||||
},
|
||||
type: QueryTypes.SELECT,
|
||||
},
|
||||
);
|
||||
return { since, installs, receipts };
|
||||
},
|
||||
);
|
||||
if (!installs.length && !receipts.length) return null;
|
||||
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
const minute = 60000;
|
||||
const plans = installs.map((plan) => ({
|
||||
...plan,
|
||||
tasks: new Map(
|
||||
(JSON.parse(plan.rules) as SystemRule[]).map((rule) => [rule.id, rule]),
|
||||
),
|
||||
}));
|
||||
const matched = details && details.kind !== 'missing' ? new Map<string, { time: number; name?: string }>() : null;
|
||||
const groups = new Map<string, Receipt[]>();
|
||||
const dispatchedTasks = new Set<string>();
|
||||
const legacyThrough = new Map<string, number>();
|
||||
const receiptKey = (task: number, rule: string | null, time: number) =>
|
||||
JSON.stringify([task, rule, time]);
|
||||
for (const row of receipts) {
|
||||
if (row.system_dispatch_at == null || !row.system_rule) {
|
||||
const key = JSON.stringify([row.cron_id, row.system_rule]);
|
||||
legacyThrough.set(
|
||||
key,
|
||||
Math.max(legacyThrough.get(key) ?? 0, row.observed_at),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
dispatchedTasks.add(
|
||||
row.cron_id + '/' + Math.floor(row.system_dispatch_at / minute),
|
||||
);
|
||||
const key = receiptKey(
|
||||
row.cron_id,
|
||||
row.system_rule,
|
||||
Math.floor(row.system_dispatch_at / minute) * minute,
|
||||
);
|
||||
const group = groups.get(key) ?? [];
|
||||
group.push(row);
|
||||
groups.set(key, group);
|
||||
}
|
||||
let expected = 0,
|
||||
observed = 0,
|
||||
dispatched = 0,
|
||||
skipped = 0,
|
||||
missing = 0,
|
||||
duplicates = 0,
|
||||
matchedReceipts = 0;
|
||||
let uncertain = 0,
|
||||
awaiting = 0,
|
||||
switchSlots = 0,
|
||||
partial = false;
|
||||
type Slot = {
|
||||
time: number;
|
||||
task: number;
|
||||
name?: string;
|
||||
status: string;
|
||||
triggerCount: number;
|
||||
startCount: number;
|
||||
skipCount: number;
|
||||
unknownExitCount: number;
|
||||
id?: string;
|
||||
};
|
||||
const recent: Slot[] = [];
|
||||
const dst =
|
||||
new Date(dayStart).getTimezoneOffset() !==
|
||||
new Date(+next - 1).getTimezoneOffset();
|
||||
let baseline = -1,
|
||||
last = -1;
|
||||
const calendar = new Map<string, Set<number>>();
|
||||
for (
|
||||
let time =
|
||||
Math.ceil(Math.max(since, plans[0]?.staged ?? since) / minute) * minute;
|
||||
time <= through;
|
||||
time += minute
|
||||
) {
|
||||
// A successful crontab install acknowledges the file. crond reads changes at
|
||||
// its minute tick. Around that tick either file can still explain a callback.
|
||||
while (last + 1 < plans.length && plans[last + 1].staged <= time + 5000)
|
||||
last++;
|
||||
while (baseline + 1 <= last) {
|
||||
let confirmed = baseline + 1;
|
||||
while (confirmed <= last && plans[confirmed].confirmed == null)
|
||||
confirmed++;
|
||||
if (confirmed > last || plans[confirmed].confirmed! >= time - minute)
|
||||
break;
|
||||
baseline = confirmed;
|
||||
}
|
||||
if (last < 0) continue;
|
||||
const possible = plans.slice(Math.max(0, baseline), last + 1);
|
||||
if (dst || possible.some((plan) => plan.zone !== zone)) {
|
||||
partial = true;
|
||||
continue;
|
||||
}
|
||||
const tasks = new Set<number>();
|
||||
for (const plan of possible)
|
||||
for (const id of plan.tasks.keys()) tasks.add(id);
|
||||
const block = time - (time % blockSize);
|
||||
if (time === block) calendar.clear();
|
||||
const entries: Slot[] = [];
|
||||
for (const task of tasks) {
|
||||
const schedules = new Set<string>();
|
||||
let name: string | undefined;
|
||||
for (const plan of possible) {
|
||||
const rule = plan.tasks.get(task);
|
||||
if (!rule) continue;
|
||||
name = rule.name;
|
||||
let times = calendar.get(rule.schedule);
|
||||
if (!times) {
|
||||
times = new Set(blockSlots(rule.schedule, zone, block));
|
||||
calendar.set(rule.schedule, times);
|
||||
}
|
||||
if (times.has(time)) schedules.add(rule.schedule);
|
||||
}
|
||||
if (!schedules.size) continue;
|
||||
const [schedule] = schedules;
|
||||
const stable =
|
||||
baseline >= 0 &&
|
||||
schedules.size === 1 &&
|
||||
possible.every(
|
||||
(plan) =>
|
||||
plan.confirmed != null &&
|
||||
plan.tasks.get(task)?.schedule === schedule,
|
||||
);
|
||||
const group = [...schedules].flatMap(
|
||||
(rule) => groups.get(receiptKey(task, rule, time)) ?? [],
|
||||
);
|
||||
let status: string;
|
||||
const launched = group.find((row) => row.launched === 1);
|
||||
const skip = group.find((row) => !row.launched && row.state === 'skipped');
|
||||
if (group.length) {
|
||||
++expected;
|
||||
++observed;
|
||||
if (matched) for (const row of group) matched.set(row.id, { time, name });
|
||||
matchedReceipts += group.length;
|
||||
duplicates += group.length - 1;
|
||||
if (launched) ++dispatched;
|
||||
else if (skip) ++skipped;
|
||||
status = launched ? 'started' : skip ? 'skipped' : 'unconfirmed';
|
||||
} else if (!stable) {
|
||||
++switchSlots;
|
||||
partial = true;
|
||||
status = 'switch';
|
||||
} else {
|
||||
++expected;
|
||||
const lastUndated = Math.max(
|
||||
legacyThrough.get(JSON.stringify([task, null])) ?? 0,
|
||||
legacyThrough.get(JSON.stringify([task, schedule])) ?? 0,
|
||||
);
|
||||
if (
|
||||
time <= lastUndated ||
|
||||
dispatchedTasks.has(task + '/' + time / minute)
|
||||
) {
|
||||
++uncertain;
|
||||
status = 'uncertain';
|
||||
} else if (time + minute > now) {
|
||||
++awaiting;
|
||||
status = 'awaiting';
|
||||
} else {
|
||||
++missing;
|
||||
if (details?.kind === 'missing') details.add({ task, name, rule: schedule, time, source: 'system',
|
||||
trigger: null, observed: null, reason: null, logPath: null });
|
||||
status = 'missing';
|
||||
}
|
||||
}
|
||||
entries.push({
|
||||
time,
|
||||
task,
|
||||
name,
|
||||
status,
|
||||
triggerCount: group.length,
|
||||
startCount: group.filter((row) => row.launched === 1).length,
|
||||
skipCount: group.filter((row) => !row.launched && row.state === 'skipped').length,
|
||||
unknownExitCount: group.filter((row) => row.launched === 1 && row.state === 'unknown').length,
|
||||
id: (launched || skip || group[0])?.id,
|
||||
});
|
||||
}
|
||||
if (entries.length)
|
||||
recent.unshift(...entries.sort((a, b) => a.task - b.task).slice(0, 25));
|
||||
recent.splice(25);
|
||||
}
|
||||
let actualSkips = 0, actualUnconfirmed = 0;
|
||||
for (const row of receipts) {
|
||||
if (row.launched === 1) continue;
|
||||
const kind = row.state === 'skipped' ? 'skipped' : 'unconfirmed';
|
||||
if (kind === 'skipped') actualSkips++;
|
||||
else actualUnconfirmed++;
|
||||
if (details?.kind === kind) {
|
||||
const slot = matched?.get(row.id);
|
||||
details.add({ task: row.cron_id, name: slot?.name, rule: row.system_rule, time: slot?.time ?? null,
|
||||
source: 'system', trigger: row.id, observed: row.observed_at, reason: row.reason, logPath: row.log_path });
|
||||
}
|
||||
}
|
||||
return {
|
||||
since: Math.max(since, plans[0]?.staged ?? since),
|
||||
through,
|
||||
confirmedAt:
|
||||
[...plans].reverse().find((p) => p.confirmed != null)?.confirmed ?? null,
|
||||
pending: plans.at(-1)?.confirmed == null,
|
||||
partial,
|
||||
expected,
|
||||
observed,
|
||||
dispatched,
|
||||
skipped,
|
||||
missing,
|
||||
duplicates,
|
||||
uncertain,
|
||||
awaiting,
|
||||
switchSlots,
|
||||
actualSkips, actualUnconfirmed,
|
||||
actualStarts: receipts.filter((row) => row.launched === 1).length,
|
||||
unmatched: receipts.length - matchedReceipts,
|
||||
recent,
|
||||
};
|
||||
}
|
||||
@@ -74,7 +74,9 @@ export function isAllowedTaskEnvName(name: unknown): name is string {
|
||||
);
|
||||
}
|
||||
|
||||
export function assertAllowedTaskEnvName(name: unknown): asserts name is string {
|
||||
export function assertAllowedTaskEnvName(
|
||||
name: unknown,
|
||||
): asserts name is string {
|
||||
if (!isAllowedTaskEnvName(name)) {
|
||||
throw Object.assign(new Error(t('环境变量名称不可使用')), {
|
||||
status: 400,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,15 @@
|
||||
import { lock } from 'proper-lockfile';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { writeFile, open, chmod } from 'fs/promises';
|
||||
import { fileExist } from '../config/util';
|
||||
import { writeFile, open, chmod, access } from 'fs/promises';
|
||||
export async function fileExist(file: any) {
|
||||
try {
|
||||
await access(file);
|
||||
return true;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function getUniqueLockPath(filePath: string) {
|
||||
const sanitizedPath = filePath
|
||||
|
||||
Reference in new issue
Block a user