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:
whyour committed 2026-11-22 12:24:29 +08:00
1 parent 77ece406ac
commit c5458596c8
346 files changed
+32133 -11556

No files matched your search

+26 -1
View File
@@ -3,22 +3,47 @@ const path = require('node:path');
const { createRequire } = require('node:module');
const ts = require('typescript');
function moduleFile(file, name) {
const target = path.resolve(path.dirname(file), name);
const resolved = [
target,
`${target}.ts`,
`${target}.js`,
`${target}.cjs`,
path.join(target, 'index.ts'),
path.join(target, 'index.js'),
].find(
(candidate) => fs.existsSync(candidate) && fs.statSync(candidate).isFile(),
);
return resolved;
}
module.exports = function loadSecurityModule(
file,
mocks = {},
cache = new Map(),
resolvedMocks,
) {
file = path.resolve(file);
// A dependency keeps its mock when a nested module imports it at another depth.
resolvedMocks ??= new Map(
Object.entries(mocks).flatMap(([name, value]) => {
const target = name.startsWith('.') ? moduleFile(file, name) : undefined;
return target ? [[target, value]] : [];
}),
);
if (cache.has(file)) return cache.get(file).exports;
const module = { exports: {} };
cache.set(file, module);
const localRequire = createRequire(file);
const requireModule = (name) => {
const resolved = name.startsWith('.') ? moduleFile(file, name) : undefined;
if (resolvedMocks.has(resolved)) return resolvedMocks.get(resolved);
if (Object.hasOwn(mocks, name)) return mocks[name];
if (name.startsWith('.')) {
const target = path.resolve(path.dirname(file), name);
if (fs.existsSync(`${target}.ts`)) {
return loadSecurityModule(`${target}.ts`, mocks, cache);
return loadSecurityModule(`${target}.ts`, mocks, cache, resolvedMocks);
}
}
return localRequire(name);
+43 -16
View File
@@ -7,7 +7,12 @@ const { LogStreamManager } = require('../../back/shared/logStreamManager');
const [root, command] = process.argv.slice(2);
process.env.QL_DATA_DIR = root;
const reporter = path.join(root, 'reporter.cjs');
fs.writeFileSync(reporter, `require('node:fs').writeFileSync(${JSON.stringify(path.join(root, 'receipt.json'))}, process.argv[2]);`);
fs.writeFileSync(
reporter,
`require('node:fs').writeFileSync(${JSON.stringify(
path.join(root, 'receipt.json'),
)}, process.argv[2]);`,
);
const Service = load('back/services/cron.ts', {
'../config': { logPath: root },
'../data/cron': {
@@ -17,22 +22,44 @@ const Service = load('back/services/cron.ts', {
'../data/runningInstance': {},
'../config/util': { getUniqPath: async () => "log's $directory" },
'../schedule/client': {},
'../shared/pLimit': { manualRunWithCronLimit: fn => fn() },
'../shared/triggerHistory': { TriggerHistory: class {
async bindCommand(_, pid, log) { process.send({ pid, log }); return true; }
async shouldStop() { return false; }
async complete() {}
} },
'../shared/logStreamManager': { logStreamManager: new LogStreamManager(root) },
'cross-spawn': { spawn: (file, args, options) => {
// Record the real supervisor's receipt without starting a panel database.
if (file === 'python3') args[7] = reporter;
return spawn(file, args, options);
} },
'../cron/execution/cronLimit': { manualRunWithCronLimit: (fn) => fn() },
'../cron/history': {
TriggerHistory: class {
async bindCommand(_, pid, log) {
process.send({ pid, log });
return true;
}
async shouldStop() {
return false;
}
async complete() {}
},
},
'../shared/logStreamManager': {
logStreamManager: new LogStreamManager(root),
},
'cross-spawn': {
spawn: (file, args, options) => {
// Record the real supervisor's receipt without starting a panel database.
if (file === 'python3') args[7] = reporter;
return spawn(file, args, options);
},
},
}).default;
const service = new Service({ info() {}, error(...args) { console.error(...args); } });
service.getDb = async () => ({ id: 1, status: 3, command, queued_token: 'test', log_path: '' });
const service = new Service({
info() {},
error(...args) {
console.error(...args);
},
});
service.getDb = async () => ({
id: 1,
status: 3,
command,
queued_token: 'test',
log_path: '',
});
service.makeCommand = () => command;
service.runSingle(1, 'test', 'manual-log-test').then(result => {
service.runSingle(1, 'test', 'manual-log-test').then((result) => {
process.send({ result }, () => process.disconnect());
});
+76 -37
View File
@@ -8,54 +8,93 @@ const { once } = require('node:events');
const { setTimeout: delay } = require('node:timers/promises');
const { createHash } = require('node:crypto');
const volume = '/ql/data/db';
const moduleFile = '/ql/static/build/shared/managedExit.cjs';
const moduleFile = '/ql/static/build/cron/settlement/exitReceipt.cjs';
const { receiptPath, readExit, retiringExits } = require(moduleFile);
(async () => {
const usage = await fs.statfs(volume);
assert.equal(usage.type,0xef53);
assert.ok(usage.blocks * usage.bsize <= 32 * 1024 * 1024 && usage.files <= 8192);
await fs.access(path.join(volume,'.qa-isolated-volume'));
const root = await fs.mkdtemp(path.join(volume,'.qa-slot-'));
assert.equal(usage.type, 0xef53);
assert.ok(
usage.blocks * usage.bsize <= 32 * 1024 * 1024 && usage.files <= 8192,
);
await fs.access(path.join(volume, '.qa-isolated-volume'));
const root = await fs.mkdtemp(path.join(volume, '.qa-slot-'));
const workers = [];
try {
process.env.QL_DATA_DIR = root;
const id = 'occupied-slot', directory = path.join(path.dirname(receiptPath(id)),'.claim.' + id + '.qaTest');
await fs.mkdir(directory,{recursive:true});
const slot = path.join(directory,'receipt');
const receipt = code => JSON.stringify({code, signal:null, time:1000, version:1,
checksum:createHash('sha256').update(JSON.stringify([id,code,null,1000])).digest('hex')});
await fs.writeFile(slot,receipt(17),{flag:'wx'});
for (const role of ['A','B']) {
const id = 'occupied-slot',
directory = path.join(
path.dirname(receiptPath(id)),
'.claim.' + id + '.qaTest',
);
await fs.mkdir(directory, { recursive: true });
const slot = path.join(directory, 'receipt');
const receipt = (code) =>
JSON.stringify({
code,
signal: null,
time: 1000,
version: 1,
checksum: createHash('sha256')
.update(JSON.stringify([id, code, null, 1000]))
.digest('hex'),
});
await fs.writeFile(slot, receipt(17), { flag: 'wx' });
for (const role of ['A', 'B']) {
const barrier = path.join(root, role);
const child = spawn(process.execPath,[path.join(__dirname,'receipt-claim-reuse-worker.cjs'),
moduleFile, slot, id, '17', '1000', barrier],{stdio:'inherit'});
workers.push({barrier,child,done:once(child,'exit')});
const child = spawn(
process.execPath,
[
path.join(__dirname, 'receipt-claim-reuse-worker.cjs'),
moduleFile,
slot,
id,
'17',
'1000',
barrier,
],
{ stdio: 'inherit' },
);
workers.push({ barrier, child, done: once(child, 'exit') });
}
const deadline = performance.now() + 10000;
const before = await Promise.all(workers.map(async ({barrier}) => {
while (performance.now() < deadline) {
try { return JSON.parse(await fs.readFile(barrier+'.ready','utf8')); }
catch (error) { if (error.code !== 'ENOENT') throw error; }
await delay(20);
}
throw Error('Both collectors must validate the original slot');
}));
assert.equal(before[0].fileInode,before[1].fileInode);
assert.equal(before[0].directoryInode,before[1].directoryInode);
await fs.writeFile(slot+'.new',receipt(42),{flag:'wx'});
await fs.rename(slot+'.new',slot);
const before = await Promise.all(
workers.map(async ({ barrier }) => {
while (performance.now() < deadline) {
try {
return JSON.parse(await fs.readFile(barrier + '.ready', 'utf8'));
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
await delay(20);
}
throw Error('Both collectors must validate the original slot');
}),
);
assert.equal(before[0].fileInode, before[1].fileInode);
assert.equal(before[0].directoryInode, before[1].directoryInode);
await fs.writeFile(slot + '.new', receipt(42), { flag: 'wx' });
await fs.rename(slot + '.new', slot);
const inode = (await fs.stat(slot)).ino;
assert.notEqual(inode,before[0].fileInode);
for (const {barrier} of workers) await fs.writeFile(barrier+'.go','');
for (const {done} of workers) assert.deepEqual(await done,[0,null]);
assert.notEqual(inode, before[0].fileInode);
for (const { barrier } of workers) await fs.writeFile(barrier + '.go', '');
for (const { done } of workers) assert.deepEqual(await done, [0, null]);
const captures = await retiringExits();
assert.equal(captures.length,1);
assert.equal((await fs.stat(captures[0].file)).ino,inode);
assert.equal((await readExit(id,captures[0].file)).code,42);
console.log(JSON.stringify({before,replacementInode:inode,retained:captures[0].file}));
assert.equal(captures.length, 1);
assert.equal((await fs.stat(captures[0].file)).ino, inode);
assert.equal((await readExit(id, captures[0].file)).code, 42);
console.log(
JSON.stringify({
before,
replacementInode: inode,
retained: captures[0].file,
}),
);
} finally {
for (const {child} of workers) if (child.exitCode === null) child.kill();
await fs.rm(root,{recursive:true,force:true});
for (const { child } of workers) if (child.exitCode === null) child.kill();
await fs.rm(root, { recursive: true, force: true });
}
})().catch(error => { console.error(error); process.exitCode=1; });
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});
+37 -11
View File
@@ -5,14 +5,21 @@ const path = require('node:path');
const [operation, stage, side, id] = process.argv.slice(2);
const root = process.env.QL_DATA_DIR;
const load = require('./load-security-module.cjs');
const db = load('back/data/index.ts', { '../config/index': { dbPath: root } }).sequelize;
const { TriggerHistory } = require('../../back/shared/triggerHistory');
const db = load('back/data/index.ts', {
'../config/index': { dbPath: root },
}).sequelize;
const { TriggerHistory } = require('../../back/cron/history');
const history = new TriggerHistory(db);
const stats = load('back/data/cronStats.ts', { '.': { sequelize: db } });
const running = load('back/data/runningInstance.ts', { '.': { sequelize: db } });
const running = load('back/data/runningInstance.ts', {
'.': { sequelize: db },
});
const Retention = load('back/services/retention.ts', {
'../data': { sequelize: db }, '../data/cronStats': stats, '../data/runningInstance': running,
'../data/system': {}, '../config': {},
'../data': { sequelize: db },
'../data/cronStats': stats,
'../data/runningInstance': running,
'../data/system': {},
'../config': {},
}).default;
function barrier() {
@@ -45,7 +52,8 @@ function intercept(object, method, matches) {
return result;
};
}
const captured = file => path.basename(file).startsWith('.pending.' + id + '.r-');
const captured = (file) =>
path.basename(file).startsWith('.pending.' + id + '.r-');
if (stage === 'readClaim') {
const open = fs.promises.open.bind(fs.promises);
fs.promises.open = async (file, ...options) => {
@@ -53,16 +61,34 @@ if (stage === 'readClaim') {
if (captured(file)) {
if (side === 'before') barrier();
const close = handle.close.bind(handle);
handle.close = async () => { await close(); if (side === 'after') barrier(); };
handle.close = async () => {
await close();
if (side === 'after') barrier();
};
}
return handle;
};
} else if (stage === 'move') intercept(fs.promises, 'rename', (src) => path.basename(src) === id);
} else if (stage === 'move')
intercept(fs.promises, 'rename', (src) => path.basename(src) === id);
else if (stage === 'unlink') intercept(fs.promises, 'unlink', captured);
else intercept(db, 'query', sql => String(sql).replace(/[`"]/g, '').startsWith(statements[stage].replace(/"/g, '')));
else
intercept(db, 'query', (sql) =>
String(sql)
.replace(/[`"]/g, '')
.startsWith(statements[stage].replace(/"/g, '')),
);
(async () => {
if (operation === 'prune') await new Retention().cleanup({ runningInstanceRetentionDays: 1, cronStatRetentionDays: 1 });
if (operation === 'prune')
await new Retention().cleanup({
runningInstanceRetentionDays: 1,
cronStatRetentionDays: 1,
});
else await history.complete(id, 'unknown', null, null);
throw Error('Expected barrier was never reached: ' + operation + '/' + stage);
})().catch(e => { console.error(e); process.exitCode = 1; }).finally(() => db.close());
})()
.catch((e) => {
console.error(e);
process.exitCode = 1;
})
.finally(() => db.close());
+50 -18
View File
@@ -1,6 +1,7 @@
const fs = require('node:fs');
const path = require('node:path');
const [moduleFile, file, id, outcome, time, barrier, recovery, stage] = process.argv.slice(2);
const [moduleFile, file, id, outcome, time, barrier, recovery, stage] =
process.argv.slice(2);
const { retireLegacyFile } = require(moduleFile);
// Both collectors have read the source and hold its directory lock at this point.
const rename = fs.promises.rename.bind(fs.promises);
@@ -10,38 +11,69 @@ async function gate(suffix, data, release) {
fs.renameSync(barrier + '.tmp', barrier + suffix);
const limit = performance.now() + 90000;
while (!fs.existsSync(barrier + release)) {
if (performance.now() > limit) throw Error('Timed out waiting for ' + release);
await new Promise(resolve => setTimeout(resolve, 25));
if (performance.now() > limit)
throw Error('Timed out waiting for ' + release);
await new Promise((resolve) => setTimeout(resolve, 25));
}
}
fs.promises.rename = async (source, target) => {
if (await fs.promises.realpath(source) !== file) return rename(source, target);
const ready = { pid: process.pid, path:file, target,
if ((await fs.promises.realpath(source)) !== file)
return rename(source, target);
const ready = {
pid: process.pid,
path: file,
target,
directoryInode: (await fs.promises.stat(path.dirname(source))).ino,
fileInode: (await fs.promises.stat(source)).ino };
fileInode: (await fs.promises.stat(source)).ino,
};
await gate('.ready', ready, '.go');
try {
await rename(source, target);
} catch (error) {
if (stage === 'recordMoveError')
fs.writeFileSync(barrier + '.error', JSON.stringify({code:error.code, errno:error.errno, syscall:error.syscall}));
fs.writeFileSync(
barrier + '.error',
JSON.stringify({
code: error.code,
errno: error.errno,
syscall: error.syscall,
}),
);
throw error;
}
captured = target;
if (stage === 'holdMoved') await gate('.moved', {target, inode:(await fs.promises.stat(target)).ino}, '.release');
if (stage === 'holdMoved')
await gate(
'.moved',
{ target, inode: (await fs.promises.stat(target)).ino },
'.release',
);
};
const unlink = fs.promises.unlink.bind(fs.promises);
fs.promises.unlink = async file => {
fs.promises.unlink = async (file) => {
if (stage === 'holdUnlink' && captured === file)
await gate('.checked', {target:file, inode:(await fs.promises.stat(file)).ino}, '.release');
await gate(
'.checked',
{ target: file, inode: (await fs.promises.stat(file)).ino },
'.release',
);
return unlink(file);
};
const settlement = recovery
? require(recovery).triggerHistory().complete(id,'unknown',null,null)
: retireLegacyFile(id, file, {outcome, time:Number(time)});
settlement.catch(error => {
// Another collector may have already removed the same settled inode.
if (error.code !== 'ENOENT') { console.error(error); process.exitCode = 1; }
}).finally(() => {
if (recovery) return require(path.join(path.dirname(recovery),'../data')).sequelize.close();
});
? require(recovery).triggerHistory().complete(id, 'unknown', null, null)
: retireLegacyFile(id, file, { outcome, time: Number(time) });
settlement
.catch((error) => {
// Another collector may have already removed the same settled inode.
if (error.code !== 'ENOENT') {
console.error(error);
process.exitCode = 1;
}
})
.finally(() => {
if (recovery)
return require(path.join(
path.dirname(recovery),
'../data',
)).sequelize.close();
});
+31 -15
View File
@@ -4,21 +4,37 @@ const fs = require('node:fs');
const path = require('node:path');
const [modules, side, checkpoint] = process.argv.slice(2);
const { sequelize } = require(path.join(modules, 'data'));
const { migrateSchema, prunedExitMigrationId } = require(path.join(modules, 'shared/schemaMigrations'));
if (!['before', 'after'].includes(side)) throw new Error('Unknown commit boundary');
const { migrateSchema, prunedExitMigrationId } = require(path.join(
modules,
'data/schemaMigrations',
));
if (!['before', 'after'].includes(side))
throw new Error('Unknown commit boundary');
const transaction = sequelize.transaction.bind(sequelize);
sequelize.transaction = callback => transaction(async tx => {
await callback(tx);
const [rows] = await sequelize.query(`SELECT
sequelize.transaction = (callback) =>
transaction(async (tx) => {
await callback(tx);
const [rows] = await sequelize.query(
`SELECT
(SELECT COUNT(*) FROM SchemaMigrations WHERE id=$id) AS marker,
(SELECT COUNT(*) FROM CronUnmatchedBoundExits) AS proofs`, { transaction: tx, bind: { id: prunedExitMigrationId } });
if (rows[0].marker !== 1 || rows[0].proofs === 0) throw new Error('No verified migration batch');
const hold = () => {
fs.writeFileSync(checkpoint + '.tmp', JSON.stringify({ side, pid: process.pid, ...rows[0] }), {flag: 'wx'});
fs.renameSync(checkpoint + '.tmp', checkpoint);
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
};
if (side === 'before') hold();
else tx.afterCommit(hold);
(SELECT COUNT(*) FROM CronUnmatchedBoundExits) AS proofs`,
{ transaction: tx, bind: { id: prunedExitMigrationId } },
);
if (rows[0].marker !== 1 || rows[0].proofs === 0)
throw new Error('No verified migration batch');
const hold = () => {
fs.writeFileSync(
checkpoint + '.tmp',
JSON.stringify({ side, pid: process.pid, ...rows[0] }),
{ flag: 'wx' },
);
fs.renameSync(checkpoint + '.tmp', checkpoint);
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
};
if (side === 'before') hold();
else tx.afterCommit(hold);
});
migrateSchema(sequelize).catch((error) => {
console.error(error);
process.exitCode = 1;
});
migrateSchema(sequelize).catch(error => { console.error(error); process.exitCode = 1; });
+1 -1
View File
@@ -1,6 +1,6 @@
const fs = require('node:fs');
const path = require('node:path');
const { writeExit } = require('../../back/shared/managedExit.cjs');
const { writeExit } = require('../../back/cron/settlement/exitReceipt.cjs');
const [stage, time] = process.argv.slice(2);
const write = fs.writeFileSync;
function checkpoint(point) {
+88 -27
View File
@@ -4,14 +4,24 @@ const fs = require('node:fs');
const path = require('node:path');
const { exhaust } = require('./receipt-volume-full.cjs');
const { sequelize } = require('/ql/static/build/data');
const { TriggerHistory } = require('/ql/static/build/shared/triggerHistory');
const { TriggerHistory } = require('/ql/static/build/cron/history');
const [stage, id] = process.argv.slice(2);
const volume = '/ql/data/db';
const canonical = path.join(volume, 'cron-exits', id);
const control = '/tmp/journal-qa';
const capacity = () => fs.statfsSync(volume).bavail;
if (fs.statfsSync(volume).type !== 0xef53 || !/^[a-z0-9-]+$/.test(id) ||
!['rename-before','rename-after','rename-enospc','unlink-before','unlink-after','unlink-injected'].includes(stage)) {
if (
fs.statfsSync(volume).type !== 0xef53 ||
!/^[a-z0-9-]+$/.test(id) ||
![
'rename-before',
'rename-after',
'rename-enospc',
'unlink-before',
'unlink-after',
'unlink-injected',
].includes(stage)
) {
throw Error('Expected a supported ext4 collection boundary and execution ID');
}
@@ -30,8 +40,9 @@ async function atBoundary(source, destination, operation) {
const pin = path.join(volume, '.qa-reclaim-pin');
fs.linkSync(source, pin);
exhaust(false);
const event = {stage, id, source, destination, blocksBefore: capacity()};
if (event.blocksBefore !== 0) throw Error('Expected an exhausted data volume');
const event = { stage, id, source, destination, blocksBefore: capacity() };
if (event.blocksBefore !== 0)
throw Error('Expected an exhausted data volume');
if (stage === 'rename-enospc') {
// Fill the target directory with entries the same length as the capture name.
// Hard links expend directory space without needing another inode.
@@ -39,7 +50,16 @@ async function atBoundary(source, destination, operation) {
let count = 0;
try {
for (;;) {
fs.linkSync(pin, path.join(dir, 'q' + count.toString(36).padStart(path.basename(destination).length - 1, '0')));
fs.linkSync(
pin,
path.join(
dir,
'q' +
count
.toString(36)
.padStart(path.basename(destination).length - 1, '0'),
),
);
count++;
}
} catch (error) {
@@ -47,45 +67,86 @@ async function atBoundary(source, destination, operation) {
}
event.extraDirectoryEntries = count;
}
if (stage.endsWith('-before')) hold({...event, called:false});
if (stage.endsWith('-before')) hold({ ...event, called: false });
if (stage === 'unlink-injected') {
// Explicitly synthetic. Keep the file and let the real collector unwind.
throw Object.assign(Error('Injected unlink capacity error'), {code:'ENOSPC', event});
throw Object.assign(Error('Injected unlink capacity error'), {
code: 'ENOSPC',
event,
});
}
try {
await operation();
} catch (error) {
if (stage !== 'rename-enospc' || error.code !== 'ENOSPC') throw error;
hold({...event, called:true, result:error.code, errno:error.errno, syscall:error.syscall,
sourceExists:fs.existsSync(source), destinationExists:fs.existsSync(destination)});
hold({
...event,
called: true,
result: error.code,
errno: error.errno,
syscall: error.syscall,
sourceExists: fs.existsSync(source),
destinationExists: fs.existsSync(destination),
});
}
if (stage === 'rename-enospc') throw Error('Expected rename to need another directory block');
hold({...event, called:true, result:'success', blocksAfter:capacity(),
sourceExists:fs.existsSync(source), destinationExists:destination && fs.existsSync(destination)});
if (stage === 'rename-enospc')
throw Error('Expected rename to need another directory block');
hold({
...event,
called: true,
result: 'success',
blocksAfter: capacity(),
sourceExists: fs.existsSync(source),
destinationExists: destination && fs.existsSync(destination),
});
}
const rename = fs.promises.rename.bind(fs.promises);
const unlink = fs.promises.unlink.bind(fs.promises);
let reached = false, injected;
fs.promises.rename = (from,to) => {
let reached = false,
injected;
fs.promises.rename = (from, to) => {
if (!reached && stage.startsWith('rename-') && from === canonical) {
reached = true;
const destination = path.join(fs.realpathSync(path.dirname(to)), path.basename(to));
return atBoundary(from,destination,() => rename(from,to));
const destination = path.join(
fs.realpathSync(path.dirname(to)),
path.basename(to),
);
return atBoundary(from, destination, () => rename(from, to));
}
return rename(from,to);
return rename(from, to);
};
fs.promises.unlink = async file => {
if (!reached && stage.startsWith('unlink-') && path.basename(file).startsWith('.pending.' + id + '.r-')) {
fs.promises.unlink = async (file) => {
if (
!reached &&
stage.startsWith('unlink-') &&
path.basename(file).startsWith('.pending.' + id + '.r-')
) {
reached = true;
try {return await atBoundary(fs.realpathSync(file),null,() => unlink(file));}
catch (error) { if (stage === 'unlink-injected') injected = error; throw error; }
try {
return await atBoundary(fs.realpathSync(file), null, () => unlink(file));
} catch (error) {
if (stage === 'unlink-injected') injected = error;
throw error;
}
}
return unlink(file);
};
new TriggerHistory(sequelize).complete(id,'unknown',null,null).then(() => {
if (injected?.code === 'ENOSPC') hold({...injected.event, called:false, injected:'ENOSPC',
privateFileRetained:fs.existsSync(injected.event.source)});
throw Error('Collector did not reach the expected power cut');
}).catch(error => {console.error(error); process.exitCode = 1;}).finally(() => sequelize.close());
new TriggerHistory(sequelize)
.complete(id, 'unknown', null, null)
.then(() => {
if (injected?.code === 'ENOSPC')
hold({
...injected.event,
called: false,
injected: 'ENOSPC',
privateFileRetained: fs.existsSync(injected.event.source),
});
throw Error('Collector did not reach the expected power cut');
})
.catch((error) => {
console.error(error);
process.exitCode = 1;
})
.finally(() => sequelize.close());
+107 -34
View File
@@ -6,15 +6,27 @@ const volume = '/ql/data/db';
const barriers = '/tmp/journal-qa';
const [mode, id] = process.argv.slice(2);
const capacity = fs.statfsSync(volume);
const filesystem = fs.readFileSync('/proc/self/mountinfo', 'utf8').split('\n')
.find(line => line.split(' ')[4] === volume)?.split(' - ')[1].split(' ')[0];
const filesystem = fs
.readFileSync('/proc/self/mountinfo', 'utf8')
.split('\n')
.find((line) => line.split(' ')[4] === volume)
?.split(' - ')[1]
.split(' ')[0];
const ext4 = filesystem === 'ext4' && capacity.type === 0xef53;
if (!(ext4 || (filesystem === 'tmpfs' && capacity.type === 0x01021994)) || capacity.blocks <= 0 || capacity.blocks * capacity.bsize > 32 * 1024 * 1024 ||
capacity.files <= 0 || capacity.files > 8192 || !fs.existsSync(path.join(volume, '.qa-isolated-volume'))) {
throw Error('Requires a dedicated bounded ext4 or tmpfs for receipt acceptance');
if (
!(ext4 || (filesystem === 'tmpfs' && capacity.type === 0x01021994)) ||
capacity.blocks <= 0 ||
capacity.blocks * capacity.bsize > 32 * 1024 * 1024 ||
capacity.files <= 0 ||
capacity.files > 8192 ||
!fs.existsSync(path.join(volume, '.qa-isolated-volume'))
) {
throw Error(
'Requires a dedicated bounded ext4 or tmpfs for receipt acceptance',
);
}
const { sequelize: db } = require('/ql/static/build/data');
const { TriggerHistory } = require('/ql/static/build/shared/triggerHistory');
const { TriggerHistory } = require('/ql/static/build/cron/history');
function record(name, data) {
fs.writeFileSync(path.join(barriers, name + '.tmp'), JSON.stringify(data));
fs.renameSync(path.join(barriers, name + '.tmp'), path.join(barriers, name));
@@ -34,61 +46,102 @@ function exhaust(inodes) {
if (ext4) {
if (fd !== undefined) {
// A large allocation may fail while individual blocks remain usable.
try { for (;;) fs.writeSync(fd, Buffer.alloc(capacity.bsize)); }
catch (last) { if (last.code !== 'ENOSPC') throw last; }
try {
for (;;) fs.writeSync(fd, Buffer.alloc(capacity.bsize));
} catch (last) {
if (last.code !== 'ENOSPC') throw last;
}
fs.fsyncSync(fd);
}
for (const entry of [dir, volume]) {
const handle = fs.openSync(entry, fs.constants.O_DIRECTORY);
try { fs.fsyncSync(handle); } finally { fs.closeSync(handle); }
try {
fs.fsyncSync(handle);
} finally {
fs.closeSync(handle);
}
}
}
record(mode + '-capacity', { dir, error: error.code, statfs: fs.statfsSync(volume) });
} finally { if (fd !== undefined) fs.closeSync(fd); }
record(mode + '-capacity', {
dir,
error: error.code,
statfs: fs.statfsSync(volume),
});
} finally {
if (fd !== undefined) fs.closeSync(fd);
}
}
// A short receipt fits one block. Request another block beyond any ext4
// preallocation to obtain kernel ENOSPC while the original prefix is intact.
function writePartialReceipt() {
const receipt = JSON.parse(process.argv[4]);
const { writeExit } = require('/ql/static/build/shared/managedExit.cjs');
const {
writeExit,
} = require('/ql/static/build/cron/settlement/exitReceipt.cjs');
const write = fs.writeFileSync;
fs.writeFileSync = (file, content, options) => {
if (!content || path.dirname(file) !== path.join(volume, 'cron-exits')) return write(file, content, options);
const fd = fs.openSync(file, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY | fs.constants.O_SYNC, 0o600);
if (!content || path.dirname(file) !== path.join(volume, 'cron-exits'))
return write(file, content, options);
const fd = fs.openSync(
file,
fs.constants.O_CREAT |
fs.constants.O_EXCL |
fs.constants.O_WRONLY |
fs.constants.O_SYNC,
0o600,
);
try {
const bytes = Buffer.from(content);
fs.writeSync(fd, bytes, 0, 12, 0);
record('partial-ready', { id, file, bytes: fs.fstatSync(fd).size });
const deadline = performance.now() + 120000;
while (!fs.existsSync(path.join(barriers, 'partial-continue'))) {
if (performance.now() > deadline) throw Error('Short-write barrier expired');
if (performance.now() > deadline)
throw Error('Short-write barrier expired');
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 30);
}
const offset = ext4 ? (capacity.blocks + 1) * capacity.bsize : capacity.bsize;
try { fs.writeSync(fd, bytes, 12, bytes.length - 12, offset); }
catch (error) {
record('partial-error', { id, file, code: error.code, bytes: fs.fstatSync(fd).size, offset });
const offset = ext4
? (capacity.blocks + 1) * capacity.bsize
: capacity.bsize;
try {
fs.writeSync(fd, bytes, 12, bytes.length - 12, offset);
} catch (error) {
record('partial-error', {
id,
file,
code: error.code,
bytes: fs.fstatSync(fd).size,
offset,
});
// Keep the torn file open across the guest power cut in the ext4 run.
if (ext4) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 120000);
if (ext4)
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 120000);
throw error;
}
throw Error('Expected ENOSPC while allocating the next page');
} finally { fs.closeSync(fd); }
} finally {
fs.closeSync(fd);
}
};
writeExit(id, receipt.code, receipt.signal, receipt.time);
}
async function main() {
if (mode === 'partial') return writePartialReceipt();
if (!['commit','collect'].includes(mode)) throw Error('Unexpected fault mode');
if (!['commit', 'collect'].includes(mode))
throw Error('Unexpected fault mode');
await db.query('CREATE TABLE IF NOT EXISTS qa_commit_payload (payload BLOB)');
const original = db.query.bind(db);
if (mode === 'commit') {
db.query = async (sql, ...args) => {
if (!String(sql).startsWith('COMMIT')) return original(sql, ...args);
exhaust(false);
try { return await original(sql, ...args); }
catch (error) {
record('commit-error', { code: error.original?.code, sql: String(sql) });
try {
return await original(sql, ...args);
} catch (error) {
record('commit-error', {
code: error.original?.code,
sql: String(sql),
});
throw error;
}
};
@@ -102,27 +155,47 @@ async function main() {
}
try {
await rename(...args);
record('collect-moved', { source:args[0], destination:args[1] });
record('collect-moved', { source: args[0], destination: args[1] });
} catch (error) {
record('collect-error', { code: error.code, prefix: args[0] });
throw error;
}
catch (error) { record('collect-error', { code: error.code, prefix: args[0] }); throw error; }
};
}
await db.transaction(async transaction => {
await db.transaction(async (transaction) => {
if (mode === 'commit') {
await db.query('PRAGMA cache_spill=OFF', { transaction });
await db.query('INSERT INTO qa_commit_payload VALUES (zeroblob(524288))', { transaction });
await db.query(
'INSERT INTO qa_commit_payload VALUES (zeroblob(524288))',
{ transaction },
);
}
record(mode + '-ready', { id });
const deadline = Date.now() + 86400000 * 3;
while (!fs.existsSync(path.join(barriers, mode + '-continue'))) {
if (Date.now() >= deadline) throw Error('Timed out at database barrier');
await new Promise(r => setTimeout(r, 30));
await new Promise((r) => setTimeout(r, 30));
}
await new TriggerHistory(db).completeCommandExit(id, 'unknown', null, null, transaction);
await new TriggerHistory(db).completeCommandExit(
id,
'unknown',
null,
null,
transaction,
);
});
}
module.exports = { exhaust };
if (require.main === module) main().catch(error => {
if (mode !== 'commit' || error.original?.code !== 'SQLITE_FULL') {console.error(error); process.exitCode = 1;}
}).finally(async () => { await db.close(); record(mode + '-done', { id }); });
if (require.main === module)
main()
.catch((error) => {
if (mode !== 'commit' || error.original?.code !== 'SQLITE_FULL') {
console.error(error);
process.exitCode = 1;
}
})
.finally(async () => {
await db.close();
record(mode + '-done', { id });
});
+90
View File
@@ -0,0 +1,90 @@
const fs = require('node:fs');
const path = require('node:path');
const ts = require('typescript');
// Inspect emitted imports so type-only references do not become false cycles.
// Include literal require() calls inside functions and executable entry points.
function runtimeModuleGraph(root) {
const files = [];
const walk = (directory) => {
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
const file = path.join(directory, entry.name);
if (entry.isDirectory()) walk(file);
else if (/\.(ts|js|cjs)$/.test(file) && !file.endsWith('.d.ts'))
files.push(file);
}
};
walk(root);
const graph = new Map(files.map((file) => [file, new Set()]));
for (const file of files) {
const source = fs.readFileSync(file, 'utf8');
const emitted = file.endsWith('.ts')
? ts.transpileModule(source, {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2017,
experimentalDecorators: true,
emitDecoratorMetadata: true,
esModuleInterop: true,
},
}).outputText
: source;
const parsed = ts.createSourceFile(
file,
emitted,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.JS,
);
const visit = (node) => {
if (
ts.isCallExpression(node) &&
ts.isIdentifier(node.expression) &&
node.expression.text === 'require' &&
node.arguments.length === 1 &&
ts.isStringLiteral(node.arguments[0]) &&
node.arguments[0].text.startsWith('.')
) {
const base = path.normalize(
path.join(path.dirname(file), node.arguments[0].text),
);
const target = [
base,
base + '.ts',
base + '.js',
base + '.cjs',
path.join(base, 'index.ts'),
path.join(base, 'index.js'),
].find((candidate) => graph.has(candidate));
if (target) graph.get(file).add(target);
}
ts.forEachChild(node, visit);
};
visit(parsed);
}
return graph;
}
function moduleCycles(graph) {
const visited = new Set(),
active = new Set(),
stack = [],
cycles = [];
const visit = (file) => {
if (active.has(file)) {
cycles.push([...stack.slice(stack.indexOf(file)), file]);
return;
}
if (visited.has(file)) return;
visited.add(file);
active.add(file);
stack.push(file);
for (const dependency of graph.get(file) || []) visit(dependency);
stack.pop();
active.delete(file);
};
for (const file of graph.keys()) visit(file);
return cycles;
}
module.exports = { runtimeModuleGraph, moduleCycles };