mirror of
https://github.com/whyour/qinglong.git
synced 2026-12-01 01:39:52 +08:00
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:
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
@@ -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`;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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(); }
|
||||
});
|
||||
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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': {
|
||||
|
||||
@@ -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`,
|
||||
|
||||
@@ -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': {},
|
||||
|
||||
@@ -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, '');
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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', {
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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 }));
|
||||
|
||||
@@ -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; });
|
||||
`);
|
||||
});
|
||||
@@ -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');
|
||||
|
||||
@@ -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']]);
|
||||
});
|
||||
@@ -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,
|
||||
);
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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'), []);
|
||||
});
|
||||
}
|
||||
@@ -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'));
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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],
|
||||
|
||||
@@ -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 ]]`);
|
||||
});
|
||||
@@ -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',
|
||||
|
||||
@@ -21,6 +21,7 @@ function create(env) {
|
||||
const cluster = {
|
||||
fork(options) {
|
||||
const worker = {
|
||||
on() {},
|
||||
id: calls.length + 1,
|
||||
process: { pid: 100 + calls.length },
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user