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

+68 -96
View File
@@ -4,33 +4,8 @@ const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { createContext } = require('../../dist/internal/runtime/context');
const { extendedLifecycle } = require('../../dist/internal/runtime/lifecycle');
const { loggedOperation } = require('../../dist/internal/runtime/commandLog');
test('installed panel version selects lifecycle schema and unknown versions stay conservative', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-lifecycle-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const context = createContext({ root }, {});
assert.equal(await extendedLifecycle(context), false);
for (const [version, expected] of [
['2.20.1', false],
['2.19.0', false],
['2.21.0-14', true],
['3.0.0', false],
['invalid', false],
]) {
await fs.writeFile(
path.join(root, 'package.json'),
JSON.stringify({ version }),
);
assert.equal(await extendedLifecycle(context), expected);
}
context.env.QL_CLI_LIFECYCLE = 'extended';
assert.equal(await extendedLifecycle(context), true);
context.env.QL_CLI_LIFECYCLE = 'legacy';
assert.equal(await extendedLifecycle(context), false);
});
test('command log preserves scheduler path and rejects escaping the log directory', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-scheduler-log-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
@@ -50,85 +25,82 @@ test('command log preserves scheduler path and rejects escaping the log director
);
});
test('released version.yaml selects lifecycle only when package version is absent', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-release-version-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const context = createContext({ root }, {});
await fs.writeFile(
path.join(root, 'package.json'),
'{"name":"released-panel"}',
);
for (const [release, expected] of [
['version: 2.20.1\nchangeLog: |\n version: 2.99.0\n', false],
['version: 2.21.0-14\npublishTime: 2026-09-25\n', true],
['version: "2.21.1" # release\n', true],
["\ufeffversion: '2.22.0'\r\n", true],
['version: 3.0.0\n', false],
['version: 2.21.invalid\n', false],
['version: 2.21.0\nversion: 2.20.1\n', false],
['changeLog: |\n version: 2.21.0\n', false],
['version: !custom 2.21.0\n', false],
]) {
await fs.writeFile(path.join(root, 'version.yaml'), release);
assert.equal(await extendedLifecycle(context), expected, release);
}
await fs.writeFile(path.join(root, 'version.yaml'), 'version: 2.21.1\n');
await fs.writeFile(path.join(root, 'package.json'), '{"version":"2.20.1"}');
assert.equal(await extendedLifecycle(context), false);
context.env.QL_CLI_LIFECYCLE = 'extended';
assert.equal(await extendedLifecycle(context), true);
context.env.QL_CLI_LIFECYCLE = 'legacy';
assert.equal(await extendedLifecycle(context), false);
delete context.env.QL_CLI_LIFECYCLE;
await fs.rm(path.join(root, 'package.json'));
assert.equal(await extendedLifecycle(context), true);
await fs.rm(path.join(root, 'version.yaml'));
assert.equal(await extendedLifecycle(context), false);
});
test('release-only version metadata controls actual task and maintenance status payloads', async (t) => {
test('managed CLI tasks and maintenance commands report against the parent receipt', async t => {
const { LocalApi } = require('../../dist/internal/runtime/api');
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-release-payload-'));
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-managed-cli-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const context = createContext(
{ root },
{ PATH: process.env.PATH, ID: '7', no_tee: 'true' },
);
const id = 'parent-receipt-7';
const context = createContext({ root }, {
PATH: process.env.PATH, ID: '7', no_tee: 'true', QL_TRIGGER_ID: id,
QL_CLI_LIFECYCLE: 'extended', QL_EXECUTION_ORIGIN: 'scheduled_system',
});
await fs.mkdir(context.paths.dir_scripts, { recursive: true });
await fs.writeFile(
path.join(context.paths.dir_scripts, 'fixture.sh'),
'return 7',
);
await fs.writeFile(path.join(context.paths.dir_scripts, 'fixture.sh'), 'return 7');
const calls = [];
t.mock.method(LocalApi.prototype, 'call', async (endpoint, method, body) => {
calls.push({ endpoint, body });
return { code: 200 };
});
for (const version of ['2.20.1', '2.21.0-14']) {
await fs.writeFile(
path.join(root, 'version.yaml'),
`version: ${version}\n`,
);
calls.length = 0;
const result = await executeTask(context, {
argv: ['fixture.sh'],
mode: 'now',
});
assert.equal(result.exitCode, 7);
const final = calls
.filter((row) => row.endpoint === 'crons/status')
.at(-1).body;
assert.equal(final.exit_code, version === '2.20.1' ? undefined : 7);
assert.equal(
calls.some((row) => row.endpoint === 'dashboard/record'),
version !== '2.20.1',
);
calls.length = 0;
await loggedOperation(context, 'extra', async () => true);
assert.equal(
calls.at(-1).body.exit_code,
version === '2.20.1' ? undefined : 0,
);
const result = await executeTask(context, { argv: ['fixture.sh'], mode: 'now' });
assert.equal(result.exitCode, 7);
assert.deepEqual(calls.map(r => r.endpoint), ['crons/status', 'crons/status', 'dashboard/record']);
await loggedOperation(context, 'extra', async () => true);
assert.equal(calls.length, 5);
for (const { body } of calls) {
assert.equal(body.trigger_id, id);
assert.equal(body.execution_id, undefined);
}
calls.length = 0;
context.env.QL_CLI_LIFECYCLE = 'legacy';
await loggedOperation(context, 'extra', async () => true);
assert.ok(calls.length);
assert.ok(calls.every(r => !('trigger_id' in r.body)));
});
test('distinct managed triggers in the same clock tick have separate maintenance and task logs', async t => {
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-same-tick-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
t.mock.method(Date, 'now', () => 1800000000000);
const run = async id => {
const context = createContext({ root }, { QL_CLI_LIFECYCLE: 'extended', QL_TRIGGER_ID: id,
PATH: process.env.PATH, no_tee: 'true', log_name: 'shared' });
await fs.mkdir(context.paths.dir_scripts, { recursive: true });
await fs.writeFile(path.join(context.paths.dir_scripts, id + '.sh'), 'echo ' + id);
const command = await loggedOperation(context, 'extra', async () => {});
const task = await executeTask(context, { argv: [id + '.sh'], mode: 'now' });
return { command: command.logPath, file: task.logPath,
content: await fs.readFile(path.join(context.paths.dir_log, task.logPath), 'utf8') };
};
const [a, b] = await Promise.all([run('marker-alpha'), run('marker-bravo')]);
assert.notEqual(a.command, b.command);
assert.notEqual(a.file, b.file);
assert.match(a.content, /marker-alpha/);
assert.doesNotMatch(a.content, /marker-bravo/);
assert.match(b.content, /marker-bravo/);
assert.doesNotMatch(b.content, /marker-alpha/);
});
test('same-tick standalone tasks and commands share a receipt only within one invocation', async t => {
const { LocalApi } = require('../../dist/internal/runtime/api');
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-client-receipts-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
t.mock.method(Date, 'now', () => 1800000000000);
const context = createContext({root}, {ID:'5', QL_CLI_LIFECYCLE:'extended', no_tee:'true',
real_log_path:'shared.log', PATH:process.env.PATH});
await fs.mkdir(context.paths.dir_scripts, {recursive:true});
await fs.writeFile(path.join(context.paths.dir_scripts, 'receipt.sh'), 'exit 0');
const groups = new Map();
t.mock.method(LocalApi.prototype, 'call', async (endpoint, method, body) => {
const id = body.execution_id;
assert.match(id, /^client-[0-9a-f-]{36}$/);
groups.set(id, [...(groups.get(id) || []), body.status ?? 'stat']);
return {code:200};
});
await Promise.all([executeTask(context, {argv:['receipt.sh'], mode:'now'}),
executeTask(context, {argv:['receipt.sh'], mode:'now'}),
loggedOperation(context, 'extra', async () => {})]);
assert.deepEqual([...groups.values()].map(sequence => sequence.join(',')).sort(), ['0,1','0,1,stat','0,1,stat']);
});
+1
View File
@@ -759,6 +759,7 @@ test('lifecycle reports share execution identity and statistics survive a reject
ref_id: 12,
code: 9,
elapsed: result.durationSeconds,
execution_id: result.executionId,
});
assert.match(
fs.readFileSync(path.join(context.paths.dir_log, result.logPath), 'utf8'),
+119
View File
@@ -287,3 +287,122 @@ for (const language of ['zh', 'en', 'unsupported']) {
assert.deepEqual(seen, ['/open/http', '/open/rejected']);
});
}
test('a lifecycle timeout retries the identical payload once and other writes are not retried', async t => {
const context = await fixture(t, () => {});
await token(context);
const requests = [];
const timer = global.setTimeout;
t.mock.method(global, 'setTimeout', (fn, ms, ...args) => timer(fn, ms === 30000 ? 5 : ms, ...args));
t.mock.method(global, 'fetch', async (_, {body, signal}) => {
requests.push(body);
return new Promise((_, reject) => signal.addEventListener('abort', () => reject(signal.reason), {once:true}));
});
const api = new LocalApi(context);
for (const [endpoint, method, body, attempts] of [
['crons/status','PUT',{ execution_id:'client-' + require('node:crypto').randomUUID(), status:'0' },2],
['dashboard/record','POST',{ trigger_id:'managed-fixture', code:0 },2],
['crons/status','PUT',{ status:'0' },1],
['crons','POST',{ trigger_id:'unrelated' },1],
]) {
requests.length = 0;
await assert.rejects(api.call(endpoint, method, body));
assert.deepEqual(requests, Array(attempts).fill(JSON.stringify(body)));
}
});
test('the live status schema selects every receipt on old, intermediate and upgraded panels', async t => {
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const { loggedOperation } = require('../../dist/internal/runtime/commandLog');
let protocol;
const written = [], rejected = [];
const context = await fixture(t, async (req, res) => {
let raw = '';
for await (const chunk of req) raw += chunk;
const body = JSON.parse(raw);
const forbidden = req.url.endsWith('/status') && Object.keys(body).find(field =>
(protocol !== 'identified' && ['execution_id','trigger_id'].includes(field)) ||
(protocol === 'legacy' && field === 'exit_code'));
if (forbidden) {
rejected.push(forbidden);
res.writeHead(400).end(JSON.stringify({validation:{body:{source:'body',keys:[forbidden]}}}));
return;
}
written.push([req.url,body]);
res.end('{"code":200}');
});
await token(context);
Object.assign(context.env, { ID: '12', no_tee: 'true' });
await fs.mkdir(context.paths.dir_scripts, {recursive:true});
await fs.writeFile(path.join(context.paths.dir_scripts,'probe.sh'), 'return 7');
// Even a full newer installation on disk cannot speak on behalf of the old process.
await fs.mkdir(path.join(context.root,'static/build/shared'), {recursive:true});
await fs.writeFile(path.join(context.root,'static/build/shared/executionIdentity.js'), '');
for (protocol of ['legacy', 'exit-code', 'identified']) {
await fs.writeFile(path.join(context.root,'package.json'), JSON.stringify({version:protocol === 'identified' ? '2.20.1' : '2.25.0'}));
for (const managed of [false,true]) {
if (managed) context.env.QL_TRIGGER_ID = 'parent-123';
else delete context.env.QL_TRIGGER_ID;
for (const task of [true,false]) {
written.length = rejected.length = 0;
if (task) assert.equal((await executeTask(context,{argv:['probe.sh'],mode:'now'})).exitCode,7);
else await loggedOperation(context,'extra',async()=>{});
const [start,end] = written.map(r=>r[1]);
const key = managed ? 'trigger_id' : 'execution_id';
assert.deepEqual(rejected, protocol === 'legacy' ? [key,'exit_code'] : protocol === 'exit-code' ? [key] : []);
assert.equal(start.status,'0'); assert.equal(end.status,'1');
assert.equal(end.exit_code, protocol === 'legacy' ? undefined : task ? 7 : 0);
assert.equal(written.length, task && protocol !== 'legacy' ? 3 : 2);
for (const [,body] of written) assert.equal(body[key],start[key]);
if (protocol === 'identified') assert.ok(managed ? start[key] === 'parent-123' : /^client-/.test(start[key]));
else assert.equal(start[key],undefined);
}
}
}
});
test('a missing start response or a non-schema failure never switches a receipt to anonymous', async t => {
const { LifecycleReceipt } = require('../../dist/internal/runtime/lifecycle');
const calls = [];
let rejectedField;
const ctx = await fixture(t, async (req,res) => {
let raw=''; for await (const chunk of req) raw+=chunk;
calls.push(JSON.parse(raw));
if (!rejectedField) { res.destroy(); return; }
res.writeHead(400).end(JSON.stringify({ validation: {body: {source:'body',keys:[rejectedField]}} }));
});
await token(ctx);
const receipt = new LifecycleReceipt(ctx,10);
await assert.rejects(receipt.status({ids:[5],status:'0'}));
rejectedField = 'execution_id';
await assert.rejects(receipt.status({ids:[5],status:'1'},7));
assert.equal(calls.length,2);
assert.equal(calls[0].execution_id,calls[1].execution_id);
rejectedField = 'pid';
await assert.rejects(new LifecycleReceipt(ctx,11).status({ids:[5],status:'0'}));
assert.equal(calls.length,3);
});
test('dated status, statistics and retries share an exit instant without changing the identified body schema', async t => {
const { LifecycleReceipt } = require('../../dist/internal/runtime/lifecycle');
const writes=[];
const ctx=await fixture(t,async(req,res)=>{
let raw=''; for await(const chunk of req)raw+=chunk;
const body=JSON.parse(raw);
writes.push({body, time:req.headers['x-ql-finished-at']});
res.end(JSON.stringify({code:200}));
});
await token(ctx);
const receipt=new LifecycleReceipt(ctx,Math.floor(Date.now()/1000));
await receipt.status({status:'0'});
await receipt.status({status:'1'},17);
await receipt.status({status:'1'},17);
await receipt.statistics(1,17,2);
assert.equal(writes[0].time,undefined);
assert.match(writes[1].time,/^\d{13}$/);
for (const {body,time} of writes.slice(1)) {
assert.equal(time,writes[1].time);
assert.equal(body.execution_id,writes[0].body.execution_id);
assert.equal(body.finished_at,undefined);
}
});
+21 -1
View File
@@ -164,7 +164,7 @@ test('subscription reconciliation scopes removals to canonical paths and the cur
});
assert.equal(result.added, 1);
assert.equal(result.removed, 1);
assert.deepEqual(requests.find((r) => r.method === 'DELETE').body, [1]);
assert.deepEqual(requests.find((r) => r.method === 'DELETE').body, [{ id: 1, script: 'owner_repository/old.js', command: rows[0].command, sub_id: 7 }]);
assert.deepEqual(requests.find((r) => r.method === 'POST').body, {
name: 'New task',
schedule: '0 9 * * *',
@@ -359,6 +359,7 @@ test('subscription copy precedence preserves local dependencies while selected s
env: {
...context.env,
SOURCE: source,
dir_shell: path.resolve(__dirname, '../../../shell'),
dir_scripts: legacyRoot,
dir_list_tmp: context.paths.dir_list_tmp,
dir_dep: context.paths.dir_dep,
@@ -431,3 +432,22 @@ test('cron metadata precedence agrees with unchanged legacy add_cron', (t) => {
});
}
});
test('a slash in a branch cannot publish through a linked namespace parent', async t => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-nested-namespace-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const context = createContext({ root }, { PATH: process.env.PATH });
const outside = path.join(root, 'outside');
fs.mkdirSync(outside);
fs.writeFileSync(path.join(outside, 'sentinel'), 'untouched');
for (const dir of [context.paths.dir_repo, context.paths.dir_scripts]) {
fs.mkdirSync(dir, { recursive: true });
const link = path.join(dir, 'owner_repo_feature');
fs.symlinkSync(outside, link);
await assert.rejects(syncRepository(context, {
url: 'https://example.invalid/owner/repo.git', branch: 'feature/branch',
}), /管理目录|managed directory/);
assert.deepEqual(fs.readdirSync(outside), ['sentinel']);
fs.unlinkSync(link);
}
});
+14 -9
View File
@@ -24,11 +24,11 @@ exports.verifyAccountMaintenance = async function verifyAccountMaintenance(
assert.equal(result.status, 0, `${action} failed: ${result.stderr}`);
assert.equal(JSON.parse(result.stdout).data.completed, true);
};
const login = async () => {
const login = async (password = credentials.password) => {
const response = await fetch('http://127.0.0.1:5700/api/user/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(credentials),
body: JSON.stringify({ ...credentials, password }),
signal: AbortSignal.timeout(5000),
});
return response.json();
@@ -36,18 +36,23 @@ exports.verifyAccountMaintenance = async function verifyAccountMaintenance(
local('resetname', credentials.username);
local('resetpwd', credentials.password);
assert.equal((await login()).code, 200, 'New credentials were not saved');
await api('system/auth/reset', 'PUT', { retries: 4 });
assert.notEqual(
const incorrect = randomUUID();
for (let attempt = 0; attempt < 3; attempt++) {
assert.equal((await login(incorrect)).code, 400, 'Expected a rejected password before throttling');
}
assert.equal(
(await login()).code,
200,
410,
'Fixture failed to activate login limit',
);
local('resetlet');
assert.equal((await login()).code, 200, 'Login limit was not cleared');
await api('system/auth/reset', 'PUT', { twoFactorActivated: true });
assert.notEqual(
const session = await login();
assert.equal(session.code, 200, 'Login limit was not cleared');
assert.ok(session.data.token, 'Fresh owner session required');
await api('system/auth/reset', 'PUT', { twoFactorActivated: true }, session.data.token);
assert.equal(
(await login()).code,
200,
420,
'Fixture failed to activate second factor',
);
local('resettfa');
+10 -1
View File
@@ -2,7 +2,8 @@ const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const { spawnSync } = require('node:child_process');
const { spawn, spawnSync } = require('node:child_process');
const { once } = require('node:events');
exports.verifyOperator = async function verifyOperator(api) {
const ql = path.join(os.homedir(), 'bin/ql');
@@ -26,12 +27,18 @@ exports.verifyOperator = async function verifyOperator(api) {
schedule: '0 0 1 1 *',
})
).data;
const child = spawn('sleep', ['60']);
const ended = once(child, 'exit');
const start = Math.floor(Date.now() / 1000);
try {
await api('crons/status', 'PUT', {
ids: [task.id],
status: '0',
pid: String(child.pid),
last_execution_time: start,
log_path: 'cli-retention/2000-01-01-kept.log',
});
assert.equal((await api(`crons/${task.id}`)).data.log_path, 'cli-retention/2000-01-01-kept.log');
const result = invoke(['rmlog', '7']);
assert.ok(result.removed.includes('cli-retention/2000-01-01-unused.log'));
assert.ok(result.retained.includes('cli-retention/2000-01-01-kept.log'));
@@ -41,6 +48,8 @@ exports.verifyOperator = async function verifyOperator(api) {
'referenced',
);
} finally {
child.kill();
await ended;
await api('crons', 'DELETE', [task.id]);
}
const service = invoke(['reload']);
+2 -2
View File
@@ -16,12 +16,12 @@ let restoreEntrypoints;
);
const base = 'http://127.0.0.1:5700';
let token;
async function api(endpoint, method = 'GET', body) {
async function api(endpoint, method = 'GET', body, sessionToken = token) {
const response = await fetch(`${base}/api/${endpoint}`, {
method,
headers: {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(sessionToken ? { Authorization: `Bearer ${sessionToken}` } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(10000),