feat: harden cron execution recovery and expose scheduling diagnostics

Reconcile scheduled and system cron triggers, isolate concurrent executions and retain verifiable exit statistics across restarts. Add paged task history, log and script browsing, dashboard timing details and regression coverage.
This commit is contained in:
whyour committed 2026-11-17 01:01:57 +08:00
1 parent 3b6a873520
commit 8a9e70e90b
166 files changed
+18942 -1800

No files matched your search

File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -16,9 +16,9 @@ test('system and node modes route extended cron once and keep portable rules in
for (const mode of ['system', 'node']) {
const module = { exports: {} };
let file = '', installs = 0;
new Function('module', 'process', 'execSync', 'ScheduleType', 'config', 'writeFileWithLock', 'CrontabModel', js)(
new Function('module', 'process', 'execFileSync', 'ScheduleType', 'config', 'writeFileWithLock', 'CrontabModel', 'shellQuote', 'stageSystemPlan', 'confirmSystemPlan', 'suspendSystemPlan', js)(
module, { env: { QL_SCHEDULER: mode } }, () => { installs++; }, ScheduleType,
{ crontabFile: '/unused' }, async (_, data) => { file = data; }, { update: async () => {} },
{ crontabFile: '/unused' }, async (_, data) => { file = data; }, { update: async () => {} }, require('../../back/shared/shellQuote').shellQuote, async () => 1, async () => {}, async () => {},
);
const service = new module.exports();
service.makeCommand = (row) => `task ${row.id}.js`;
+23
View File
@@ -74,6 +74,7 @@ test('create and update reject invalid extra schedules before calling the servic
const load = require('../helpers/load-security-module.cjs');
const mutations = [];
const service = {
async status(value) { return value; },
async create(value) {
mutations.push(value);
return { id: 1, ...value };
@@ -110,6 +111,20 @@ test('create and update reject invalid extra schedules before calling the servic
});
t.after(() => new Promise((resolve) => server.close(resolve)));
// Released CLI wrappers reuse this execution_id for start and exit; both must reach the same receipt.
const uuid = require('node:crypto').randomUUID();
const statusRequest = (status, extra = {}) => fetch(`http://127.0.0.1:${server.address().port}/crons/status`, {
method: 'PUT', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ ids: [1], pid: '122', status, execution_id: `legacy-system:123:${uuid}`, ...extra }),
});
for (const status of ['0', '1']) {
const res = await statusRequest(status);
assert.equal(res.status, 200);
assert.equal((await res.json()).data.trigger_id, `system-cli-123-${uuid}`);
}
assert.equal((await statusRequest('1', { trigger_id: 'another' })).status, 400);
assert.equal((await statusRequest('1', { execution_id: 'broken' })).status, 400);
for (const method of ['POST', 'PUT']) {
const payload = {
command: 'task valid.js',
@@ -167,3 +182,11 @@ test('create and update reject invalid extra schedules before calling the servic
}
assert.equal(mutations.length, 2);
});
test('saving a migrated task accepts a null pending policy and rejects invalid input', () => {
const task = { name: 'legacy', command: 'task old.sh', schedule: '1 * * * *' };
for (const value of [null, false, true]) {
assert.equal(schema.validate({ ...task, skip_if_pending: value }).error, undefined);
}
assert.ok(schema.validate({ ...task, skip_if_pending: 'invalid' }).error);
});
+8 -3
View File
@@ -76,8 +76,10 @@ test('isolated initialization creates a fresh database and does not retain ORM m
const db = new Sequelize({ dialect: 'sqlite', storage: f.storage, logging: false });
try {
const tables = await db.getQueryInterface().showAllTables();
for (const table of ['Crontabs', 'Envs', 'RunningInstances', 'SchemaMigrations']) assert.ok(tables.includes(table), table);
assert.equal((await db.query('SELECT id FROM SchemaMigrations', { type: QueryTypes.SELECT })).length, 15);
for (const table of ['Crontabs', 'Envs', 'RunningInstances', 'SchemaMigrations', 'CronLegacyExitBookings']) assert.ok(tables.includes(table), table);
const migrations = await db.query('SELECT id FROM SchemaMigrations', { type: QueryTypes.SELECT });
assert.ok(migrations.some(row => row.id === 'preserve-pruned-bound-exits-v1'));
assert.equal(migrations.length, 27);
} finally { await db.close(); }
});
@@ -96,7 +98,10 @@ test('isolated initialization upgrades an existing database and remains idempote
const rows = await db.query('SELECT * FROM Crontabs', { type: QueryTypes.SELECT });
assert.equal(rows[0].name, 'keep-me');
assert.ok(Object.hasOwn(rows[0], 'queued_token'));
assert.equal((await db.query('SELECT id FROM SchemaMigrations', { type: QueryTypes.SELECT })).length, 15);
assert.ok(Object.hasOwn(await db.getQueryInterface().describeTable('CrontabStats'), 'fixed_max_time'));
const migrations = await db.query('SELECT id FROM SchemaMigrations', { type: QueryTypes.SELECT });
assert.ok(migrations.some(row => row.id === 'preserve-pruned-bound-exits-v1'));
assert.equal(migrations.length, 27);
} finally { await db.close(); }
});
+79
View File
@@ -0,0 +1,79 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { checkDirectoryVersions, readDirectoryPage } = require('../../back/shared/directoryPage');
test('directory cursors survive inserts and deletes and search reaches unloaded folders', async t => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-file-page-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
await fs.mkdir(path.join(root,'dir'));
await fs.mkdir(path.join(root,'.tmp'));
await fs.writeFile(path.join(root,'.tmp','secret'),'');
await fs.symlink(os.tmpdir(), path.join(root,'outside'));
for (const name of ['a','c','e','dir/needle#&.js','dir/needle2.js']) await fs.writeFile(path.join(root,name),'1');
const read = (after='', search='', dir='', folders=false, newest=false) => readDirectoryPage(root,['.tmp'],dir,after,search,folders,newest,2);
const first = await read();
assert.deepEqual(first.data.map(x=>x.key),['dir','a']);
await fs.unlink(path.join(root,'a'));
await fs.writeFile(path.join(root,'b'),'2');
const second = await read(first.next);
assert.deepEqual(second.data.map(x=>x.key),['b','c']);
assert.deepEqual((await read(second.next)).data.map(x=>x.key),['e']);
assert.deepEqual((await read('','','',false,true)).data.map(x=>x.key),['dir','e']);
assert.deepEqual((await read('','','',true)).data.map(x=>x.key),['dir']);
assert.deepEqual((await read('','needle')).data.map(x=>x.key),['dir/needle#&.js','dir/needle2.js']);
assert.deepEqual((await read('','secret')).data,[]);
for (const dir of ['../','.tmp','outside']) await assert.rejects(read('','',dir), { status:403 });
});
test('a sparse cross-directory search resumes after an empty batch', async t => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-file-search-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
for (let i=0; i<513; i++) await fs.writeFile(path.join(root, 'a'+i), '');
await fs.mkdir(path.join(root,'z')); await fs.writeFile(path.join(root,'z','needle'),'');
const page = after => readDirectoryPage(root,[], '',after,'needle',false,false);
const first = await page('');
assert.deepEqual(first.data,[]); assert.ok(first.next);
assert.deepEqual((await page(first.next)).data.map(x=>x.key),['z/needle']);
});
test('a delayed terminal page detects changes on either side of its cursor, including a previously traversed sibling', async t => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-moved-page-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
for (const dir of ['a', 'b']) await fs.mkdir(path.join(root, dir));
for (const key of ['a/one.js', 'b/two.js']) await fs.writeFile(path.join(root, key), key);
const first = await readDirectoryPage(root, [], '', '', '.js', false, false, 1);
const last = await readDirectoryPage(root, [], '', first.next, '.js', false, false, 2);
assert.equal(last.next, null);
assert.deepEqual(last.data.map(r => r.key), ['b/two.js']);
const versions = [...first.versions, ...last.versions];
assert.equal(await checkDirectoryVersions(root, [], versions), true);
await fs.rename(path.join(root, 'b/two.js'), path.join(root, 'a/first.js'));
await fs.unlink(path.join(root, 'a/one.js'));
await fs.writeFile(path.join(root, 'b/new.js'), 'new');
assert.equal(await checkDirectoryVersions(root, [], versions), false);
const fresh = await readDirectoryPage(root, [], '', '', '.js', false, false);
assert.deepEqual(fresh.data.map(r => r.key), ['a/first.js', 'b/new.js']);
assert.equal(await checkDirectoryVersions(root, [], fresh.versions), true);
});
test('deleting and replacing the open directory invalidates its pages and a missing path can be checked again', async t => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-replaced-page-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const dir = path.join(root, 'open');
await fs.mkdir(dir);
const list = () => readDirectoryPage(root, [], 'open', '', '', false, false);
const before = await list();
await fs.rename(dir, path.join(root, 'moved'));
const missing = await list();
assert.deepEqual(missing.data, []);
assert.equal(await checkDirectoryVersions(root, [], before.versions), false);
assert.equal(await checkDirectoryVersions(root, [], missing.versions), true);
await fs.mkdir(dir);
assert.equal(await checkDirectoryVersions(root, [], missing.versions), false);
assert.equal(await checkDirectoryVersions(root, [], before.versions), false);
await fs.symlink(os.tmpdir(), path.join(root, 'external'));
assert.equal(await checkDirectoryVersions(root, [], [['external', null], ['../escape', null]]), false);
});
+1 -2
View File
@@ -90,8 +90,7 @@ test('real gRPC server rejects plaintext and TLS without client certificates, ac
}
},
},
'../schedule/addCron': {},
'../schedule/delCron': {},
'../schedule/registeredPlans': {},
'../schedule/setConcurrency': {},
'../schedule/api': {},
'../schedule/health': {
+12
View File
@@ -207,6 +207,9 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
router.post('/logs/download', (_req, res) =>
res.json({ code: 200, data: 'downloaded' }),
);
router.post('/logs/entries/check', (_req, res) =>
res.json({ code: 200, current: true }),
);
router.get('/system', (_req, res) => res.json({ code: 200 }));
router.put('/system/notify', (_req, res) => res.json({ code: 200 }));
router.put('/system/auth/reset', (_req, res) => {
@@ -389,6 +392,15 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
.body.data,
'downloaded',
);
for (const [namespace, ownToken, otherToken] of [
['scripts', 'script-read-app', 'logs:read-app'],
['logs', 'logs:read-app', 'script-read-app'],
]) {
const url = `${prefix}/${namespace}/entries/check`;
const versions = [['absent-directory', null]];
assert.equal((await request(url, ownToken, 'POST', versions)).body.current, true);
assert.equal((await request(url, otherToken, 'POST', versions)).status, 401);
}
}
const importedWithHead = await fetch(
`http://127.0.0.1:${server.address().port}/open/crons/import`,
+1 -2
View File
@@ -46,8 +46,7 @@ for (const host of ['127.0.0.1', '::1', '192.0.2.1', '::']) {
'../protos/cron': { CronService: {} },
'../protos/health': { HealthService: {} },
'../protos/api': { ApiService: {} },
'../schedule/addCron': {},
'../schedule/delCron': {},
'../schedule/registeredPlans': {},
'../schedule/setConcurrency': {},
'../schedule/health': {},
'../schedule/api': {},
+49
View File
@@ -156,3 +156,52 @@ test('manual execution rejects escaping log names before creating directories or
assert.equal(await fs.readFile(victim, 'utf8'), 'unchanged');
assert.deepEqual(await fs.readdir(outside), ['victim.log']);
});
test('creating log folders normalizes valid absolute paths and rejects sibling or symlink escapes before mkdir', async t => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-log-root-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const logs = path.join(root, 'log'), outside = path.join(root, 'log-other');
await Promise.all([fs.mkdir(logs), fs.mkdir(outside)]);
await fs.symlink(outside, path.join(logs, 'escape'));
const Service = load(path.resolve('back/services/cron.ts'), {
'../config': { logPath: logs }, '../config/util': {}, '../data/cron': {},
'../data/runningInstance': {}, '../schedule/client': {}, '../shared/pLimit': {},
'../shared/logStreamManager': {}, '../loaders/logger': {},
}).default;
const service = new Service({});
for (const candidate of [path.join(outside, 'new'), 'escape/new', '../log-other/new'])
await assert.rejects(service.getLogName({ log_name: candidate }), { status: 400 });
assert.deepEqual(await fs.readdir(outside), []);
assert.equal(await service.getLogName({ log_name: path.join(logs, 'safe') }), 'safe');
assert.ok((await fs.stat(path.join(logs, 'safe'))).isDirectory());
});
test('a cursor from the previous run reads the tail of the current log instead of splicing two files', async t => {
const { root } = await fixture(t);
const Service = load(path.resolve('back/services/cron.ts'), {
'../config': {logPath: root}, '../config/util': {fileExist: async p => (await fs.stat(p)).isFile()},
'../data/cron': {CrontabStatus: {running: 0, queued: 3}}, '../data/runningInstance': {},
'../schedule/client': {}, '../shared/pLimit': {}, '../shared/logStreamManager': {}, '../loaders/logger': {},
}).default;
const service = new Service({});
service.getDb = async () => ({status: 0, log_path: 'current.log'});
await fs.writeFile(path.join(root, 'current.log'), 'current example');
const resumed = await service.log(1, {offset: 3, previousPath: 'current.log', limit: 7});
assert.equal(resumed.content, 'rent ex');
const switched = await service.log(1, {offset: 3, previousPath: '../previous.log', limit: 7});
assert.equal(switched.content, 'example');
assert.equal(switched.logPath, 'current.log');
const followed = await service.log(1, { offset: 3, previousPath: 'previous.log', limit: 7, follow: true });
assert.equal(followed.offset, 0);
assert.equal(followed.content, 'current');
const rest = await service.log(1, { offset: followed.nextOffset, cursor: followed.cursor, previousPath: followed.logPath });
assert.equal(rest.reset, false);
assert.equal(followed.content + rest.content, 'current example');
service.getDb = async () => ({ status: 3, queued_token: 'new-run', log_path: 'current.log' });
const queued = await service.log(1, { follow: true, tail: true });
assert.equal(queued.status, 'running');
assert.equal(queued.nextOffset, 0);
assert.equal(queued.logPath, undefined);
assert.equal(queued.content, '');
});
+33
View File
@@ -70,3 +70,36 @@ test('missing logs return an empty chunk', async () => {
truncated: false,
});
});
test('following a file distinguishes append, same-inode rewrites, and replacement', async t => {
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-log-follow-'));
t.after(() => fs.rm(dir, { recursive: true, force: true }));
const file = path.join(dir, 'run.log');
const original = 'A\n' + '相同内容🚀\n'.repeat(80);
await fs.writeFile(file, original);
const first = await readLogChunk(file, { follow: true, offset: 0 });
const resume = chunk => readLogChunk(file, { cursor: chunk.cursor, offset: chunk.nextOffset });
assert.equal((await resume(first)).cursor, first.cursor);
await fs.appendFile(file, '追加\n');
const appended = await resume(first);
assert.equal(appended.reset, false);
assert.equal(appended.content, '追加\n');
// Preserve the entire suffix at the old offset while changing an earlier line.
const sameSize = 'B' + original.slice(1) + appended.content;
await fs.writeFile(file, sameSize);
const rewritten = await resume(appended);
assert.equal(rewritten.reset, true);
assert.equal(rewritten.content, sameSize);
await fs.rename(file, path.join(dir, 'previous.log'));
await fs.writeFile(file, sameSize + '下一轮\n');
const replaced = await resume(rewritten);
assert.equal(replaced.reset, true);
assert.equal(replaced.offset, 0);
await fs.truncate(file, 0);
const empty = await resume(replaced);
assert.equal(empty.reset, true);
assert.equal(empty.nextOffset, 0);
await fs.appendFile(file, '新的第一行\n');
assert.equal((await resume(empty)).content, '新的第一行\n');
});
+5 -1
View File
@@ -30,6 +30,7 @@ for (const conflict of ['stop', 'newer-queue', 'stop-requeue']) {
pid: DataTypes.INTEGER,
log_path: DataTypes.STRING,
queued_token: DataTypes.STRING,
last_execution_time: DataTypes.INTEGER,
command: DataTypes.STRING,
});
const instances = db.define('Instance', {
@@ -38,6 +39,7 @@ for (const conflict of ['stop', 'newer-queue', 'stop-requeue']) {
pid: DataTypes.INTEGER,
});
await db.sync();
await db.transaction((tx) => require('../../back/shared/triggerHistory').installTriggerHistory(db, tx));
await crons.create({
id: 1,
status: 3,
@@ -110,7 +112,7 @@ for (const conflict of ['stop', 'newer-queue', 'stop-requeue']) {
await service.stop([1]);
// Queue again through the real API; leave the new runner pending.
const pendingRuns = [];
service.runSingle = (id, token) => pendingRuns.push({ id, token });
service.runSingle = async (id, token) => pendingRuns.push({ id, token });
await service.run([1]);
assert.equal(pendingRuns.length, 1);
assert.equal(
@@ -171,8 +173,10 @@ test('a runner waiting for a concurrency slot cannot adopt a newer queued genera
pid: DataTypes.INTEGER,
log_path: DataTypes.STRING,
queued_token: DataTypes.STRING,
last_execution_time: DataTypes.INTEGER,
});
await db.sync();
await db.transaction((tx) => require('../../back/shared/triggerHistory').installTriggerHistory(db, tx));
await crons.create({ id: 1, status: 1, log_path: 'same.log' });
const waiting = [];
const CronService = load('back/services/cron.ts', {
+2 -1
View File
@@ -37,7 +37,7 @@ async function packageFixture(t) {
const lock = 'lockfileVersion: 6.0\n';
await fs.writeFile(path.join(root, 'pnpm-lock.yaml'), lock);
const files = {};
for (const name of ['build/app.js', 'build/token.js', 'build/bootstrap/upgradeProbe.js', 'dist/index.html', 'build/app.js.map', 'dist/app.js.gz']) {
for (const name of ['build/app.js', 'build/token.js', 'build/shared/managedExit.cjs', 'build/bootstrap/upgradeProbe.js', 'dist/index.html', 'build/app.js.map', 'dist/app.js.gz']) {
const bytes = name.endsWith('.html') ? '<html>pack fixture</html>' : '{}';
await fs.mkdir(path.dirname(path.join(root, 'static', name)), { recursive: true });
await fs.writeFile(path.join(root, 'static', name), bytes);
@@ -69,6 +69,7 @@ test('real npm pack excludes local state and its installed lifecycle restores ve
checkPackedFiles(archive.files);
const names = new Set(archive.files.map((file) => file.path));
assert.ok(names.has('shell/upgrade-lock.yaml'));
assert.ok(names.has('shell/subscription-files.py'));
for (const name of Object.keys(files)) assert.ok(names.has('static/' + name));
await assert.rejects(fs.access(path.join(root, 'shell/upgrade-lock.yaml')), { code: 'ENOENT' });
const prefix = path.join(temp, 'installed');
+15
View File
@@ -241,6 +241,21 @@ test('failed download persists its failure without stopping the panel and can be
assert.equal((await finished(f.tmp)).status, 'ready');
});
test('a terminal state published between the status read and PID probe wins', async (t) => {
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-finished-job-'));
t.after(() => fs.rm(tmp, { recursive: true, force: true }));
const file = path.join(tmp, 'panel-upgrade.json');
const running = { id: 'finishing', status: 'running', pid: 123456, startedAt: 1 };
await fs.writeFile(file, JSON.stringify(running));
const kill = process.kill;
t.mock.method(process, 'kill', (pid, signal) => {
if (pid !== running.pid || signal !== 0) return kill(pid, signal);
syncFs.writeFileSync(file, JSON.stringify({ ...running, status: 'ready' }));
throw Object.assign(new Error('worker exited'), { code: 'ESRCH' });
});
assert.equal((await getStatus(tmp)).status, 'ready');
});
test('orphaned jobs become retryable and status log reads are bounded', async (t) => {
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-orphan-job-'));
t.after(() => fs.rm(tmp, { recursive: true, force: true }));
+85
View File
@@ -166,3 +166,88 @@ os.environ['NOTIFY_READY'] = '1'
assert QLAPI.notify('retry') == ('retry',)
`);
});
for (const extension of ['js', 'mjs', 'py']) {
test(`the ${extension} entry marker appears after hooks and before the first user instruction`, (t) => {
const f = fixture(t, extension === 'py' ? 'python' : 'javascript');
const marker = path.join(f.root, 'started');
f.env.QL_SCRIPT_START_FILE = marker;
f.env.QL_SCRIPT_ENTRY = path.join(fs.realpathSync(f.root), 'entry.' + extension);
fs.copyFileSync('shell/preload/script-start.cjs', path.join(f.root, 'script-start.cjs'));
f.write('before.sh', 'test ! -e "$QL_SCRIPT_START_FILE" && touch "$dir_scripts/hook-ran"\n');
const read = "const stamp = Number(fs.readFileSync(process.env.QL_SCRIPT_START_FILE, 'utf8'));";
const check = "if (!Number.isSafeInteger(stamp) || stamp <= 0 || stamp > Date.now()) throw Error('invalid entry timestamp');";
if (extension === 'py') {
f.run("assert 0 < int(open(__import__('os').environ['QL_SCRIPT_START_FILE']).read()) <= __import__('time').time_ns() // 1000000\n");
} else if (extension === 'mjs') {
f.write('dependency.mjs', "import fs from 'node:fs'; if (fs.existsSync(process.env.QL_SCRIPT_START_FILE)) throw Error('entry reported during dependency evaluation');");
f.run("import './dependency.mjs';\nimport fs from 'node:fs';\n" + read + check, extension);
} else {
f.run("const fs = require('node:fs'); " + read + check);
}
assert.ok(fs.existsSync(path.join(f.root, 'hook-ran')));
});
}
test('the panel client defers gRPC until an API call, uses panel dependencies and shares one channel', (t) => {
const f = fixture(t, 'javascript');
f.env.QL_DIR = f.root;
f.env.QL_NODE_GLOBAL_PATH = path.join(f.root, 'global');
fs.copyFileSync('shell/preload/client.js', path.join(f.root, 'client.js'));
function packageFile(base, name, source) {
const dir = path.join(base, 'node_modules', name);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'index.js'), source);
}
packageFile(f.env.QL_NODE_GLOBAL_PATH, '@grpc/grpc-js', 'exports.fromGlobal = true;');
packageFile(f.root, '@grpc/proto-loader', `
exports.loadSync = () => {
if (process.env.FAIL_PROTO === '1') throw Error('missing proto');
return {};
};
`);
packageFile(f.root, '@grpc/grpc-js', `
global.grpcLoads = (global.grpcLoads || 0) + 1;
exports.credentials = { createInsecure: () => ({}) };
exports.Metadata = class {};
class Api {
constructor() { global.channels = (global.channels || 0) + 1; }
GetEnvs(params, metadata, options, callback) { callback(null, params); }
close() { global.closes = (global.closes || 0) + 1; }
}
exports.loadPackageDefinition = () => ({com: { ql: { api: {Api} }}});
`);
f.run(`
const assert = require('node:assert/strict');
(async () => {
assert.equal(global.grpcLoads, undefined);
assert.equal(require('@grpc/grpc-js').fromGlobal, true);
const { getEnvs } = QLAPI;
assert.deepEqual(await Promise.all([getEnvs({n:1}), getEnvs({n:2})]), [{n:1},{n:2}]);
assert.equal(global.grpcLoads, 1);
assert.equal(global.channels, 1);
QLAPI.close(); QLAPI.close();
assert.equal(global.closes, 1);
await assert.rejects(getEnvs(), /Channel has been shut down/);
})().catch(error => { console.error(error); process.exitCode = 1; });
`);
f.run(`
const assert = require('node:assert/strict');
(async () => {
process.env.FAIL_PROTO = '1';
await assert.rejects(QLAPI.getEnvs(), /missing proto/);
assert.equal(global.channels, undefined);
delete process.env.FAIL_PROTO;
assert.deepEqual(await QLAPI.getEnvs(), {});
assert.equal(global.channels, 1);
QLAPI.close();
})().catch(error => { console.error(error); process.exitCode = 1; });
`);
f.run(`
const assert = require('node:assert/strict');
QLAPI.close();
assert.rejects(QLAPI.getEnvs(), /Channel has been shut down/)
.then(() => assert.equal(global.grpcLoads, undefined))
.catch(error => { console.error(error); process.exitCode = 1; });
`);
});
+1 -1
View File
@@ -13,7 +13,7 @@ test('container APM policy keeps worker isolation and can restore all inherited
const env={QL_CONTAINER:'true',QL_PRIMARY_APM:primary,QL_WORKER_APM:workers};
const conf=config(env);env.pm_id='0';env.pmx=String(conf.pmx);
const calls=[],module={exports:{}};
vm.runInNewContext(compiled,{module,exports:module.exports,process:{env},require(name){if(name==='cluster')return {fork(options){calls.push({...env,...options});return {id:1,process:{pid:123}}}};if(name==='express')return ()=>({use(){}});return {};}});
vm.runInNewContext(compiled,{module,exports:module.exports,process:{env},require(name){if(name==='cluster')return {fork(options){calls.push({...env,...options});return {id:1,process:{pid:123},on(){}}}};if(name==='express')return ()=>({use(){}});return {};}});
new module.exports().forkWorker('http');
assert.equal(conf.pmx,primary==='true');
assert.equal(calls[0].pmx,primary==='true'&&workers==='true'?'true':'false');
+80 -3
View File
@@ -2,9 +2,44 @@ const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const ts = require('typescript');
const load = require('../helpers/load-security-module.cjs');
test('BSD identity and parent lookups distinguish a vanished PID from ps failures', () => {
const platform = Object.getOwnPropertyDescriptor(process, 'platform');
const pid = process.pid;
let result, field;
const probes = load('back/shared/cronProcess.ts', {
child_process: { spawnSync(command, args) {
assert.equal(command, 'ps');
assert.deepEqual(args, ['-p', String(pid), '-o', field + '=']);
return result;
} },
});
Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' });
try {
for (const [name, probe] of [
['lstart', () => probes.systemOwner(pid)],
['ppid', () => probes.isProcessDescendant(pid, 1)],
]) {
field = name;
result = { status: 1, stdout: '', stderr: '' };
assert.throws(probe, { code: 'ESRCH' });
for (result of [
{ status: 1, stdout: '', stderr: 'Permission denied' },
{ status: 0, stdout: '', stderr: '' },
{ status: null, signal: 'SIGTERM', stdout: '', stderr: '' },
{ error: Object.assign(Error('spawn ps ENOENT'), { code: 'ENOENT' }) },
]) {
assert.throws(probe, error => !['ESRCH', 'ENOENT'].includes(error.code) && /ps|PID/.test(error.message));
}
}
} finally {
Object.defineProperty(process, 'platform', platform);
}
});
// Exercise the production function with a deterministic process-tree race.
function fixture(descendants, probe = () => {}) {
function fixture(descendants, probe = () => {}, birth, descendant) {
const source = fs.readFileSync('back/config/util.ts', 'utf8');
const start = source.indexOf('export async function killTask(');
const end = source.indexOf('export async function getPid(', start);
@@ -16,7 +51,7 @@ function fixture(descendants, probe = () => {}) {
}).outputText;
const signals = [];
const exports = {};
new Function('exports', 'process', 'psTree', 'fs', 'setTimeout', code)(
new Function('exports', 'process', 'psTree', 'fs', 'setTimeout', 'systemOwner', 'isProcessDescendant', code)(
exports,
{
platform: 'linux',
@@ -28,7 +63,7 @@ function fixture(descendants, probe = () => {}) {
},
async () => [...descendants],
{},
setTimeout,
setTimeout, birth, descendant,
);
return { killTask: exports.killTask, signals };
}
@@ -75,3 +110,45 @@ test('a leaf retains SIGINT and a process tree retains child-first SIGTERM', asy
[100, 'SIGTERM'],
]);
});
test('verified stop ignores reused, vanished and reparented descendants from the tree snapshot', async () => {
const seen = new Set();
let rootExited = false;
const birth = pid => {
if (pid === 102 || (pid === 100 && rootExited)) throw Object.assign(Error('gone'), { code: 'ESRCH' });
if (pid === 101 && seen.has(pid)) return 'replacement';
seen.add(pid);
return 'original-' + pid;
};
const f = fixture([101, 102, 103], (pid, sig) => {
if (pid === 100 && sig === 'SIGTERM') rootExited = true;
}, birth, pid => pid !== 103);
await f.killTask(100, true, () => {}, async signal => signal());
assert.deepEqual(f.signals, [[100, 'SIGTERM']]);
});
test('a root exiting immediately before TERM cannot claim a stop or signal a surviving child', async () => {
const f = fixture([101], (pid, sig) => {
if (pid === 100 && sig === 'SIGTERM') throw Object.assign(Error('gone'), { code: 'ESRCH' });
}, pid => 'birth-' + pid, () => true);
let committed = false;
await assert.rejects(f.killTask(100, true, () => {}, async signal => {
signal();
committed = true;
}), { code: 'ESRCH' });
assert.equal(committed, false);
assert.deepEqual(f.signals, [[100, 'SIGTERM']]);
});
test('a descendant delivery failure after root TERM preserves the claim and still signals siblings', async () => {
const denied = Object.assign(Error('denied'), { code: 'EPERM' });
const f = fixture([101, 102], (pid, signal) => {
if (pid === 102 && signal === 'SIGTERM') throw denied;
}, pid => 'birth-' + pid, () => true);
await assert.rejects(f.killTask(100, true, () => {}, async signal => {
const delivery = signal();
assert.equal(delivery, denied);
throw delivery;
}), error => error === denied);
assert.deepEqual(f.signals, [[100, 'SIGTERM'], [102, 'SIGTERM'], [101, 'SIGTERM']]);
});
+18 -4
View File
@@ -10,19 +10,31 @@ test('startup closes interrupted instances without inventing exit codes or rewri
logging: false,
});
t.after(() => db.close());
const instances = db.define('Instance', {
const instances = db.define('RunningInstance', {
cron_id: DataTypes.INTEGER,
pid: DataTypes.INTEGER,
log_path: DataTypes.TEXT,
status: DataTypes.INTEGER,
started_at: DataTypes.INTEGER,
finished_at: DataTypes.INTEGER,
exit_code: DataTypes.INTEGER,
});
const crons = db.define('Crontab', { status: DataTypes.INTEGER, pid: DataTypes.INTEGER, queued_token: DataTypes.STRING, command: DataTypes.STRING });
await db.sync();
await db.transaction(tx => require('../../back/shared/triggerHistory').installTriggerHistory(db, tx));
await instances.bulkCreate([
{ id: 1, status: 0, started_at: 100 },
{ id: 2, status: 1, started_at: 100, finished_at: 110, exit_code: 0 },
{ id: 3, status: 2, started_at: 100, finished_at: 120, exit_code: 143 },
{ id: 4, status: 3, started_at: 100, finished_at: 130, exit_code: 7 },
]);
const {TriggerHistory, systemOwner} = require('../../back/shared/triggerHistory');
const history = new TriggerHistory(db);
await crons.create({id: 9, status: 0, pid: process.pid, command: 'task live.sh'});
await instances.create({id: 9, status: 0, started_at: 100});
await db.query("INSERT INTO CronTriggers(id,cron_id,source,state,owner,instance_id,observed_at) VALUES ('live',9,'system','running',$owner,9,100)",
{bind:{owner:systemOwner(process.pid)}});
await history.interrupt('http');
const systemConfig = { info: { lang: 'en-US' } };
const startupEvents = [];
const service = {
@@ -40,7 +52,7 @@ test('startup closes interrupted instances without inventing exit codes or rewri
'../services/user': class {},
'../services/open': class {},
'../data/cron': {
CrontabModel: { update: async () => {}, findAll: async () => [] },
CrontabModel: { sequelize: db, update: async () => {}, findAll: async () => [] },
CrontabStatus: { idle: 1 },
},
'../data/dependence': {
@@ -87,7 +99,9 @@ test('startup closes interrupted instances without inventing exit codes or rewri
global.setTimeout = originalTimeout;
}
assert.deepEqual(startupEvents, ['environment', 'scheduler']);
const rows = await instances.findAll({ order: [['id', 'ASC']], raw: true });
assert.equal((await instances.findByPk(9)).status,0);
assert.equal((await crons.findByPk(9)).pid,process.pid);
const rows = await instances.findAll({ where:{id:[1,2,3,4]}, order: [['id', 'ASC']], raw: true });
assert.equal(rows[0].status, 2);
assert.ok(
rows[0].finished_at >= before &&
@@ -118,7 +132,7 @@ test('startup closes interrupted instances without inventing exit codes or rewri
'environment', 'scheduler', 'environment', 'scheduler',
]);
assert.deepEqual(
await instances.findAll({ order: [['id', 'ASC']], raw: true }),
await instances.findAll({ where:{id:[1,2,3,4]}, order: [['id', 'ASC']], raw: true }),
rows,
);
});
+10
View File
@@ -47,6 +47,12 @@ test('cleanup previews first, protects running instances, and uses explicit opti
await fs.writeFile(path.join(nodeCache, 'cache'), Buffer.alloc(13));
const config = require('../../back/config').default;
const originalDataDir = process.env.QL_DATA_DIR;
process.env.QL_DATA_DIR = directory;
t.after(() => {
if (originalDataDir === undefined) delete process.env.QL_DATA_DIR;
else process.env.QL_DATA_DIR = originalDataDir;
});
const originalCachePath = config.dependenceCachePath;
const RunningInstanceModel = {};
const CrontabStatModel = {};
@@ -101,6 +107,8 @@ test('cleanup previews first, protects running instances, and uses explicit opti
CrontabStatModel.destroy = async () => 3;
sequelize.transaction = async (callback) => callback({});
sequelize.query = async (query) => {
if (query.startsWith('SELECT COUNT(*) AS count FROM CronTriggers')) return [{count: 4}];
if (query.startsWith('DELETE FROM CronTriggers')) return 4;
vacuumed = query === 'VACUUM';
return [];
};
@@ -110,6 +118,7 @@ test('cleanup previews first, protects running instances, and uses explicit opti
runningInstanceRetentionDays: 0,
cronStatRetentionDays: 0,
});
assert.equal(disabledPreview.triggers, 0);
assert.equal(disabledPreview.runningInstances, 0);
assert.equal(disabledPreview.cronStats, 0);
assert.equal(instanceCountCalls, 0);
@@ -123,6 +132,7 @@ test('cleanup previews first, protects running instances, and uses explicit opti
});
assert.equal(instanceWhere.status[Op.ne], InstanceStatus.running);
assert.equal(result.deleted.triggers, 4);
assert.equal(result.deleted.runningInstances, 2);
assert.equal(result.deleted.cronStats, 3);
assert.equal(result.deleted.dependenceCacheBytes, 13);
+1 -2
View File
@@ -90,8 +90,7 @@ async function rpcFixture(t) {
'../config/grpcCerts': { initGrpcCerts: async () => certs },
'../loaders/logger': logger,
'./metrics': { metricsService: { record() {} } },
'../schedule/addCron': {},
'../schedule/delCron': {},
'../schedule/registeredPlans': {},
'../schedule/api': {},
'../schedule/health': { check: (_call, cb) => cb(null, { status: 1 }) },
'../schedule/setConcurrency': handler,
+7 -2
View File
@@ -42,6 +42,7 @@ async function fixture(t) {
});
const jobs = new Map();
const client = {
readiness: { invalidate() {} },
addCron: async (items, replace) => {
if (replace) jobs.clear();
items.forEach((item) => jobs.set(item.id, item.command));
@@ -178,12 +179,14 @@ for (const operation of ['create', 'update', 'enabled']) {
await assert.rejects(
mutation,
(err) =>
err.status === 503 && err.cause === cause && /回滚/.test(err.message),
err.status === 503 && err.cause === cause &&
(operation === 'update' ? /原调度未能恢复/ : /回滚/).test(err.message),
);
if (operation === 'create') assert.equal(await crons.count(), 0);
else {
const row = await crons.findByPk(1);
assert.equal(row.command, 'old');
if (operation === 'update') assert.equal(row.saved, false);
assert.equal(row.isDisabled, operation === 'enabled' ? 1 : 0);
}
client.addCron = async () => {};
@@ -257,6 +260,8 @@ for (const operation of ['update', 'remove', 'disabled']) {
id: 1, command: 'old', schedule: '* * * * *', isDisabled: 0,
});
jobs.set('1', 'old');
// Only a handoff out of Node needs a deletion RPC before the DB write.
if (operation === 'update') service.shouldUseCronClient = row => row.schedule !== '@once';
const before = await crons.findAll({ raw: true });
const failure = Object.assign(Error('uncertain deletion'), { code, status: 503 });
let deletes = 0;
@@ -270,7 +275,7 @@ for (const operation of ['update', 'remove', 'disabled']) {
service.setCrontab = async () => assert.fail('must not publish after failed deletion');
await assert.rejects(
operation === 'update'
? service.update({ id: 1, command: 'new' })
? service.update({ id: 1, command: 'new', schedule: '@once' })
: service[operation]([1]),
(error) => error === failure && error.status === 503,
);
@@ -25,6 +25,7 @@ function fixture(client) {
);
const service = new module.exports();
service.setCrontab = async () => {};
service.markSchedulesSaved = async () => {};
service.logger = { warn() {} };
service.shouldUseCronClient = () => true;
service.makeCommand = () => 'true';
+131 -2
View File
@@ -3,7 +3,7 @@ const test = require('node:test');
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const { Sequelize, DataTypes, QueryTypes } = require('sequelize');
const { Sequelize, DataTypes, QueryTypes, Transaction } = require('sequelize');
const { migrateSchema } = require('../../back/shared/schemaMigrations');
const load = require('../helpers/load-security-module.cjs');
@@ -12,6 +12,7 @@ async function createLegacy(storage = ':memory:', omitEnvs = false) {
dialect: 'sqlite',
storage,
logging: false,
transactionType: Transaction.TYPES.IMMEDIATE,
});
for (const table of [
'CrontabViews',
@@ -26,6 +27,11 @@ async function createLegacy(storage = ':memory:', omitEnvs = false) {
await database.query(
'INSERT INTO "Crontabs" (id, name) VALUES (1, \'keep-me\')',
);
await database.query('ALTER TABLE Crontabs ADD COLUMN last_execution_time INTEGER');
await database.query('ALTER TABLE Crontabs ADD COLUMN last_running_time INTEGER');
load('back/data/runningInstance.ts', { '.': { sequelize: database } });
load('back/data/cronStats.ts', { '.': { sequelize: database } });
await database.sync();
return database;
}
@@ -43,7 +49,11 @@ test('legacy database upgrades without losing rows and repeated migration is ide
const applied = await database.query('SELECT id FROM "SchemaMigrations"', {
type: QueryTypes.SELECT,
});
assert.equal(applied.length, 15);
assert.equal(applied.length, 27);
assert.ok(Object.hasOwn(await database.getQueryInterface().describeTable('CrontabStats'), 'fixed_max_time'));
assert.equal(rows[0].last_instance_id, null);
assert.equal(rows[0].catchup_seconds, null);
assert.equal(rows[0].max_queue_wait, null);
});
test('migration repairs malformed environment labels before ORM reads', async (t) => {
@@ -158,3 +168,122 @@ test('database loader rejects initialization failure rather than allowing worker
const initialize = load(path.resolve('back/loaders/db.ts'), mocks).default;
await assert.rejects(initialize(), /SQLITE_FULL/);
});
test('upgrading stop batches preserves completed and pending idempotency bindings', async t => {
const database = await createLegacy();
t.after(() => database.close());
await database.query('CREATE TABLE CronStopBatches (request_id TEXT PRIMARY KEY,cron_ids TEXT NOT NULL,snapshot TEXT)');
await database.query("INSERT INTO CronStopBatches VALUES ('done','[1]',NULL),('retry','[2]','{}')");
await migrateSchema(database);
await migrateSchema(database);
const rows = await database.query('SELECT request_id,cron_ids,snapshot,status_code FROM CronStopBatches ORDER BY request_id',
{ type: QueryTypes.SELECT });
assert.deepEqual(rows, [
{ request_id: 'done', cron_ids: '[1]', snapshot: null, status_code: 200 },
{ request_id: 'retry', cron_ids: '[2]', snapshot: '{}', status_code: 200 },
]);
});
test('upgrade preserves an already pruned bound booking when its canonical file was reclaimed before restart', async t => {
const database = await createLegacy();
t.after(() => database.close());
await migrateSchema(database);
// Previous panel committed both bookings, then removed the files. An
// unbound result by itself cannot authenticate a later versioned receipt.
await database.query("DELETE FROM SchemaMigrations WHERE id='preserve-pruned-bound-exits-v1'");
await database.query(`INSERT INTO CronLegacyExitBookings(trigger_id,cron_id,source,started_at,finished_at,outcome,day,bound)
VALUES ('bound-before-upgrade',1,'manual',1000,2000,'31','1970-01-01',1),
('legacy-before-upgrade',1,'manual',1000,2000,'0','1970-01-01',0)`);
await migrateSchema(database);
await database.query('DELETE FROM CronLegacyExitBookings');
await migrateSchema(database);
assert.deepEqual(await database.query('SELECT trigger_id,outcome,finished_at FROM CronUnmatchedBoundExits',
{ type: QueryTypes.SELECT }), [{trigger_id:'bound-before-upgrade', outcome:'31', finished_at:2000}]);
assert.deepEqual(await database.query('SELECT * FROM CrontabStats', { type: QueryTypes.SELECT }), []);
});
for (const committed of [false, true]) {
test('pruned booking evidence and its marker survive cleanup after migration ' +
(committed ? 'commit' : 'rollback'), async t => {
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-migration-cut-'));
const previousDataDir = process.env.QL_DATA_DIR;
process.env.QL_DATA_DIR = directory;
await fs.mkdir(path.join(directory, 'db'));
await fs.writeFile(path.join(directory, '.env'), '');
const db = await createLegacy(path.join(directory, 'db/database.sqlite'));
t.after(async () => {
if (previousDataDir === undefined) delete process.env.QL_DATA_DIR;
else process.env.QL_DATA_DIR = previousDataDir;
await db.close();
await fs.rm(directory, { recursive: true, force: true });
});
await migrateSchema(db);
const marker = 'preserve-pruned-bound-exits-v1', id = 'old-bound';
const select = sql => db.query(sql, { type: QueryTypes.SELECT });
const late = Date.now();
const retainedDay = require('dayjs')(late).format('YYYY-MM-DD');
const stats = db.models.CrontabStat;
const expired = await stats.create({ ref_id: 1, date: '1970-01-01', run_count: 1, fail_count: 1, total_time: 1000, max_time: 1000 });
await stats.create({ ref_id: 1, date: retainedDay, run_count: 1, success_count: 1, total_time: 333, max_time: 333 });
const daily = () => select('SELECT date,run_count,success_count,fail_count,total_time,max_time FROM CrontabStats ORDER BY date');
const sibling = { date: retainedDay, run_count: 1, success_count: 1, fail_count: 0, total_time: 333, max_time: 333 };
await db.query('DELETE FROM SchemaMigrations WHERE id=$marker', { bind: { marker } });
await db.query(`INSERT INTO CronLegacyExitBookings(trigger_id,cron_id,source,started_at,finished_at,outcome,day,bound,stat_id)
VALUES ($id,1,'manual',1000,2000,'31','1970-01-01',1,$stat)`, { bind: { id, stat: expired.id } });
const side = committed ? 'after' : 'before';
const gate = path.join(directory, 'checkpoint');
const worker = require('node:child_process').spawn(process.execPath, [
'-r', 'ts-node/register/transpile-only', require.resolve('../helpers/receipt-migration-worker.cjs'),
path.resolve(__dirname, '../../back'), side, gate,
], { env: { ...process.env, QL_DIR: directory }, stdio: ['ignore', 'ignore', 'pipe'] });
let errorOutput = '';
worker.stderr.on('data', data => { errorOutput += data; });
const closed = require('node:events').once(worker, 'close');
try {
const deadline = Date.now() + 30000;
while (!require('node:fs').existsSync(gate)) {
assert.ok(worker.exitCode === null && worker.signalCode === null && Date.now() < deadline,
'Migration worker failed to reach COMMIT boundary: ' + errorOutput);
await new Promise(resolve => setTimeout(resolve, 25));
}
const checkpoint = JSON.parse(await fs.readFile(gate, 'utf8'));
assert.deepEqual(checkpoint, { side, pid: worker.pid, marker: 1, proofs: 1 });
// Observe from the parent's independent connection while the writer is still frozen.
assert.equal((await select('SELECT trigger_id FROM CronUnmatchedBoundExits')).length, Number(committed));
} finally {
worker.kill('SIGKILL');
await closed;
}
const proof = () => select('SELECT trigger_id,outcome,finished_at FROM CronUnmatchedBoundExits');
const expected = [{trigger_id:id, outcome:'31', finished_at:2000}];
assert.deepEqual(await proof(), committed ? expected : []);
assert.equal((await select("SELECT id FROM SchemaMigrations WHERE id='preserve-pruned-bound-exits-v1'")).length, +committed);
const policy = new (load('back/services/retention.ts', {
'../data': { sequelize: db }, '../data/cronStats': { CrontabStatModel: db.models.CrontabStat },
'../data/runningInstance': { RunningInstanceModel: db.models.RunningInstance, InstanceStatus: { running: 0 } },
'../data/system': {}, '../config': {},
}).default)();
const clean = () => policy.cleanup({ runningInstanceRetentionDays: 0, cronStatRetentionDays: 1 });
await clean(); // This writer acquires the lock before the migration retry.
assert.deepEqual(await daily(), [sibling]);
assert.deepEqual(await select('SELECT trigger_id FROM CronLegacyExitBookings'), committed ? [] : [{trigger_id:id}]);
await migrateSchema(db);
await clean();
await migrateSchema(db);
assert.deepEqual(await proof(), expected);
assert.deepEqual(await select('SELECT trigger_id FROM CronLegacyExitBookings'), []);
const { writeExit } = require('../../back/shared/managedExit.cjs');
const { TriggerHistory } = require('../../back/shared/triggerHistory');
const history = new TriggerHistory(db);
writeExit(id, 0, null, late);
await history.retryPendingExits();
writeExit(id, 31, null, 2000);
await Promise.all([clean(), history.retryPendingExits()]);
await history.interrupt('http');
assert.deepEqual(await select('SELECT outcome,finished_at FROM CronBoundExitConflicts ORDER BY finished_at'),
[{outcome: '31', finished_at: 2000}, {outcome: '0', finished_at: late}]);
assert.deepEqual(await daily(), [sibling]);
assert.deepEqual(await select('SELECT id FROM CronTriggers'), []);
});
}
+47
View File
@@ -182,3 +182,50 @@ test('success-shaped invalid documents retain the raw-response error fallback',
}
assert.equal(f.count(), cases.length * 2);
});
test('Shell retries the same identified receipt after a timeout and starts the next run with a fresh ID', t => {
const f = fixture(t);
const result = f.run(`
ID=7; unset QL_TRIGGER_ID
curl() {
while [[ $1 != --data-raw ]]; do shift; done
printf '%s\n' "$2" >> "$RESPONSE_FILE"
if [[ ! -e $RESPONSE_FILE.pending ]]; then touch "$RESPONSE_FILE.pending"; return 28; fi
rm "$RESPONSE_FILE.pending"; printf '{"code":200}'
}
for execution in 1 2; do
init_execution_id
update_cron 7 0 "$$" same.log 100
update_cron 7 1 "$$" same.log 100 1 5
record_cron_stat 7 5 1
done
`);
assert.equal(result.status, 0, result.stderr);
const lines = fs.readFileSync(f.response, 'utf8').trim().split('\n');
assert.equal(lines.length, 12);
for (let i = 0; i < lines.length; i += 2) assert.equal(lines[i], lines[i+1]);
const ids = lines.map(line => JSON.parse(line).execution_id);
assert.match(ids[0], /^client-[0-9a-f-]{36}$/);
assert.ok(ids.slice(0, 6).every(id => id === ids[0]));
assert.ok(ids.slice(6).every(id => id === ids[6]));
assert.notEqual(ids[0], ids[6]);
});
test('a standalone shell reuses the observed end for both receipts, including timeout retries', t => {
const f = fixture(t);
const result = f.run([
'ql_execution_id="client-123"; directory=$(dirname "$RESPONSE_FILE");',
'ql_api_request() {',
' local arg; for arg in "$@"; do case "$arg" in "X-QL-Finished-At:"*) printf "%s\\n" "$arg" >> "$directory/headers";; esac; done;',
' if [[ ! -e "$directory/retried" ]]; then touch "$directory/retried"; return 28; fi;',
' printf \'{"code":200}\';',
'}',
'update_cron 5 0 501 task.log 1700000000;',
'rm -f "$directory/retried";',
'update_cron 5 1 501 task.log 1700000000 60 17 1700000060;',
'record_cron_stat 5 17 60 1700000060;',
'cat "$directory/headers";',
].join('\n'));
assert.equal(result.status,0,result.stderr);
assert.deepEqual(result.stdout.trim().split('\n'),Array(3).fill('X-QL-Finished-At: 1700000060000'));
});
+49 -7
View File
@@ -54,13 +54,14 @@ for (const [label, args] of [
f.write(`shell/${name}`, source(`shell/${name}`));
f.write(
'shell/api.sh',
'update_cron(){ :; }; record_cron_stat(){ :; }\n',
extract('shell/api.sh', 'init_execution_id') + '\nupdate_cron(){ :; }; record_cron_stat(){ :; }\n',
);
f.write('shell/preload/env.sh', 'export QA_PANEL="one&two"\n');
f.write('shell/preload/sitecustomize.js', '// fixture preloader\n');
// An unreaped watchdog outlives the fixture's 15-second process timeout.
f.write(
'data/config/config.sh',
'DefaultCronRule="0 0 * * *"\nCommandTimeoutTime="2s"\n',
'DefaultCronRule="0 0 * * *"\nCommandTimeoutTime="30s"\n',
);
f.write('data/config/task_before.sh', 'printf "BEFORE\\n"\n');
f.write('data/config/task_after.sh', 'printf "AFTER\\n"\n');
@@ -74,7 +75,6 @@ for (const [label, args] of [
'data/scripts/nested folder/probe [1] $name.js',
'console.log("ARG=" + process.argv[2]);\n',
);
const started = Date.now();
const result = f.run(
'exec "$QA_BASH" "$QL_DIR/shell/task.sh" "$@"',
{
@@ -90,12 +90,9 @@ for (const [label, args] of [
},
[...args, literal],
);
assert.ifError(result.error);
assert.equal(result.status, 0, result.stderr);
assert.equal(result.stderr, '');
assert.ok(
Date.now() - started < 1800,
'completion must not wait for the two-second watchdog',
);
const log = fs.readFileSync(
path.join(f.root, 'data/log/literal [log] $name.log'),
'utf8',
@@ -353,6 +350,7 @@ for (const fail of [false, true]) {
exit "$result"`,
].join('\n'),
{
dir_shell: path.resolve('shell'),
dir_raw: path.join(f.root, 'raw'),
dir_scripts: path.join(f.root, 'scripts'),
list_crontab_user: path.join(f.root, 'crontab.list'),
@@ -558,3 +556,47 @@ for (const version of ['2.23.0', '2.23.0-beta.1+build.2', 'invalid']) {
}
});
}
test('ql extra propagates a sourced script failure through every logging mode', t => {
const f = fixture(t);
f.write('shell/update.sh', source('shell/update.sh'));
f.write('shell/env.sh', '');
f.write('shell/share.sh', [
'load_ql_envs() { :; }; import_config() { :; }; make_dir() { mkdir -p "$1"; }',
't() { :; }; format_timestamp() { echo 1; }; format_time() { echo now; }',
].join('\n'));
f.write('shell/api.sh', [
extract('shell/api.sh', 'init_execution_id'),
'update_cron() { echo "status:$2:${7:-}" >> "$QL_DIR/records"; }',
'record_cron_stat() { echo "stat:$2" >> "$QL_DIR/records"; }',
].join('\n'));
for (const [real_time, no_tee] of [['false','false'], ['false','true'], ['true','false']]) {
for (const [script, code] of [['return 17', 17], ['exit 17', 17], ['return 0', 0],
['false | true', 0], ['set -o pipefail; false | true', 1]]) {
f.write('records', '');
const result = f.run('exec "$QA_BASH" "$QL_DIR/shell/update.sh" extra', {
QA_BASH: bash, QL_DIR: f.root, ID: '42', real_time, no_tee,
dir_log: path.join(f.root, 'log'), file_extra_shell: f.write('extra.sh', script),
});
assert.equal(result.status, code, result.stderr);
assert.equal(fs.readFileSync(path.join(f.root, 'records'), 'utf8'),
`status:0:\nstatus:1:${code}\nstat:${code}\n`);
}
}
});
test('raw sync recognizes the exact quoted operand in a wrapped crontab across repeated downloads', t => {
const f = fixture(t), file = "raw_owner_what's new.js";
const { shellQuote } = require('../../back/shared/shellQuote');
f.write('raw/.keep', ''); f.write('scripts/.keep', '');
f.write('crontab.list', '1 * * * * ID=7 QL_TRIGGER_SOURCE=system bash "$QL_DIR/shell/system-cron.sh" ' +
shellQuote('QL_CRON_REVISION=10 real_time=false ID=7 task ' + shellQuote(file)) + '\n');
const result = f.run([extract('shell/update.sh', 'update_raw'), 't(){ :; }; set_proxy(){ :; }; unset_proxy(){ :; }',
'wget(){ printf "body" > "$4"; }; add_cron(){ exit 55; }',
'update_raw https://fixture.invalid/script.js "" true false'].join('\n'), {
dir_shell: path.resolve('shell'), dir_raw: path.join(f.root, 'raw'), dir_scripts: path.join(f.root, 'scripts'),
list_crontab_user: path.join(f.root, 'crontab.list'), cmd_task: 'task', uniq_path: "owner_what's new",
});
assert.equal(result.status, 0, result.stderr);
assert.equal(fs.readFileSync(path.join(f.root, 'scripts', file), 'utf8'), 'body');
});
+2 -1
View File
@@ -112,7 +112,8 @@ function runCallback(endpoint, scenario) {
ENDPOINT: endpoint, ql_port: '5700' },
encoding: 'utf8', timeout: 10_000,
});
assert.equal(child.status, 0, child.stderr);
const denied = ['persistent', 'forbidden', 'unavailable'].includes(scenario);
assert.equal(child.status, denied && ['add', 'delete'].includes(endpoint) ? 1 : 0, child.stderr);
assert.equal(child.stderr, '');
const lines = fs.readFileSync(path.join(directory, 'requests'), 'utf8').trim().split('\n');
const refreshes = lines.filter((line) => line === 'refresh').length;
+198 -7
View File
@@ -14,23 +14,28 @@ async function fixture(t, onKill = async () => {}) {
logging: false,
});
t.after(() => db.close());
const crons = db.define('Cron', {
const crons = db.define('Crontab', {
command: DataTypes.STRING,
status: DataTypes.INTEGER,
pid: DataTypes.INTEGER,
log_path: DataTypes.STRING,
queued_token: DataTypes.STRING,
queued_token: DataTypes.STRING,
last_execution_time: DataTypes.INTEGER,
last_instance_id: DataTypes.INTEGER,
last_running_time: DataTypes.INTEGER,
});
const instances = db.define('Instance', {
const instances = db.define('RunningInstance', {
cron_id: DataTypes.INTEGER,
pid: DataTypes.INTEGER,
status: DataTypes.INTEGER,
exit_code: DataTypes.INTEGER,
finished_at: DataTypes.INTEGER,
started_at: { type: DataTypes.INTEGER, defaultValue: 100 },
log_path: { type: DataTypes.STRING, defaultValue: 'one.log' },
});
load('back/data/cronStats.ts', { '.': { sequelize: db } });
await db.sync();
await db.transaction(tx => require('../../back/shared/triggerHistory').installTriggerHistory(db, tx));
await crons.bulkCreate([
{ id: 1, command: 'task one.js', status: 0, pid: 101, log_path: 'one.log' },
{ id: 2, command: 'task two.js', status: 0, pid: 201, log_path: 'two.log' },
@@ -54,6 +59,10 @@ async function fixture(t, onKill = async () => {}) {
RunningInstanceModel: instances,
InstanceStatus: { running: 0, finished: 1, stopped: 2, error: 3 },
},
'../shared/cronProcess': {
pidNamespaceOwner: require('../../back/shared/cronProcess').pidNamespaceOwner,
verifyCronProcess() {},
},
'../config/util': {
killTask: async (pid, wait) => {
assert.equal(wait, true);
@@ -88,7 +97,7 @@ async function report(service, pid, code) {
exit_code: code,
});
}
test('stop wins when shell exit writes error or success during termination, preserving exit codes', async (t) => {
test('batch stop preserves a legacy exit already settled during termination', async (t) => {
const f = await fixture(t, async ({ service }) => {
await report(service, 101, 143);
await report(service, 102, 0);
@@ -98,8 +107,8 @@ test('stop wins when shell exit writes error or success during termination, pres
assert.deepEqual(
rows.map((r) => [r.id, r.status, r.exit_code]),
[
[1, 2, 143],
[2, 2, 0],
[1, 3, 143],
[2, 1, 0],
[3, 1, 0],
[4, 3, 7],
[5, 0, null],
@@ -163,9 +172,191 @@ test('failed termination is not finalized as stopped', async (t) => {
const f = await fixture(t, async ({ pid }) => {
if (pid === 102) throw Error('still alive');
});
await f.service.stop([1]);
await assert.rejects(f.service.stop([1]), /still alive/);
assert.deepEqual(f.killed, [101, 102]);
assert.equal((await f.instances.findByPk(1)).status, 2);
assert.equal((await f.instances.findByPk(2)).status, 0);
assert.equal((await f.crons.findByPk(1)).status, 0);
});
test('stop instance verifies cron ownership, waits for exit and never confirms a failed signal', async (t) => {
const f = await fixture(t, async ({pid}) => { if (pid===102) throw Error('still alive'); });
assert.equal((await f.service.stopInstance(2,1)).code,404);
await f.instances.create({ id: 6, cron_id: 1, status: 0, pid: null });
assert.equal((await f.service.stopInstance(1,6)).code,409);
assert.deepEqual(f.killed,[]);
await assert.rejects(f.service.stopInstance(1,2), /still alive/);
assert.equal((await f.instances.findByPk(2)).status,0);
assert.equal((await f.service.stopInstance(1,1)).code,200);
assert.equal((await f.service.stopInstance(1,1)).data.outcome,'stopped');
assert.equal((await f.instances.findByPk(1)).status,2);
});
test('legacy instances sharing a numeric PID cannot be individually signalled', async t => {
const f = await fixture(t);
await f.instances.create({ id: 6, cron_id: 1, pid: 101, status: 0 });
assert.equal((await f.service.stopInstance(1, 1)).code, 409);
assert.deepEqual(f.killed, []);
assert.equal((await f.instances.findByPk(6)).status, 0);
});
test('concurrent single stops join only the same task and instance; failures release a retry', async t => {
let release, entered, fail = true;
const waiting = new Promise(resolve => { entered = resolve; });
const gate = new Promise(resolve => { release = resolve; });
const f = await fixture(t, async ({ pid }) => {
if (pid === 101 && fail) { entered(); await gate; throw Error('denied'); }
});
const first = f.service.stopInstance(1, 1);
const duplicates = Array.from({ length: 8 }, () => f.service.stopInstance(1, 1));
await waiting;
assert.equal((await f.service.stopInstance(2, 1)).code, 404);
assert.equal((await f.instances.findByPk(2)).status, 0);
assert.deepEqual(f.killed, [101]);
fail = false;
release();
for (const r of await Promise.allSettled([first, ...duplicates])) assert.match(r.reason.message, /denied/);
const second = await Promise.all([f.service.stopInstance(1, 1), f.service.stopInstance(1, 1)]);
assert.deepEqual(second.map(r => r.data.outcome), ['stopped', 'stopped']);
assert.deepEqual(f.killed, [101, 101]);
assert.equal((await f.service.stopInstance(1, 3)).data.outcome, 'ended');
assert.equal((await f.instances.findByPk(3)).exit_code, 0);
});
test('single and batch stop share the in-flight termination and keep the batch snapshot across retries', async t => {
let release, entered;
const gate = new Promise(resolve => { release = resolve; });
const firstSignal = new Promise(resolve => { entered = resolve; });
const f = await fixture(t, async ({ pid }) => {
if (pid === 101) { entered(); await gate; }
});
const single = f.service.stopInstance(1, 1);
await firstSignal;
let captured;
const batchJoined = new Promise(resolve => { captured = resolve; });
const stopInstance = f.service.stopInstance.bind(f.service);
f.service.stopInstance = (cronId, id) => {
if (id === 1) captured();
return stopInstance(cronId, id);
};
const bulk = f.service.stop([1]);
await batchJoined;
const history = new (require('../../back/shared/triggerHistory').TriggerHistory)(f.crons.sequelize);
assert.deepEqual((await history.pendingStops()).map(r => r.instance_id), [1, 2]);
await f.instances.create({ id: 6, cron_id: 1, pid: 103, status: 0 });
const duplicate = stopInstance(1, 1);
release();
await Promise.all([single, bulk, duplicate]);
assert.deepEqual(f.killed, [101, 102]);
assert.deepEqual((await f.instances.findAll({ order: [['id', 'ASC']] })).map(r => r.status), [2, 2, 1, 3, 0, 0]);
assert.deepEqual(await history.pendingStops(), []);
});
test('a single stop is durable before asynchronous tree traversal and a replacement worker resumes it', async t => {
let interrupted = true;
const f = await fixture(t, async () => { if (interrupted) throw Error('interrupted while enumerating tree'); });
await assert.rejects(f.service.stopInstance(1, 2), /interrupted/);
const history = new (require('../../back/shared/triggerHistory').TriggerHistory)(f.crons.sequelize);
const pending = await history.pendingStops();
assert.deepEqual(pending.map(r => [r.cron_id, r.instance_id, r.pid, r.targets]), [[1, 2, 102, null]]);
interrupted = false;
const replacement = new f.service.constructor({ error() {}, warn() {} });
await replacement.resumePendingStops(history, pending);
assert.equal((await f.instances.findByPk(2)).status, 2);
assert.deepEqual(await history.pendingStops(), []);
assert.equal((await f.instances.findByPk(1)).status, 0);
});
test('an interrupted batch replays its original instances and leaves later queued and live runs alone', async t => {
let blocked = true;
const f = await fixture(t, async ({ pid }) => { if (pid === 102 && blocked) throw Error('interrupted'); });
const history = new (require('../../back/shared/triggerHistory').TriggerHistory)(f.crons.sequelize);
const key = require('node:crypto').randomUUID();
await history.enqueue('before', 1, 'manual', null);
await assert.rejects(f.service.stop([1], key), /interrupted/);
const pending = await history.pendingStopBatches();
assert.deepEqual(pending, [{ request_id: key, cron_ids: '[1]' }]);
await history.enqueue('after', 1, 'manual', null);
await f.instances.create({ id: 6, cron_id: 1, pid: 103, status: 0 });
await f.crons.update({ status: 3, queued_token: 'later' }, { where: { id: 1 } });
blocked = false;
const replacement = () => new f.service.constructor({ warn() {}, error() {} });
await replacement().resumePendingStops(history, await history.pendingStops(), pending);
await replacement().resumePendingStops(history, [], pending);
await replacement().stop([1, 1], key);
await assert.rejects(replacement().stop([2], key), { status: 409 });
assert.deepEqual(f.killed, [101, 102, 102]);
assert.deepEqual(await history.pendingStopBatches(), []);
assert.equal((await f.instances.findByPk(6)).status, 0);
assert.equal((await f.crons.findByPk(1)).queued_token, 'later');
const rows = await history.recent(1, 0);
assert.equal(rows.find(r => r.id === 'before').state, 'stopped');
assert.equal(rows.find(r => r.id === 'after').state, 'queued');
await replacement().stop([1], require('node:crypto').randomUUID());
assert.equal((await f.instances.findByPk(6)).status, 2);
assert.equal((await history.recent(1, 0)).find(r => r.id === 'after').state, 'stopped');
});
test('replaying an empty original snapshot never targets the first later run', async t => {
const f = await fixture(t);
const key = require('node:crypto').randomUUID();
await f.service.stop([3], key);
await f.crons.create({ id: 3, status: 0, pid: 301 });
await f.instances.create({ cron_id: 3, pid: 301, status: 0 });
await f.service.stop([3], key);
assert.deepEqual(f.killed, []);
await f.service.stop([3]);
assert.deepEqual(f.killed, [301]);
});
test('a second restart rolls back receipt deletion when settling a legacy instance fails', async t => {
const f = await fixture(t);
const history = new (require('../../back/shared/triggerHistory').TriggerHistory)(f.crons.sequelize);
await history.queueInstanceStop(1, 1, 101);
const stop = () => f.service.stopInstance(1, 1);
const transactionError = () => { throw Error('interrupted during settlement'); };
f.instances.addHook('beforeBulkUpdate', 'crash', transactionError);
await assert.rejects(stop(), /interrupted during settlement/);
f.instances.removeHook('beforeBulkUpdate', 'crash');
assert.equal((await history.pendingStops())[0].instance_id, 1);
await f.service.resumePendingStops(history, await history.pendingStops());
assert.equal((await f.instances.findByPk(1)).status, 2);
assert.deepEqual(await history.pendingStops(), []);
});
test('simultaneous first submissions share a partial failure, then retry only the original instances', async t => {
let entered, release, fail = true;
const reached = new Promise(resolve => { entered = resolve; });
const gate = new Promise(resolve => { release = resolve; });
const f = await fixture(t, async ({ pid }) => {
if (pid === 102 && fail) { entered(); await gate; throw Error('partial failure'); }
});
const key = require('node:crypto').randomUUID();
const calls = Array.from({ length: 6 }, (_, i) => f.service.stop(i % 2 ? [1, 1] : [1], key));
const results = Promise.allSettled(calls);
await reached;
await assert.rejects(f.service.stop([2], key), { status: 409 });
await f.instances.create({ id: 6, cron_id: 1, pid: 103, status: 0 });
release();
for (const result of await results) assert.match(result.reason.message, /partial failure/);
assert.deepEqual(f.killed, [101, 102]);
fail = false;
const replacement = new f.service.constructor({ error() {}, warn() {} });
await Promise.all([replacement.stop([1], key), replacement.stop([1, 1], key)]);
assert.deepEqual(f.killed, [101, 102, 102]);
assert.equal((await f.instances.findByPk(6)).status, 0);
assert.equal((await f.instances.findByPk(5)).status, 0);
});
test('a legacy task pointing to a different task’s PID cannot consume its stop result', async t => {
const f = await fixture(t);
await f.crons.create({ id: 3, status: 0, pid: 101 });
const key = require('node:crypto').randomUUID();
await assert.rejects(f.service.stop([1, 3], key), { status: 409 });
assert.deepEqual(f.killed, [101, 102]);
assert.equal((await f.crons.findByPk(3)).status, 0);
assert.equal((await f.crons.findByPk(1)).status, 1);
await f.instances.create({ cron_id: 1, pid: 103, status: 0 });
await assert.rejects(f.service.stop([3, 1], key), { status: 409 });
assert.deepEqual(f.killed, [101, 102]);
});
@@ -305,7 +305,7 @@ git_clone_scripts() { mkdir -p "$2"; cp "$QA_ROOT/template/"* "$2/"; exit_status
ql() { get_uniq_path "$2" "$6"; update_repo "${'${@:2}'}"; }
${formatCommand(doc)}`;
execFileSync('/bin/bash', ['-c', code], {
env: { ...process.env, QA_ROOT: root },
env: { ...process.env, dir_shell: path.resolve('shell'), QA_ROOT: root },
encoding: 'utf8',
timeout: 5000,
});
@@ -605,3 +605,140 @@ test('valid subscription scheduling still creates quoted commands for both sched
);
}
});
test('repeated subscription sync recognizes installed system-wrapper and legacy rules', t => {
const f = updateFixture(t);
const { shellQuote } = load(path.resolve('back/shared/shellQuote.ts'));
const wrapped = shellQuote("real_time=false ID=1 task_before='task owner_repo/hook.js' task node 'owner_repo/keep.js' -- 'one two'");
fs.writeFileSync(path.join(f.root, 'crontab'), [
'1 * * * * ID=1 QL_TRIGGER_SOURCE=system bash "$QL_DIR/shell/system-cron.sh" ' + wrapped,
'# 2 * * * * ID=2 task owner_repo/keep.py',
'3 * * * * ID=3 other-task owner_repo/unrelated.js',
].join('\n'));
const lists = path.join(f.root, 'lists');
for (let sync = 0; sync < 2; sync++) {
f.run('js|py');
assert.deepEqual(fs.readFileSync(path.join(lists, 'owner_repo_user.list'), 'utf8').trim().split('\n'),
['owner_repo/keep.js', 'owner_repo/keep.py']);
execFileSync('/bin/bash', ['-c', shellFunction('diff_cron') + '\ndiff_cron owner_repo_scripts.list owner_repo_user.list added removed'], { cwd: lists });
for (const name of ['added', 'removed']) assert.equal(fs.readFileSync(path.join(lists, name), 'utf8'), '');
}
});
test('subscription cleanup deletes only exact script operands and keeps files outside its repository', t => {
const f = updateFixture(t);
const { shellQuote } = load(path.resolve('back/shared/shellQuote.ts'));
const wrapper = cmd => '1 * * * * ID=12 QL_TRIGGER_SOURCE=system bash "$QL_DIR/shell/system-cron.sh" ' + shellQuote(cmd);
fs.writeFileSync(path.join(f.root, 'crontab'), [
'1 * * * * ID=10 task consumer.js owner_repo/drop.js',
wrapper('real_time=false ID=12 task node owner_repo/drop.js -- argument'),
'1 * * * * ID=13 task owner_repo/../../outside',
'1 * * * * ID=14 task owner_repo/link/outside',
'1 * * * * ID=15 task consumer.js owner_repo/../../outside',
'1 * * * * ID=16 task owner_repo/keep.js',
'1 * * * * ID=17 task owner_repo/keep.py',
'1 * * * * ID=18 task owner_repo/keepXjs',
'1 * * * * ID=19 task "owner_repo/keep spaces.js"',
'1 * * * * ID=20 task consumer.js bash "$QL_DIR/shell/system-cron.sh" "ID=21 task owner_repo/wrong.js"',
wrapper('real_time=false ID=22 task owner_repo/foreign.js'),
].join('\n'));
fs.writeFileSync(path.join(f.root, 'template', 'keep spaces.js'), 'keep');
const scripts = f.run('js|py');
fs.writeFileSync(path.join(f.root, 'outside'), 'keep');
fs.symlinkSync(f.root, path.join(scripts, 'link'));
fs.writeFileSync(path.join(scripts, 'drop.js'), 'old');
const lists = path.join(f.root, 'lists');
execFileSync('/bin/bash', ['-c', [
shellFunction('diff_cron'), shellFunction('del_cron'), 't(){ :; }; notify_api(){ :; }',
'del_cron_api(){ echo "$1" > deleted; }',
'diff_cron owner_repo_scripts.list owner_repo_user.list added removed',
'del_cron removed owner_repo',
].join('\n')], { cwd: lists, env: { ...process.env, dir_shell: path.resolve('shell'), dir_list_tmp: lists, dir_scripts: path.dirname(scripts) } });
assert.deepEqual(fs.readFileSync(path.join(lists, 'deleted'), 'utf8').trim().split(',').sort(), ['12', '18']);
assert.equal(fs.readFileSync(path.join(f.root, 'outside'), 'utf8'), 'keep');
assert.equal(fs.existsSync(path.join(scripts, 'drop.js')), false);
assert.ok(fs.existsSync(path.join(scripts, 'keep.js')));
assert.ok(fs.existsSync(path.join(scripts, 'keep spaces.js')));
});
test('subscription creation retains schedule and passes a quoted script name as one operand', t => {
const root = temporary(t);
fs.mkdirSync(path.join(root, 'repo'));
const filename = "repo/what's new.js";
fs.writeFileSync(path.join(root, filename), "// 7 6 * * * what's new.js\n");
fs.writeFileSync(path.join(root, 'added'), filename + '\n');
const instructions = [
shellFunction('add_cron'), 'cmd_task=task; dir_scripts=$1',
'notify_api(){ :; }; t(){ :; }',
'add_cron_api(){ printf "%s\\n%s\\n" "$1" "$2" > "$dir_scripts/result"; }',
'add_cron "$1/added" repo',
].join('\n');
execFileSync('/bin/bash', ['-c', instructions, '--', root], { cwd: root });
const [rule, command] = fs.readFileSync(path.join(root, 'result'), 'utf8').trimEnd().split('\n');
assert.equal(rule, '7 6 * * *');
assert.equal(command, 'task ' + load(path.resolve('back/shared/shellQuote.ts')).shellQuote(filename));
});
test('invalid include, exclude or dependency filters never become an empty successful sync', t => {
const f = updateFixture(t);
const scripts = f.run('js|py');
const listing = path.join(f.root, 'lists', 'owner_repo_scripts.list');
const original = fs.readFileSync(listing, 'utf8');
const code = shellFunction('gen_list_repo') + '\ngen_list_repo "$QA_ROOT/template" owner "$1" "$2" "$3" js';
for (const filters of [['[', '', ''], ['', '[', ''], ['no-match', '', '[']]) {
const result = require('node:child_process').spawnSync('/bin/bash', ['-c', code, '--', ...filters], { env: {
...process.env, dir_shell: path.resolve('shell'), QA_ROOT: f.root, uniq_path: 'owner_repo',
dir_list_tmp: path.dirname(listing), dir_scripts: path.dirname(scripts),
} });
assert.notEqual(result.status, 0);
assert.match(result.stderr.toString(), /invalid subscription filter/);
assert.equal(fs.readFileSync(listing, 'utf8'), original);
assert.equal(fs.readFileSync(path.join(scripts, 'keep.js'), 'utf8'), 'keep.js');
}
});
test('subscription writes reject destination links and replace hardlinks without altering the other inode name', t => {
const f = updateFixture(t);
const scripts = path.join(f.root, 'scripts'), repo = path.join(scripts, 'owner_repo');
const outside = path.join(f.root, 'outside');
fs.mkdirSync(outside);
const file = path.join(outside, 'keep.js');
fs.writeFileSync(file, 'protected');
const helper = path.resolve('shell/subscription-files.py');
const install = (dest) => require('node:child_process').spawnSync('python3', [helper, 'copy', path.join(f.root, 'template/keep.js'), scripts, dest]);
fs.symlinkSync(outside, repo);
assert.notEqual(install('owner_repo/keep.js').status, 0);
fs.unlinkSync(repo); fs.mkdirSync(repo);
fs.symlinkSync(outside, path.join(repo, 'nested'));
assert.notEqual(install('owner_repo/nested/keep.js').status, 0);
for (const dest of ['owner_repo/notify.js', 'owner_repo/dep.js', 'owner_repo/keep.js', 'raw_test.js']) {
fs.symlinkSync(file, path.join(scripts, dest));
assert.notEqual(install(dest).status, 0);
assert.equal(fs.readFileSync(file, 'utf8'), 'protected');
fs.unlinkSync(path.join(scripts, dest));
}
fs.linkSync(file, path.join(repo, 'keep.js'));
assert.equal(install('owner_repo/keep.js').status, 0);
assert.equal(fs.readFileSync(path.join(repo, 'keep.js'), 'utf8'), 'keep.js');
assert.equal(fs.readFileSync(file, 'utf8'), 'protected');
});
test('a rejected guarded deletion preserves its file and propagates failure to subscription sync', t => {
const f = updateFixture(t);
const scripts = f.run('js');
const lists = path.join(f.root, 'lists'), operand = "owner_repo/what's old.js";
fs.writeFileSync(path.join(f.root, 'scripts', operand), 'old contents');
fs.writeFileSync(path.join(lists, 'owner_repo_registered.list'), '37\t' + operand + '\t1234\n');
fs.writeFileSync(path.join(lists, 'removed'), operand + '\n');
const shell = [
shellFunction('del_cron'), 't(){ :; }; notify_api(){ :; }',
'del_cron_api(){ printf "%s" "$2" > "$dir_list_tmp/request"; return 1; }',
'del_cron "$dir_list_tmp/removed" owner_repo',
].join('\n');
const result = require('node:child_process').spawnSync('/bin/bash', ['-c', shell], {
env: { ...process.env, dir_shell: path.resolve('shell'), dir_scripts: path.dirname(scripts), dir_list_tmp: lists },
});
assert.notEqual(result.status, 0);
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(lists, 'request'))), [{id: 37, script: operand, revision: 1234}]);
assert.equal(fs.readFileSync(path.join(f.root, 'scripts', operand), 'utf8'), 'old contents');
});
+25
View File
@@ -48,6 +48,31 @@ function fixture(t) {
return { write, run };
}
test('managed task propagates the sourced script status through direct output, redirection and tee', t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-wrapper-status-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const shellDir = path.join(root, 'shell');
fs.mkdirSync(shellDir);
// Exercise the real outer wrapper with deterministic paths and a failing payload.
fs.writeFileSync(path.join(shellDir, 'share.sh'), [
'is_macos=0; no_delay=true; dir_log=$QL_DIR; log_name=logs',
'import_config() { :; }', 'make_dir() { mkdir -p "$1"; }',
'format_timestamp() { echo 1; }', 'format_time() { echo now; }',
].join('\n'));
fs.writeFileSync(path.join(shellDir, 'api.sh'), '');
fs.writeFileSync(path.join(shellDir, 'task-timeout.sh'), '');
fs.writeFileSync(path.join(shellDir, 'otask.sh'), 'echo payload; return 17\n');
for (const [direct, noTee] of [[true,false], [false,true], [false,false]]) {
const run = spawnSync('/bin/bash', [path.resolve('shell/task.sh'), 'probe.sh'], {
env: { ...process.env, QL_DIR: root, ID: '42', QL_TRIGGER_ID: 'shell-probe',
real_time: String(direct), no_tee: String(noTee) }, encoding: 'utf8',
});
assert.equal(run.status, 17, run.stderr);
if (noTee) assert.equal(run.stdout, '');
else assert.match(run.stdout, /payload/);
}
});
for (const [label, body, code] of [
['normal return', ':', 0],
['exit zero', 'exit 0', 0],
+13 -3
View File
@@ -68,7 +68,7 @@ init_begin_time
handle_task_end`,
);
assert.equal(r.text('dates').trim().split('\n').length, 3);
assert.match(r.text('stats'), /^42 0 1\n$/);
assert.match(r.text('stats'), /^42 0 1 101\n$/);
assert.match(r.text('messages'), /2026-09-13 00:00:00/);
});
test('explicit log paths and output mode remain intact', (t) => {
@@ -85,7 +85,7 @@ test('task failure keeps exit code and minimum one-second runtime', (t) => {
`begin_timestamp=101; _task_exit_code=7; log_path=test.log
handle_task_end`,
);
assert.equal(r.text('stats'), '42 7 1\n');
assert.equal(r.text('stats'), '42 7 1 101\n');
assert.match(r.text('messages'), /失败/);
assert.match(r.text('status'), /101 1 7/);
});
@@ -95,7 +95,7 @@ test('manual stop retains stopped message and exit status reporting', (t) => {
`begin_timestamp=99; _task_exit_code=1; log_path=test.log; MANUAL=true
handle_task_end`,
);
assert.equal(r.text('stats'), '42 1 2\n');
assert.equal(r.text('stats'), '42 1 2 101\n');
assert.match(r.text('messages'), /已停止/);
});
for (const mode of ['macos', 'custom'])
@@ -114,3 +114,13 @@ handle_task_end
`,
);
});
test('scheduled tasks starting in the same millisecond write different files', t => {
run(t, `log_name=common
QL_TRIGGER_ID=first; handle_log_path same.py
first=$log_path
QL_TRIGGER_ID=second; handle_log_path same.py
[[ "$first" != "$log_path" ]]
QL_TRIGGER_ID=../invalid; handle_log_path same.py
[[ "$log_path" == common/2026-09-12-23-59-59-999.log ]]`);
});
+15
View File
@@ -10,6 +10,17 @@ const {
repairDependencies,
} = require('../../cli/src/internal/maintenance/upgradePrestart.cjs');
function checkGroupSignals(t) {
const kill = t.mock.method(process, 'kill');
return () => {
if (process.platform === 'win32') return;
const groups = kill.mock.calls.filter(call => call.arguments[0] < 0 && call.arguments[1] === 'SIGKILL')
.map(call => call.arguments[0]);
assert.ok(groups.length > 0);
assert.equal(new Set(groups).size, groups.length, 'a retired process group was signalled twice');
};
}
for (const [version, exitCode] of [
['2.23.0', 0],
['2.23.0', 1],
@@ -43,12 +54,14 @@ for (const [version, exitCode] of [
},message:'simulated prestart failure',build:{sourceCommit:'a'.repeat(40),version:${JSON.stringify(version)},backendSha256:crypto.createHash('sha256').update('backend').digest('hex')}},()=>process.exit(${exitCode}));
`,
);
const checkSignals = checkGroupSignals(t);
const operation = prestartBackend(
{ source, static: statics },
{ target: { arch: 'armv6' }, limits: { heapMb: 128, timeoutMs: 3000 } },
);
if (exitCode) await assert.rejects(operation, /simulated prestart failure/);
else await operation;
checkSignals();
assert.deepEqual((await fs.readdir(root)).sort(), ['source', 'static']);
await new Promise((r) => setTimeout(r, 700));
await assert.rejects(fs.access(survivor), { code: 'ENOENT' });
@@ -84,6 +97,7 @@ for (const phase of ['install', 'rebuild'])
`,
{ mode: 0o755 },
);
const checkSignals = checkGroupSignals(t);
await assert.rejects(
repairDependencies(source, {
target: { arch: 'armv6' },
@@ -96,6 +110,7 @@ for (const phase of ['install', 'rebuild'])
}),
/simulated repair failure/,
);
checkSignals();
assert.equal(
await fs.readFile(path.join(source, 'node_modules/old'), 'utf8'),
'preserved',
+1
View File
@@ -21,6 +21,7 @@ function create(env) {
const cluster = {
fork(options) {
const worker = {
on() {},
id: calls.length + 1,
process: { pid: 100 + calls.length },
};
+102
View File
@@ -0,0 +1,102 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const ts = require('typescript');
// Exercise the real list effect while explicitly releasing each HTTP response.
function listEffect() {
const source = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/index.tsx'), 'utf8');
const ast = ts.createSourceFile('index.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const effects = [];
function visit(node) {
if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect' &&
node.arguments[1]?.getText(ast).includes('searchText')) effects.push(node.arguments[0]);
ts.forEachChild(node, visit);
}
visit(ast);
assert.equal(effects.length, 1);
const js = ts.transpile('const effect = ' + effects[0].getText(ast), {target: ts.ScriptTarget.ES2022});
const requests = [], timers = new Set(), rows = [], totals = [], failures = [];
const bindings = {
pageConf: { page: 1, size: 20 }, viewConf: null, config: {apiPrefix: '/api/'},
request: { get(url, options) {
return new Promise((resolve, reject) => requests.push({url, options, resolve, reject}));
} }, setValue: value => rows.push(value), setTotal: value => totals.push(value),
setLoading() {}, setListFailed(failed) { failures.push(failed); },
setTimeout(fn) { timers.add(fn); return fn; }, clearTimeout(fn) { timers.delete(fn); },
};
return { requests, timers, rows, totals, failures, start(searchText) {
return Function('searchText', ...Object.keys(bindings), js + '\nreturn effect();')(searchText, ...Object.values(bindings));
} };
}
const flush = () => new Promise(resolve => setImmediate(resolve));
const page = (id, sub_id) => ({code: 200, data: {data: [{id, sub_id}], total: 1}});
test('switching searches discards stale list and subscription responses and cancels old polling', async () => {
for (const delaySubscription of [false, true]) {
const view = listEffect();
const closeA = view.start('A');
if (delaySubscription) { view.requests[0].resolve(page(1, 7)); await flush(); }
const stale = view.requests.at(-1);
closeA();
assert.ok(stale.options.signal.aborted);
const closeB = view.start('B&+');
const fresh = view.requests.at(-1);
assert.equal(fresh.options.params.searchValue, 'B&+');
fresh.resolve(page(2));
await flush();
stale.resolve(delaySubscription ? {code: 200, data: [{id: 7}]} : page(1, 7));
await flush();
assert.deepEqual(view.rows.map(rows => rows.map(r => r.id)), [[2]]);
assert.deepEqual(view.totals, [1]);
assert.equal(view.requests.length, delaySubscription ? 3 : 2);
assert.equal(view.timers.size, 1);
closeB();
assert.equal(view.timers.size, 0);
}
});
test('list polling recovers on the next tick after a network failure', async () => {
const view = listEffect();
const stop = view.start('same query');
view.requests[0].reject(Error('interrupted'));
await flush();
assert.deepEqual(view.failures, [true]);
const [tick] = view.timers;
view.timers.delete(tick);
const poll = tick();
view.requests[1].resolve(page(3));
await poll;
assert.deepEqual(view.failures, [true, false]);
assert.equal(view.rows[0][0].id, 3);
assert.equal(view.timers.size, 1);
stop();
});
test('the next search can be submitted while the table request is in flight', () => {
const source = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/index.tsx'), 'utf8');
const ast = ts.createSourceFile('index.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const controls = [];
function visit(node) {
if (ts.isJsxSelfClosingElement(node) && node.tagName.getText(ast) === 'Search') controls.push(node);
ts.forEachChild(node, visit);
}
visit(ast);
assert.equal(controls.length, 1);
const attributes = controls[0].attributes.properties.map(p => p.name?.getText(ast));
assert.ok(attributes.includes('onSearch'));
assert.ok(!attributes.includes('loading') && !attributes.includes('disabled'));
});
test('a failed subscription lookup still displays the current task list', async () => {
const view = listEffect();
const stop = view.start('updated');
view.requests[0].resolve(page(42, 1));
await flush();
view.requests[1].reject(Error('offline'));
await flush();
assert.deepEqual(view.rows[0].map(row => row.id), [42]);
assert.deepEqual(view.totals, [1]);
stop();
});
+177 -11
View File
@@ -23,7 +23,7 @@ const declarations = new Map();
function visit(node) {
if (
ts.isVariableDeclaration(node) &&
['getCronLog', 'cancel'].includes(node.name.getText(ast))
['getCronLog', 'stopReading', 'cancel'].includes(node.name.getText(ast))
)
declarations.set(node.name.getText(ast), node.initializer.getText(ast));
ts.forEachChild(node, visit);
@@ -32,7 +32,6 @@ visit(ast);
function fixture(get) {
const timers = new Map();
const storage = new Map([['logCron', '1']]);
const values = { content: '', executing: true };
const pending = [];
let timerId = 0;
@@ -40,25 +39,23 @@ function fixture(get) {
logUrl: undefined,
config: { apiPrefix: '/api/' },
cron: { id: 1 },
uniqPath: '1',
session: { current: new AbortController() },
pinnedTrigger: {}, reading: {current: false}, drained: {}, lastPath: {}, lastCursor: {}, scrollTimer: {},
LOG_CHUNK_BYTES: 256 * 1024,
MAX_LOG_VIEW_CHARS: 1024 * 1024,
logOffsetRef: { current: undefined },
valueRef: { current: '' },
pollTimerRef: {},
request: {
get(url) {
const result = get(url);
get(url, options) {
const result = get(url, options);
pending.push(result);
return result;
},
},
localStorage: {
getItem: (key) => storage.get(key),
removeItem: (key) => storage.delete(key),
},
intl: { get: (value) => value },
setLoading() {},
setLoading(value) { values.loading = value; },
setReadFailed(value) { values.failed = value; },
autoScroll() {},
handleCancel() {},
setValue(value) {
@@ -84,12 +81,13 @@ function fixture(get) {
context,
);
async function settle() {
await Promise.all(pending.splice(0));
await Promise.allSettled(pending.splice(0));
await new Promise((resolve) => setImmediate(resolve));
}
return {
values,
timers,
retry() { context.getCronLog(context.logOffsetRef.current === undefined); },
start() {
context.getCronLog(true);
},
@@ -126,6 +124,8 @@ test('completed tasks drain unread chunks and display the final exit marker', as
const chunk = await readLogChunk(file, {
offset,
tail: query.get('tail') === 'true',
follow: query.get('follow') === 'true',
cursor: query.get('cursor'),
limit: Number(query.get('limit')),
});
return {
@@ -212,3 +212,169 @@ test('legacy and non-advancing completed responses do not loop', async () => {
assert.equal(view.timers.size, 0);
}
});
test('first log read failure is recoverable on retry', async () => {
let calls = 0;
const view = fixture(async () => {
if (++calls === 1) throw new Error('connection interrupted');
return { code: 200, data: 'actual log' };
});
await view.read();
assert.equal(view.values.failed, true);
await view.read();
assert.equal(view.values.failed, false);
assert.equal(view.values.content, 'actual log');
});
test('independent log readers can receive responses in reverse order across close and reopen', async () => {
let resolveOld;
const old = fixture(() => new Promise(resolve => { resolveOld = resolve; }));
old.start();
old.close();
const current = fixture(async () => ({code: 200, data: 'new log'}));
await current.read();
resolveOld({code: 200, data: 'old log', logStatus: 'running'});
await old.settle();
assert.equal(current.values.content, 'new log');
assert.equal(old.values.content, '');
assert.equal(old.timers.size, 0);
});
test('repeated retries share one in-flight read and closing aborts its transport', async () => {
const pending = [];
const view = fixture((url, { signal }) => new Promise(resolve => pending.push({ signal, resolve })));
view.start();
view.retry();
assert.equal(pending.length, 1);
view.close();
assert.equal(pending[0].signal.aborted, true);
pending[0].resolve({ code: 200, data: 'old', logStatus: 'running' });
await view.settle();
assert.equal(view.timers.size, 0);
assert.equal(view.values.content, '');
});
test('polling a missing log displays its status once and retries from the last confirmed byte', async () => {
const calls = [];
const responses = [
{data: 'waiting', total: 0, nextOffset: 0}, {data: 'waiting', total: 0, nextOffset: 0},
{data: 'abc', total: 3, nextOffset: 3, logPath: 'a'}, null,
{data: 'd', total: 4, nextOffset: 4, logPath: 'a'},
{data: 'new!', total: 4, nextOffset: 4, logPath: 'b', logStatus: 'completed'},
];
const view = fixture(async url => {
calls.push(new URL(url, 'http://localhost').searchParams);
const r = responses.shift();
if (!r) throw Error('offline');
return {code: 200, logStatus: 'running', ...r};
});
await view.read(); await view.tick();
assert.equal(view.values.content, 'waiting');
await view.tick(); await view.tick();
assert.equal(view.values.failed, true);
assert.equal(view.values.content, 'abc');
view.retry(); view.retry(); await view.settle();
assert.equal(view.values.content, 'abcd');
assert.deepEqual(calls.slice(3).map(p => [p.get('offset'), p.get('previousPath')]), [['3','a'],['3','a']]);
await view.tick();
assert.equal(view.values.content, 'new!');
assert.equal(view.timers.size, 0);
});
test('a shortened file during a retry is reread from its new tail', async () => {
const responses = [
{data: 'previous log', nextOffset: 12, total: 12}, {data: '', nextOffset: 3, total: 3},
{data: 'new', nextOffset: 3, total: 3},
];
const calls = [];
const view = fixture(async url => {
calls.push(url);
return {code: 200, logStatus: responses.length === 3 ? 'running' : 'completed', ...responses.shift()};
});
await view.read(); await view.tick(); await view.tick();
assert.match(calls[2], /tail=true/);
assert.equal(view.values.content, 'new');
assert.equal(view.timers.size, 0);
});
test('retry after a truncate and regrow replaces displayed bytes and drains all pages exactly once', async t => {
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'ql-log-regrow-'));
t.after(() => fsp.rm(dir, { recursive: true, force: true }));
const file = path.join(dir, 'run.log');
await fsp.writeFile(file, 'previous run\n');
let running = true;
let fail = false;
const offsets = [];
const view = fixture(async url => {
const p = new URL(url, 'http://localhost').searchParams;
const offset = p.has('offset') ? Number(p.get('offset')) : undefined;
offsets.push(offset);
if (fail) throw Error('timeout');
const chunk = await readLogChunk(file, {
offset, follow: p.get('follow') === 'true', cursor: p.get('cursor'),
tail: p.get('tail') === 'true', limit: Number(p.get('limit')),
});
return { ...chunk, code: 200, data: chunk.content, logPath: 'run.log',
logStatus: running ? 'running' : 'completed' };
});
await view.read();
fail = true;
await view.tick();
assert.equal(view.values.failed, true);
const current = Array.from({ length: 16000 }, (_, i) => `${i} · 中文日志🚀\n`).join('');
await fsp.writeFile(file, current);
fail = running = false;
view.retry();
view.retry();
await view.settle();
while (view.timers.size) await view.tick();
assert.equal(view.values.content, current);
assert.equal(view.values.failed, false);
assert.equal(view.values.executing, false);
assert.deepEqual(offsets.slice(0, 3), [undefined, 13, 13]);
assert.equal(offsets.length, 4);
});
test('a fresh list snapshot wakes a drained live viewer only for a new path or active task', () => {
const effects = [];
function visitEffect(node) {
if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect' &&
node.arguments[1]?.getText(ast) === '[cron]') effects.push(node.arguments[0]);
ts.forEachChild(node, visitEffect);
}
visitEffect(ast);
assert.equal(effects.length, 1);
const wake = ts.transpile('var wake = ' + effects[0].getText(ast), {target: ts.ScriptTarget.ES2020});
let calls = 0;
const context = { cron: { log_path: 'old', status: 1 }, lastPath: {current: 'old'},
drained: {current: true}, pinnedTrigger: {}, logUrl: undefined,
CrontabStatus: {running: 0, queued: 3}, getCronLog: () => calls++ };
const update = () => vm.runInNewContext(wake + '\nwake()', context);
update(); assert.equal(calls, 0);
context.cron = {log_path: 'new', status: 1};
update(); assert.equal(calls, 1);
context.cron = {log_path: 'old', status: 3};
update(); assert.equal(calls, 2);
context.drained.current = false;
update(); assert.equal(calls, 2);
context.drained.current = true;
context.logUrl = '/api/logs/detail?file=old';
update(); assert.equal(calls, 2);
});
test('concurrent live log polling and retries stay scoped to the initially selected trigger', async () => {
const calls = [];
const view = fixture(async url => {
const p = new URL(url, 'http://localhost').searchParams;
calls.push(p.get('triggerId'));
if (calls.length === 2) throw Error('timeout');
const selected = p.get('triggerId') || (calls.length === 1 ? 'a' : 'b');
return { code: 200, triggerId: selected, logPath: selected + '.log', total: calls.length === 1 ? 1 : 2,
nextOffset: calls.length === 1 ? 1 : 2, logStatus: calls.length < 3 ? 'running' : 'completed',
data: calls.length === 1 ? 'A' : selected === 'a' ? '!' : 'B!' };
});
await view.read(); await view.tick(); view.retry(); await view.settle();
assert.deepEqual(calls, [null, 'a', 'a']);
assert.equal(view.values.content, 'A!');
assert.equal(view.timers.size, 0);
});
+121
View File
@@ -0,0 +1,121 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const ts = require('typescript');
function dashboard() {
const source = fs.readFileSync(require.resolve('../../src/pages/dashboard/index.tsx'), 'utf8');
const ast = ts.createSourceFile('dashboard.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let effect;
function visit(node) {
if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect' &&
node.arguments[0].getText(ast).includes('setOverview')) effect = node.arguments[0].getText(ast);
ts.forEachChild(node, visit);
}
visit(ast);
assert.ok(effect);
const requests = [], results = [], failures = [], timers = new Set();
const noop = () => {};
const bindings = {
config: { apiPrefix: '/api/' }, REFRESH_INTERVAL: 30000,
setOverview: value => results.push(value), setOverviewFailed: value => failures.push(value),
setLoading: noop, setTrend: noop, setSystem: noop, setTopTime: noop, setTopCount: noop, setLabels: noop, setRuntime: noop,
setInterval(fn) { timers.add(fn); return fn; }, clearInterval(fn) { timers.delete(fn); },
request: { get(url, options) {
return new Promise((resolve, reject) => requests.push({ url, options, resolve, reject }));
} },
};
const js = ts.transpile('const start = ' + effect, { target: ts.ScriptTarget.ES2022 });
return {
start: Function(...Object.keys(bindings), js + '\nreturn start;')(...Object.values(bindings)),
tick() { for (const fn of timers) fn(); }, timers, results, failures,
requests: section => requests.filter(r => r.url === '/api/dashboard/' + section),
};
}
const flush = () => new Promise(resolve => setImmediate(resolve));
test('slow dashboard cards do not block crond counts, overlap a pending refresh or restart polling after unmount', async () => {
const view = dashboard(), leave = view.start();
view.tick();
assert.equal(view.requests('overview').length, 1);
view.requests('overview')[0].resolve({ code: 200, data: { actualSkips: 0 } });
await flush();
view.tick();
assert.equal(view.requests('trend').length, 1);
const pending = view.requests('overview')[1];
assert.equal(pending.options.retryInPlace, true);
pending.reject(new Error('502 during restart'));
await flush();
assert.deepEqual(view.results, [{ actualSkips: 0 }]);
assert.deepEqual(view.failures, [false, true]);
view.tick();
view.requests('overview')[2].resolve({ code: 200, data: { actualSkips: 1 } });
await flush();
assert.deepEqual(view.failures, [false, true, false]);
view.tick();
const stale = view.requests('overview')[3];
leave();
assert.equal(stale.options.signal.aborted, true);
assert.equal(view.timers.size, 0);
const closeAgain = view.start();
view.requests('overview')[4].resolve({ code: 200, data: { actualSkips: 2 } });
await flush();
stale.resolve({ code: 200, data: { actualSkips: 0 } });
await flush();
assert.deepEqual(view.results, [{ actualSkips: 0 }, { actualSkips: 1 }, { actualSkips: 2 }]);
assert.deepEqual(view.failures, [false, true, false, false]);
assert.equal(view.timers.size, 1);
closeAgain();
});
test('system crond results distinguish missing records, unknown exits and recorded skips', async () => {
const intl = require('react-intl-universal');
const messages = require('../../src/locales/zh-CN.json');
await intl.init({ currentLocale: 'zh-CN', locales: { 'zh-CN': messages } });
const source = fs.readFileSync(require.resolve('../../src/pages/dashboard/index.tsx'), 'utf8');
const ast = ts.createSourceFile('dashboard.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let renderer;
function visit(node) {
if (ts.isObjectLiteralExpression(node) && node.properties.some(p =>
ts.isPropertyAssignment(p) && p.name.getText(ast) === 'title' &&
p.initializer.getText(ast) === "intl.get('执行情况')")) {
renderer = node.properties.find(p => p.name.getText(ast) === 'render').initializer;
}
ts.forEachChild(node, visit);
}
visit(ast);
assert.ok(renderer);
const js = ts.transpileModule('const render = ' + renderer.getText(ast), {
fileName: 'cell.tsx', compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 },
}).outputText;
const cell = Function('React', 'intl', js + '\nreturn render;')(require('react'), intl);
const html = row => require('react-dom/server').renderToStaticMarkup(cell(null, row));
assert.equal(html({ status: 'missing', triggerCount: 0 }), '未收到触发记录');
assert.equal(html({ status: 'skipped', triggerCount: 1, skipCount: 1 }), '已跳过');
assert.equal(html({ status: 'started' }), '命令已启动');
assert.equal(html({ status: 'started', triggerCount: 1, startCount: 1, unknownExitCount: 1 }),
'命令已启动 · 结果未知');
assert.equal(html({ status: 'started', triggerCount: 2, startCount: 1, skipCount: 1, unknownExitCount: 1 }),
'启动 1 次 · 跳过 1 次 · 其中 1 次执行结果未知');
});
test('dashboard timing preserves millisecond precision, rounds long waits and distinguishes zero from no samples', async () => {
const intl = require('react-intl-universal');
const locales = { 'zh-CN': require('../../src/locales/zh-CN.json'), 'en-US': require('../../src/locales/en-US.json') };
const source = fs.readFileSync(require.resolve('../../src/pages/dashboard/timingStatistic.tsx'), 'utf8');
const { outputText } = ts.transpileModule(source, { compilerOptions: {
jsx: ts.JsxEmit.ReactJSX, module: ts.ModuleKind.CommonJS, esModuleInterop: true,
} });
const component = {};
Function('require', 'exports', outputText)(require, component);
await intl.init({ currentLocale: 'zh-CN', locales });
assert.deepEqual([null, 0, 136, 1000, 5989, 59999, 60000, 119999, 1703994].map(component.formatTiming),
['—', '0 ms', '136 ms', '1 秒', '5.989 秒', '59.999 秒', '1 分 0 秒', '2 分 0 秒', '28 分 24 秒']);
const render = ms => require('react-dom/server').renderToStaticMarkup(
require('react').createElement(component.default, { title: 'P95', ms }));
assert.match(render(1703994), /title="1703994 ms">28 分 24 秒/);
assert.match(render(null), /—/);
assert.doesNotMatch(render(136), /个样本/);
await intl.init({ currentLocale: 'en-US', locales });
assert.equal(component.formatTiming(1703994), '28 min 24 s');
});
+407
View File
@@ -0,0 +1,407 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const ts = require('typescript');
function action(file, name, bindings) {
const filename = path.join(__dirname, '../../src', file);
const ast = ts.createSourceFile(
filename,
fs.readFileSync(filename, 'utf8'),
ts.ScriptTarget.Latest,
true,
);
let body;
function visit(node) {
if (node.name?.getText(ast) === name) {
if (ts.isFunctionDeclaration(node)) body = node.getText(ast);
if (ts.isVariableDeclaration(node)) body = 'const ' + node.getText(ast);
}
ts.forEachChild(node, visit);
}
visit(ast);
assert.ok(body, name);
const js = ts.transpileModule(body.replace(/^export /, ''), {
fileName: filename,
compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },
}).outputText;
return Function(
...Object.keys(bindings),
js + '\nreturn ' + name,
)(...Object.values(bindings));
}
function transport() {
const calls = [];
return {
calls,
get(url, config) {
return new Promise((resolve, reject) =>
calls.push({ url, config, resolve, reject }),
);
},
};
}
const flush = () => new Promise((resolve) => setImmediate(resolve));
const pastCursor = action('components/fileBrowser/index.tsx', 'pastCursor', {});
test('a retry at the top restores the next visible file when the first file was deleted', () => {
const row = (title, top) => ({ title, getBoundingClientRect: () => ({ top, bottom: top + 24 }) });
const element = {
scrollTop: 0, clientHeight: 48, getBoundingClientRect: () => ({ top: 100 }),
querySelectorAll: () => [row('gone', 100), row('survivor', 124), row('below', 148)],
querySelector: selector => selector === 'button[title="survivor"]' ? row('survivor', 364) : null,
};
const viewport = { current: element }, position = {};
action('components/fileBrowser/index.tsx', 'rememberPosition', { viewport, position })();
assert.deepEqual([...position.current.offsets], [['gone', 0], ['survivor', 24]]);
const emptyListing = { rows: [], next: '', versions: new Map() };
action('components/fileBrowser/index.tsx', 'Entries', {
React: require('react'), emptyListing, Spin: 'i', CSS: { escape: key => key },
useRef: value => value === null ? viewport : value === undefined ? position : { current: value },
useState: value => [value, () => {}], useEffect() {}, useLayoutEffect: effect => effect(),
})({ source: 'logs', path: '', search: '' });
assert.equal(element.scrollTop, 240);
assert.equal(position.current, undefined);
});
test('a new execution has its own title before its log path arrives', () => {
const readableLogName = action('components/fileBrowser/name.ts', 'readableLogName', {});
const title = action('pages/crontab/detail.tsx', 'instanceTitle', {
readableLogName, intl: { get: (key, { id }) => key.replace('{id}', id) },
});
const next = { id: 34834, status: 0, log_path: null };
const stopped = { id: 34814, status: 2, log_path: 'task/old.log' };
assert.equal(title(stopped), 'old.log');
assert.equal(title(next), '执行实例 #34834');
assert.equal(title({ ...next, log_path: 'task/new.log' }), 'new.log');
});
test('file rows preserve meaningful suffixes, separate the search directory and expose the full path', () => {
const React = require('react');
const names = ['async_components___init__', 'async_components_register.js', '中文任务_同步明细.log'];
const rows = names.map(title => ({ title, parent: 'workers', key: 'workers/' + title, type: 'file' }));
const emptyListing = { rows, next: '', versions: new Map() };
const entries = action('components/fileBrowser/index.tsx', 'Entries', {
React, useRef: current => ({ current }), useState: value => [value, () => {}], useEffect() {}, useLayoutEffect() {},
emptyListing, FileOutlined: 'i', Spin: 'i', Typography: { Text: 'span' }, readableLogName: value => value,
})({ source: 'logs', path: '', search: 'work' }).props.children[0];
const tails = ['___init__', '_register.js', '_同步明细.log'];
for (const [i, button] of entries.entries()) {
const [name, parent] = button.props.children[1].props.children;
const parts = name.props.children.map(span => span.props.children);
assert.equal(parts.join(''), names[i]);
assert.equal(parts[1], tails[i]);
assert.equal(parent.props.children, 'workers');
assert.equal(button.props.title, rows[i].key);
assert.equal(button.props['aria-label'], rows[i].key);
}
});
for (const remaining of [0, 2, 8]) {
test(`manual retry retains the requested depth through churn and a network error with ${remaining} files left`, async () => {
const emptyListing = { rows: [], next: '', versions: new Map() };
const listing = { current: { rows: [0, 1, 2, 3], next: '4', versions: new Map([['a', '1']]) } };
const states = [], failures = [];
let checks = 0, reads = 0, phase = 'churn';
const read = action('components/fileBrowser/index.tsx', 'read', {
pastCursor, rememberPosition() {},
listing, emptyListing, pending: {}, path: 'a', source: 'scripts', search: '', folders: false,
config: { apiPrefix: '/api/' }, setLoading() {}, setFailed: v => failures.push(v),
setListing: page => states.push(page.rows),
request: {
async get(_url, { params }) {
reads++;
if (phase === 'offline') throw new Error('network unavailable');
const count = phase === 'churn' ? 8 : remaining;
const offset = Number(params.after);
const data = Array.from({ length: Math.min(2, count - offset) }, (_, i) => offset + i);
return { code: 200, data, next: offset + 2 < count ? String(offset + 2) : null, versions: [['a', '1']] };
},
async post() { checks++; return { code: 200, current: phase === 'stable' }; },
},
});
await read(listing.current);
assert.equal(checks, 3);
assert.deepEqual(states, [[], [], []]);
assert.equal(failures.at(-1), true);
await read(listing.current); // The directory keeps changing during manual retry.
assert.equal(checks, 6);
assert.equal(failures.at(-1), true);
const retry = listing.current;
phase = 'offline';
await read(retry);
assert.equal(failures.at(-1), true);
phase = 'stable';
await Promise.all([read(retry), read(retry)]);
const count = Math.min(6, remaining);
assert.deepEqual(listing.current.rows, Array.from({ length: count }, (_, i) => i));
assert.equal(listing.current.next, remaining > count ? String(count) : '');
const completedReads = reads;
await read(retry);
assert.equal(reads, completedReads);
});
}
for (const [source, search, boundary, cursors] of [
['scripts', '', '1m', ['0z', '1a', '1b', '1l', '1n', '1z']],
['logs', '', '1m', ['0z', '1z', '1x', '1n', '1k', '1a']],
// DFS enters directory "a" before visiting sibling "a-".
['logs', 'needle', 'a-', ['a/1', 'a/2', 'a/3', 'a/x', 'a.', 'z']],
]) {
test(`retry traverses the old boundary after earlier inserts and deletion of the cursor (${source}, ${search || 'directory'})`, async () => {
const emptyListing = { rows: [], next: '', versions: new Map() };
const listing = { current: { rows: ['old1', 'old2'], next: boundary, versions: new Map() } };
const failures = [];
let stable = false;
const read = action('components/fileBrowser/index.tsx', 'read', {
pastCursor, rememberPosition() {}, listing, emptyListing, pending: {}, source, path: '', search, folders: false,
config: { apiPrefix: '/api/' }, setLoading() {}, setFailed: v => failures.push(v), setListing() {},
request: {
async get(_url, { params }) {
const index = params.after === boundary ? 4 : cursors.indexOf(params.after) + 1;
assert.ok(index < cursors.length);
return { code: 200, next: cursors[index], data: search && index === 3 ? [] : [cursors[index]], versions: [['', '1']] };
},
async post() { return { code: 200, current: stable }; },
},
});
await read(listing.current);
assert.equal(failures.at(-1), true);
assert.equal(listing.current.retryAfter, boundary);
stable = true;
await read(listing.current);
assert.equal(failures.at(-1), false);
assert.equal(listing.current.next, cursors[4]);
assert.deepEqual(listing.current.rows, cursors.slice(0, 5).filter((_, i) => !search || i !== 3));
});
}
test('loading more rebuilds the original depth if a delayed last page missed a move into a previous directory', async () => {
const pages = [
{ data: ['c/old'], next: null, versions: [['c', '1']] },
{ data: ['a/moved', 'b/kept'], next: 'b/kept', versions: [['a', '2'], ['b', '1']] },
{ data: ['c/new'], next: null, versions: [['c', '2']] },
];
const cursors = [], checks = [], commits = [], emptyListing = { rows: [], next: '', versions: new Map() };
const listing = { current: { rows: ['a/deleted', 'b/kept'], next: 'b/kept', versions: new Map([['a', '1'], ['b', '1']]) } };
const read = action('components/fileBrowser/index.tsx', 'read', {
pastCursor, rememberPosition() {},
pending: {}, listing, emptyListing, source: 'logs', path: '', search: 'match',
folders: false, config: { apiPrefix: '/api/' }, setListing: value => commits.push(value.rows),
setLoading() {}, setFailed(value) { assert.equal(value, false); },
request: {
async get(_url, { params }) { cursors.push(params.after); return { code: 200, ...pages.shift() }; },
async post(_url, stamps) { checks.push(Object.fromEntries(stamps)); return { code: 200, current: checks.length > 1 }; },
},
});
const previous = listing.current;
await read(previous);
await read(previous); // A late second click from the previous render.
assert.deepEqual(cursors, ['b/kept', '', 'b/kept']);
assert.deepEqual(checks, [{ a: '1', b: '1', c: '1' }, { a: '2', b: '1', c: '2' }]);
assert.deepEqual(commits, [[], ['a/moved', 'b/kept', 'c/new']]);
});
for (const retrying of [false, true]) {
test(`abandoning a search discards its delayed validation during ${retrying ? 'manual retry' : 'initial load'}`, async () => {
const pending = {}, commits = [];
const emptyListing = { rows: [], next: '', versions: new Map() };
const previous = retrying ? { ...emptyListing, retryMinimum: 2 } : emptyListing;
let finish, reads = 0;
const read = action('components/fileBrowser/index.tsx', 'read', {
pastCursor, rememberPosition() {},
pending, listing: { current: previous }, emptyListing, source: 'scripts', path: '', search: 'old',
folders: false, config: { apiPrefix: '/api/' }, setListing: value => commits.push(value),
setLoading() {}, setFailed() {},
request: {
async get() {
reads++;
return { code: 200, data: [`old-${reads}.js`], next: reads === 1 ? 'more' : null, versions: [['', '1']] };
},
post() { return new Promise(resolve => { finish = resolve; }); },
},
});
const loading = read(previous);
await flush();
pending.current.abort();
finish({ code: 200, current: true });
await loading;
assert.equal(reads, retrying ? 2 : 1);
assert.deepEqual(commits, []);
});
}
test('directory navigation shows the current path separately and returns exactly one level', () => {
const React = require('react');
for (const source of ['scripts', 'logs']) {
let directory = 'parent/child';
const render = (input = '') => {
const states = [[directory, next => { directory = next; }], [input, () => {}], [input, () => {}]];
return action('components/fileBrowser/index.tsx', 'FileBrowser', {
React, Entries: 'div', Spin: 'span', ArrowUpOutlined: 'i', Button: 'button',
Input: { Search: 'input' }, Typography: { Text: 'span' }, intl: { get: key => key },
useEffect() {}, useState: () => states.shift(),
})({ source }).props.children[1];
};
assert.ok(!render('query'));
for (const expected of ['parent/child', 'parent']) {
const [up, location] = render().props.children;
assert.equal(up.props.children, '上一级');
assert.equal(location.props.title, expected);
assert.equal(location.props.children, expected);
up.props.onClick();
}
assert.ok(!render());
}
});
test('typing a different search removes the old interactive list throughout the debounce', () => {
const React = require('react');
function Entries() {}
function Spin() {}
let input = 'old';
let search = 'old';
const render = () => {
const values = ['', input, search];
return action('components/fileBrowser/index.tsx', 'FileBrowser', {
React,
Entries,
Spin,
Input: { Search: 'input' },
intl: { get: (key) => key },
useEffect() {},
useState: () => [values.shift(), () => {}],
})({ source: 'logs' }).props.children.at(-1);
};
assert.equal(render().type, Entries);
input = 'new';
assert.equal(render().type, Spin);
search = 'new';
assert.equal(render().props.search, 'new');
});
for (const [source, name] of [
['log', 'getLog'],
['script', 'getDetail'],
]) {
test(
source + ' keeps the newest read when A, B and A resolve in reverse order',
async () => {
const request = transport(),
key = { current: 'A' },
contents = [];
const select = action('pages/' + source + '/index.tsx', name, {
request,
config: { apiPrefix: '/api/' },
detailRequest: { current: undefined },
currentKeyRef: key,
selectedKey: key,
savedContentRef: { current: '' },
setReadState() {},
setReadFailed() {},
setValue: (value) => contents.push(value),
});
for (const file of ['A', 'B', 'A']) {
key.current = file;
select({ key: file, title: file });
}
assert.deepEqual(
request.calls.map((call) => call.config.signal.aborted),
[true, true, false],
);
for (const [n, data] of [
[2, 'new A'],
[1, 'B'],
[0, 'old A'],
]) {
request.calls[n].resolve({ code: 200, data });
await flush();
}
assert.deepEqual(contents, ['new A']);
},
);
}
test('expanded history retains its cursor and original head during inserts and retries the failed latest action', async () => {
const state = {
current: { rows: [], next: null, head: 0, hasNew: false, expanded: false },
};
const request = transport(),
pending = {},
paging = {},
visibleIds = { current: new Set([3]) };
let failure = '';
const scrolls = [];
const load = action('pages/crontab/instanceHistory.tsx', 'load', {
state,
request,
pending,
paging,
visibleIds,
list: { current: { scrollTo: position => scrolls.push(position) } },
pageSize: 2,
config: { apiPrefix: '/api/' },
id: 1,
setBusy() {},
setView() {},
setFailed(next) {
failure = typeof next === 'function' ? next(failure) : next;
},
});
function answer(ids, next) {
request.calls
.at(-1)
.resolve({ code: 200, data: ids.map((id) => ({ id, status: 1 })), next });
}
let reading = load('refresh');
answer([4, 3], 3);
await reading;
reading = load('older');
await load('older');
assert.deepEqual(request.calls.at(-1).config.params, { paged: true, limit: 2, before: 3 });
assert.equal(request.calls.length, 2);
request.calls.at(-1).reject(new Error('older request interrupted'));
await reading;
assert.equal(failure, 'older');
reading = load('refresh');
assert.deepEqual(request.calls.at(-1).config.params, { paged: true, limit: 1 });
answer([5], null);
await flush();
answer([3], null);
await reading;
assert.equal(state.current.hasNew, true);
assert.equal(failure, 'older');
reading = load(failure);
assert.deepEqual(request.calls.at(-1).config.params, { paged: true, limit: 2, before: 3 });
answer([2, 1], null);
await reading;
reading = load('refresh');
answer([6], null);
await flush();
assert.deepEqual(request.calls.at(-1).config.params, { paged: true, ids: '3' });
answer([3], null);
await reading;
assert.deepEqual(
state.current.rows.map((r) => r.id),
[4, 3, 2, 1],
);
assert.equal(state.current.hasNew, true);
reading = load('latest');
request.calls.at(-1).reject(new Error('offline'));
await reading;
assert.equal(failure, 'latest');
reading = load('refresh');
answer([6], null);
await flush();
answer([3], null);
await reading;
assert.equal(failure, 'latest');
reading = load(failure);
assert.deepEqual(scrolls, []);
answer([6, 5], 5);
await reading;
assert.deepEqual(
state.current.rows.map((r) => r.id),
[6, 5],
);
assert.equal(state.current.hasNew, false);
assert.deepEqual(scrolls, [0]);
});
+11
View File
@@ -150,3 +150,14 @@ test('healthy bootstrap continues loading system information', async () => {
await new Promise(setImmediate);
assert.deepEqual(events, ['system', ['loading', false]]);
});
test('retryable panel reads retain their route on gateway failures and still enforce login expiry', async () => {
for (const [status, retryInPlace, expected] of [[502, true, []], [504, true, []],
[502, false, ['/error']], [401, true, ['/login']]]) {
const {request, pushes} = fixture('/crontab');
await assert.rejects(request.get('/api/crons/1/triggers', {retryInPlace, adapter: async config => {
throw new axios.AxiosError('failed', 'ERR_BAD_RESPONSE', config, null, {status, config, data: {}});
}}));
assert.deepEqual(pushes, expected);
}
});
+29
View File
@@ -3,6 +3,35 @@ const test = require('node:test');
const path = require('node:path');
const load = require('../helpers/load-security-module.cjs');
test('debugger keeps the selected script when an older read completes after it', async () => {
const ts = require('typescript');
const file = path.resolve(__dirname, '../../src/pages/script/editModal.tsx');
const source = ts.createSourceFile(file, require('fs').readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
let read;
function visit(node) {
if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'getDetail')
read = node.initializer.getText(source);
ts.forEachChild(node, visit);
}
visit(source);
const js = ts.transpile('const read = ' + read, { target: ts.ScriptTarget.ES2022 });
const responses = [], ready = [], contents = [];
const get = Function('request', 'pendingFile', 'setFileReady', 'setValue', 'config', js + '\nreturn read;')(
{ get: (_url, { signal }) => new Promise(resolve => responses.push({ resolve, signal })) },
{ current: undefined }, state => ready.push(state), text => contents.push(text), { apiPrefix: '/api/' },
);
get({ title: 'slow.js' });
get({ title: 'current.js' });
assert.equal(responses[0].signal.aborted, true);
assert.equal(ready.at(-1), false);
responses[1].resolve({ code: 200, data: 'current' });
await tick();
responses[0].resolve({ code: 200, data: 'stale' });
await tick();
assert.deepEqual(contents, ['', '', 'current']);
assert.equal(ready.at(-1), true);
});
function fixture(send) {
const dialogs = [],
notices = [],
+940
View File
@@ -0,0 +1,940 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const fs = require('node:fs');
const path = require('node:path');
const ts = require('typescript');
const { createTriggerPoll } = require('../../src/pages/crontab/triggerUpdates');
// Run one tick to settlement for the filtering and single-round tests.
async function refreshExpandedHistory(rows, head, read, active, onHead, onBatch, open = new Set()) {
let failed = false;
createTriggerPoll(head, read, active, onHead, onBatch, value => { failed = value; }, open)(rows);
await new Promise(resolve => setImmediate(resolve));
return !failed;
}
const entry = (id, state = 'finished', reason) => ({
id: String(id), observed_at: 100, state, reason,
});
test('expanded terminal history checks for new triggers without fetching stable rows', async () => {
for (const [latest, expected] of [
[[], false], [[entry('a')], false], [[entry('b')], true],
[[{ ...entry('0'), observed_at: 101 }], true],
]) {
let notice;
const ok = await refreshExpandedHistory([entry('a')], entry('a'), async params => {
assert.equal(params.toString(), 'limit=1');
return latest;
}, () => true, newer => { notice = newer; }, assert.fail);
assert.equal(ok, true);
assert.equal(notice, expected);
}
});
test('refreshes recovered receipts and applies successful batches even if another request fails', async () => {
const rows = Array.from({ length: 25 }, (_, i) => entry(i, 'running'));
rows.push(entry('replay', 'skipped', 'restart'), entry('late', 'unknown', 'restart'),
entry('wait', 'queued'), entry('done'), entry('skipped', 'skipped', 'changed'));
for (const failing of [true, false]) {
const applied = [];
const ok = await refreshExpandedHistory(rows, rows[0], async params => {
const ids = params.getAll('ids');
if (failing && (!ids.length || ids.includes('0'))) throw new Error('temporary');
return ids.filter(id => id !== 'late').map(id => entry(id));
}, () => true, () => {}, (ids, updated) => applied.push([ids, updated.map(row => row.id)]));
assert.equal(ok, !failing);
assert.equal(applied.length, failing ? 1 : 2);
assert.deepEqual(applied.at(-1), [['replay', 'late', 'wait'], ['replay', 'wait']]);
}
});
test('an in-flight response after leaving expanded history cannot update the page', async () => {
let active = true;
let calls = 0;
await refreshExpandedHistory([entry('r', 'running')], entry('a'), async params => {
calls++;
if (params.has('ids')) active = false;
return [entry('b')];
}, () => active, () => {}, assert.fail);
assert.equal(calls, 2);
});
// Run the component's actual action and refresh handlers against controlled requests.
const source = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/detail.tsx'), 'utf8');
const ast = ts.createSourceFile('detail.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
function handler(name, bindings) {
let body;
function visit(node) {
if (ts.isVariableDeclaration(node) && node.name.getText(ast) === name)
body = node.initializer.getText(ast);
ts.forEachChild(node, visit);
}
visit(ast);
const js = ts.transpileModule('const implementation = ' + body, { fileName: 'handler.tsx',
compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText;
return Function(...Object.keys(bindings), js + '\nreturn implementation;')(...Object.values(bindings));
}
test('fresh task status survives an older detail poll without reading all instances', async () => {
let task;
const pending = [];
const refresh = handler('refreshDetails', {
cron: { id: 7 }, config: { apiPrefix: '/api/' }, refreshVersion: { current: 0 }, session: {current: new AbortController()}, setRefreshFailed() {},
request: { get(url) { return new Promise(resolve => pending.push({ url, resolve })); } },
setCurrentCron: value => { task = value; },
});
const old = refresh();
const fresh = refresh();
assert.deepEqual(pending.map(q => q.url), ['/api/crons/7', '/api/crons/7']);
pending[1].resolve({ code: 200, data: { status: 3 } });
await fresh;
pending[0].resolve({ code: 200, data: { status: 0 } });
await old;
assert.deepEqual(task, { status: 3 });
});
test('opening a historical log preserves the filename and lets the log reader issue the first request', () => {
let selected, opened = false;
const open = handler('viewInstanceLog', { cron: {id: 7}, config: { apiPrefix: '/api/' }, URLSearchParams,
setLogUrl(url) { selected = url; }, setIsLogModalVisible(value) { opened = value; },
});
open({ log_path: 'a & b/x#+%&.log' });
assert.equal(opened, true);
const query = new URL(selected, 'http://localhost').searchParams;
assert.equal(query.get('file'), 'x#+%&.log');
assert.equal(query.get('path'), 'a & b');
open({ id: 42, log_path: 'a & b/x#+%&.log' });
assert.equal(selected, '/api/crons/7/log?instanceId=42');
open({ id: 'selected', log_path: 'old.log' }, 'selected');
assert.equal(selected, '/api/crons/7/log?triggerId=selected');
});
test('cancelled page load cannot append, replace the cursor or restart its timer after a task switch', async () => {
const file = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8');
const tree = ts.createSourceFile('triggerList.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const effects = [];
function visit(node) {
if (ts.isCallExpression(node) && node.expression.getText(tree) === 'useEffect' &&
node.arguments[1]?.getText(tree).includes('before')) effects.push(node.arguments[0]);
ts.forEachChild(node, visit);
}
visit(tree);
assert.equal(effects.length, 1);
const compiled = ts.transpile('const effect = ' + effects[0].getText(tree), {target: ts.ScriptTarget.ES2022});
let rows = [], cursor;
const pending = [], timers = new Set();
const bindings = {
config: {apiPrefix: '/api/'}, pageSize: 25, pageRequest: {}, paused: false,
request: { get(url, options) { return new Promise(resolve => pending.push({url, options, resolve})); } },
setRows(fn) { rows = fn(rows); }, setLoading() {}, setFailed() {}, setNextCursor(row) { cursor = row; },
setTimeout(fn) { timers.add(fn); return fn; }, clearTimeout(fn) { timers.delete(fn); },
};
const start = Function('id', 'before', ...Object.keys(bindings), compiled + '\nreturn effect();');
const begin = (id, before) => start(id, before, ...Object.values(bindings));
const flush = () => new Promise(resolve => setImmediate(resolve));
const page = Array.from({length: 26}, (_, i) => entry('A' + i));
const stopFirst = begin(1, null);
pending[0].resolve({data: page});
await flush();
assert.equal(rows.length, 25);
stopFirst();
const stopOlder = begin(1, cursor);
assert.equal(pending[1].options.params.beforeId, 'A24');
stopOlder();
const stopB = begin(2, null);
pending[2].resolve({data: [entry('B')]});
await flush();
pending[1].resolve({data: page});
await flush();
assert.deepEqual(rows.map(row => row.id), ['B']);
assert.equal(cursor, null);
assert.equal(timers.size, 1);
stopB();
});
test('multiple clicks before React commits the loading state admit just one page transition', () => {
const source = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8');
const ast = ts.createSourceFile('triggerList.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let body;
function visit(node) {
if (ts.isJsxAttribute(node) && node.name.getText(ast) === 'onClick' &&
node.initializer?.getText(ast).includes('setBefore(nextCursor)')) body = node.initializer.expression.getText(ast);
ts.forEachChild(node, visit);
}
visit(ast);
assert.ok(body);
const compiled = ts.transpile('const click = ' + body, {target: ts.ScriptTarget.ES2022});
const controller = new AbortController();
const cursor = entry('tail'), transitions = [];
const bindings = {loading: false, pageRequest: {current: controller}, expanded: false,
rows: [entry('head')], headRef: {}, failed: false, nextCursor: cursor,
setBefore: value => transitions.push(value), setLoading() {}};
const click = Function(...Object.keys(bindings), compiled + '\nreturn click;')(...Object.values(bindings));
click(); click(); click();
assert.deepEqual(transitions, [cursor]);
assert.ok(controller.signal.aborted);
});
test('an operation completing after closing the task cannot launch another detail poll', async () => {
const controller = new AbortController();
const resolveReads = [];
const refresh = handler('refreshDetails', {
cron: {id: 1}, config: {apiPrefix: '/api/'}, refreshVersion: {current: 0},
session: {current: controller}, setRefreshFailed: assert.fail,
setCurrentCron: assert.fail, setRunningInstances: assert.fail,
request: {get(url, {signal}) {
assert.equal(signal, controller.signal);
return new Promise(resolve => resolveReads.push(resolve));
}},
});
const old = refresh();
controller.abort();
await refresh();
assert.equal(resolveReads.length, 1);
resolveReads.forEach(resolve => resolve({code: 200, data: 'old'}));
await old;
});
test('failed script read remains unavailable until a retry successfully loads the selected file', async () => {
const controller = new AbortController();
const states = [], values = [];
let response = Promise.resolve({code: 500, data: ''});
const get = handler('getScript', {
cron: {command: 'test'}, session: {current: controller}, getCommandScript: () => ['a#b.sh', 'dir'],
config: {apiPrefix: '/api/'}, tabList: [], setValidTabs() {}, setScriptInfo() {},
setScriptState: state => states.push(state), setValue: value => values.push(value),
request: {get(url, options) {
assert.equal(url, '/api/scripts/detail');
assert.equal(options.params.file, 'a#b.sh');
assert.equal(options.signal, controller.signal);
return response;
}},
});
get(); await new Promise(resolve => setImmediate(resolve));
assert.deepEqual(states, ['loading','failed']);
assert.deepEqual(values, []);
response = Promise.resolve({code: 200, data: 'loaded'});
get(); await new Promise(resolve => setImmediate(resolve));
assert.equal(states.at(-1), 'ready');
assert.deepEqual(values, ['loaded']);
});
test('switching to trigger history refreshes the task header without waiting for the next poll', () => {
const events = [];
const change = handler('onTabChange', {
setActiveTabKey: key => events.push(key),
refreshDetails: () => events.push('refresh'),
});
change('triggers');
assert.deepEqual(events, ['triggers', 'refresh']);
});
test('dashboard live rows open the clicked instance even when the task ID is shared', () => {
const source = fs.readFileSync(path.join(__dirname, '../../src/pages/dashboard/index.tsx'), 'utf8');
const tree = ts.createSourceFile('dashboard.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let click, url;
function visit(node) {
if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onClick' &&
node.initializer?.expression?.getText(tree).includes('setLogCron({')) click = node.initializer.expression;
if (ts.isJsxSelfClosingElement(node) && node.tagName.getText(tree) === 'CronLogModal') {
url = node.attributes.properties.find(p => p.name?.getText(tree) === 'logUrl')?.initializer.expression;
}
ts.forEachChild(node, visit);
}
visit(tree);
assert.ok(click && url);
for (const instanceId of [41, 42]) {
let selection;
Function('setLogCron', 'record', 'id', '(' + click.getText(tree) + ')()')(
value => { selection = value; }, { name: 'concurrent', instanceId }, 7);
const endpoint = Function('config', 'logCron', 'return ' + url.getText(tree))({ apiPrefix: '/api/' }, selection);
assert.equal(endpoint, '/api/crons/7/log?instanceId=' + instanceId);
}
});
test('a double click opens a single stop confirmation and natural completion refreshes the selected task', async () => {
const dialogs = [], messages = [], requests = [];
const open = handler('stopRunningInstance', {
stopDialogs: { current: new Set() }, Modal: { confirm: opts => dialogs.push(opts) },
React: require('react'), intl: { get: text => text }, cron: { id: 7 }, config: { apiPrefix: '/api/' },
request: { post: async url => { requests.push(url); return { code: 200, data: { outcome: 'ended' } }; } },
message: { info: text => messages.push(text), success: assert.fail },
refreshAfterChange: () => messages.push('refresh'),
});
open({ id: 11, pid: 101 });
open({ id: 11, pid: 101 });
open({ id: 12, pid: 102 });
assert.equal(dialogs.length, 2);
await dialogs[0].onOk();
assert.deepEqual(requests, ['/api/crons/7/instances/11/stop']);
assert.deepEqual(messages, ['实例已结束', 'refresh']);
dialogs[0].afterClose();
open({ id: 11, pid: 101 });
assert.equal(dialogs.length, 3);
});
test('retrying the same stop confirmation retains its key and selections, and a fresh action gets a new key', async () => {
const load = require('../helpers/load-security-module.cjs');
const sent = [];
const notices = [];
const { createStopRequest } = load('src/pages/crontab/stopRequest.ts', {
antd: { message: { error: m => notices.push(m) } },
'react-intl-universal': { get: s => s },
'@/utils/config': { apiPrefix: '/api/' },
'@/utils/http': { request: { put: async (url, ids, options) => {
sent.push([url, [...ids], options.headers['Idempotency-Key']]);
if (sent.length === 1) throw Error('connection lost');
return { code: 200 };
} } },
});
const ids = [3, 1];
const confirm = createStopRequest(ids);
ids.push(7);
await assert.rejects(confirm(), /connection lost/);
await confirm();
await createStopRequest(ids)();
assert.deepEqual(sent[0], sent[1]);
assert.deepEqual(sent[0][1], [3, 1]);
assert.notEqual(sent[0][2], sent[2][2]);
assert.deepEqual(notices, ['停止请求未确认,可重试本次操作']);
});
test('expanded history refreshes a pending exit until the repaired result replaces it', async () => {
let rows = [entry('older', 'unknown', 'exit_pending'), entry('stable')];
const requested = [];
const refresh = () => refreshExpandedHistory(rows, rows[0], async params => {
if (!params.has('ids')) return [rows[0]];
requested.push(params.getAll('ids'));
return [entry('older', 'failed')];
}, () => true, () => {}, (_, updates) => { rows = [updates[0], rows[1]]; });
await refresh();
await refresh();
assert.deepEqual(requested, [['older']]);
assert.equal(rows[0].state, 'failed');
});
test('expanded history follows a booked legacy exit through dispute and definitive resolution', async () => {
let rows = [{ ...entry('old', 'finished'), legacy_exit_booking: 1 }, entry('sibling', 'finished')];
const requests = [];
for (const next of [entry('old', 'unknown', 'exit_conflict'), entry('old', 'failed'), null]) {
await refreshExpandedHistory(rows, rows[0], async params => {
if (!params.has('ids')) return [rows[0]];
requests.push(params.getAll('ids'));
assert.ok(next);
return [next];
}, () => true, () => {}, (_, updates) => { rows = [updates[0], rows[1]]; });
}
assert.deepEqual(requests, [['old'], ['old']]);
assert.deepEqual(rows.map(row => row.state), ['failed', 'finished']);
});
test('dashboard never rounds a missed plan up to 100 percent or treats an empty denominator as punctual', () => {
const file = fs.readFileSync(path.join(__dirname, '../../src/pages/dashboard/index.tsx'), 'utf8');
const tree = ts.createSourceFile('dashboard.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const component = tree.statements.find(node => ts.isFunctionDeclaration(node) && node.name?.text === 'ScheduleRate');
const {outputText} = ts.transpileModule(component.getText(tree), {fileName:'rate.tsx',
compilerOptions:{jsx:ts.JsxEmit.React,target:ts.ScriptTarget.ES2020}});
const rate = new Function('React','Statistic',outputText+';return ScheduleRate;')(
{createElement: (_type, props) => props}, 'Statistic');
for (const [count,total,value] of [[9999,10000,'>99.9%'],[10000,10000,'100.0%'],[0,1,'0.0%'],[0,0,'—']]) {
assert.equal(rate({title:'on time',count,total}).value,value);
}
});
test('opened terminal timelines keep receiving late samples by trigger ID alongside live siblings', async () => {
const sameSecond = [entry('old'), entry('sibling'), entry('live', 'queued')];
const open = new Set(['old', 'live']);
const states = new Map(sameSecond.map(row => [row.id, row]));
for (const state of ['running', 'finished']) {
await refreshExpandedHistory([...states.values()], sameSecond[0], async params => {
const ids = params.getAll('ids');
if (!ids.length) return [entry('new')];
assert.deepEqual(ids, ['old', 'live']);
return [{...entry('live', state), started_at: 22}, {...entry('old'), script_started_at: 17}];
}, () => true, newer => assert.equal(newer, false), (_, rows) => {
for (const row of rows) states.set(row.id, row);
}, open);
assert.equal(states.get('old').script_started_at, 17);
assert.equal(states.get('live').state, state);
assert.equal(states.get('sibling').script_started_at, undefined);
}
});
test('opening a timeline cancels an in-flight first page and pins its head until the last detail closes', async () => {
const source = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8');
const tree = ts.createSourceFile('triggerList.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let toggle, fetchPage, pageDeps;
function visit(node) {
if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onToggle') toggle = node.initializer.expression;
if (ts.isCallExpression(node) && node.expression.getText(tree) === 'useEffect'
&& node.arguments[1]?.getText(tree).includes('before')) [fetchPage, pageDeps] = node.arguments;
ts.forEachChild(node, visit);
}
visit(tree);
const rows = [entry('newer'), entry('subject')], headRef = {}, pageRequest = {}, requests = [];
let opened = new Set(), paused = false, visible = rows, attempt = 0;
const context = {
rows, row: rows[1], headRef, pageRequest, statusRequest:{}, before:null, id:7, pageSize:25, config:{apiPrefix:'/api/'},
expanded:false, get pinned() {return opened.size > 0;}, get paused() {return paused;},
get attempt() {return attempt;}, setAttempt(fn) {attempt = fn(attempt);},
setOpenIds(fn) {opened = fn(opened);},
request:{get:() => new Promise(resolve => requests.push(resolve))},
setRows(fn) { visible = fn(visible); },
setRefreshFailed(){},setHasNew(){},setLoading(){},setNextCursor(){},setFailed(){},
setTimeout(){return 1;},clearTimeout(){},
};
const invoke = body => Function(...Object.keys(context),
ts.transpile('const fn = '+body.getText(tree), {target:ts.ScriptTarget.ES2022})+'\nreturn fn();')(...Object.values(context));
const stopFirst = invoke(fetchPage);
invoke(toggle);
assert.ok(pageRequest.current.signal.aborted);
assert.equal(headRef.current.id,'newer');
assert.deepEqual([...opened], ['subject']);
stopFirst();paused = true;
const leavePinned = invoke(fetchPage);
assert.equal(requests.length,1);
requests[0]({data:[entry('late-first-page')]});
await new Promise(resolve=>setImmediate(resolve));
assert.deepEqual(visible, rows);
invoke(toggle);assert.equal(opened.size,0);
leavePinned();paused = false;
const close = invoke(fetchPage);
requests[1]({data:[entry('current-first-page')]});
await new Promise(resolve=>setImmediate(resolve));
assert.equal(visible[0].id,'current-first-page');
// Two activations in a single commit leave the first page visible.
const dependencies = () => Function(...Object.keys(context), 'return '+pageDeps.getText(tree))(...Object.values(context));
const prior = dependencies();
const click = Function(...Object.keys(context), ts.transpile('const fn = '+toggle.getText(tree),
{target:ts.ScriptTarget.ES2022})+'\nreturn fn;')(...Object.values(context));
click(); click();
assert.equal(opened.size,0);
assert.ok(pageRequest.current.signal.aborted);
assert.notDeepEqual(dependencies(),prior,'the aborted first-page poll needs a replacement even when the page stays unpinned');
close();
});
test('reopening a timeline with its sibling still open supersedes stale running and queued responses', async () => {
const file = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8');
const tree = ts.createSourceFile('triggerList.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let toggle, pollEffect, deps;
function visit(node) {
if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onToggle') toggle = node.initializer.expression;
if (ts.isCallExpression(node) && node.expression.getText(tree) === 'useEffect'
&& node.arguments[1]?.getText(tree).includes('pinned')) [pollEffect, deps] = node.arguments;
ts.forEachChild(node, visit);
}
visit(tree);
const old = [entry('a','running'), {...entry('b','queued'), queue_wait_ms:1000}];
const latest = [{...entry('b','finished'), started_at:1200, queued_at:1000, script_started_at:1300},
{...entry('a','failed'), exit_code:7, script_started_at:1100}];
const requests = [], timers = new Set();
let rows = old, opened = new Set(['a','b']);
const headRef = {current:old[0]}, statusRequest = {}, pageRequest = {};
const context = {id:1, pinned:true, updateStatus:{}, row:old[1], rows:old, headRef, rowsRef:{current:old},
get openIds() {return opened;}, get firstPageSelection(){return opened;}, expanded:false, statusRequest, pageRequest,
setOpenIds(update){ opened=update(opened); },
createTriggerPoll, config:{apiPrefix:'/api/'}, setHasNew(){},setRefreshFailed(){},
setRows(update){rows=update(rows);}, setTimeout(fn){timers.add(fn);return fn;}, clearTimeout(fn){timers.delete(fn);},
request:{ get(url,{params,signal}) {return params.has('ids')
? new Promise(resolve=>requests.push({signal,resolve})) : Promise.resolve({data:[old[0]]});} },
};
function evaluate(body) {
return Function(...Object.keys(context),ts.transpile('const result = '+body,{target:ts.ScriptTarget.ES2022})+
'\nreturn result;')(...Object.values(context));
}
let previousDeps, dispose;
const flush = () => new Promise(resolve=>setImmediate(resolve));
async function commit() {
const next=evaluate(deps.getText(tree));
if (!previousDeps || next.some((value,i)=>value!==previousDeps[i])) {
dispose?.();
dispose=evaluate(pollEffect.getText(tree))();
}
previousDeps=next;
await flush();
}
await commit();
evaluate(toggle.getText(tree))();
assert.ok(requests[0].signal.aborted, 'close must revoke the old response before effects run');
await commit();
evaluate(toggle.getText(tree))();
await commit();
assert.equal(requests.length,3);
requests[2].resolve({data:latest});
await flush();
for (const stale of requests.slice(0,2).reverse()) stale.resolve({data:old});
await flush();
assert.deepEqual(rows,[latest[1],latest[0]]);
assert.deepEqual([...opened].sort(),['a','b']);
assert.equal(timers.size,1);
dispose();
assert.equal(timers.size,0);
});
test('opening a detail and loading an older page in the same commit keep the page request and its loading indicator', () => {
const file = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8');
const tree = ts.createSourceFile('triggerList.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let toggle, load;
function visit(node) {
if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onToggle') toggle = node.initializer.expression;
if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onClick' && node.initializer.getText(tree).includes('setBefore(nextCursor)')) load = node.initializer.expression;
ts.forEachChild(node, visit);
}
visit(tree);
for (const order of [[toggle, load, load], [load, toggle, load]]) {
const rows = [entry('first'), entry('tail')], cursors = [];
let loading = false;
const bindings = {row:rows[0], rows, pageRequest:{current:new AbortController()}, statusRequest:{},
pinned:false, loading:false, expanded:false, failed:false, nextCursor:rows[1], headRef:{},
setBefore:value=>cursors.push(value), setLoading:value=>{loading=value;},
setOpenIds(){},setHasNew(){},setFailed(){},setRefreshFailed(){},setAttempt(){}};
for (const action of order) {
const compiled=ts.transpile('const action='+action.getText(tree),{target:ts.ScriptTarget.ES2022});
Function(...Object.keys(bindings),compiled+'\naction();')(...Object.values(bindings));
}
assert.deepEqual(cursors,[rows[1]],'a click must request the cursor exactly once');
assert.equal(loading,true,'pinning details must not clear an accepted page load');
}
});
test('a stalled head and first status batch do not hold up a later batch with a late entry sample', async () => {
const rows = Array.from({length:51}, (_,i)=>entry(i,'running'));
const batches = [], resolved = [];
let head;
let failed;
const tick = createTriggerPoll(rows[0],params=>{
const ids=params.getAll('ids');
if (!ids.length) return new Promise(resolve=>{head=resolve;});
return new Promise((resolve,reject)=>batches.push({ids,resolve,reject}));
},()=>true,()=>{},(_,updates)=>resolved.push(...updates),value=>{failed=value;},new Set());
tick(rows);
try {
await new Promise(resolve=>setImmediate(resolve));
assert.deepEqual(batches.map(x=>x.ids.length),[25,25]);
const late={...entry('30','finished'),script_started_at:421};
batches[1].resolve([late]);
await new Promise(resolve=>setImmediate(resolve));
assert.deepEqual(resolved,[late]);
assert.deepEqual(batches[2].ids,['50']);
batches[2].resolve([]);
batches[0].reject(new Error('timeout'));
head([]);
await new Promise(resolve=>setImmediate(resolve));
assert.equal(failed,true);
assert.deepEqual(resolved,[late]);
} finally {
head([]);
for (const batch of batches) batch.resolve([]);
}
});
test('page and status retries can settle in either order before both abandoned reads return', async () => {
const file = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8');
const tree = ts.createSourceFile('triggerList.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const effects = {};
function visit(node) {
if (ts.isCallExpression(node) && node.expression.getText(tree) === 'useEffect') {
const dependencies = node.arguments[1]?.getText(tree);
if (dependencies?.includes('pinned')) effects.status = node.arguments[0];
if (dependencies?.includes('before')) effects.page = node.arguments[0];
}
ts.forEachChild(node, visit);
}
visit(tree);
const flush = () => new Promise(resolve => setImmediate(resolve));
for (const pageFirst of [false, true]) {
const first = entry('simultaneous-B', 'running');
const tail = entry('simultaneous-A', 'queued');
const completed = { ...first, state: 'failed', exit_code: 7, script_started_at: 1220 };
const dispatched = { ...tail, state: 'running', queued_at: 1110, started_at: 1200 };
const older = entry('earlier');
let rows = [first, tail];
let nextCursor = tail;
const calls = { page: [], status: [] };
const openIds = new Set(rows.map(row => row.id));
const timers = new Set();
const bindings = {
rowsRef: { current: rows }, headRef: { current: first }, pageRequest: {}, statusRequest: {}, updateStatus: {},
before: tail, id: 17, openIds, pinned: true, paused: false, pageSize: 25, createTriggerPoll,
config: { apiPrefix: '/api/' },
request: { get(url, { params, signal }) {
if (params instanceof URLSearchParams && !params.has('ids')) return Promise.resolve({ data: [first] });
const kind = params instanceof URLSearchParams ? 'status' : 'page';
return new Promise(resolve => calls[kind].push({ params, signal, resolve }));
} },
setNextCursor(value) { nextCursor = value; },
setRows(update) { rows = update(rows); },
setHasNew() {}, setLoading() {}, setRefreshFailed() {}, setFailed() {},
setTimeout(fn) { timers.add(fn); return fn; }, clearTimeout(fn) { timers.delete(fn); },
};
function start(kind) {
const js = ts.transpile('const effect = ' + effects[kind].getText(tree), { target: ts.ScriptTarget.ES2022 });
return Function(...Object.keys(bindings), js + '\nreturn effect();')(...Object.values(bindings));
}
const endOldPage = start('page');
const endOldStatus = start('status');
endOldPage();
endOldStatus();
const endPage = start('page');
const endStatus = start('status');
try {
assert.deepEqual(calls.page.map(call => call.params.beforeId), [tail.id, tail.id]);
assert.deepEqual(calls.status[1].params.getAll('ids'), [...openIds]);
const sequence = pageFirst ? ['page', 'status'] : ['status', 'page'];
for (const kind of sequence) {
calls[kind][1].resolve({ data: kind === 'page' ? [older] : [dispatched, completed] });
await flush();
}
for (const kind of sequence.reverse()) {
const old = calls[kind][0];
assert.ok(old.signal.aborted);
old.resolve({ data: kind === 'page' ? [older] : [first, tail] });
await flush();
assert.deepEqual(rows, [completed, dispatched, older]);
assert.equal(nextCursor, null);
}
assert.equal(timers.size, 1);
} finally {
endPage();
endStatus();
}
assert.equal(timers.size, 0);
}
});
test('a held batch cannot delay later polls of other IDs or hide its failure on a sibling success', async () => {
const rows = Array.from({ length: 76 }, (_, i) => entry(i));
const open = new Set(rows.map(row => row.id));
const requests = [], notices = [], errors = [], updates = [];
let active = true;
const tick = createTriggerPoll(rows[0], params => new Promise((resolve, reject) => {
requests.push({ ids: params.getAll('ids'), resolve, reject });
}), () => active, value => notices.push(value), (ids, data) => updates.push(...data),
value => errors.push(value), open);
const flush = () => new Promise(resolve => setImmediate(resolve));
const cycle = () => { tick(rows); };
const headReads = () => requests.filter(r => !r.ids.length);
const batches = () => requests.filter(r => r.ids.length);
cycle();
const slow = batches()[0];
const latest = { ...rows[25], script_started_at: 321, state: 'failed', exit_code: 7 };
for (let round = 0; round < 3; round++) {
for (let offset = 25; offset < rows.length; offset += 25) {
const batch = batches().at(-1);
assert.deepEqual(batch.ids, rows.slice(offset, offset + 25).map(r => r.id));
batch.resolve(offset === 25 && round === 2 ? [latest] : []);
await flush();
}
if (round < 2) cycle();
}
assert.ok(updates.includes(latest));
assert.equal(batches().filter(r => r.ids.includes('0')).length, 1);
assert.equal(headReads().length, 1);
slow.reject(new Error('timeout'));
await flush();
assert.equal(errors.at(-1), true);
headReads()[0].resolve([entry('new')]);
await flush();
assert.equal(errors.at(-1), true);
cycle();
const retry = batches().findLast(r => r.ids.includes('0'));
assert.notEqual(retry, slow);
retry.resolve(rows.slice(0, 25));
await flush();
assert.equal(errors.at(-1), false);
active = false;
const prior = { updates: updates.length, notices: notices.length, errors: errors.length };
requests.forEach(r => r.resolve([entry('stale', 'running')]));
await flush();
assert.deepEqual({ updates: updates.length, notices: notices.length, errors: errors.length }, prior);
});
test('the mounted list keeps its five-second timer while a status batch is pending and cancels it on exit', async () => {
const file = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8');
const tree = ts.createSourceFile('triggerList.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let effect;
function visit(node) {
if (ts.isCallExpression(node) && node.expression.getText(tree) === 'useEffect' &&
node.arguments[1]?.getText(tree).includes('pinned')) effect = node.arguments[0];
ts.forEachChild(node, visit);
}
visit(tree);
const rows = Array.from({ length: 51 }, (_, i) => entry(i, 'running'));
const reads = [], timers = new Map(), changes = [];
const bindings = {
rowsRef: { current: rows }, headRef: { current: rows[0] }, statusRequest: {}, updateStatus: {},
id: 23, pinned: true, openIds: new Set(rows.map(row => row.id)), createTriggerPoll,
config: { apiPrefix: '/api/' }, setHasNew() {}, setRefreshFailed() {},
setRows(update) { changes.push(update(rows)); },
setTimeout(fn, ms) { timers.set(fn, ms); return fn; }, clearTimeout(fn) { timers.delete(fn); },
request: { get(url, { params, signal }) {
const ids = params.getAll('ids');
if (!ids.length) return Promise.resolve({ data: [rows[0]] });
if (ids.includes('25')) return new Promise(resolve => reads.push({ ids, signal, resolve }));
reads.push({ ids, signal });
return Promise.resolve({ data: rows.filter(row => ids.includes(row.id)) });
} },
};
const js = ts.transpile('const setup = ' + effect.getText(tree), { target: ts.ScriptTarget.ES2022 });
const dispose = Function(...Object.keys(bindings), js + '\nreturn setup();')(...Object.values(bindings));
const flush = () => new Promise(resolve => setImmediate(resolve));
try {
for (let tick = 0; tick < 2; tick++) {
await flush();
assert.equal(timers.size, 1);
const [[next, ms]] = timers;
assert.equal(ms, 5000);
timers.delete(next);
next();
}
await flush();
assert.equal(reads.filter(read => read.ids.includes('0')).length, 3);
assert.equal(reads.filter(read => read.ids.includes('25')).length, 1);
} finally {
dispose();
}
const count = changes.length;
const old = reads.find(read => read.resolve);
assert.ok(old.signal.aborted);
old.resolve({ data: rows });
await flush();
assert.equal(changes.length, count);
assert.equal(timers.size, 0);
});
test('pending IDs keep their place when pages change between ticks and each ID has at most one outstanding read', async () => {
const initial = Array.from({ length: 85 }, (_, i) => entry(i, 'running'));
let active = true;
const calls = [];
const tick = createTriggerPoll(initial[0], params => {
if (!params.has('ids')) return Promise.resolve([]);
return new Promise(resolve => calls.push({ ids: params.getAll('ids'), resolve }));
}, () => active, () => {}, () => {}, () => {}, new Set());
tick(initial);
assert.equal(calls.length, 2);
// Drop one queued row, append two newly loaded rows, then reverse display order.
const changed = [...initial.filter(r => r.id !== '60'), entry('85', 'queued'), entry('86', 'queued')];
tick(changed.toReversed());
tick(changed);
assert.equal(calls.length, 2);
calls[1].resolve([]);
await new Promise(resolve => setImmediate(resolve));
assert.deepEqual(calls[2].ids, changed.slice(50, 75).map(r => r.id));
tick(changed);
calls[2].resolve([]);
await new Promise(resolve => setImmediate(resolve));
assert.deepEqual(calls[3].ids.slice(0, 11), [...initial.slice(76).map(r => r.id), '86', '85']);
assert.ok(!calls[3].ids.some(id => calls[0].ids.includes(id)));
active = false;
calls[3].resolve([]);
calls[0].resolve([]);
});
test('consecutive double timeouts give the waiting tail its turn and retries leave healthy reads alone', async () => {
const rows = Array.from({ length: 75 }, (_, i) => entry(i, 'running'));
const calls = [], errors = [], updated = [];
let heads = 0;
const poll = createTriggerPoll(rows[0], params => {
if (!params.has('ids')) {
heads++;
return Promise.resolve([]);
}
return new Promise((resolve, reject) => calls.push({ ids: params.getAll('ids'), resolve, reject }));
}, () => true, () => {}, (_, data) => updated.push(...data), value => errors.push(value), new Set());
const flush = () => new Promise(resolve => setImmediate(resolve));
poll(rows);
assert.equal(calls.length, 2);
calls[0].reject(new Error('timeout'));
calls[1].reject(new Error('timeout'));
await flush();
assert.deepEqual(calls[2].ids, rows.slice(50).map(r => r.id));
poll(rows, 'retry');
poll(rows, 'retry');
assert.equal(calls.length, 4);
assert.equal(heads, 1, 'retry must not restart the successful head check');
const late = { ...rows[60], state: 'finished', script_started_at: 1234 };
calls[2].resolve([late]);
await flush();
assert.equal(calls.length, 5);
assert.deepEqual(calls.slice(3).flatMap(c => c.ids), rows.slice(0, 50).map(r => r.id));
calls[3].reject(new Error('timeout again'));
calls[4].reject(new Error('timeout again'));
await flush();
poll(rows);
const newest = { ...rows[60], state: 'finished', script_started_at: 1234, exit_code: 0 };
calls[5].resolve([]);
calls[6].resolve([]);
await flush();
assert.deepEqual(calls[7].ids, rows.slice(50).map(r => r.id));
calls[7].resolve([newest]);
await flush();
assert.deepEqual(updated, [late, newest]);
assert.equal(errors.at(-1), false);
const before = calls.length;
poll(rows, 'retry');
assert.equal(calls.length, before, 'retry with no remaining failure must not query healthy rows');
});
test('retry button preserves pending responses and bounds the two status reads in the mounted list', async () => {
const file = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8');
const tree = ts.createSourceFile('triggerList.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let effect, retry;
function visit(node) {
if (ts.isCallExpression(node) && node.expression.getText(tree) === 'useEffect' &&
node.arguments[1]?.getText(tree).includes('pinned')) effect = node.arguments[0];
if (ts.isJsxElement(node) && node.openingElement.tagName.getText(tree) === 'Button' &&
node.children.some(child => child.getText(tree).includes("intl.get('重试')"))) {
retry = node.openingElement.attributes.properties.find(a => a.name?.getText(tree) === 'onClick').initializer.expression;
}
ts.forEachChild(node, visit);
}
visit(tree);
const rows = Array.from({ length: 76 }, (_, i) => entry(i, 'running'));
const calls = [], mutations = [];
const bindings = {
id: 4, pinned: true, openIds: new Set(), createTriggerPoll,
rowsRef: {current:rows}, headRef: {current:rows[0]}, statusRequest:{}, updateStatus: {},
config: {apiPrefix:'/api/'}, setHasNew(){}, setRefreshFailed(){},
setRows(update){ mutations.push(update(rows)); }, setTimeout(){}, clearTimeout(){},
request: { get(url, { signal, timeout, params }) {
if (!params.has('ids')) return Promise.resolve({data:[]});
return new Promise((resolve,reject)=>calls.push({ids:params.getAll('ids'),signal,timeout,resolve,reject}));
} },
};
function run(node) {
const js=ts.transpile('const action='+node.getText(tree),{target:ts.ScriptTarget.ES2022});
return Function(...Object.keys(bindings),js+'\nreturn action();')(...Object.values(bindings));
}
const dispose=run(effect);
const flush=()=>new Promise(resolve=>setImmediate(resolve));
try {
assert.equal(calls.length,2);
assert.ok(calls.every(call=>call.timeout===10000));
calls[0].reject(new Error('timeout'));
await flush();
run(retry);
run(retry);
assert.equal(calls.length,3);
assert.ok(calls.every(call=>!call.signal.aborted));
const terminal={...rows[60],state:'failed',exit_code:7,script_started_at:721};
calls[2].resolve({data:[terminal]});
await flush();
assert.ok(mutations.at(-1).includes(terminal));
assert.equal(calls[3].ids[0],'75', 'oldest waiting ID must precede the manual retry');
} finally {
dispose();
}
const count=mutations.length;
for (const call of calls) call.resolve({data: rows});
await flush();
assert.equal(mutations.length,count);
});
test('selection churn and retries cannot move waiting IDs behind the front pages or cancel an unrelated read', async () => {
const rows = Array.from({ length: 100 }, (_, i) => entry(i, 'finished'));
const open = new Set(rows.map(r => r.id));
const calls = [], updates = [];
let heads = 0;
const poll = createTriggerPoll(rows[0], params => {
if (!params.has('ids')) { heads++; return Promise.resolve([]); }
return new Promise((resolve, reject) => calls.push({ ids: params.getAll('ids'), resolve, reject }));
}, () => true, () => {}, (_, entries) => updates.push(...entries), () => {}, open);
const flush = () => new Promise(resolve => setImmediate(resolve));
poll(rows);
for (const id of ['2', '29', '50', '75']) {
const closed = new Set(open);
closed.delete(id);
poll(rows, closed);
poll(rows, 'retry');
poll(rows, open);
}
assert.equal(calls.length, 2);
assert.equal(heads, 1);
calls[0].reject(new Error('timeout'));
calls[1].reject(new Error('timeout'));
await flush();
assert.deepEqual(calls.slice(2).map(c => c.ids), [rows.slice(50,75), rows.slice(75)].map(group => group.map(r => r.id)));
const closed = new Set(open);
closed.delete('0');
poll(rows, closed);
poll(rows, 'retry');
calls[2].resolve([]);
calls[3].resolve([{ ...rows[78], script_started_at: 1234 }]);
await flush();
assert.ok(updates.some(r => r.id === '78' && r.script_started_at === 1234));
assert.ok(!calls.slice(4).some(c => c.ids.includes('0')));
for (const call of calls.slice(4)) call.resolve([]);
});
test('an opened in-flight row gets one fresh read after its peers, even after several close and reopen events', async () => {
const rows = Array.from({ length: 60 }, (_, i) => entry(i));
const open = new Set(rows.map(r => r.id));
const closed = new Set(open);
closed.delete('4');
const calls = [], applied = [];
const poll = createTriggerPoll(rows[0], params => {
if (!params.has('ids')) return Promise.resolve([]);
return new Promise(resolve => calls.push({ ids: params.getAll('ids'), resolve }));
}, () => true, () => {}, (_, values) => applied.push(...values), () => {}, open);
const flush = () => new Promise(resolve => setImmediate(resolve));
poll(rows);
for (let i = 0; i < 5; i++) {
poll(rows, closed);
poll(rows, open);
}
assert.equal(calls.length, 2);
calls[0].resolve([rows[4]]);
await flush();
assert.deepEqual(calls[2].ids, [...rows.slice(50).map(r => r.id), '4']);
const sampled = { ...rows[4], script_started_at: 12345, exit_code: 0 };
calls[2].resolve([sampled]);
calls[1].resolve([]);
await flush();
assert.deepEqual(applied, [rows[4], sampled]);
assert.equal(calls.length, 3);
});
test('the paginated list keeps its polling session when details change and forwards the new selection', () => {
const file = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/triggerList.tsx'), 'utf8');
const tree = ts.createSourceFile('triggerList.tsx', file, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
let toggle, dependencies, firstPage, notify;
function visit(node) {
if (ts.isVariableDeclaration(node) && node.name.getText(tree) === 'firstPageSelection') firstPage = node.initializer;
if (ts.isJsxAttribute(node) && node.name.getText(tree) === 'onToggle') toggle = node.initializer.expression;
if (ts.isCallExpression(node) && node.expression.getText(tree) === 'useEffect') {
if (node.arguments[0].getText(tree).includes('createTriggerPoll(')) dependencies = node.arguments[1];
if (node.arguments[1]?.getText(tree) === '[expanded, openIds]') notify = node.arguments[0];
}
ts.forEachChild(node, visit);
}
visit(tree);
const rows = Array.from({ length: 100 }, (_, i) => entry(i));
let opened = new Set();
const requests = [];
const controller = new AbortController();
const bindings = {
id: 1, pinned: true, expanded: true, rows, rowsRef: { current: rows }, row: rows[76],
get openIds() { return opened; },
setOpenIds(change) { opened = change(opened); },
statusRequest: { current: controller },
updateStatus: { current: (visible, selection) => requests.push({ visible, selection }) },
};
function evaluate(expression, extra = {}) {
const scope = { ...bindings, ...extra };
return Function(...Object.keys(scope), 'return (' + expression.getText(tree) + ');')(...Object.values(scope));
}
const deps = () => evaluate(dependencies, { firstPageSelection: evaluate(firstPage) });
const before = deps();
for (const index of [76, 32, 76, 2, 76]) {
bindings.row = rows[index];
evaluate(toggle)();
assert.deepEqual(deps(), before);
assert.ok(!controller.signal.aborted);
evaluate(notify)();
assert.equal(requests.at(-1).selection, opened);
assert.equal(requests.at(-1).visible, rows);
}
});
+128
View File
@@ -0,0 +1,128 @@
const assert = require('node:assert/strict');
const { before, test } = require('node:test');
const fs = require('node:fs');
const ts = require('typescript');
const React = require('react');
const { renderToStaticMarkup } = require('react-dom/server');
const intl = require('react-intl-universal');
const zh = require('../../src/locales/zh-CN.json');
const en = require('../../src/locales/en-US.json');
// Render the actual TSX, including disclosure markup and translated field names.
const source = fs.readFileSync(require.resolve('../../src/pages/crontab/triggerTiming.tsx'), 'utf8');
const { outputText } = ts.transpileModule(source, { compilerOptions: {
jsx: ts.JsxEmit.ReactJSX, module: ts.ModuleKind.CommonJS, esModuleInterop: true,
target: ts.ScriptTarget.ES2022,
}});
const output = {};
Function('require', 'exports', outputText)(require, output);
const base = new Date(2026, 10, 16, 14, 55).getTime();
before(() => intl.init({currentLocale: 'zh-CN', locales: {'zh-CN': zh, 'en-US': en}}));
function render(fields) {
const html = renderToStaticMarkup(React.createElement(output.default, { row: {
observed_at: base, state: 'running', source: 'node', exit_code: null, ...fields,
}}));
const [summary, details] = html.split(/<details[^>]*>/);
assert.doesNotMatch(html, /<details[^>]* open/);
assert.match(details, /<summary>时间明细<\/summary>/);
assert.equal((details.match(/<dt>/g) || []).length, 6);
return { summary, details };
}
test('summary separates 57 ms in queue from 158 ms to command start and optional script entry', () => {
const fields = { scheduled_at: base, queued_at: base + 10, started_at: base + 67,
command_started_at: base + 158 };
for (const script_started_at of [null, base + 201]) {
const { summary, details } = render({ ...fields, script_started_at });
assert.match(summary, /排队等待 <b>57 ms/);
assert.match(summary, /计划到命令启动 <b>158 ms/);
assert.doesNotMatch(summary, /结束时间|脚本/);
assert.match(details, /命令启动<\/dt><dd>14:55:00.158/);
if (script_started_at == null) {
assert.match(details, /脚本开始执行(采样)<\/dt><dd>未采集到开始时间/);
assert.doesNotMatch(details, /计划到脚本开始/);
} else {
assert.match(details, /计划到脚本开始 <b>201 ms/);
}
}
const {summary} = render({...fields, state:'finished', finished_at:base+3158});
assert.match(summary, /计划到命令启动 <b>158 ms/);
assert.match(summary, /结束时间 <b>14:55:03/);
});
test('only a currently queued run accumulates wait; skip or stop freezes the wait', (t) => {
t.mock.method(Date, 'now', () => base + 7000);
const fields = { queued_at:base, scheduled_at:base, started_at:null };
assert.match(render({...fields, state:'queued'}).summary, /已排队 <b>7 s/);
const { summary, details } = render({...fields, state:'skipped', finished_at:base+12});
assert.doesNotMatch(summary, /已排队|计划到命令启动|排队等待/);
assert.match(details, /跳过前等待 <b>12 ms/);
const stopped = render({...fields,state:'stopped',finished_at:base+2100});
assert.match(stopped.summary,/排队等待 <b>2.1 s/);
const unknown = render({...fields,state:'unknown',finished_at:base+6000});
assert.doesNotMatch(unknown.summary,/排队等待|结束时间|已排队/);
assert.match(unknown.details,/状态记录时间/);
});
test('manual and legacy rows never synthesize a schedule, queue time, command start or sample', () => {
const manual=render({source:'manual',queued_at:base, started_at:base+30,command_started_at:base+51});
assert.match(manual.summary,/进入队列/);
assert.match(manual.summary,/命令启动 <b>14:55:00/);
assert.doesNotMatch(manual.summary,/计划到命令启动/);
for (const source of ['system','legacy','client']) {
const {summary,details}=render({source,started_at:base, state:'failed',exit_code:17});
assert.match(summary,/记录启动/);
assert.match(summary,/退出码 <b>17/);
assert.doesNotMatch(summary,/计划运行|排队等待|计划到命令启动/);
assert.match(details,/记录启动<\/dt><dd>14:55:00.000/);
assert.match(details,/命令启动<\/dt><dd>未记录/);
}
});
test('retain precision and dates across midnight, accept zero latency, omit reversed timestamps', () => {
const scheduled = new Date(2026, 11, 31, 23, 59, 59, 900).getTime();
const {summary,details}=render({state:'finished',scheduled_at:scheduled,queued_at:scheduled,
started_at:scheduled,command_started_at:scheduled+150,finished_at:scheduled+3100});
assert.match(summary,/2026-12-31 23:59:59/);
assert.match(summary,/排队等待 <b>0 ms/);
assert.match(summary,/结束时间 <b>2027-01-01 00:00:03/);
assert.match(details,/命令启动<\/dt><dd>2027-01-01 00:00:00.050/);
assert.doesNotMatch(render({scheduled_at:base, command_started_at:base-1}).summary,/计划到命令启动/);
});
test('an entry sample with no schedule names the measured starting point and keeps millisecond precision', () => {
const script_started_at = base + 1635;
const manual = render({source:'manual', queued_at:base, started_at:base+10, script_started_at});
assert.match(manual.details,/入队到脚本开始 <b>1.635 s/);
const client = render({source:'client', started_at:base, script_started_at});
assert.match(client.details,/启动记录到脚本开始 <b>1.635 s/);
for (const {summary,details} of [manual,client]) {
assert.doesNotMatch(summary + details,/计划到脚本开始|计划到命令启动/);
}
});
test('an expanded queued row uses its server snapshot even when the browser clock is ten minutes fast', (t) => {
t.mock.method(Date, 'now', () => base + 600000);
const queued = { queued_at: base, queue_wait_ms: 375, state: 'queued' };
assert.match(render(queued).summary, /已排队 <b>375 ms/);
assert.match(render({...queued, queue_wait_ms:0}).summary, /已排队 <b>0 ms/);
assert.match(render({...queued, state:'running', started_at:base+812}).summary, /排队等待 <b>812 ms/);
});
test('expanded wait reasons retain the actual slot holders after the timer freezes', () => {
const queue_context=JSON.stringify({queue:'manual',limit:2,occupied:2,holders:[{id:'instance-101',name:'长任务 A'},{id:'instance-102',name:'长任务 B'}]});
const {summary,details}=render({state:'finished',queued_at:base,started_at:base+3712,finished_at:base+5000,queue_context});
assert.match(summary,/排队等待 <b>3.712 s/);
assert.match(details,/手动执行队列/);assert.match(details,/入队时已达并发上限(运行 2,上限 2)/);
assert.match(details,/长任务 A/);assert.match(details,/长任务 B/);
assert.match(render({state:'queued',queued_at:base}).details,/尚无同时运行的任务记录/);
});
test('a live queue shows the resampled holders and preserves the measured dequeue time after preparation',()=>{
const admission=JSON.stringify({queue:'manual',occupied:2,limit:2,holders:[{id:'a',name:'holder-A'},{id:'b',name:'holder-B'}]});
const live=JSON.stringify({queue:'manual',occupied:1,limit:1,holders:[{id:'b',name:'holder-B'}]});
const row={state:'queued',queued_at:base,queue_context:admission,queue_live_context:live};
assert.match(render(row).details,/最近一次检查(运行 1,上限 1)/);assert.doesNotMatch(render(row).details,/holder-A/);
assert.match(render({...row,state:'finished',dequeued_at:base+210,started_at:base+810}).summary,/排队等待 <b>210 ms/);
});
@@ -0,0 +1,61 @@
// Run on the dedicated ext4 test disk. Two independent recovery processes have
// validated one slot. A third writer replaces just the file before either move.
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const path = require('node:path');
const { spawn } = require('node:child_process');
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 { 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-'));
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 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 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 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]);
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}));
} finally {
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; });
+68
View File
@@ -0,0 +1,68 @@
// Run real panel operations in a separate process. The parent replaces public
// files and runs two independent publishers while this worker is at the barrier.
const fs = require('node:fs');
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 history = new TriggerHistory(db);
const stats = load('back/data/cronStats.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': {},
}).default;
function barrier() {
const ready = path.join(root, 'at-barrier');
fs.writeFileSync(ready + '.tmp', stage + '/' + side);
fs.renameSync(ready + '.tmp', ready);
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
}
const statements = {
booking: 'INSERT OR IGNORE INTO CronLegacyExitBookings',
claim: 'UPDATE CronTriggers SET counted=1',
increment: 'INSERT INTO "CrontabStats"',
dispute: 'INSERT OR IGNORE INTO CronBoundExitConflicts',
debit: 'UPDATE CrontabStats SET run_count=run_count-1',
commit: 'COMMIT',
deleteDay: 'DELETE FROM CrontabStats WHERE date',
cutoff: 'INSERT INTO CronStatRetention',
historyCutoff: 'INSERT INTO CronHistoryRetention',
deleteHistory: 'DELETE FROM CronTriggers WHERE',
pruneBooking: 'DELETE FROM CronLegacyExitBookings WHERE day',
};
function intercept(object, method, matches) {
const original = object[method].bind(object);
object[method] = async (...args) => {
const matched = matches(...args);
if (matched && side === 'before') barrier();
const result = await original(...args);
if (matched && side === 'after') barrier();
return result;
};
}
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) => {
const handle = await open(file, ...options);
if (captured(file)) {
if (side === 'before') barrier();
const close = handle.close.bind(handle);
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 === 'unlink') intercept(fs.promises, 'unlink', captured);
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 });
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());
@@ -0,0 +1,47 @@
const fs = require('node:fs');
const path = require('node:path');
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);
let captured;
async function gate(suffix, data, release) {
fs.writeFileSync(barrier + '.tmp', JSON.stringify(data));
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));
}
}
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,
directoryInode: (await fs.promises.stat(path.dirname(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}));
throw error;
}
captured = target;
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 => {
if (stage === 'holdUnlink' && captured === file)
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();
});
+54
View File
@@ -0,0 +1,54 @@
"""Reserve or release the final receipt inode on the isolated acceptance disk."""
import json
import os
from pathlib import Path
import runpy
import shutil
import sys
helpers = runpy.run_path(str(Path(__file__).with_name('receipt-unlink-ext4.py')))
volume = helpers['VOLUME']
stats = os.statvfs(volume)
mount = next((line for line in Path('/proc/self/mountinfo').read_text().splitlines()
if line.split()[4] == str(volume)), '')
if (' - ext4 ' not in mount or not (volume / '.qa-isolated-volume').is_file()
or not 0 < stats.f_blocks * stats.f_frsize <= 32 * 1024 * 1024
or not 0 < stats.f_files <= 8192):
raise RuntimeError('Requires the marked bounded ext4 acceptance volume')
def sync_dir(directory):
fd = os.open(directory, os.O_DIRECTORY)
try:
os.fsync(fd)
finally:
os.close(fd)
folder = volume / '.qa-empty-exit-fill'
operation = sys.argv[1]
if operation == 'fill':
folder.mkdir()
(folder / 'one-inode').touch(exist_ok=False)
fd = os.open(folder / 'blocks', os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_SYNC, 0o600)
try:
helpers['fill_inodes'](folder)
helpers['fill_blocks'](fd)
finally:
os.close(fd)
sync_dir(folder)
sync_dir(volume)
elif operation == 'lend':
(folder / 'one-inode').unlink()
sync_dir(folder)
elif operation == 'release':
shutil.rmtree(folder)
sync_dir(volume)
elif operation != 'inspect':
raise ValueError(operation)
state = helpers['capacity']()
if operation in ('fill', 'lend'):
assert state == {'blocks': 0, 'inodes': int(operation == 'lend')}, state
elif operation == 'release':
assert min(state.values()) > 0, state
print(json.dumps(dict(**state, boot=Path('/proc/sys/kernel/random/boot_id').read_text().strip(),
mount=mount)))
@@ -0,0 +1,91 @@
"""Hold a Linux test supervisor at syscall exit, before it can handle ENOSPC."""
import ctypes
import errno
import json
import os
from pathlib import Path
import platform
import signal
import sys
PTRACE_PEEKDATA = 2
PTRACE_SYSCALL = 24
PTRACE_SEIZE = 0x4206
PTRACE_INTERRUPT = 0x4207
PTRACE_GET_SYSCALL_INFO = 0x420e
pid = int(sys.argv[1])
receipt = sys.argv[2]
control = Path(sys.argv[3])
if control.parent != Path('/tmp/journal-qa') or not receipt.isascii() or not receipt.replace('-', '').isalnum():
raise ValueError('Requires isolated fixture control path and execution ID')
if b'cron-command.py' not in Path(f'/proc/{pid}/cmdline').read_bytes():
raise ValueError('Expected the real cron supervisor')
openat = {'aarch64': 56, 'x86_64': 257}[platform.machine()]
libc = ctypes.CDLL(None, use_errno=True)
libc.ptrace.argtypes = [ctypes.c_uint, ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p]
libc.ptrace.restype = ctypes.c_long
def ptrace(op, addr=0, data=0):
ctypes.set_errno(0)
rc = libc.ptrace(op, pid, addr, data)
if rc == -1 and ctypes.get_errno():
raise OSError(ctypes.get_errno(), os.strerror(ctypes.get_errno()))
return rc
def path_at(addr):
data = bytearray()
word = ctypes.sizeof(ctypes.c_long)
for offset in range(0, 4096, word):
data.extend(ptrace(PTRACE_PEEKDATA, addr + offset).to_bytes(word, sys.byteorder, signed=True))
if 0 in data:
return os.fsdecode(bytes(data[:data.index(0)]))
raise RuntimeError('Unterminated pathname')
def publish(suffix, value):
with Path(str(control) + suffix).open('x') as out:
json.dump(value, out)
out.flush()
os.fsync(out.fileno())
# TRACESYSGOOD identifies syscall stops. EXITKILL prevents an accidental tracer
# exit from releasing the supervisor into its retry path before the VM cut.
ptrace(PTRACE_SEIZE, 0, 1 | (1 << 20))
ptrace(PTRACE_INTERRUPT)
assert os.WIFSTOPPED(os.waitpid(pid, 0)[1])
publish('.ready', {'supervisor': pid, 'tracer': os.getpid()})
deliver = 0
target = None
while True:
ptrace(PTRACE_SYSCALL, 0, deliver)
_, status = os.waitpid(pid, 0)
if not os.WIFSTOPPED(status):
raise RuntimeError(f'Supervisor exited early, wait status {status}')
deliver = os.WSTOPSIG(status)
if deliver != signal.SIGTRAP | 0x80:
continue
deliver = 0
# linux/ptrace.h: op at byte 0, entry.nr / exit.rval at 24,
# entry.args at 32. Request the kernel-reported stop type, independent of
# whether attachment happened inside a previous syscall.
info = ctypes.create_string_buffer(88)
ptrace(PTRACE_GET_SYSCALL_INFO, len(info), ctypes.addressof(info))
raw = info.raw
number = int.from_bytes(raw[24:32], sys.byteorder, signed=True)
if raw[0] == 1:
target = None
if number == openat:
flags = int.from_bytes(raw[48:56], sys.byteorder)
if flags & os.O_EXCL and flags & os.O_CREAT:
name = path_at(int.from_bytes(raw[40:48], sys.byteorder))
if name.startswith('/ql/data/db/cron-exits/.pending.' + receipt + '.full-'):
target = name
elif raw[0] == 2 and target:
if number != -errno.ENOSPC:
raise RuntimeError(f'First marker creation returned {number}')
children = Path(f'/proc/{pid}/task/{pid}/children').read_text().split()
assert not children, children
publish('.stopped', dict(supervisor=pid, tracer=os.getpid(), receipt=receipt, path=target,
syscall='openat', result=number, children=children, stop='syscall-exit'))
while True:
signal.pause()
+24
View File
@@ -0,0 +1,24 @@
// Stop the real migration transaction on either side of COMMIT. The harness
// reads through a separate SQLite connection before killing the worker or VM.
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 transaction = sequelize.transaction.bind(sequelize);
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);
});
migrateSchema(sequelize).catch(error => { console.error(error); process.exitCode = 1; });
@@ -0,0 +1,36 @@
const fs = require('node:fs');
const path = require('node:path');
const { writeExit } = require('../../back/shared/managedExit.cjs');
const [stage, time] = process.argv.slice(2);
const write = fs.writeFileSync;
function checkpoint(point) {
if (point !== stage) return;
const ready = path.join(process.env.QL_DATA_DIR, 'publisher-ready');
write(ready + '.tmp', point);
fs.renameSync(ready + '.tmp', ready);
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
}
let writes = 0;
fs.writeFileSync = (file, contents, options) => {
if (writes++ === 0) {
checkpoint('before-write');
write(file, contents, options);
checkpoint('after-write');
} else {
checkpoint('before-mirror');
if (stage === 'partial') {
write(file, contents.slice(0, 12), options);
checkpoint('partial');
}
write(file, contents, options);
checkpoint('after-mirror');
}
};
const link = fs.linkSync;
fs.linkSync = (...args) => {
checkpoint('before-link');
link(...args);
checkpoint('after-link');
};
writeExit(process.env.QL_TRIGGER_ID, 23, null, Number(time));
checkpoint('published');
+63
View File
@@ -0,0 +1,63 @@
"""Interrupt the real Python supervisor at the requested publication boundary."""
import os
import pathlib
import runpy
import signal
import sys
import tempfile
import time
stage, finish, script, marker, owner = sys.argv[1:]
time.time_ns = lambda: int(finish) * 1_000_000
def checkpoint(point):
if point == stage:
ready = pathlib.Path(os.environ['QL_DATA_DIR']) / 'publisher-ready'
pending = ready.with_suffix('.tmp')
pending.write_text(point)
pending.replace(ready)
signal.pause()
open_temp = tempfile.NamedTemporaryFile
writes = 0
class TempFile:
def __init__(self, **kwargs):
global writes
self.first = writes == 0
writes += 1
checkpoint('before-write' if self.first else 'before-mirror')
self.file = open_temp(**kwargs)
def __enter__(self):
self.file.__enter__()
if not self.first and stage == 'partial':
self.file.write('{"code":')
self.file.flush()
checkpoint('partial')
return self.file
def __exit__(self, *args):
self.file.__exit__(*args)
checkpoint('after-write' if self.first else 'after-mirror')
link = os.link
def publish(source, dest):
checkpoint('before-link')
link(source, dest)
checkpoint('after-link')
tempfile.NamedTemporaryFile = TempFile
os.link = publish
sys.argv = [script, 'exit 23', owner, marker, '', '']
main = runpy.run_path(script)['main']
status = main()
checkpoint('published')
sys.exit(status)
+91
View File
@@ -0,0 +1,91 @@
// Run inside the dedicated bounded ext4 acceptance volume, alongside receipt-volume-full.cjs.
// Pause the actual post-commit collector before or after its filesystem call.
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 [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)) {
throw Error('Expected a supported ext4 collection boundary and execution ID');
}
function hold(event) {
const target = path.join(control, stage + '-event');
fs.writeFileSync(target + '.tmp', JSON.stringify(event));
fs.renameSync(target + '.tmp', target);
// The outside observer cuts power here. A failed orchestrator has a bounded wait.
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 120000);
throw Error('Power cut did not occur');
}
async function atBoundary(source, destination, operation) {
// A hard link outside the receipt namespace keeps the allocation constant even
// if unlink succeeds.
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');
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.
const dir = path.dirname(destination);
let count = 0;
try {
for (;;) {
fs.linkSync(pin, path.join(dir, 'q' + count.toString(36).padStart(path.basename(destination).length - 1, '0')));
count++;
}
} catch (error) {
if (error.code !== 'ENOSPC') throw error;
}
event.extraDirectoryEntries = count;
}
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});
}
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)});
}
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) => {
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));
}
return rename(from,to);
};
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; }
}
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());
+112
View File
@@ -0,0 +1,112 @@
"""Drive the real block/inode limits for the private-slot power-cut regression.
The controller supplies a private receipt already verified by two collectors.
Stage the writer's only copy before filling the disk, install it by rename at
zero capacity, then release only this fixture's allocations after reboot.
"""
import errno
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import sys
if not __debug__:
raise RuntimeError('The dedicated-volume checks require Python assertions')
volume = Path('/ql/data/db')
spool = volume / 'cron-exits'
filler = volume / '.qa-slot-capacity'
def capacity():
stat = os.statvfs(volume)
return dict(blocks=stat.f_bavail, freeBlocks=stat.f_bfree, inodes=stat.f_favail)
def sync(path):
fd = os.open(path, os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
def fill(slot, mode, body):
filler.mkdir(mode=0o700)
# Otherwise freeing the old inode or its empty parent directory could give
# ext4 enough space to pass the next stage without exercising ENOSPC.
os.link(slot, slot.parent / '.qa-old-pin')
staged = slot.parent / '.qa-staged'
with staged.open('xb') as dest:
dest.write(body.encode())
dest.flush()
os.fsync(dest.fileno())
sync(slot.parent)
errors = {}
with (filler / 'blocks').open('xb', buffering=0) as dest:
if mode == 'both':
i = 0
try:
while True:
(filler / str(i)).touch(exist_ok=False)
i += 1
except OSError as exc:
if exc.errno != errno.ENOSPC or capacity()['inodes'] != 0:
raise
errors['create'] = exc.errno
for size in (65536, os.statvfs(volume).f_frsize):
buf = bytes(size)
try:
while True:
dest.write(buf)
os.fsync(dest.fileno())
except OSError as exc:
if exc.errno != errno.ENOSPC:
raise
errors['write'] = exc.errno
sync(filler)
sync(volume)
result = capacity()
assert result['blocks'] == 0, result
assert mode != 'both' or result['inodes'] == 0
return dict(capacity=result, errno=errors, stagedInode=staged.stat().st_ino)
def main():
op, execution, mode = sys.argv[1:4]
assert re.fullmatch(r'[a-z0-9-]{1,120}', execution) and mode in ('blocks', 'both')
mounts = [line.split() for line in Path('/proc/mounts').read_text().splitlines()]
assert any(row[1:3] == [str(volume), 'ext4'] for row in mounts)
stat = os.statvfs(volume)
assert (volume / '.qa-isolated-volume').is_file()
assert 0 < stat.f_blocks * stat.f_frsize <= 32 * 1024 * 1024 and 0 < stat.f_files <= 8192
claim = spool / ('.claim.' + execution + '.qaTest')
slot = claim / 'receipt'
if op == 'fill':
return fill(slot, mode, sys.argv[4])
if op == 'replace':
before = capacity()
assert before['blocks'] == 0 and (mode == 'blocks' or before['inodes'] == 0)
os.replace(claim / '.qa-staged', slot)
sync(claim)
assert slot.stat().st_nlink == 1
return dict(directory=claim.stat().st_ino, inode=slot.stat().st_ino,
sha256=hashlib.sha256(slot.read_bytes()).hexdigest(), capacity=capacity())
if op == 'release':
before = capacity()
assert (filler / 'blocks').is_file()
shutil.rmtree(filler)
(claim / '.qa-old-pin').unlink()
sync(claim)
sync(volume)
return dict(before=before, after=capacity())
if op == 'capacity':
return capacity()
raise ValueError(op)
if __name__ == '__main__':
print(json.dumps(main()))
+38
View File
@@ -0,0 +1,38 @@
// Linux acceptance probe for the SQLite driver used in the panel image.
// cc -O2 -Wall -Werror -shared -fPIC receipt-sqlite-power.c -o probe.so -ldl
// Preload only in the dedicated receipt-volume-full.cjs commit worker.
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
static void pause_failed_database_write(int fd) {
char link[64], target[256];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
ssize_t size = readlink(link, target, sizeof(target) - 1);
if (size < 0) return;
target[size] = '\0';
if (strcmp(target, "/ql/data/db/database.sqlite") != 0 ||
access("/ql/data/db/.qa-isolated-volume", F_OK) != 0) return;
// The control file is on a different filesystem from the full database.
int barrier = open("/tmp/journal-qa/native-full", O_WRONLY | O_CREAT | O_EXCL, 0600);
if (barrier < 0) return;
dprintf(barrier, "{\"syscall\":\"write\",\"errno\":%d,\"pid\":%d}", ENOSPC, getpid());
close(barrier);
raise(SIGSTOP);
}
ssize_t write(int fd, const void *bytes, size_t length) {
// Call the kernel first so the fault is an actual filesystem response.
ssize_t (*real_write)(int, const void *, size_t) = dlsym(RTLD_NEXT, "write");
ssize_t written = real_write(fd, bytes, length);
int saved_errno = errno;
if (written < 0 && saved_errno == ENOSPC) pause_failed_database_write(fd);
errno = saved_errno;
return written;
}
+87
View File
@@ -0,0 +1,87 @@
"""Measure real unlink outcomes on the isolated Docker acceptance disk."""
import errno
import json
import os
from pathlib import Path
import tempfile
VOLUME = Path('/ql/data/db')
PAYLOAD = b'{"code":23,"signal":null,"time":1790000000123}'
def capacity():
stats = os.statvfs(VOLUME)
return {'blocks': stats.f_bavail, 'inodes': stats.f_favail}
def fill_inodes(directory):
try:
for index in range(os.statvfs(VOLUME).f_files + 1):
(directory / str(index)).touch(exist_ok=False)
except OSError as error:
if error.errno != errno.ENOSPC:
raise
assert capacity()['inodes'] == 0
def fill_blocks(fd):
block_size = os.statvfs(VOLUME).f_frsize
for size in (64 * 1024, block_size):
data = bytes(size)
try:
while True:
os.write(fd, data)
except OSError as error:
if error.errno != errno.ENOSPC:
raise
os.fsync(fd)
assert capacity()['blocks'] == 0
def observe(mode):
with tempfile.TemporaryDirectory(prefix='.qa-unlink-', dir=VOLUME) as folder:
root = Path(folder)
linked, opened, closed = (root / name for name in ('linked', 'opened', 'closed'))
for file in (linked, opened, closed):
file.write_bytes(PAYLOAD)
alias = root / 'other-link'
os.link(linked, alias)
filler = os.open(root / 'blocks', os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_SYNC, 0o600)
try:
if mode != 'blocks':
fill_inodes(root)
if mode != 'inodes':
fill_blocks(filler)
with opened.open('rb') as live:
rows = []
for file in (linked, opened, closed):
before = capacity()
assert mode == 'inodes' or before['blocks'] == 0
assert mode == 'blocks' or before['inodes'] == 0
links = file.stat().st_nlink
try:
file.unlink()
result = 'success'
assert not file.exists()
except OSError as error:
if error.errno != errno.ENOSPC:
raise
result = 'ENOSPC'
assert file.read_bytes() == PAYLOAD
rows.append({'layout': file.name, 'linksBefore': links, 'result': result,
'before': before, 'after': capacity()})
assert live.read() == PAYLOAD and alias.read_bytes() == PAYLOAD
return rows
finally:
os.close(filler)
if __name__ == '__main__':
mount = next((line.split(' - ')[1].split()[0] for line in Path('/proc/self/mountinfo').read_text().splitlines()
if line.split()[4] == str(VOLUME)), None)
stats = os.statvfs(VOLUME)
if (mount != 'ext4' or not (VOLUME / '.qa-isolated-volume').is_file()
or not 0 < stats.f_blocks * stats.f_frsize <= 32 * 1024 * 1024
or not 0 < stats.f_files <= 8192):
raise RuntimeError('Requires the marked bounded ext4 acceptance volume')
print(json.dumps({mode: observe(mode) for mode in ('blocks', 'inodes', 'both')}))
+128
View File
@@ -0,0 +1,128 @@
// Docker acceptance worker. Both capacity limits are checked before filling the
// explicitly mounted test filesystem. Barrier files live outside that mount.
const fs = require('node:fs');
const path = require('node:path');
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 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');
}
const { sequelize: db } = require('/ql/static/build/data');
const { TriggerHistory } = require('/ql/static/build/shared/triggerHistory');
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));
}
function exhaust(inodes) {
const dir = fs.mkdtempSync(path.join(volume, '.qa-fill-'));
let fd;
try {
if (!inodes) fd = fs.openSync(path.join(dir, 'data'), 'wx');
const block = Buffer.alloc(64 * 1024);
for (let n = 0; ; n++) {
if (inodes) fs.closeSync(fs.openSync(path.join(dir, String(n)), 'wx'));
else fs.writeSync(fd, block);
}
} catch (error) {
if (error.code !== 'ENOSPC') throw error;
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; }
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); }
}
}
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 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);
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');
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 });
// 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);
throw error;
}
throw Error('Expected ENOSPC while allocating the next page');
} 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');
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) });
throw error;
}
};
} else {
const rename = fs.promises.rename.bind(fs.promises);
let injected = false;
fs.promises.rename = async (...args) => {
if (!injected) {
injected = true;
exhaust(true);
}
try {
await rename(...args);
record('collect-moved', { source:args[0], destination:args[1] });
}
catch (error) { record('collect-error', { code: error.code, prefix: args[0] }); throw error; }
};
}
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 });
}
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 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 }); });