feat(cron): expose run receipts and modularize execution

Return committed trigger IDs and add CLI wait and trigger-specific logs while
preserving API, CLI, transaction, deduplication and unknown-result semantics.

Move scheduling, lifecycle, settlement, queries and legacy adapters into
back/cron; remove obsolete internal import paths and circular dependencies.

Apply project formatting across the repository, cover CJS/MJS in formatting
hooks, add prettier:check and require formatting checks in AGENTS.md.

Validation: backend build; 1398 backend/frontend tests passed (17 platform
skips); 327 CLI tests passed (6 platform skips); 670 files pass format checks.
This commit is contained in:
whyour committed 2026-11-22 12:24:29 +08:00
1 parent 77ece406ac
commit c5458596c8
346 files changed
+32133 -11556

No files matched your search

+37 -12
View File
@@ -50,7 +50,11 @@ test('environment API rejects execution controls and legacy rows stay out of tas
const legacy = [
{ id: 1, name: 'task_before', value: 'touch /tmp/untrusted' },
{ id: 2, name: 'NODE_OPTIONS', value: '--require /tmp/untrusted.js' },
{ id: 3, name: 'PREV_NODE_OPTIONS', value: '--import=data:text/javascript,bad' },
{
id: 3,
name: 'PREV_NODE_OPTIONS',
value: '--import=data:text/javascript,bad',
},
{ id: 4, name: 'GIT_SSH_COMMAND', value: 'sh -c bad' },
{ id: 5, name: 'PATH', value: '/tmp/untrusted' },
{ id: 6, name: 'file_task_before', value: '/tmp/untrusted.sh' },
@@ -72,7 +76,11 @@ test('environment API rejects execution controls and legacy rows stay out of tas
typedi: decorators,
'../config': { envFile: 'sh', jsEnvFile: 'js', pyEnvFile: 'py' },
'../data/env': {
Env: class { constructor(value) { Object.assign(this, value); } },
Env: class {
constructor(value) {
Object.assign(this, value);
}
},
EnvModel: {
update: async (value, query) => {
writes++;
@@ -83,7 +91,9 @@ test('environment API rejects execution controls and legacy rows stay out of tas
},
'../data': { sequelize: { literal: (value) => value } },
'../shared/utils': {
writeFileWithLock: async (file, value) => { output[file] = value; },
writeFileWithLock: async (file, value) => {
output[file] = value;
},
},
}).default;
const service = new Env({
@@ -91,15 +101,30 @@ test('environment API rejects execution controls and legacy rows stay out of tas
warn: (...args) => warnings.push(args),
});
service.envs = async () => legacy;
service.insert = async () => { writes++; return []; };
service.insert = async () => {
writes++;
return [];
};
service.getDb = async () => ({ id: 1, name: 'SAFE_VALUE', value: 'kept' });
service.updateDb = async () => { writes++; return {}; };
service.updateDb = async () => {
writes++;
return {};
};
for (const name of [
'task_before', 'PREV_NODE_OPTIONS', 'GIT_SSH_COMMAND', 'work_dir',
'task_shell_params', 'which_program', 'script_params', 'LOG_DIR',
'task_before',
'PREV_NODE_OPTIONS',
'GIT_SSH_COMMAND',
'work_dir',
'task_shell_params',
'which_program',
'script_params',
'LOG_DIR',
'EXPORTED_VARIABLES',
'begin_timestamp', 'is_macos', 'RandomDelayIgnoredMinutes', 'ID',
'begin_timestamp',
'is_macos',
'RandomDelayIgnoredMinutes',
'ID',
'BASH_XTRACEFD',
]) {
await assert.rejects(
@@ -252,11 +277,11 @@ function cronService(config, updates = []) {
'../config/util': { fileExist: async (p) => fs.existsSync(p) },
'../config/const': {},
'../schedule/client': {},
'../shared/pLimit': {},
'../shared/utils': {},
'../cron/execution/cronLimit': {},
'../shared/utils': { fileExist: async (p) => fs.existsSync(p) },
'../shared/i18n': translate,
'../shared/logStreamManager': {},
'../shared/cronSchedule': {},
'../cron/scheduling/cronSchedule': {},
}).default;
return new Cron(logger);
}
@@ -364,7 +389,7 @@ function systemService(config, overrides = {}) {
DependenceStatus: {},
},
'../data/system': {},
'../shared/pLimit': {},
'../cron/execution/cronLimit': {},
'../schedule/client': {},
'../shared/i18n': { ...translate, setLang() {} },
'./notify': {},
+1 -1
View File
@@ -12,7 +12,7 @@ test('unknown API requests return JSON 404 while env.js and SPA deep links work'
fs.writeFileSync(path.join(dir, 'static/dist/index.html'), 'SPA');
const app = express();
load('back/loaders/express.ts', {
'../api': () => express.Router(),
'../api/index': () => express.Router(),
'./logger': { error() {} },
'../config': {
rootPath: dir,
+3 -3
View File
@@ -37,9 +37,9 @@ for (const [arch, armVersion, mode, timeout] of [
['x64', undefined, 'development', 120000],
['arm64', undefined, 'development', 120000],
]) {
test(`${arch} v${
armVersion ?? ''
} ${mode ?? 'default'} waits for scheduler readiness before HTTP and job recovery`, async () => {
test(`${arch} v${armVersion ?? ''} ${
mode ?? 'default'
} waits for scheduler readiness before HTTP and job recovery`, async () => {
const cluster = new EventEmitter();
const module = { exports: {} };
const logger = { info() {}, warn() {}, error() {} };
+4 -5
View File
@@ -46,12 +46,11 @@ test('release images receive the same-run artifact and verify it before use', ()
fs.readFileSync('.github/workflows/build-docker-image.yml', 'utf8'),
);
assert.equal(workflow.jobs['build-static'].needs, 'validate');
const upload = workflow.jobs['build-static'].steps.find(step => step.uses?.startsWith('actions/upload-artifact@'));
const upload = workflow.jobs['build-static'].steps.find((step) =>
step.uses?.startsWith('actions/upload-artifact@'),
);
assert.equal(upload.with['include-hidden-files'], true);
for (const name of [
'build-alpine',
'build-debian',
]) {
for (const name of ['build-alpine', 'build-debian']) {
const job = workflow.jobs[name];
assert.equal(job.needs, 'build-static');
const download = job.steps.find((step) =>
+16 -7
View File
@@ -19,7 +19,11 @@ test('config saves share a rate limit across API mounts before writing files', a
'../config/const': { SAMPLE_FILES: [] },
'../services/config': {},
'../shared/i18n': { t: (x) => x },
'../shared/utils': { writeFileWithLock: async () => { writes++; } },
'../shared/utils': {
writeFileWithLock: async () => {
writes++;
},
},
typedi: { Container: { get: () => ({}) } },
}).default(router);
app.use('/api', router);
@@ -30,11 +34,14 @@ test('config saves share a rate limit across API mounts before writing files', a
t.after(() => new Promise((resolve) => server.close(resolve)));
const base = `http://127.0.0.1:${server.address().port}`;
for (let i = 0; i < 601; i++) {
const response = await fetch(`${base}/${i % 2 ? 'api' : 'open'}/configs/save`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'settings.json', content: '{}' }),
});
const response = await fetch(
`${base}/${i % 2 ? 'api' : 'open'}/configs/save`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'settings.json', content: '{}' }),
},
);
if (i < 600) {
assert.equal(response.status, 200);
assert.equal((await response.json()).code, 200);
@@ -81,7 +88,9 @@ test('Python environment generation escapes backslashes and triple quotes togeth
});
test('cron lookup treats regex and shell metacharacters as literal command text', () => {
const { findCronId } = load(path.resolve('back/shared/cronCommand.ts'));
const { findCronId } = load(
path.resolve('back/cron/execution/cronCommand.ts'),
);
const command = 'task file[1].js --value "$(touch ignored)"';
const crontab =
`* * * * * real_time=false no_tee=true ID=17 ${command}\n` +
+4 -2
View File
@@ -1,8 +1,10 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
const { createCronJob } = require('../../back/shared/cronScheduler');
const { isValidCronSchedule } = require('../../back/shared/cronSchedule');
const { createCronJob } = require('../../back/cron/scheduling/cronScheduler');
const {
isValidCronSchedule,
} = require('../../back/cron/scheduling/cronSchedule');
const native = require('node-cron');
const fixture = require('../fixtures/cron-calendar-boundaries.json');
+47
View File
@@ -0,0 +1,47 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const {
runtimeModuleGraph,
moduleCycles,
} = require('../helpers/runtime-module-graph.cjs');
const graph = runtimeModuleGraph('back');
test('cron and shared libraries do not import service implementations or the orphan reporter', () => {
for (const [file, dependencies] of graph) {
if (
!/^back\/(cron|shared)\//.test(file) ||
file === 'back/shared/managedExit.cjs'
)
continue;
for (const dependency of dependencies) {
assert.ok(
!dependency.startsWith('back/services/'),
file + ' -> ' + dependency,
);
assert.notEqual(dependency, 'back/shared/managedExit.cjs', file);
if (file.startsWith('back/shared/'))
assert.ok(
!dependency.startsWith('back/cron/'),
file + ' -> ' + dependency,
);
}
}
});
test('runtime imports involving cron, services and shared have no circular dependency', () => {
const cycles = moduleCycles(graph).filter((cycle) =>
cycle.some((file) => /^back\/(cron|services|shared)\//.test(file)),
);
assert.deepEqual(cycles, []);
});
test('receipt storage and schema installation do not load the execution coordinator', () => {
assert.deepEqual([...graph.get('back/cron/settlement/exitReceipt.cjs')], []);
assert.deepEqual([...graph.get('back/cron/schema.ts')], []);
assert.ok(
graph.get('back/data/schemaMigrations.ts').has('back/cron/schema.ts'),
);
assert.ok(
!graph.get('back/data/schemaMigrations.ts').has('back/cron/history.ts'),
);
});
File diff suppressed because it is too large. Load diff
+58 -13
View File
@@ -1,7 +1,9 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { createCronJob } = require('../../back/shared/cronScheduler');
const { isValidCronSchedule } = require('../../back/shared/cronSchedule');
const { createCronJob } = require('../../back/cron/scheduling/cronScheduler');
const {
isValidCronSchedule,
} = require('../../back/cron/scheduling/cronSchedule');
// node-cron caches timezone formatters; model each deployment in a fresh process.
if (!process.env.QL_MACRO_TEST_TZ) {
@@ -9,30 +11,65 @@ if (!process.env.QL_MACRO_TEST_TZ) {
test(`macro execution in ${tz}`, () => {
const env = { ...process.env, TZ: tz, QL_MACRO_TEST_TZ: tz };
delete env.NODE_TEST_CONTEXT;
const result = require('node:child_process').spawnSync(process.execPath,
const result = require('node:child_process').spawnSync(
process.execPath,
['-r', 'ts-node/register/transpile-only', '--test', __filename],
{ env, encoding: 'utf8' });
{ env, encoding: 'utf8' },
);
assert.equal(result.status, 0, result.stdout + result.stderr);
assert.match(result.stdout, /@annually fires at the expected local times/);
assert.match(
result.stdout,
/@annually fires at the expected local times/,
);
});
}
}
for (const tz of process.env.QL_MACRO_TEST_TZ ? [process.env.QL_MACRO_TEST_TZ] : []) {
for (const tz of process.env.QL_MACRO_TEST_TZ
? [process.env.QL_MACRO_TEST_TZ]
: []) {
for (const [macro, start, next] of [
['@annually', [2026, 11, 31, 23, 59, 59], [[2027, 0, 1, 0, 0, 0], [2028, 0, 1, 0, 0, 0]]],
['@midnight', [2026, 8, 27, 23, 59, 59], [[2026, 8, 28, 0, 0, 0], [2026, 8, 29, 0, 0, 0]]],
['@minutely', [2026, 8, 27, 12, 34, 59], [[2026, 8, 27, 12, 35, 0], [2026, 8, 27, 12, 36, 0]]],
[
'@annually',
[2026, 11, 31, 23, 59, 59],
[
[2027, 0, 1, 0, 0, 0],
[2028, 0, 1, 0, 0, 0],
],
],
[
'@midnight',
[2026, 8, 27, 23, 59, 59],
[
[2026, 8, 28, 0, 0, 0],
[2026, 8, 29, 0, 0, 0],
],
],
[
'@minutely',
[2026, 8, 27, 12, 34, 59],
[
[2026, 8, 27, 12, 35, 0],
[2026, 8, 27, 12, 36, 0],
],
],
]) {
test(`${macro} fires at the expected local times in ${tz}`, async (t) => {
const previousTZ = process.env.TZ;
process.env.TZ = tz;
t.after(() => { if (previousTZ === undefined) delete process.env.TZ; else process.env.TZ = previousTZ; });
t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: new Date(...start) });
t.after(() => {
if (previousTZ === undefined) delete process.env.TZ;
else process.env.TZ = previousTZ;
});
t.mock.timers.enable({
apis: ['Date', 'setTimeout', 'setInterval'],
now: new Date(...start),
});
const expected = next.map((parts) => new Date(...parts).getTime());
const actual = [];
assert.equal(isValidCronSchedule(` ${macro} `), true);
const job = createCronJob(macro, (date) => actual.push(date.getTime()), {
name: macro, logger: { warn() {}, error() {} },
name: macro,
logger: { warn() {}, error() {} },
});
t.after(() => job.cancel());
for (const time of expected) {
@@ -48,7 +85,15 @@ for (const tz of process.env.QL_MACRO_TEST_TZ ? [process.env.QL_MACRO_TEST_TZ] :
}
test('new aliases do not enable unknown macros or raw parser extensions', () => {
for (const schedule of ['@annuallyx', '@midnightx', '@minutelyx', '@secondly', '@reboot', 'H * * * *', '0 /5 * * * *']) {
for (const schedule of [
'@annuallyx',
'@midnightx',
'@minutelyx',
'@secondly',
'@reboot',
'H * * * *',
'0 /5 * * * *',
]) {
assert.equal(isValidCronSchedule(schedule), false, schedule);
}
});
+58
View File
@@ -0,0 +1,58 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const fs = require('node:fs/promises');
const os = require('node:os');
const { spawnSync } = require('node:child_process');
test('the compiled orphan reporter loads cron history without a legacy forwarding entry', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-reporter-path-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
for (const directory of ['shared', 'cron/settlement', 'data']) {
await fs.mkdir(path.join(root, directory), { recursive: true });
}
const reporter = path.join(root, 'shared/managedExit.cjs');
const report = path.join(root, 'report.json');
await fs.copyFile(path.resolve('back/shared/managedExit.cjs'), reporter);
await fs.copyFile(
path.resolve('back/cron/settlement/exitReceipt.cjs'),
path.join(root, 'cron/settlement/exitReceipt.cjs'),
);
await fs.writeFile(
path.join(root, 'cron/history.js'),
`
exports.triggerHistory = () => ({ complete: (...args) => {
require('node:fs').writeFileSync(process.env.REPORT, JSON.stringify(args));
return Promise.resolve();
} });
`,
);
await fs.writeFile(
path.join(root, 'data/index.js'),
'exports.sequelize = { close: async () => {} };',
);
const time = Date.now();
const result = spawnSync(
process.execPath,
[reporter, JSON.stringify({ code: 7, signal: null, time })],
{
env: {
...process.env,
NODE_OPTIONS: '',
QL_TRIGGER_ID: 'compiled-report',
REPORT: report,
},
encoding: 'utf8',
timeout: 10000,
},
);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(JSON.parse(await fs.readFile(report, 'utf8')), [
'compiled-report',
'failed',
null,
7,
time,
'legacy',
]);
});
+3 -3
View File
@@ -5,8 +5,8 @@ const {
parseCronSchedule,
isValidCronSchedule,
getInvalidCronSchedules,
} = require('../../back/shared/cronSchedule');
const { createCronJob } = require('../../back/shared/cronScheduler');
} = require('../../back/cron/scheduling/cronSchedule');
const { createCronJob } = require('../../back/cron/scheduling/cronScheduler');
const logger = { warn() {}, error() {} };
@@ -132,7 +132,7 @@ for (const [schedule, patterns, maxValidations] of [
test(`supported expressions skip field validation: ${schedule}`, () => {
const load = require('../helpers/load-security-module.cjs');
const validations = [];
const isolated = load('back/shared/cronSchedule.ts', {
const isolated = load('back/cron/scheduling/cronSchedule.ts', {
'node-cron': {
validate(pattern) {
validations.push(pattern);
+184
View File
@@ -0,0 +1,184 @@
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 { once } = require('node:events');
const express = require('express');
const { Sequelize, Transaction } = require('sequelize');
const load = require('../helpers/load-security-module.cjs');
const {
TriggerHistory,
installTriggerHistory,
} = require('../../back/cron/history');
async function fixture(t) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-run-receipt-'));
const db = new Sequelize({
dialect: 'sqlite',
storage: path.join(root, 'panel.sqlite'),
logging: false,
transactionType: Transaction.TYPES.IMMEDIATE,
});
t.after(async () => {
await db.close();
await fs.rm(root, { recursive: true, force: true });
});
const models = load('back/data/cron.ts', { './index': { sequelize: db } });
const instances = load('back/data/runningInstance.ts', {
'./index': { sequelize: db },
});
load('back/data/cronStats.ts', { './index': { sequelize: db } });
await db.sync();
await db.transaction((transaction) => installTriggerHistory(db, transaction));
const history = new TriggerHistory(db);
const Service = load('back/services/cron.ts', {
'../data/cron': models,
'../data/runningInstance': instances,
'../config/index': { logPath: root },
'../cron/execution/cronLimit': {},
'../schedule/client': {},
'../shared/logStreamManager': {},
'../config/util': {
fileExist: async (file) => {
try {
await fs.access(file);
return true;
} catch {
return false;
}
},
},
}).default;
const service = new Service({ error() {}, info() {}, warn() {} });
const launched = [];
service.runSingle = async (...args) => {
launched.push(args);
};
await models.CrontabModel.bulkCreate([
{
id: 1,
command: 'true',
isDisabled: 0,
status: 1,
allow_multiple_instances: 1,
},
{
id: 2,
command: 'sleep 1',
isDisabled: 0,
status: 0,
pid: process.pid,
allow_multiple_instances: 0,
},
]);
return { root, db, models, history, service, launched };
}
test('run returns committed per-task receipts including overlap skips and preserves dispatch identity', async (t) => {
const { service, launched, history, models } = await fixture(t);
const receipts = await service.run([1, 2, 1, 999]);
assert.equal(receipts.length, 2);
const queued = receipts.find((row) => row.taskId === 1);
const skipped = receipts.find((row) => row.taskId === 2);
assert.deepEqual(
{ ...queued, triggerId: 'id' },
{ taskId: 1, triggerId: 'id', state: 'queued', reason: null },
);
assert.deepEqual(
{ ...skipped, triggerId: 'id' },
{ taskId: 2, triggerId: 'id', state: 'skipped', reason: 'overlap' },
);
for (const receipt of receipts) {
const [row] = await history.visibleTriggers(receipt.taskId, [
receipt.triggerId,
]);
assert.equal(row.state, receipt.state);
assert.equal(row.reason, receipt.reason);
}
assert.equal(launched.length, 1);
assert.equal(launched[0][0], 1);
assert.equal(launched[0][2], queued.triggerId);
assert.equal(
(await models.CrontabModel.findByPk(1)).queued_token,
launched[0][1],
);
const [next] = await service.run([1]);
assert.notEqual(next.triggerId, queued.triggerId);
assert.deepEqual(await service.run([999]), []);
const [boot] = await service.run([1], 'boot');
assert.equal(
(await history.visibleTriggers(1, [boot.triggerId]))[0].source,
'boot',
);
});
test('transaction failure publishes neither a receipt nor a dispatch', async (t) => {
const { service, launched, history, models } = await fixture(t);
t.mock.method(models.CrontabModel, 'update', async () => {
throw new Error('write failed');
});
await assert.rejects(service.run([1]), /write failed/);
assert.deepEqual(await history.recent(1, 0), []);
assert.deepEqual(launched, []);
});
test('HTTP run receipts select their own history and logs despite a newer sibling run', async (t) => {
const { service, history, db, root } = await fixture(t);
const router = express.Router();
load('back/api/cron.ts', {
typedi: { Container: { get: () => service } },
'../services/cron': class {},
'../services/cronView': class {},
'../schedule/client': { readiness: { ensureReady: async () => {} } },
'../validation/schedule': { commonCronSchema: {} },
'../cron/history': { triggerHistory: () => history },
}).default(router);
const server = express()
.use(express.json())
.use('/api', router)
.listen(0, '127.0.0.1');
await once(server, 'listening');
t.after(() => {
server.closeAllConnections();
server.close();
});
const base = `http://127.0.0.1:${server.address().port}/api/crons`;
const run = () =>
fetch(`${base}/run`, {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: '[1]',
}).then((r) => r.json());
const first = await run();
const second = await run();
assert.equal(first.code, 200);
const a = first.data[0].triggerId,
b = second.data[0].triggerId;
assert.notEqual(a, b);
for (const [id, name] of [
[a, 'first'],
[b, 'second'],
]) {
await fs.writeFile(path.join(root, `${name}.log`), `${name} execution\n`);
await db.query(
"UPDATE CronTriggers SET state='finished',exit_code=0,log_path=$file WHERE id=$id",
{ bind: { id, file: `${name}.log` } },
);
}
const selected = await fetch(
`${base}/1/triggers?${new URLSearchParams({ ids: a })}`,
).then((r) => r.json());
assert.equal(selected.data.length, 1);
assert.equal(selected.data[0].id, a);
const log = await fetch(
`${base}/1/log?${new URLSearchParams({ triggerId: a })}`,
).then((r) => r.json());
assert.equal(log.triggerId, a);
assert.equal(log.data, 'first execution\n');
const wrongTask = await fetch(
`${base}/2/log?${new URLSearchParams({ triggerId: a })}`,
).then((r) => r.json());
assert.equal(wrongTask.logStatus, 'notFound');
assert.doesNotMatch(wrongTask.data, /first execution|second execution/);
});
+51 -15
View File
@@ -1,7 +1,9 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { isValidCronSchedule } = require('../../back/shared/cronSchedule');
const { createCronJob } = require('../../back/shared/cronScheduler');
const {
isValidCronSchedule,
} = require('../../back/cron/scheduling/cronSchedule');
const { createCronJob } = require('../../back/cron/scheduling/cronScheduler');
const legacy = require('../fixtures/legacy-cron.json');
const logger = { warn() {}, error() {} };
const flush = () => new Promise(setImmediate);
@@ -10,7 +12,11 @@ test('validation preserves legacy syntax except the explicitly added macros', ()
const addedMacros = new Set(['@annually', '@midnight', '@minutely']);
assert.ok(legacy.validation.length > 250);
for (const { schedule, accepted } of legacy.validation) {
assert.equal(isValidCronSchedule(schedule), accepted || addedMacros.has(schedule), schedule);
assert.equal(
isValidCronSchedule(schedule),
accepted || addedMacros.has(schedule),
schedule,
);
}
});
@@ -18,10 +24,20 @@ for (const sample of legacy.times) {
test(`calendar compatibility: ${sample.schedule} from ${sample.currentDate}`, async (t) => {
const previousTZ = process.env.TZ;
process.env.TZ = 'UTC';
t.after(() => { if (previousTZ === undefined) delete process.env.TZ; else process.env.TZ = previousTZ; });
t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: new Date(sample.currentDate) });
t.after(() => {
if (previousTZ === undefined) delete process.env.TZ;
else process.env.TZ = previousTZ;
});
t.mock.timers.enable({
apis: ['Date', 'setTimeout', 'setInterval'],
now: new Date(sample.currentDate),
});
const actual = [];
const job = createCronJob(sample.schedule, (date) => actual.push(date.toISOString()), { name: 'calendar', logger });
const job = createCronJob(
sample.schedule,
(date) => actual.push(date.toISOString()),
{ name: 'calendar', logger },
);
t.after(() => job.cancel());
for (const expected of sample.next) {
t.mock.timers.tick(new Date(expected).getTime() - Date.now());
@@ -32,13 +48,22 @@ for (const sample of legacy.times) {
}
test('late callbacks catch up exactly once and cancellation destroys native tasks', async (t) => {
t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: new Date('2026-09-27T00:00:00Z') });
t.mock.timers.enable({
apis: ['Date', 'setTimeout', 'setInterval'],
now: new Date('2026-09-27T00:00:00Z'),
});
const native = require('node-cron');
const before = native.getTasks().size;
const dates = [], warnings = [];
const job = createCronJob('* * * * * *', (date) => dates.push(date.getTime()), {
name: 'late', logger: { warn: (...args) => warnings.push(args), error() {} },
});
const dates = [],
warnings = [];
const job = createCronJob(
'* * * * * *',
(date) => dates.push(date.getTime()),
{
name: 'late',
logger: { warn: (...args) => warnings.push(args), error() {} },
},
);
t.after(() => job.cancel());
t.mock.timers.tick(8000);
await flush();
@@ -53,12 +78,23 @@ test('late callbacks catch up exactly once and cancellation destroys native task
});
test('callback rejection is logged and future executions continue', async (t) => {
t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: new Date('2026-09-27T00:00:00Z') });
t.mock.timers.enable({
apis: ['Date', 'setTimeout', 'setInterval'],
now: new Date('2026-09-27T00:00:00Z'),
});
const errors = [];
let count = 0;
const job = createCronJob('* * * * * *', async () => { count++; throw Error('callback failed'); }, {
name: 'failure', logger: { warn() {}, error: (...args) => errors.push(args) },
});
const job = createCronJob(
'* * * * * *',
async () => {
count++;
throw Error('callback failed');
},
{
name: 'failure',
logger: { warn() {}, error: (...args) => errors.push(args) },
},
);
t.after(() => job.cancel());
t.mock.timers.tick(1000);
await flush();
+254 -24
View File
@@ -1,26 +1,55 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const ts = require('typescript');
const { ScheduleType } = require('../../back/interface/schedule');
const load = require('../helpers/load-security-module.cjs');
const {
makeCommand,
nodeCron,
} = require('../../back/cron/scheduling/cronScheduling');
function fixture(mode, failAt) {
const events = [];
const step = (name, ...args) => {
events.push([name, ...args]);
if (name === failAt) throw Error(`failed ${name}`);
};
const Service = load('back/services/cron.ts', {
'../config/index': { crontabFile: '/unused' },
'../config/util': {},
'../data/cron': {
CrontabModel: {
sequelize: {},
update: async (values, options) => step('saved', values, options.where),
},
},
'../data/runningInstance': {},
'../cron/execution/cronLimit': {},
'../shared/logStreamManager': {},
'../schedule/client': {
readiness: { invalidate: () => step('invalidate') },
},
'../shared/utils': {
writeFileWithLock: async (file, contents) =>
step('write', file, contents),
},
'../cron/scheduling/systemScheduleAudit': {
stageSystemPlan: async (db, rules) => {
step('stage', rules);
return 42;
},
confirmSystemPlan: async (db, plan) => step('confirm', plan),
suspendSystemPlan: async () => step('suspend'),
},
child_process: { execFileSync: (...args) => step('install', ...args) },
'../shared/i18n': { t: (value) => value },
}).default;
const service = new Service({ error: (...args) => step('error', ...args) });
Object.defineProperty(service, 'schedulerMode', { value: mode });
return { service, events };
}
test('system and node modes route extended cron once and keep portable rules in crontab', async () => {
const source = fs.readFileSync('back/services/cron.ts', 'utf8');
const begin = source.indexOf(' private isNodeCron(');
const end = source.indexOf(' private async getLogName', begin);
const saveBegin = source.indexOf(' private async setCrontab(');
const saveEnd = source.indexOf(' public importCrontab(', saveBegin);
const js = ts.transpileModule(`class Fixture {${source.slice(begin, end)}${source.slice(saveBegin, saveEnd)}}; module.exports = Fixture;`, {
compilerOptions: { target: ts.ScriptTarget.ES2020 },
}).outputText;
for (const mode of ['system', 'node']) {
const module = { exports: {} };
let file = '', installs = 0;
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 () => {} }, require('../../back/shared/shellQuote').shellQuote, async () => 1, async () => {}, async () => {},
);
const service = new module.exports();
const { service, events } = fixture(mode);
service.makeCommand = (row) => `task ${row.id}.js`;
const rows = [
{ id: 'plain', schedule: '*/5 0-23 * * 1,3' },
@@ -40,20 +69,221 @@ test('system and node modes route extended cron once and keep portable rules in
{ id: 'named', schedule: '0 0 * JAN MON' },
{ id: 'macro', schedule: '@daily' },
{ id: 'short', schedule: '*' },
{ id: 'extra', schedule: '* * * * *', extra_schedules: [{ schedule: '0 * * * *' }] },
{
id: 'extra',
schedule: '* * * * *',
extra_schedules: [{ schedule: '0 * * * *' }],
},
{ id: 'wait', schedule: '* * * * *', max_queue_wait: 30 },
{ id: 'catchup', schedule: '* * * * *', catchup_seconds: 60 },
{ id: 'pending', schedule: '* * * * *', skip_if_pending: 1 },
{ id: 'once', schedule: '@once' },
{ id: 'boot', schedule: '@boot' },
];
for (const row of rows) {
const special = ['once', 'boot'].includes(row.id);
const portable = ['plain', 'spaces'].includes(row.id);
assert.equal(service.shouldUseCronClient(row), !special && (mode === 'node' || !portable), `${mode}: ${row.id}`);
assert.equal(
service.shouldUseCronClient(row),
!special && (mode === 'node' || !portable),
`${mode}: ${row.id}`,
);
}
await service.setCrontab({ data: rows, total: rows.length });
assert.equal(installs, mode === 'system' ? 1 : 0);
for (const id of ['numeric-step', 'sunday-seven', 'day-step', 'restricted-days', 'restricted-week', 'annually', 'midnight', 'minutely', 'seconds', 'question', 'last', 'nth', 'named', 'macro', 'short', 'extra', 'once', 'boot']) {
const line = file.split('\n').find((line) => line.endsWith(`task ${id}.js`));
assert.ok(line.startsWith('# '), `${mode}: ${id} cannot also run from system crontab`);
assert.deepEqual(
events.map(([name]) => name),
mode === 'system'
? ['stage', 'write', 'install', 'confirm']
: ['suspend', 'write'],
);
const file = events.find(([name]) => name === 'write')[2];
for (const id of rows
.filter((row) => !['plain', 'spaces'].includes(row.id))
.map((row) => row.id)) {
const line = file
.split('\n')
.find((line) => line.endsWith(`task ${id}.js`));
assert.ok(
line.startsWith('# '),
`${mode}: ${id} cannot also run from system crontab`,
);
}
for (const id of ['plain', 'spaces']) {
const line = file.split('\n').find((line) => line.includes(`ID=${id} `));
assert.ok(!line.startsWith('# '));
assert.ok(line.includes('QL_SYSTEM_DISPATCHED=$(date +\\%s)'));
assert.ok(
line.includes(
'QL_TRIGGER_SOURCE=system bash "$QL_DIR/shell/system-cron.sh"',
),
);
}
}
});
test('only acknowledged registrations become saved after system publication completes', async () => {
const { service, events } = fixture('system');
const rows = [
{ id: 1, name: 'portable', command: 'a.js', schedule: '* * * * *' },
{ id: 2, command: 'b.js', schedule: '@minutely' },
];
await service.setCrontab({ data: rows, total: rows.length }, [1]);
assert.deepEqual(
events.map(([name]) => name),
['stage', 'write', 'install', 'confirm', 'saved'],
);
assert.deepEqual(events[0][1], [
{ id: 1, name: 'portable', schedule: '* * * * *' },
]);
assert.deepEqual(events.at(-1), [
'saved',
{ saved: true },
{ id: [1], saved: false },
]);
});
for (const mode of ['system', 'node']) {
for (const phase of mode === 'system'
? ['stage', 'write', 'install', 'confirm']
: ['suspend', 'write']) {
test(`${mode} publication failure at ${phase} invalidates readiness without acknowledging schedules`, async () => {
const { service, events } = fixture(mode, phase);
const rows = [
{ id: 1, command: 'a.js', schedule: '* * * * *' },
{ id: 2, command: 'b.js', schedule: '* * * * *', isDisabled: 1 },
{ id: 3, command: 'c.js', schedule: '@minutely' },
{ id: 4, command: 'd.js', schedule: '@boot' },
];
await assert.rejects(
service.setCrontab({ data: rows, total: rows.length }, [1, 3]),
(error) =>
error.status === 503 && /旧规则可能仍在运行/.test(error.message),
);
const sequence =
mode === 'system'
? ['stage', 'write', 'install', 'confirm']
: ['suspend', 'write'];
assert.deepEqual(
events.map(([name]) => name),
[
...sequence.slice(0, sequence.indexOf(phase) + 1),
'error',
'invalidate',
...(mode === 'system' ? ['saved'] : []),
],
);
if (mode === 'system') {
assert.deepEqual(events.at(-1), [
'saved',
{ saved: false },
{ id: [1, 2] },
]);
}
});
}
}
test('manual and scheduled commands preserve the shell contract and Node registration fields', () => {
const doc = {
id: 7,
name: 'task',
command: 'ql repo https://example.test/repo',
schedule: '* * * * *',
log_name: "logs/it's a task",
work_dir: "/scripts/it's here",
task_before: 'echo before;\necho ready',
task_after: 'echo done',
extra_schedules: [{ schedule: '0 0 * * *' }],
max_queue_wait: 30,
catchup_seconds: 60,
skip_if_pending: 1,
recovery_from: 1234,
};
const scheduled = makeCommand(doc);
assert.equal(
scheduled,
"QL_CRON_REVISION=1234 real_time=false no_tee=true ID=7 log_name='logs/it'\\''s a task' task_before='echo before;echo ready' task_after='echo done' work_dir='/scripts/it'\\''s here' ql repo https://example.test/repo",
);
assert.equal(
makeCommand(doc, true),
scheduled.replace('real_time=false', 'real_time=true'),
);
assert.deepEqual(nodeCron(doc, scheduled), {
id: '7',
name: 'task',
command: scheduled,
schedule: '* * * * *',
extra_schedules: [{ schedule: '0 0 * * *' }],
max_queue_wait: 30,
catchup_seconds: 60,
skip_if_pending: true,
recovery_from: 1234,
});
assert.equal(
makeCommand({ id: 8, command: 'script.js' }),
'real_time=false no_tee=true ID=8 task script.js',
);
assert.equal(
makeCommand({ id: 8, command: 'task script.js', log_name: '/dev/null' }),
'real_time=false no_tee=true ID=8 log_name=/dev/null task script.js',
);
});
test('scheduler mode honors explicit overrides and probes crond again for automatic selection', (t) => {
const previous = process.env.QL_SCHEDULER;
t.after(() => {
if (previous === undefined) delete process.env.QL_SCHEDULER;
else process.env.QL_SCHEDULER = previous;
});
let installed = true,
probes = 0;
const { schedulerMode } = load('back/cron/scheduling/cronScheduling.ts', {
child_process: {
execSync: (command, options) => {
probes++;
assert.equal(command, 'which crond');
assert.deepEqual(options, { stdio: 'ignore' });
if (!installed) throw Error('missing crond');
},
},
});
for (const mode of ['system', 'node']) {
process.env.QL_SCHEDULER = mode;
assert.equal(schedulerMode(), mode);
}
assert.equal(probes, 0);
delete process.env.QL_SCHEDULER;
assert.equal(schedulerMode(), 'system');
installed = false;
assert.equal(schedulerMode(), 'node');
process.env.QL_SCHEDULER = 'auto';
installed = true;
assert.equal(schedulerMode(), 'system');
assert.equal(probes, 3);
});
test('a gRPC worker still notifies its parent when system installation fails', async (t) => {
const previousType = process.env.SERVICE_TYPE;
const previousSend = process.send;
const messages = [];
process.env.SERVICE_TYPE = 'grpc';
process.send = (message) => {
messages.push(message);
return true;
};
t.after(() => {
if (previousType === undefined) delete process.env.SERVICE_TYPE;
else process.env.SERVICE_TYPE = previousType;
if (previousSend === undefined) delete process.send;
else process.send = previousSend;
});
const { service } = fixture('system', 'install');
await assert.rejects(
service.setCrontab({
data: [{ id: 1, command: 'a.js', schedule: '* * * * *' }],
total: 1,
}),
(error) => error.status === 503,
);
assert.deepEqual(messages, ['crontab-install-failed']);
});
+98 -42
View File
@@ -4,7 +4,10 @@ const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { once } = require('node:events');
const { spawnCronCommand, releaseCronCommand } = require('../../back/shared/cronCommandProcess');
const {
spawnCronCommand,
releaseCronCommand,
} = require('../../back/cron/execution/cronCommandProcess');
const { observeChildProcess } = require('../../back/shared/childProcess');
const { shellQuote } = require('../../back/shared/shellQuote');
@@ -24,38 +27,72 @@ function nodeCommand(code) {
return `${shellQuote(process.execPath)} -e ${shellQuote(code)}`;
}
test('supervisor appends complete merged output once and preserves start telemetry and exit status', { timeout: 10000 }, async t => {
const root = await fixture(t);
const log = path.join(root, "log's $name.log");
const output = '尾行 '.repeat(100000);
await fs.writeFile(log, 'previous\n');
let started;
let forwarded = '';
const child = spawnCronCommand(nodeCommand(`const fs=require('node:fs');const b=Buffer.from('尾行 '.repeat(100000));let i=0;while(i<b.length)i+=fs.writeSync(1,b,i,b.length-i);fs.writeSync(2,'STDERR\\n');process.exitCode=17;`),
'log-append', value => { started = value; }, log);
const result = await observeChildProcess(child, {
onStart: () => releaseCronCommand(child),
onStdout: async text => { forwarded += text; },
onStderr: async text => { forwarded += text; },
}).completed;
assert.equal(result.code, 17);
assert.equal(result.error, undefined);
assert.equal(forwarded, '');
assert.ok(Number.isInteger(started) && Math.abs(Date.now() - started) < 10000);
assert.equal(await fs.readFile(log, 'utf8'), 'previous\n' + output + 'STDERR\n');
});
test(
'supervisor appends complete merged output once and preserves start telemetry and exit status',
{ timeout: 10000 },
async (t) => {
const root = await fixture(t);
const log = path.join(root, "log's $name.log");
const output = '尾行 '.repeat(100000);
await fs.writeFile(log, 'previous\n');
let started;
let forwarded = '';
const child = spawnCronCommand(
nodeCommand(
`const fs=require('node:fs');const b=Buffer.from('尾行 '.repeat(100000));let i=0;while(i<b.length)i+=fs.writeSync(1,b,i,b.length-i);fs.writeSync(2,'STDERR\\n');process.exitCode=17;`,
),
'log-append',
(value) => {
started = value;
},
log,
);
const result = await observeChildProcess(child, {
onStart: () => releaseCronCommand(child),
onStdout: async (text) => {
forwarded += text;
},
onStderr: async (text) => {
forwarded += text;
},
}).completed;
assert.equal(result.code, 17);
assert.equal(result.error, undefined);
assert.equal(forwarded, '');
assert.ok(
Number.isInteger(started) && Math.abs(Date.now() - started) < 10000,
);
assert.equal(
await fs.readFile(log, 'utf8'),
'previous\n' + output + 'STDERR\n',
);
},
);
for (const fault of ['open', 'full']) {
for (const disconnected of [false, true]) {
test(`log ${fault} failure drains output without interrupting command (reader disconnected=${disconnected})`,
{ timeout: 10000, skip: fault === 'full' && process.platform !== 'linux' }, async t => {
test(
`log ${fault} failure drains output without interrupting command (reader disconnected=${disconnected})`,
{
timeout: 10000,
skip: fault === 'full' && process.platform !== 'linux',
},
async (t) => {
const root = await fixture(t);
const marker = path.join(root, 'completed');
// A directory fails at open; /dev/full opens but every write fails ENOSPC.
const log = fault === 'open' ? root : '/dev/full';
const code = `const fs=require('node:fs');const b=Buffer.alloc(65536,120);for(let n=0;n<64;n++){let i=0;while(i<b.length)i+=fs.writeSync(n%2?2:1,b,i,b.length-i);}fs.writeFileSync(${JSON.stringify(marker)},'completed');`;
const child = spawnCronCommand(nodeCommand(code), 'log-fault', undefined, log);
let result, errors = '';
const code = `const fs=require('node:fs');const b=Buffer.alloc(65536,120);for(let n=0;n<64;n++){let i=0;while(i<b.length)i+=fs.writeSync(n%2?2:1,b,i,b.length-i);}fs.writeFileSync(${JSON.stringify(
marker,
)},'completed');`;
const child = spawnCronCommand(
nodeCommand(code),
'log-fault',
undefined,
log,
);
let result,
errors = '';
if (disconnected) {
const closed = once(child, 'close');
child.stdout.destroy();
@@ -66,28 +103,47 @@ for (const fault of ['open', 'full']) {
} else {
result = await observeChildProcess(child, {
onStart: () => releaseCronCommand(child),
onStderr: async text => { errors += text; },
onStderr: async (text) => {
errors += text;
},
}).completed;
assert.equal(result.error, undefined);
assert.equal((errors.match(/Could not write command log/g) || []).length, 1);
assert.match(errors, fault === 'full' ? /No space left/ : /Is a directory/);
assert.equal(
(errors.match(/Could not write command log/g) || []).length,
1,
);
assert.match(
errors,
fault === 'full' ? /No space left/ : /Is a directory/,
);
}
assert.equal(result.code, 0);
assert.equal(result.signal, null);
assert.equal(await fs.readFile(marker, 'utf8'), 'completed');
});
},
);
}
}
test('cancelled launch neither creates a log nor executes the command', { timeout: 10000 }, async t => {
const root = await fixture(t);
const marker = path.join(root, 'executed');
const log = path.join(root, 'cancelled.log');
const child = spawnCronCommand(nodeCommand(`require('node:fs').writeFileSync(${JSON.stringify(marker)},'bad')`),
'log-cancel', undefined, log);
const closed = once(child, 'close');
child.stdin.end();
assert.equal((await closed)[0], 125);
await assert.rejects(fs.access(log), { code: 'ENOENT' });
await assert.rejects(fs.access(marker), { code: 'ENOENT' });
});
test(
'cancelled launch neither creates a log nor executes the command',
{ timeout: 10000 },
async (t) => {
const root = await fixture(t);
const marker = path.join(root, 'executed');
const log = path.join(root, 'cancelled.log');
const child = spawnCronCommand(
nodeCommand(
`require('node:fs').writeFileSync(${JSON.stringify(marker)},'bad')`,
),
'log-cancel',
undefined,
log,
);
const closed = once(child, 'close');
child.stdin.end();
assert.equal((await closed)[0], 125);
await assert.rejects(fs.access(log), { code: 'ENOENT' });
await assert.rejects(fs.access(marker), { code: 'ENOENT' });
},
);
+32 -9
View File
@@ -74,7 +74,9 @@ 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 status(value) {
return value;
},
async create(value) {
mutations.push(value);
return { id: 1, ...value };
@@ -113,17 +115,31 @@ test('create and update reject invalid extra schedules before calling the servic
// 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 }),
});
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);
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 = {
@@ -184,9 +200,16 @@ test('create and update reject invalid extra schedules before calling the servic
});
test('saving a migrated task accepts a null pending policy and rejects invalid input', () => {
const task = { name: 'legacy', command: 'task old.sh', schedule: '1 * * * *' };
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.equal(
schema.validate({ ...task, skip_if_pending: value }).error,
undefined,
);
}
assert.ok(schema.validate({ ...task, skip_if_pending: 'invalid' }).error);
});
+233 -106
View File
@@ -19,7 +19,9 @@ function fixture(t) {
fs.mkdirSync(path.join(dir, 'data/syslog'), { recursive: true });
fs.writeFileSync(path.join(dir, '.env'), '');
const wrapper = path.join(dir, 'parent.cjs');
fs.writeFileSync(wrapper, `
fs.writeFileSync(
wrapper,
`
const cp = require('node:child_process');
const original = cp.fork;
cp.fork = (...args) => {
@@ -35,24 +37,39 @@ function fixture(t) {
console.error(error.message);
process.exitCode = 1;
}).finally(() => { if (process.connected) process.disconnect(); });
`);
`,
);
return {
dir,
storage: path.join(dir, 'data/db/database.sqlite'),
run(entrypoint = initializer) {
const child = fork(wrapper, [entrypoint], {
env: { ...process.env, QL_DIR: dir, QL_DATA_DIR: path.join(dir, 'data') },
env: {
...process.env,
QL_DIR: dir,
QL_DATA_DIR: path.join(dir, 'data'),
},
stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
});
const messages = [];
let output = '';
child.on('message', (message) => messages.push(message));
child.stdout.on('data', (data) => { output += data; });
child.stderr.on('data', (data) => { output += data; });
t.after(() => {
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
child.stdout.on('data', (data) => {
output += data;
});
const done = once(child, 'close').then(([code, signal]) => ({ code, signal, output, messages }));
child.stderr.on('data', (data) => {
output += data;
});
t.after(() => {
if (child.exitCode === null && child.signalCode === null)
child.kill('SIGKILL');
});
const done = once(child, 'close').then(([code, signal]) => ({
code,
signal,
output,
messages,
}));
return { child, done, messages };
},
};
@@ -62,132 +79,242 @@ async function waitFor(predicate) {
const deadline = Date.now() + 10000;
while (!predicate()) {
assert.ok(Date.now() < deadline, 'timed out waiting for child');
await new Promise(resolve => setTimeout(resolve, 20));
await new Promise((resolve) => setTimeout(resolve, 20));
}
}
test('isolated initialization creates a fresh database and does not retain ORM modules in the parent', { timeout: 20000 }, async t => {
const f = fixture(t);
const result = await f.run().done;
assert.equal(result.code, 0, result.output);
const done = result.messages.find(message => message.done);
assert.ok(done);
assert.equal(done.modules.some(file => /[\\/]sequelize[\\/]|[\\/]data[\\/]index\.ts$/.test(file)), false);
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', '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(); }
});
test('isolated initialization upgrades an existing database and remains idempotent', { timeout: 30000 }, async t => {
const f = fixture(t);
let db = new Sequelize({ dialect: 'sqlite', storage: f.storage, logging: false });
await db.query('CREATE TABLE Crontabs (id INTEGER PRIMARY KEY, name TEXT)');
await db.query("INSERT INTO Crontabs (id, name) VALUES (1, 'keep-me')");
await db.close();
for (let i = 0; i < 2; i++) {
test(
'isolated initialization creates a fresh database and does not retain ORM modules in the parent',
{ timeout: 20000 },
async (t) => {
const f = fixture(t);
const result = await f.run().done;
assert.equal(result.code, 0, result.output);
}
db = new Sequelize({ dialect: 'sqlite', storage: f.storage, logging: false });
try {
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.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(); }
});
const done = result.messages.find((message) => message.done);
assert.ok(done);
assert.equal(
done.modules.some((file) =>
/[\\/]sequelize[\\/]|[\\/]data[\\/]index\.ts$/.test(file),
),
false,
);
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',
'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();
}
},
);
test('database errors and missing initializer files reject startup', { timeout: 20000 }, async t => {
const f = fixture(t);
fs.writeFileSync(f.storage, 'invalid SQLite database');
const invalid = await f.run().done;
assert.equal(invalid.code, 1);
assert.match(invalid.output, /SQLITE_NOTADB/);
assert.equal(invalid.messages.some(message => message.done), false);
const missing = await f.run(path.join(f.dir, 'missing.cjs')).done;
assert.equal(missing.code, 1);
assert.match(missing.output, /MODULE_NOT_FOUND/);
});
test(
'isolated initialization upgrades an existing database and remains idempotent',
{ timeout: 30000 },
async (t) => {
const f = fixture(t);
let db = new Sequelize({
dialect: 'sqlite',
storage: f.storage,
logging: false,
});
await db.query('CREATE TABLE Crontabs (id INTEGER PRIMARY KEY, name TEXT)');
await db.query("INSERT INTO Crontabs (id, name) VALUES (1, 'keep-me')");
await db.close();
for (let i = 0; i < 2; i++) {
const result = await f.run().done;
assert.equal(result.code, 0, result.output);
}
db = new Sequelize({
dialect: 'sqlite',
storage: f.storage,
logging: false,
});
try {
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.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();
}
},
);
test(
'database errors and missing initializer files reject startup',
{ timeout: 20000 },
async (t) => {
const f = fixture(t);
fs.writeFileSync(f.storage, 'invalid SQLite database');
const invalid = await f.run().done;
assert.equal(invalid.code, 1);
assert.match(invalid.output, /SQLITE_NOTADB/);
assert.equal(
invalid.messages.some((message) => message.done),
false,
);
const missing = await f.run(path.join(f.dir, 'missing.cjs')).done;
assert.equal(missing.code, 1);
assert.match(missing.output, /MODULE_NOT_FOUND/);
},
);
for (const signal of ['SIGTERM', 'SIGINT']) {
test(`startup ${signal} terminates the initializer and never reports success`, { timeout: 15000 }, async t => {
const f = fixture(t);
const target = path.join(f.dir, 'waiting.cjs');
const ready = path.join(f.dir, 'ready');
fs.writeFileSync(target, `
require('node:fs').writeFileSync(${JSON.stringify(ready)}, String(process.pid));
test(
`startup ${signal} terminates the initializer and never reports success`,
{ timeout: 15000 },
async (t) => {
const f = fixture(t);
const target = path.join(f.dir, 'waiting.cjs');
const ready = path.join(f.dir, 'ready');
fs.writeFileSync(
target,
`
require('node:fs').writeFileSync(${JSON.stringify(
ready,
)}, String(process.pid));
setInterval(() => {}, 1000);
`);
const running = f.run(target);
await waitFor(() => fs.existsSync(ready));
const pid = Number(fs.readFileSync(ready, 'utf8'));
running.child.kill(signal);
const result = await running.done;
assert.equal(result.code, 1, result.output);
assert.match(result.output, new RegExp(signal));
assert.equal(result.messages.some(message => message.done), false);
assert.throws(() => process.kill(pid, 0), { code: 'ESRCH' });
});
`,
);
const running = f.run(target);
await waitFor(() => fs.existsSync(ready));
const pid = Number(fs.readFileSync(ready, 'utf8'));
running.child.kill(signal);
const result = await running.done;
assert.equal(result.code, 1, result.output);
assert.match(result.output, new RegExp(signal));
assert.equal(
result.messages.some((message) => message.done),
false,
);
assert.throws(() => process.kill(pid, 0), { code: 'ESRCH' });
},
);
}
test('a database initializer blocked on SQLite exits when its parent disappears', { timeout: 20000 }, async t => {
const f = fixture(t);
const db = new Sequelize({ dialect: 'sqlite', storage: f.storage, logging: false });
await db.query('BEGIN EXCLUSIVE');
try {
const running = f.run();
await waitFor(() => running.messages.some(message => message.childPid));
const pid = running.messages.find(message => message.childPid).childPid;
// Allow the real initializer to enter the database operation before losing IPC.
await new Promise(resolve => setTimeout(resolve, 1000));
running.child.kill('SIGKILL');
await running.done;
await waitFor(() => {
try { process.kill(pid, 0); return false; }
catch (error) { if (error.code === 'ESRCH') return true; throw error; }
test(
'a database initializer blocked on SQLite exits when its parent disappears',
{ timeout: 20000 },
async (t) => {
const f = fixture(t);
const db = new Sequelize({
dialect: 'sqlite',
storage: f.storage,
logging: false,
});
} finally {
await db.query('ROLLBACK');
await db.close();
}
});
await db.query('BEGIN EXCLUSIVE');
try {
const running = f.run();
await waitFor(() => running.messages.some((message) => message.childPid));
const pid = running.messages.find((message) => message.childPid).childPid;
// Allow the real initializer to enter the database operation before losing IPC.
await new Promise((resolve) => setTimeout(resolve, 1000));
running.child.kill('SIGKILL');
await running.done;
await waitFor(() => {
try {
process.kill(pid, 0);
return false;
} catch (error) {
if (error.code === 'ESRCH') return true;
throw error;
}
});
} finally {
await db.query('ROLLBACK');
await db.close();
}
},
);
test('application waits for isolated initialization and does not fork workers after a failure', async () => {
const file = path.resolve('back/app.ts');
const source = fs.readFileSync(file, 'utf8');
const compiled = ts.transpileModule(source.slice(0, source.indexOf('\nconst app = new Application();')) + '\nmodule.exports = Application;', {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020, esModuleInterop: true },
}).outputText;
const compiled = ts.transpileModule(
source.slice(0, source.indexOf('\nconst app = new Application();')) +
'\nmodule.exports = Application;',
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2020,
esModuleInterop: true,
},
},
).outputText;
for (const fail of [false, true]) {
let complete;
const pending = new Promise((resolve, reject) => { complete = () => fail ? reject(new Error('migration failed')) : resolve(); });
const exits = [], calls = [];
const pending = new Promise((resolve, reject) => {
complete = () =>
fail ? reject(new Error('migration failed')) : resolve();
});
const exits = [],
calls = [];
const localRequire = createRequire(file);
const mocks = {
cluster: { isPrimary: true },
'./config': {},
'./loaders/logger': { error() {} },
'./shared/startupProcess': { runStartupProcess: entry => { assert.equal(entry, initializer); return pending; } },
'./shared/startupProcess': {
runStartupProcess: (entry) => {
assert.equal(entry, initializer);
return pending;
},
},
};
const req = Object.assign(name => {
calls.push(name);
return Object.hasOwn(mocks, name) ? mocks[name] : localRequire(name);
}, { resolve: localRequire.resolve });
const req = Object.assign(
(name) => {
calls.push(name);
return Object.hasOwn(mocks, name) ? mocks[name] : localRequire(name);
},
{ resolve: localRequire.resolve },
);
const module = { exports: {} };
new Function('require', 'module', 'exports', 'process', compiled)(req, module, module.exports, { exit: code => exits.push(code) });
new Function('require', 'module', 'exports', 'process', compiled)(
req,
module,
module.exports,
{ exit: (code) => exits.push(code) },
);
const app = new module.exports();
let started = false;
app.startMasterProcess = () => { started = true; };
app.startMasterProcess = () => {
started = true;
};
const start = app.start();
await new Promise(resolve => setImmediate(resolve));
await new Promise((resolve) => setImmediate(resolve));
assert.equal(started, false);
complete();
await start;
+70 -18
View File
@@ -10,9 +10,15 @@ test('development launcher preserves cluster loading, decorator metadata and sou
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-dev-start-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.mkdirSync(path.join(root, 'back'));
fs.symlinkSync(path.resolve('node_modules'), path.join(root, 'node_modules'), 'dir');
fs.symlinkSync(
path.resolve('node_modules'),
path.join(root, 'node_modules'),
'dir',
);
fs.copyFileSync('back/tsconfig.json', path.join(root, 'back/tsconfig.json'));
fs.writeFileSync(path.join(root, 'back/app.ts'), `
fs.writeFileSync(
path.join(root, 'back/app.ts'),
`
import 'reflect-metadata';
import cluster from 'node:cluster';
class Dependency {}
@@ -29,18 +35,24 @@ test('development launcher preserves cluster loading, decorator metadata and sou
stack: new Error('source location').stack }));
process.disconnect!();
}
`);
`,
);
const config = JSON.parse(fs.readFileSync('nodemon.json', 'utf8'));
const [command, ...args] = config.execMap.ts.split(' ');
assert.equal(command, 'node');
const env = { ...process.env, ...config.env };
delete env.NODE_OPTIONS;
const result = spawnSync(process.execPath, [...args, 'back/app.ts'], {
cwd: root, env, encoding: 'utf8', timeout: 20000,
cwd: root,
env,
encoding: 'utf8',
timeout: 20000,
});
assert.ifError(result.error);
assert.equal(result.status, 0, result.stdout + result.stderr);
const output = JSON.parse(result.stdout.split('FIXTURE_RESULT=')[1].split('\n')[0]);
const output = JSON.parse(
result.stdout.split('FIXTURE_RESULT=')[1].split('\n')[0],
);
assert.equal(output.value, 42);
assert.equal(output.metadata, true);
assert.match(output.stack, /back[/\\]app\.ts:\d+:\d+/);
@@ -67,16 +79,41 @@ test('startup timing preserves results and failures with timing enabled or disab
const value = {};
const failure = new Error('startup failed');
let calls = 0;
assert.equal(await startupStage('success', async () => { calls++; return value; }), value);
await assert.rejects(startupStage('failure', async () => { calls++; throw failure; }),
(error) => error === failure);
await assert.rejects(startupStage('sync-failure', () => { calls++; throw failure; }),
(error) => error === failure);
assert.equal(
await startupStage('success', async () => {
calls++;
return value;
}),
value,
);
await assert.rejects(
startupStage('failure', async () => {
calls++;
throw failure;
}),
(error) => error === failure,
);
await assert.rejects(
startupStage('sync-failure', () => {
calls++;
throw failure;
}),
(error) => error === failure,
);
assert.equal(calls, 3);
assert.equal(logs.length, enabled === '1' ? 3 : 0);
if (enabled === '1') {
for (const [index, stage] of ['success', 'failure', 'sync-failure'].entries()) {
assert.match(logs[index], new RegExp('^\\[boot:timing\\] grpc:' + stage + ' \\d+ms \\(PID: \\d+\\)$'));
for (const [index, stage] of [
'success',
'failure',
'sync-failure',
].entries()) {
assert.match(
logs[index],
new RegExp(
'^\\[boot:timing\\] grpc:' + stage + ' \\d+ms \\(PID: \\d+\\)$',
),
);
}
}
}
@@ -84,18 +121,33 @@ test('startup timing preserves results and failures with timing enabled or disab
test('frontend gzip assets are enabled for production only', () => {
const source = ts.transpileModule(fs.readFileSync('.umirc.ts', 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2020,
},
}).outputText;
for (const mode of ['development', 'production']) {
const module = { exports: {} };
class Compression { constructor(options) { this.options = options; } }
class Compression {
constructor(options) {
this.options = options;
}
}
new Function('require', 'module', 'exports', 'process', source)(
(name) => name === '@umijs/max' ? { defineConfig: (config) => config } : Compression,
module, module.exports, { env: { NODE_ENV: mode } },
(name) =>
name === '@umijs/max'
? { defineConfig: (config) => config }
: Compression,
module,
module.exports,
{ env: { NODE_ENV: mode } },
);
const plugins = [];
module.exports.default.chainWebpack({ plugin: (name) => ({ use: (plugin) => plugins.push({ name, plugin }) }) });
module.exports.default.chainWebpack({
plugin: (name) => ({ use: (plugin) => plugins.push({ name, plugin }) }),
});
assert.equal(plugins.length, mode === 'production' ? 1 : 0);
if (mode === 'production') assert.equal(plugins[0].plugin.options.algorithm, 'gzip');
if (mode === 'production')
assert.equal(plugins[0].plugin.options.algorithm, 'gzip');
}
});
+104 -32
View File
@@ -3,51 +3,110 @@ 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');
const {
checkDirectoryVersions,
readDirectoryPage,
} = require('../../back/shared/directoryPage');
test('directory cursors survive inserts and deletes and search reaches unloaded folders', async t => {
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);
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');
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 });
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 => {
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);
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']);
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 => {
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);
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']);
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'));
@@ -55,11 +114,14 @@ test('a delayed terminal page detects changes on either side of its cursor, incl
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.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 => {
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');
@@ -75,5 +137,15 @@ test('deleting and replacing the open directory invalidates its pages and a miss
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);
assert.equal(
await checkDirectoryVersions(
root,
[],
[
['external', null],
['../escape', null],
],
),
false,
);
});
+14 -10
View File
@@ -104,11 +104,13 @@ test('script creation supports root and nested parents in both writable director
for (const root of [config.scriptPath, config.configPath]) {
for (const filename of ['ordinary.js', 'nested/deeper/script.js']) {
assert.equal(
(await invoke('post', '/', {
path: root,
filename,
content: 'safe',
})).code,
(
await invoke('post', '/', {
path: root,
filename,
content: 'safe',
})
).code,
200,
);
assert.equal(fs.readFileSync(path.join(root, filename), 'utf8'), 'safe');
@@ -124,11 +126,13 @@ test('script parent creation rejects sibling prefixes and external symlinks', as
fs.symlinkSync(outside, path.join(config.scriptPath, 'escape'));
for (const parent of [sibling, path.join(config.scriptPath, 'escape')]) {
assert.equal(
(await invoke('post', '/', {
path: parent,
filename: 'nested/poc.js',
content: 'blocked',
})).code,
(
await invoke('post', '/', {
path: parent,
filename: 'nested/poc.js',
content: 'blocked',
})
).code,
403,
);
}
+6 -6
View File
@@ -19,11 +19,11 @@ test(
async () => {
let releases = 0;
let active = 0;
const { runCron } = load(path.resolve('back/shared/runCron.ts'), {
const { runCron } = load(path.resolve('back/cron/execution/runCron.ts'), {
'cross-spawn': {
spawn: () => spawn('true', { shell: '/nonexistent-ql-test-shell' }),
},
'./pLimit': {
'./cronLimit': {
runWithCronLimit: async (_cron, fn) => {
active++;
try {
@@ -34,16 +34,16 @@ test(
},
removeQueuedCron: () => releases++,
},
'../loaders/logger': logger,
'../data/cron': {
'../../loaders/logger': logger,
'../../data/cron': {
CrontabModel: { findOne: async () => ({ isDisabled: 0 }) },
CrontabStatus: {},
},
'../data/runningInstance': {
'../../data/runningInstance': {
RunningInstanceModel: {},
InstanceStatus: {},
},
'../config/util': { killTask: async () => {} },
'../../config/util': { killTask: async () => {} },
});
await runCron('true', { id: '1' });
await runCron('true', { id: '2' });
+46 -23
View File
@@ -3,29 +3,52 @@ const assert = require('node:assert/strict');
const express = require('express');
const load = require('../helpers/load-security-module.cjs');
const Http = load('back/services/http.ts', {
'../config': {bindHost: '127.0.0.1'},
'../loaders/logger': {debug(){},warn(){},error(){}},
'./metrics': {metricsService: {record(){}}},
typedi: {Service:()=>x=>x},
'../config': { bindHost: '127.0.0.1' },
'../loaders/logger': { debug() {}, warn() {}, error() {} },
'./metrics': { metricsService: { record() {} } },
typedi: { Service: () => (x) => x },
}).HttpServerService;
test('HTTP listener preserves private binding and releases its port after shutdown',async(t)=>{
const app=express();app.get('/',(_q,r)=>r.send('ok'));
const first=new Http();const server=await first.initialize(app,0);
t.after(()=>first.shutdown());
assert.equal(server.address().address,'127.0.0.1');
const port=server.address().port;
const response=await fetch(`http://127.0.0.1:${port}/`,{headers:{connection:'close'}});assert.equal(await response.text(),'ok');
await assert.rejects(new Http().initialize(app,port),e=>e.code==='EADDRINUSE');
await first.shutdown();const replacement=new Http();t.after(()=>replacement.shutdown());
const next=await replacement.initialize(app,port);assert.equal(next.address().port,port);
test('HTTP listener preserves private binding and releases its port after shutdown', async (t) => {
const app = express();
app.get('/', (_q, r) => r.send('ok'));
const first = new Http();
const server = await first.initialize(app, 0);
t.after(() => first.shutdown());
assert.equal(server.address().address, '127.0.0.1');
const port = server.address().port;
const response = await fetch(`http://127.0.0.1:${port}/`, {
headers: { connection: 'close' },
});
assert.equal(await response.text(), 'ok');
await assert.rejects(
new Http().initialize(app, port),
(e) => e.code === 'EADDRINUSE',
);
await first.shutdown();
const replacement = new Http();
t.after(() => replacement.shutdown());
const next = await replacement.initialize(app, port);
assert.equal(next.address().port, port);
});
test('custom cluster deployments can restore shared listening',async(t)=>{
const previous=process.env.QL_HTTP_SHARED_LISTEN;
t.after(()=>{if(previous===undefined)delete process.env.QL_HTTP_SHARED_LISTEN;else process.env.QL_HTTP_SHARED_LISTEN=previous;});
for(const value of [undefined,'true']){
if(value===undefined)delete process.env.QL_HTTP_SHARED_LISTEN;else process.env.QL_HTTP_SHARED_LISTEN=value;
let options;const service=new Http();const app=express();const listen=app.listen.bind(app);
app.listen=(opts,cb)=>{options=opts;return listen(opts,cb);};
await service.initialize(app,0);assert.equal(options.exclusive,value!=='true');await service.shutdown();
}
test('custom cluster deployments can restore shared listening', async (t) => {
const previous = process.env.QL_HTTP_SHARED_LISTEN;
t.after(() => {
if (previous === undefined) delete process.env.QL_HTTP_SHARED_LISTEN;
else process.env.QL_HTTP_SHARED_LISTEN = previous;
});
for (const value of [undefined, 'true']) {
if (value === undefined) delete process.env.QL_HTTP_SHARED_LISTEN;
else process.env.QL_HTTP_SHARED_LISTEN = value;
let options;
const service = new Http();
const app = express();
const listen = app.listen.bind(app);
app.listen = (opts, cb) => {
options = opts;
return listen(opts, cb);
};
await service.initialize(app, 0);
assert.equal(options.exclusive, value !== 'true');
await service.shutdown();
}
});
+113 -51
View File
@@ -55,7 +55,9 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
},
{
scopes: ['configs:read'],
tokens: [{ value: 'config-read-app', expiration: Date.now() / 1000 + 3600 }],
tokens: [
{ value: 'config-read-app', expiration: Date.now() / 1000 + 3600 },
],
},
{
scopes: ['configs', 'scripts'],
@@ -69,7 +71,9 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
},
{
scopes: ['scripts:read'],
tokens: [{ value: 'script-read-app', expiration: Date.now() / 1000 + 3600 }],
tokens: [
{ value: 'script-read-app', expiration: Date.now() / 1000 + 3600 },
],
},
{
scopes: ['envs'],
@@ -87,17 +91,27 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
{
name: 'system',
scopes: ['system'],
tokens: [{ value: 'internal-system', expiration: Date.now() / 1000 + 3600 }],
tokens: [
{ value: 'internal-system', expiration: Date.now() / 1000 + 3600 },
],
},
];
for (const scope of ['crons', 'subscriptions', 'dependencies', 'logs', 'dashboard']) {
for (const scope of [
'crons',
'subscriptions',
'dependencies',
'logs',
'dashboard',
]) {
for (const suffix of ['', ':read']) {
apps.push({
scopes: [`${scope}${suffix}`],
tokens: [{
value: `${scope}${suffix}-app`,
expiration: Date.now() / 1000 + 3600,
}],
tokens: [
{
value: `${scope}${suffix}-app`,
expiration: Date.now() / 1000 + 3600,
},
],
});
}
}
@@ -111,7 +125,10 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
const User = class {};
const Script = class {
getFile(folder, filename) {
return fs.promises.readFile(path.join(config.scriptPath, folder, filename), 'utf8');
return fs.promises.readFile(
path.join(config.scriptPath, folder, filename),
'utf8',
);
}
checkFilePath(folder, filename) {
return path.join(config.scriptPath, folder || '', filename);
@@ -167,7 +184,13 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
...mocks.typedi,
Container: {
get: (x) =>
x === User ? user : x === History ? history : x === Script ? script : configService,
x === User
? user
: x === History
? history
: x === Script
? script
: configService,
},
};
mocks['../api'] = () => {
@@ -187,7 +210,11 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
res.json({ code: 200 });
});
for (const route of [
'/crons', '/subscriptions', '/dependencies', '/logs', '/dashboard/overview',
'/crons',
'/subscriptions',
'/dependencies',
'/logs',
'/dashboard/overview',
]) {
router.get(route, (_req, res) => res.json({ code: 200 }));
}
@@ -344,17 +371,21 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
assert.equal((await request('/open/envs', 'env-read-app')).body.code, 200);
for (const prefix of ['/open', '/panel/open']) {
assert.equal(
(await request(`${prefix}/envs`, 'env-read-app', 'POST', [
{ name: 'SAFE_VALUE', value: 'kept' },
])).status,
(
await request(`${prefix}/envs`, 'env-read-app', 'POST', [
{ name: 'SAFE_VALUE', value: 'kept' },
])
).status,
401,
);
}
assert.equal(envWriteCalls, 0);
assert.equal(
(await request('/open/envs', 'env-app', 'POST', [
{ name: 'SAFE_VALUE', value: 'kept' },
])).body.code,
(
await request('/open/envs', 'env-app', 'POST', [
{ name: 'SAFE_VALUE', value: 'kept' },
])
).body.code,
200,
);
assert.equal(envWriteCalls, 1);
@@ -388,8 +419,8 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
401,
);
assert.equal(
(await request(`${prefix}/logs/download`, 'logs:read-app', 'POST'))
.body.data,
(await request(`${prefix}/logs/download`, 'logs:read-app', 'POST')).body
.data,
'downloaded',
);
for (const [namespace, ownToken, otherToken] of [
@@ -398,8 +429,14 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
]) {
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);
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(
@@ -429,47 +466,61 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
for (const prefix of ['/open', '/panel/open']) {
for (const name of ['normal.txt', 'config.sh', 'task_before.sh']) {
assert.equal(
(await request(`${prefix}/configs/save`, 'config-read-app', 'POST', {
name,
content: 'untrusted',
})).status,
(
await request(`${prefix}/configs/save`, 'config-read-app', 'POST', {
name,
content: 'untrusted',
})
).status,
401,
);
}
}
assert.equal(fs.readFileSync(path.join(tmp, 'config/config.sh'), 'utf8'), 'original');
assert.equal(
fs.readFileSync(path.join(tmp, 'config/config.sh'), 'utf8'),
'original',
);
assert.equal((await request('/open/system', 'system-app')).body.code, 200);
assert.equal(
(await request('/open/system/notify', 'system-app', 'PUT', {
title: 'title',
content: 'content',
})).body.code,
(
await request('/open/system/notify', 'system-app', 'PUT', {
title: 'title',
content: 'content',
})
).body.code,
200,
);
for (const prefix of ['/open', '/panel/open']) {
assert.equal(
(await request(`${prefix}/system/auth/reset`, 'system-app', 'PUT', {
password: 'changed',
})).status,
(
await request(`${prefix}/system/auth/reset`, 'system-app', 'PUT', {
password: 'changed',
})
).status,
401,
);
assert.equal(
(await request(`${prefix}/system/command-run`, 'system-app', 'PUT', {
command: 'id',
})).status,
(
await request(`${prefix}/system/command-run`, 'system-app', 'PUT', {
command: 'id',
})
).status,
401,
);
}
assert.equal(resetCalls, 0);
assert.equal(commandCalls, 0);
assert.equal(
(await request('/open/system/auth/reset', 'internal-system', 'PUT', {
retries: 0,
})).body.code,
(
await request('/open/system/auth/reset', 'internal-system', 'PUT', {
retries: 0,
})
).body.code,
200,
);
assert.equal(
(await request('/api/system/auth/reset', valid, 'PUT', { retries: 0 })).body.code,
(await request('/api/system/auth/reset', valid, 'PUT', { retries: 0 })).body
.code,
200,
);
assert.equal(resetCalls, 2);
@@ -539,13 +590,18 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
200,
);
assert.equal(
(await request('/api/configs/save', valid, 'POST', {
name: 'config.sh',
content: 'owner config',
})).body.code,
(
await request('/api/configs/save', valid, 'POST', {
name: 'config.sh',
content: 'owner config',
})
).body.code,
200,
);
assert.equal(fs.readFileSync(path.join(tmp, 'config/config.sh'), 'utf8'), 'owner config');
assert.equal(
fs.readFileSync(path.join(tmp, 'config/config.sh'), 'utf8'),
'owner config',
);
assert.equal(
(
await request('/api/configs/save', valid, 'POST', {
@@ -608,17 +664,23 @@ test('HTTP authentication protects init, scopes, expired sessions and config sec
assert.equal(await downloaded.text(), 'authorized script');
for (const method of ['PUT', 'DELETE']) {
assert.equal(
(await request('/open/scripts', 'script-read-app', method, {
filename: 'test.js', content: 'unauthorized',
})).status,
(
await request('/open/scripts', 'script-read-app', method, {
filename: 'test.js',
content: 'unauthorized',
})
).status,
401,
);
}
for (const path of ['run', 'stop', 'rename', 'history/restore']) {
assert.equal(
(await request(`/open/scripts/${path}`, 'script-read-app', 'PUT', {
filename: 'test.js', content: 'unauthorized',
})).status,
(
await request(`/open/scripts/${path}`, 'script-read-app', 'PUT', {
filename: 'test.js',
content: 'unauthorized',
})
).status,
401,
);
}
+288
View File
@@ -0,0 +1,288 @@
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 { randomUUID } = require('node:crypto');
const { QueryTypes } = require('sequelize');
const load = require('../helpers/load-security-module.cjs');
const { installTriggerHistory } = require('../../back/cron/history');
const {
TriggerLifecycle,
} = require('../../back/cron/execution/triggerLifecycle');
const {
TriggerSettlement,
} = require('../../back/cron/settlement/triggerSettlement');
async function fixture(t) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-legacy-adapter-'));
const db = load('back/data/index.ts', {
'../config/index': { dbPath: root },
}).sequelize;
const { CrontabModel } = load('back/data/cron.ts', {
'.': { sequelize: db },
});
const { RunningInstanceModel } = load('back/data/runningInstance.ts', {
'.': { sequelize: db },
});
load('back/data/cronStats.ts', { '.': { sequelize: db } });
for (const key of ['QL_DIR', 'QL_DATA_DIR']) {
const previous = process.env[key];
process.env[key] = root;
t.after(() => {
if (previous === undefined) delete process.env[key];
else process.env[key] = previous;
});
}
t.after(async () => {
await db.close();
await fs.rm(root, { recursive: true, force: true });
});
await db.sync();
await db.transaction((tx) => installTriggerHistory(db, tx));
const task = await CrontabModel.create({ id: 1, command: 'true', status: 1 });
let lifecycle;
const settlement = new TriggerSettlement(db, {
finish: (...args) => lifecycle.finish(...args),
shouldStop: (...args) => lifecycle.shouldStop(...args),
});
lifecycle = new TriggerLifecycle(db, settlement);
const { LegacyClientAdapter } = load(
'back/cron/compatibility/legacyClient.ts',
{
'../execution/cronProcess': {
systemOwner: (pid) => 'fixture:' + pid,
legacyProcessOwner: (pid) => 'fixture:' + pid,
isProcessDescendant: () => false,
},
},
);
const adapter = new LegacyClientAdapter(db, lifecycle, settlement);
const rows = () =>
db.query('SELECT * FROM CronTriggers ORDER BY started_at,id', {
type: QueryTypes.SELECT,
});
const stats = () =>
db.query(
'SELECT run_count,success_count,fail_count,total_time FROM CrontabStats',
{ type: QueryTypes.SELECT },
);
const seconds = Math.floor(Date.now() / 1000) - 30;
return {
db,
adapter,
lifecycle,
task,
instances: RunningInstanceModel,
rows,
stats,
seconds,
};
}
test('identified Shell admission and settlement roll back with the caller transaction', async (t) => {
const { db, adapter, rows, stats, seconds } = await fixture(t);
const id = 'client-' + randomUUID();
await assert.rejects(
db.transaction(async (tx) => {
await adapter.shellReport(
id,
1,
false,
true,
'client.log',
seconds,
undefined,
false,
tx,
);
await adapter.shellReport(
id,
1,
false,
false,
'client.log',
seconds,
17,
false,
tx,
2000,
(seconds + 2) * 1000,
);
const [row] = await db.query('SELECT state,counted FROM CronTriggers', {
transaction: tx,
type: QueryTypes.SELECT,
});
assert.deepEqual(row, { state: 'failed', counted: 1 });
throw Error('caller rollback');
}),
/caller rollback/,
);
assert.deepEqual(await rows(), []);
assert.deepEqual(await stats(), []);
});
test('PID-only retries leave unknown exits uncounted and cannot overwrite the replacement execution', async (t) => {
const { adapter, task, rows, stats, instances, seconds } = await fixture(t);
const old = (running, code) =>
adapter.reportLegacy(1, running, 123, 'same.log', seconds, 2, code);
await Promise.all([old(true), old(true)]);
await old(false);
await old(true);
assert.deepEqual(
(await rows()).map((r) => [r.state, r.exit_code, r.counted]),
[['unknown', null, 0]],
);
assert.deepEqual(await stats(), []);
await adapter.reportLegacy(1, true, 123, 'same.log', seconds + 10, 0);
const replacement = (await task.reload()).last_instance_id;
await Promise.all([old(false, 17), old(false, 17)]);
await old(false, 0);
await old(true);
assert.deepEqual(
(await rows()).map((r) => [r.state, r.exit_code, r.counted]),
[
['failed', 17, 1],
['running', null, 0],
],
);
assert.deepEqual(await stats(), [
{ run_count: 1, success_count: 0, fail_count: 1, total_time: 2000 },
]);
assert.equal((await task.reload()).last_instance_id, replacement);
assert.equal(task.last_execution_time, seconds + 10);
assert.equal((await instances.findByPk(replacement)).status, 0);
});
test('failed legacy accounting rolls back the receipt and instance before retrying once', async (t) => {
const { db, adapter, task, rows, stats, instances, seconds } = await fixture(
t,
);
await adapter.reportLegacy(1, true, 123, 'legacy.log', seconds, 0);
await db.query(
"CREATE TRIGGER reject_legacy_stat BEFORE INSERT ON CrontabStats BEGIN SELECT RAISE(ABORT,'blocked accounting'); END",
);
await assert.rejects(
adapter.reportLegacy(1, false, 123, 'legacy.log', seconds, 2, 17),
(error) => {
assert.match(error.original.message, /blocked accounting/);
return true;
},
);
assert.deepEqual(
(await rows()).map((r) => [r.state, r.counted]),
[['running', 0]],
);
assert.equal((await instances.findOne()).status, 0);
assert.equal((await task.reload()).status, 0);
assert.deepEqual(await stats(), []);
await db.query('DROP TRIGGER reject_legacy_stat');
await adapter.reportLegacy(1, false, 123, 'legacy.log', seconds, 2, 17);
await adapter.reportLegacy(1, false, 123, 'legacy.log', seconds, 2, 17);
assert.deepEqual(await stats(), [
{ run_count: 1, success_count: 0, fail_count: 1, total_time: 2000 },
]);
assert.equal((await instances.findOne()).status, 3);
});
test('an exit before its identified start stays unknown until a statistics receipt resolves it once', async (t) => {
const { adapter, task, rows, stats, instances, seconds } = await fixture(t);
const id = 'client-' + randomUUID();
await adapter.reportInstance(id, 1, false, 123, 'early.log', seconds, 2);
await adapter.reportInstance(id, 1, true, 123, 'early.log', seconds, 0);
assert.deepEqual(
(await rows()).map((r) => [r.state, r.counted]),
[['unknown', 0]],
);
assert.equal((await instances.findOne()).status, 4);
assert.equal((await task.reload()).status, 1);
assert.deepEqual(await stats(), []);
await adapter.recordShellResult(id, 1, 17, 2000, Date.now());
await adapter.recordShellResult(id, 1, 0, 2000, Date.now());
await adapter.reportInstance(id, 1, true, 123, 'early.log', seconds, 0);
assert.deepEqual(
(await rows()).map((r) => [r.state, r.exit_code, r.counted]),
[['failed', 17, 1]],
);
assert.equal(await instances.count(), 1);
assert.equal((await instances.findOne()).status, 3);
assert.deepEqual(await stats(), [
{ run_count: 1, success_count: 0, fail_count: 1, total_time: 2000 },
]);
});
test('successful wrapper reports cannot settle a managed command with an unknown result', async (t) => {
const { adapter, lifecycle, rows, stats, seconds } = await fixture(t);
await lifecycle.enqueue('managed', 1, 'manual', null, seconds * 1000);
await lifecycle.start('managed', seconds * 1000);
await lifecycle.finish('managed', 'unknown', 'restart');
await adapter.reportInstance(
'managed',
1,
false,
123,
'wrapper.log',
seconds,
2,
0,
);
await adapter.recordShellResult('managed', 1, 0, 2000, Date.now());
assert.deepEqual(
(await rows()).map((r) => [r.state, r.exit_code, r.counted]),
[['unknown', null, 0]],
);
assert.deepEqual(await stats(), []);
});
test('upgrade adoption preserves prior accounting and pending stops across repeated reconciliation', async (t) => {
const { db, adapter, lifecycle, task, rows, stats, instances, seconds } =
await fixture(t);
const old = await instances.create({
cron_id: 1,
pid: 111,
status: 1,
started_at: seconds,
finished_at: seconds + 2,
exit_code: 0,
log_path: 'old.log',
});
const live = await instances.create({
cron_id: 1,
pid: 222,
status: 0,
started_at: seconds,
log_path: 'live.log',
});
const stopping = await instances.create({
cron_id: 1,
pid: 333,
status: 0,
started_at: seconds,
log_path: 'stopping.log',
});
await task.update({ status: 0, pid: 222, log_path: 'live.log' });
await db.models.CrontabStat.create({
ref_id: 1,
date: '2026-01-01',
run_count: 1,
success_count: 1,
fail_count: 0,
total_time: 2000,
});
await lifecycle.queueInstanceStop(stopping.id, 1, 333);
await adapter.reconcileInstances();
await adapter.reconcileInstances();
const linked = await rows();
assert.equal(linked.length, 2);
assert.deepEqual(
linked.find((r) => r.instance_id === old.id).state,
'finished',
);
assert.equal(linked.find((r) => r.instance_id === old.id).counted, 1);
assert.equal(linked.find((r) => r.instance_id === live.id).state, 'running');
assert.equal((await stopping.reload()).status, 0);
assert.ok(await lifecycle.pendingStop(stopping.id));
assert.deepEqual(await stats(), [
{ run_count: 1, success_count: 1, fail_count: 0, total_time: 2000 },
]);
});
+20 -8
View File
@@ -2,7 +2,9 @@ const test = require('node:test');
const assert = require('node:assert/strict');
const { format } = require('node:util');
const load = require('../helpers/load-security-module.cjs');
const { SchedulerReadiness } = require('../../back/shared/schedulerReadiness');
const {
SchedulerReadiness,
} = require('../../back/cron/scheduling/schedulerReadiness');
const { getTasks } = require('node-cron');
@@ -24,7 +26,12 @@ test('API accepts legacy question-mark schedules but rejects malformed cron', ()
for (const schedule of [...legacySchedules, '@once', '@boot']) {
assert.equal(scheduleSchema.validate(schedule).error, undefined, schedule);
}
for (const schedule of ['@bogus', '0 /5 * * * ?', '0 70 * * * ?', 'not a cron']) {
for (const schedule of [
'@bogus',
'0 /5 * * * ?',
'0 70 * * * ?',
'not a cron',
]) {
assert.ok(scheduleSchema.validate(schedule).error, schedule);
}
});
@@ -36,18 +43,23 @@ test('legacy main and extra schedules restore real jobs and healthy readiness',
});
const { addCron } = load('back/schedule/addCron.ts', {
'./data': { scheduleStacks: stacks },
'../shared/runCron': { runCron() {} },
'../cron/execution/runCron': { runCron() {} },
'../loaders/logger': { info() {}, warn() {} },
'../shared/i18n': { t: (s) => s, tf: format },
});
const crons = legacySchedules.map((schedule, index) => ({
id: `legacy-${index}`, name: 'legacy', schedule, command: 'true',
id: `legacy-${index}`,
name: 'legacy',
schedule,
command: 'true',
extra_schedules: [{ schedule: '0 0/30 * * * ?' }],
}));
const register = (rows) => new Promise((resolve, reject) => {
addCron({ request: { replace: true, crons: rows } }, (error) =>
error ? reject(error) : resolve());
});
const register = (rows) =>
new Promise((resolve, reject) => {
addCron({ request: { replace: true, crons: rows } }, (error) =>
error ? reject(error) : resolve(),
);
});
const readiness = new SchedulerReadiness(async () => {}, 60000);
t.after(() => clearTimeout(readiness.retry));
readiness.configure(() => register(crons));
+46 -10
View File
@@ -13,16 +13,31 @@ const util = load('back/config/util.ts', {
});
for (const specifier of [
'tree', ' tree=2.3.2-r0 ', 'tree>=2.3', 'tree<=2.3', 'tree~2.3',
'tree>2', 'tree<3', 'tree@testing', 'tree@testing=2.3.2-r0',
'tree',
' tree=2.3.2-r0 ',
'tree>=2.3',
'tree<=2.3',
'tree~2.3',
'tree>2',
'tree<3',
'tree@testing',
'tree@testing=2.3.2-r0',
]) {
test(`apk uninstall removes the constraint from ${specifier}`, () => {
assert.equal(util.getUninstallCommand(2, specifier, 'Alpine'), 'apk del -- tree');
assert.equal(
util.getUninstallCommand(2, specifier, 'Alpine'),
'apk del -- tree',
);
});
}
for (const osType of ['Debian', 'Ubuntu']) {
for (const specifier of ['tree', 'tree=2.1.0-1', 'tree:amd64=1:2.1.0-1+b1', 'tree/stable']) {
for (const specifier of [
'tree',
'tree=2.1.0-1',
'tree:amd64=1:2.1.0-1+b1',
'tree/stable',
]) {
test(`${osType} uninstall preserves ${specifier}, including sudo selection`, (t) => {
const original = process.env.QL_CONTAINER;
t.after(() => {
@@ -31,8 +46,12 @@ for (const osType of ['Debian', 'Ubuntu']) {
});
for (const container of ['false', 'true']) {
process.env.QL_CONTAINER = container;
assert.equal(util.getUninstallCommand(2, specifier, osType),
`${container === 'true' ? 'sudo ' : ''}apt-get remove -y ${specifier}`);
assert.equal(
util.getUninstallCommand(2, specifier, osType),
`${
container === 'true' ? 'sudo ' : ''
}apt-get remove -y ${specifier}`,
);
}
});
}
@@ -57,9 +76,19 @@ for (const osType of ['Alpine', 'Debian', 'Ubuntu']) {
if (original === undefined) delete process.env.QL_CONTAINER;
else process.env.QL_CONTAINER = original;
});
const install = `${osType === 'Alpine' ? 'apk add --no-check-certificate' : 'apt-get install -y'} ${specifier}`;
const uninstall = osType === 'Alpine' ? 'apk del -- tree' : `apt-get remove -y ${specifier}`;
const spawned = [], lookedUp = [], killed = [], removed = [];
const install = `${
osType === 'Alpine'
? 'apk add --no-check-certificate'
: 'apt-get install -y'
} ${specifier}`;
const uninstall =
osType === 'Alpine'
? 'apk del -- tree'
: `apt-get remove -y ${specifier}`;
const spawned = [],
lookedUp = [],
killed = [],
removed = [];
const dep = { id: 1, name: specifier, type: 2, status: 1, log: [] };
const Service = load('back/services/dependence.ts', {
'../config': {},
@@ -76,7 +105,14 @@ for (const osType of ['Alpine', 'Debian', 'Ubuntu']) {
'../data/dependence': {
Dependence: class {},
DependenceTypes: types,
DependenceStatus: { installed: 1, installing: 0, removing: 3, removed: 4, removeFailed: 5, cancelled: 7 },
DependenceStatus: {
installed: 1,
installing: 0,
removing: 3,
removed: 4,
removeFailed: 5,
cancelled: 7,
},
versionDependenceCommandTypes: { 0: '@', 1: '==', 2: '=' },
DependenceModel: {
findAll: async () => [dep],
+3 -3
View File
@@ -27,7 +27,7 @@ for (const scenario of [
test(`Linux mirror persistence follows the process result: ${scenario.name}`, async () => {
const logger = { info() {}, error() {} };
const ScheduleService = load('back/services/schedule.ts', {
'../shared/cronScheduler': {},
'../cron/scheduling/cronScheduler': {},
'../shared/pLimit': { runWithSystemLimit: async (_params, fn) => fn() },
'cross-spawn': {
spawn: () =>
@@ -53,9 +53,9 @@ for (const scenario of [
'../data/notify': {},
'../data/system': {},
'../schedule/client': {},
'../shared/pLimit': {},
'../cron/execution/cronLimit': {},
'../shared/i18n': {},
'../shared/schedulerMutationLock': {},
'../cron/scheduling/schedulerMutationLock': {},
'./notify': class {},
'./schedule': ScheduleService,
'./sock': class {},
+65 -19
View File
@@ -66,6 +66,11 @@ test('log initialization rejects unsafe paths before mkdir or file writes', asyn
'./share': {},
'../loaders/logger': {},
'../shared/utils': {
fileExist: (file) =>
fs.access(file).then(
() => true,
() => false,
),
writeFileWithLock: (file, data) => fs.writeFile(file, data),
},
'../data/dependence': { DependenceTypes: {} },
@@ -103,7 +108,7 @@ test('manual execution rejects escaping log names before creating directories or
'../config/util': {},
'../config/const': {},
'../schedule/client': {},
'../shared/pLimit': {
'../cron/execution/cronLimit': {
manualRunWithCronLimit: async (fn) => {
try {
return await fn();
@@ -157,48 +162,89 @@ test('manual execution rejects escaping log names before creating directories or
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 => {
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');
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': {},
'../config': { logPath: logs },
'../config/util': {},
'../data/cron': {},
'../data/runningInstance': {},
'../schedule/client': {},
'../cron/execution/cronLimit': {},
'../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 });
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.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 => {
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': {},
'../config': { logPath: root },
'../config/util': { fileExist: async (p) => (await fs.stat(p)).isFile() },
'../data/cron': { CrontabStatus: { running: 0, queued: 3 } },
'../data/runningInstance': {},
'../schedule/client': {},
'../cron/execution/cronLimit': {},
'../shared/logStreamManager': {},
'../loaders/logger': {},
}).default;
const service = new Service({});
service.getDb = async () => ({status: 0, log_path: 'current.log'});
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});
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});
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 });
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 });
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' });
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);
+7 -3
View File
@@ -57,7 +57,10 @@ test('log reader preserves UTF-8 characters across byte boundaries', async (t) =
});
assert.equal(first.content + second.content + third.content, 'aaaaa中文日志');
assert.equal((first.content + second.content + third.content).includes('�'), false);
assert.equal(
(first.content + second.content + third.content).includes('�'),
false,
);
});
test('missing logs return an empty chunk', async () => {
@@ -71,14 +74,15 @@ test('missing logs return an empty chunk', async () => {
});
});
test('following a file distinguishes append, same-inode rewrites, and replacement', async t => {
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 });
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);
+1 -1
View File
@@ -36,7 +36,7 @@ test(
'../config/util': { getUniqPath: async () => 'task' },
'../config/const': { TASK_PREFIX: 'task ', QL_PREFIX: 'ql ' },
'../schedule/client': {},
'../shared/pLimit': {
'../cron/execution/cronLimit': {
manualRunWithCronLimit: async (fn) => {
active++;
try {
+67 -40
View File
@@ -9,53 +9,80 @@ const { once } = require('node:events');
async function waitFor(read, predicate) {
const deadline = Date.now() + 10000;
while (Date.now() < deadline) {
const value = await read().catch(error => {
const value = await read().catch((error) => {
if (error.code !== 'ENOENT') throw error;
});
if (predicate(value)) return value;
await new Promise(resolve => setTimeout(resolve, 20));
await new Promise((resolve) => setTimeout(resolve, 20));
}
throw Error('Timed out waiting for command evidence');
}
for (const crash of [false, true]) {
test(`manual compound command keeps complete, nonduplicated logs (worker crash=${crash})`, { timeout: 20000 }, async t => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-log-survival-'));
const gate = path.join(root, 'continue');
const script = path.join(root, 'command.sh');
await fs.writeFile(script, `#!/bin/bash\necho BEFORE\nwhile [ ! -f '${gate}' ]; do sleep 0.02; done\necho '尾行 AFTER'\necho STDERR >&2\n`);
const command = `bash '${script}'; echo COMPOUND; exit 17`;
const worker = fork(path.resolve('test/helpers/manual-log-worker.cjs'), [root, command], {
execArgv: ['-r', require.resolve('ts-node/register/transpile-only')],
env: { ...process.env, TS_NODE_PROJECT: 'back/tsconfig.json' },
stdio: ['ignore', 'ignore', 'inherit', 'ipc'],
});
let supervisor;
const messages = [];
worker.on('message', value => messages.push(value));
const exited = once(worker, 'exit');
t.after(async () => {
test(
`manual compound command keeps complete, nonduplicated logs (worker crash=${crash})`,
{ timeout: 20000 },
async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-log-survival-'));
const gate = path.join(root, 'continue');
const script = path.join(root, 'command.sh');
await fs.writeFile(
script,
`#!/bin/bash\necho BEFORE\nwhile [ ! -f '${gate}' ]; do sleep 0.02; done\necho '尾行 AFTER'\necho STDERR >&2\n`,
);
const command = `bash '${script}'; echo COMPOUND; exit 17`;
const worker = fork(
path.resolve('test/helpers/manual-log-worker.cjs'),
[root, command],
{
execArgv: ['-r', require.resolve('ts-node/register/transpile-only')],
env: { ...process.env, TS_NODE_PROJECT: 'back/tsconfig.json' },
stdio: ['ignore', 'ignore', 'inherit', 'ipc'],
},
);
let supervisor;
const messages = [];
worker.on('message', (value) => messages.push(value));
const exited = once(worker, 'exit');
t.after(async () => {
await fs.writeFile(gate, 'continue');
worker.kill('SIGKILL');
if (supervisor) {
try {
process.kill(supervisor, 'SIGKILL');
} catch {}
}
await fs.rm(root, { recursive: true, force: true });
});
const launched = await waitFor(
async () => messages.find((x) => x.pid),
Boolean,
);
supervisor = launched.pid;
const log = path.join(root, launched.log);
await waitFor(
() => fs.readFile(log, 'utf8'),
(text) => text?.includes('BEFORE'),
);
if (crash) {
worker.kill('SIGKILL');
await exited;
}
await fs.writeFile(gate, 'continue');
worker.kill('SIGKILL');
if (supervisor) { try { process.kill(supervisor, 'SIGKILL'); } catch {} }
await fs.rm(root, { recursive: true, force: true });
});
const launched = await waitFor(async () => messages.find(x => x.pid), Boolean);
supervisor = launched.pid;
const log = path.join(root, launched.log);
await waitFor(() => fs.readFile(log, 'utf8'), text => text?.includes('BEFORE'));
if (crash) {
worker.kill('SIGKILL');
await exited;
}
await fs.writeFile(gate, 'continue');
if (crash) {
const receipt = await waitFor(() => fs.readFile(path.join(root, 'receipt.json'), 'utf8'), Boolean);
assert.equal(JSON.parse(receipt).code, 17);
} else {
await exited;
assert.equal(messages.find(x => x.result)?.result.code, 17);
}
assert.equal(await fs.readFile(log, 'utf8'), 'BEFORE\n尾行 AFTER\nSTDERR\nCOMPOUND\n');
});
if (crash) {
const receipt = await waitFor(
() => fs.readFile(path.join(root, 'receipt.json'), 'utf8'),
Boolean,
);
assert.equal(JSON.parse(receipt).code, 17);
} else {
await exited;
assert.equal(messages.find((x) => x.result)?.result.code, 17);
}
assert.equal(
await fs.readFile(log, 'utf8'),
'BEFORE\n尾行 AFTER\nSTDERR\nCOMPOUND\n',
);
},
);
}
+10 -5
View File
@@ -39,7 +39,9 @@ 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 db.transaction((tx) =>
require('../../back/cron/history').installTriggerHistory(db, tx),
);
await crons.create({
id: 1,
status: 3,
@@ -75,7 +77,7 @@ for (const conflict of ['stop', 'newer-queue', 'stop-requeue']) {
},
'../config/const': {},
'../schedule/client': {},
'../shared/pLimit': {
'../cron/execution/cronLimit': {
manualRunWithCronLimit: async (fn) => {
try {
return await fn();
@@ -112,7 +114,8 @@ 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 = async (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(
@@ -176,7 +179,9 @@ test('a runner waiting for a concurrency slot cannot adopt a newer queued genera
last_execution_time: DataTypes.INTEGER,
});
await db.sync();
await db.transaction((tx) => require('../../back/shared/triggerHistory').installTriggerHistory(db, tx));
await db.transaction((tx) =>
require('../../back/cron/history').installTriggerHistory(db, tx),
);
await crons.create({ id: 1, status: 1, log_path: 'same.log' });
const waiting = [];
const CronService = load('back/services/cron.ts', {
@@ -194,7 +199,7 @@ test('a runner waiting for a concurrency slot cannot adopt a newer queued genera
},
'../config/const': {},
'../schedule/client': {},
'../shared/pLimit': {
'../cron/execution/cronLimit': {
manualRunWithCronLimit: (fn) => {
waiting.push(fn);
return Promise.resolve();
+18 -8
View File
@@ -60,10 +60,23 @@ test('mirror verification selects GNU timeout when the default is another implem
assert.ok(realTimeout, 'The mirror script requires GNU timeout');
const bin = path.join(tmp, 'bin');
fs.mkdirSync(bin);
fs.symlinkSync(execFileSync('which', [realTimeout], { encoding: 'utf8' }).trim(), path.join(bin, 'gnutimeout'));
fs.symlinkSync(execFileSync('which', ['git'], { encoding: 'utf8' }).trim(), path.join(bin, 'git'));
fs.symlinkSync(execFileSync('which', ['sort'], { encoding: 'utf8' }).trim(), path.join(bin, 'sort'));
fs.writeFileSync(path.join(bin, 'timeout'), '#!/bin/sh\nif [ "$1" = --version ]; then echo "timeout (uutils coreutils)"; exit 0; fi\nexit 98\n', { mode: 0o755 });
fs.symlinkSync(
execFileSync('which', [realTimeout], { encoding: 'utf8' }).trim(),
path.join(bin, 'gnutimeout'),
);
fs.symlinkSync(
execFileSync('which', ['git'], { encoding: 'utf8' }).trim(),
path.join(bin, 'git'),
);
fs.symlinkSync(
execFileSync('which', ['sort'], { encoding: 'utf8' }).trim(),
path.join(bin, 'sort'),
);
fs.writeFileSync(
path.join(bin, 'timeout'),
'#!/bin/sh\nif [ "$1" = --version ]; then echo "timeout (uutils coreutils)"; exit 0; fi\nexit 98\n',
{ mode: 0o755 },
);
const args = [script, source, mirror, 'develop'];
const result = spawnSync('/bin/bash', args, options({ PATH: bin }));
assert.equal(result.status, 0, result.stderr + result.stdout);
@@ -270,10 +283,7 @@ test('Gitee workflows verify both mirrors and do not gate image publication', ()
JSON.stringify(backfill),
/GITEE_TOKEN|git@gitee|sync-static|ssh-keyscan/,
);
for (const name of [
'build-alpine',
'build-debian',
]) {
for (const name of ['build-alpine', 'build-debian']) {
assert.equal(workflow.jobs[name].needs, 'build-static');
}
});
+68 -17
View File
@@ -1,16 +1,26 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const load = require('../helpers/load-security-module.cjs');
const { createCronJob } = require('../../back/shared/cronScheduler');
const { createCronJob } = require('../../back/cron/scheduling/cronScheduler');
const logger = { info() {}, warn() {}, error() {} };
test('native calendar skips nonexistent spring time and duplicate fall hour', async (t) => {
const previous = process.env.TZ;
process.env.TZ = 'America/New_York';
t.after(() => { if (previous === undefined) delete process.env.TZ; else process.env.TZ = previous; });
t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: new Date('2026-03-08T05:00:00Z') });
t.after(() => {
if (previous === undefined) delete process.env.TZ;
else process.env.TZ = previous;
});
t.mock.timers.enable({
apis: ['Date', 'setTimeout', 'setInterval'],
now: new Date('2026-03-08T05:00:00Z'),
});
const springRuns = [];
const spring = createCronJob('0 30 2 * * *', (date) => springRuns.push(date.toISOString()), { name: 'spring', logger });
const spring = createCronJob(
'0 30 2 * * *',
(date) => springRuns.push(date.toISOString()),
{ name: 'spring', logger },
);
t.after(() => spring.cancel());
t.mock.timers.tick(new Date('2026-03-09T06:30:00Z') - Date.now());
await new Promise(setImmediate);
@@ -18,7 +28,11 @@ test('native calendar skips nonexistent spring time and duplicate fall hour', as
spring.cancel();
t.mock.timers.setTime(new Date('2026-11-01T05:30:00Z').getTime());
const fallRuns = [];
const fall = createCronJob('0 30 1 * * *', (date) => fallRuns.push(date.toISOString()), { name: 'fall', logger });
const fall = createCronJob(
'0 30 1 * * *',
(date) => fallRuns.push(date.toISOString()),
{ name: 'fall', logger },
);
t.after(() => fall.cancel());
t.mock.timers.tick(new Date('2026-11-02T06:30:00Z') - Date.now());
await new Promise(setImmediate);
@@ -31,28 +45,65 @@ test('construction failure cleans staged jobs and preserves the running snapshot
let count = 0;
const { addCron } = load('back/schedule/addCron.ts', {
'./data': { scheduleStacks: stacks },
'../shared/cronScheduler': { createCronJob: () => {
if (++count === 2) throw Error('construction failed');
return { start() { throw Error('must not start'); }, cancel: () => cancelled.push('staged') };
} },
'../shared/runCron': {}, '../loaders/logger': logger, '../shared/i18n': { tf: require('node:util').format },
'../cron/scheduling/cronScheduler': {
createCronJob: () => {
if (++count === 2) throw Error('construction failed');
return {
start() {
throw Error('must not start');
},
cancel: () => cancelled.push('staged'),
};
},
},
'../cron/execution/runCron': {},
'../loaders/logger': logger,
'../shared/i18n': { tf: require('node:util').format },
});
await assert.rejects(new Promise((resolve, reject) => addCron({ request: {
replace: true, crons: [{ id: 'new', schedule: '* * * * *', extra_schedules: [{ schedule: '0 * * * *' }] }],
} }, (error) => error ? reject(error) : resolve())), /construction failed/);
await assert.rejects(
new Promise((resolve, reject) =>
addCron(
{
request: {
replace: true,
crons: [
{
id: 'new',
schedule: '* * * * *',
extra_schedules: [{ schedule: '0 * * * *' }],
},
],
},
},
(error) => (error ? reject(error) : resolve()),
),
),
/construction failed/,
);
assert.deepEqual([...stacks.keys()], ['old']);
assert.deepEqual(cancelled, ['staged']);
});
test('invalid subscription schedules are isolated and immediate runs without a schedule survive', async () => {
const warnings = [], runs = [];
const warnings = [],
runs = [];
const Service = load('back/services/schedule.ts', {
typedi: { Service: () => (x) => x, Inject: () => () => {} },
'../shared/pLimit': {},
}).default;
const service = new Service({ ...logger, warn: (...args) => warnings.push(args) });
service.runTask = async (...args) => { runs.push(args); };
const item = { id: 123, name: 'subscription', command: 'true', runOrigin: 'subscription' };
const service = new Service({
...logger,
warn: (...args) => warnings.push(args),
});
service.runTask = async (...args) => {
runs.push(args);
};
const item = {
id: 123,
name: 'subscription',
command: 'true',
runOrigin: 'subscription',
};
await service.createCronTask({ ...item, schedule: 'not a cron' });
assert.equal(warnings.length, 1);
assert.equal(service.scheduleStacks.size, 0);
+9 -4
View File
@@ -29,7 +29,10 @@ for (const [specifier, installedName] of [
const args = execFileSync('/bin/sh', [
'-c',
'pnpm() { printf "%s\\0" "$@"; }; ' + command,
]).toString().split('\0').slice(0, -1);
])
.toString()
.split('\0')
.slice(0, -1);
assert.deepEqual(args, ['remove', '-g', '--', installedName]);
});
}
@@ -37,9 +40,11 @@ for (const [specifier, installedName] of [
test('cancel can locate an uninstall process after shell argument parsing', async (t) => {
const name = `@ql-uninstall-fixture/worker-${process.pid}`;
const command = api.getUninstallCommand(0, `${name}@1.0.0`);
const worker = spawn(process.execPath, [
'-e', 'setInterval(() => {}, 1000)', 'pnpm', 'remove', '-g', '--', name,
], { stdio: 'ignore' });
const worker = spawn(
process.execPath,
['-e', 'setInterval(() => {}, 1000)', 'pnpm', 'remove', '-g', '--', name],
{ stdio: 'ignore' },
);
t.after(() => worker.kill());
await new Promise((resolve, reject) => {
worker.once('spawn', resolve);
+18 -5
View File
@@ -70,14 +70,26 @@ test('alternating Node/crond working directories retain independent cached roots
fs.mkdirSync(path.join(f.root, 'child'));
fs.writeFileSync(path.join(f.root, 'child', '.npmrc'), 'global-dir=/child\n');
for (let i = 0; i < 4; i++) {
assert.equal(f.run({ ANSWER: '/parent/modules' }).stdout.trim(), '/parent/modules');
assert.equal(
f.run({ ANSWER: '/child/modules' }, 'cd child; ' + f.command).stdout.trim(),
f.run({ ANSWER: '/parent/modules' }).stdout.trim(),
'/parent/modules',
);
assert.equal(
f
.run({ ANSWER: '/child/modules' }, 'cd child; ' + f.command)
.stdout.trim(),
'/child/modules',
);
}
assert.equal(f.count(), 2, 'each working directory should discover only once');
assert.equal(fs.readdirSync(f.env.dir_tmp).filter((x) => x.endsWith('.cache')).length, 2);
assert.equal(
f.count(),
2,
'each working directory should discover only once',
);
assert.equal(
fs.readdirSync(f.env.dir_tmp).filter((x) => x.endsWith('.cache')).length,
2,
);
});
test('refresh retires old per-environment records without removing locks or unrelated files', (t) => {
const f = fixture(t);
@@ -92,7 +104,8 @@ test('refresh retires old per-environment records without removing locks or unre
}
assert.equal(f.run().status, 0);
assert.equal(fs.existsSync(path.join(f.env.dir_tmp, names[0])), false);
for (const name of names.slice(1)) assert.ok(fs.existsSync(path.join(f.env.dir_tmp, name)));
for (const name of names.slice(1))
assert.ok(fs.existsSync(path.join(f.env.dir_tmp, name)));
});
test('expired or malformed records refresh and failed lookups are not cached', (t) => {
const f = fixture(t);
+17 -4
View File
@@ -36,12 +36,25 @@ test('emulated Node probes have a bounded two-minute budget and reject a timeout
t.mock.method(childProcess, 'spawnSync', (_program, args, options) => {
assert.equal(options.timeout, 120000);
assert.equal(options.env.NODE_OPTIONS, '');
return { status: null, signal: 'SIGTERM', error: Object.assign(new Error('probe timed out'), { code: 'ETIMEDOUT' }) };
return {
status: null,
signal: 'SIGTERM',
error: Object.assign(new Error('probe timed out'), { code: 'ETIMEDOUT' }),
};
});
delete require.cache[modulePath];
t.after(() => { delete require.cache[modulePath]; });
t.after(() => {
delete require.cache[modulePath];
});
const probe = require(modulePath).probeNodeRuntime;
assert.throws(() => probe(), /Node URL runtime probe failed.*SIGTERM.*probe timed out/);
assert.throws(
() => probe(),
/Node URL runtime probe failed.*SIGTERM.*probe timed out/,
);
assert.ok(directory);
assert.equal(fs.existsSync(directory), false, 'Timed-out probes must remove their temporary source files');
assert.equal(
fs.existsSync(directory),
false,
'Timed-out probes must remove their temporary source files',
);
});
+4 -5
View File
@@ -30,7 +30,7 @@ async function fixture(t) {
'./schedule': class {},
'./sock': class {},
'./notify': class {},
'../shared/pLimit': {},
'../cron/execution/cronLimit': {},
'../schedule/client': {},
'../config/index': {},
'../shared/store': {},
@@ -47,12 +47,11 @@ async function fixture(t) {
NotifyStatus: { success: 0, fail: 1 },
},
'../shared/i18n': { t: (s) => s },
'./user': {},
'../data/notificationSettings': {
readNotificationMode: async () => ({ type: 'email' }),
},
}).default)(),
});
service.notificationService.userService = {
getNotificationMode: async () => ({ type: 'email' }),
};
service.notificationService.modeMap.set('email', async () => true);
service.getDb = async () => ({ info: { type: 'email' } });
return { rows, service };
+33
View File
@@ -0,0 +1,33 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const load = require('../helpers/load-security-module.cjs');
test('notification settings keep missing-row errors, empty defaults and fresh reads', async () => {
let row;
const { readNotificationMode } = load('back/data/notificationSettings.ts', {
'./system': {
AuthDataType: { notification: 'notification' },
SystemModel: {
findOne: async (query) => {
assert.deepEqual(query, { where: { type: 'notification' } });
return row;
},
},
},
});
await assert.rejects(readNotificationMode(), {
message: '{"type":"notification"} not found',
});
let info = null;
row = {
get(options) {
assert.deepEqual(options, { plain: true });
return { info };
},
};
assert.deepEqual(await readNotificationMode(), {});
info = { type: 'wpush', wpushApiKey: 'saved-key' };
assert.deepEqual(await readNotificationMode(), info);
info = { type: 'email' };
assert.deepEqual(await readNotificationMode(), info);
});
+485 -108
View File
@@ -12,24 +12,43 @@ const { restorePackageLock } = require('../../shell/install-package.cjs');
const { restoreEnvironment } = require('../../shell/install-package.cjs');
async function packageFixture(t) {
const temp = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-contract-')));
const temp = await fs.realpath(
await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-contract-')),
);
t.after(() => fs.rm(temp, { recursive: true, force: true }));
const root = path.join(temp, 'source'), output = path.join(temp, 'archives');
const root = path.join(temp, 'source'),
output = path.join(temp, 'archives');
await fs.mkdir(root);
await fs.mkdir(output);
const copy = async (name) => {
await fs.mkdir(path.dirname(path.join(root, name)), { recursive: true });
await fs.copyFile(path.resolve(name), path.join(root, name));
};
for (const name of ['.gitignore', 'docker/verify-build.cjs', 'docker/build-manifest.cjs', '.env.example', 'ecosystem.config.js', 'version.yaml', 'README.md', 'LICENSE', 'scripts/prepare-npm-package.cjs', 'back/protos/api.proto']) await copy(name);
for (const name of [
'.gitignore',
'docker/verify-build.cjs',
'docker/build-manifest.cjs',
'.env.example',
'ecosystem.config.js',
'version.yaml',
'README.md',
'LICENSE',
'scripts/prepare-npm-package.cjs',
'back/protos/api.proto',
])
await copy(name);
for (const directory of ['shell', 'sample', 'cli/src/internal/maintenance']) {
await fs.cp(directory, path.join(root, directory), {
recursive: true,
filter: (source) => !/[/\\](?:__pycache__|node_modules)(?:[/\\]|$)|[/\\]preload[/\\](?:env\.|notify\.|__ql_notify__\.|lang_env\.sh)/.test(source),
filter: (source) =>
!/[/\\](?:__pycache__|node_modules)(?:[/\\]|$)|[/\\]preload[/\\](?:env\.|notify\.|__ql_notify__\.|lang_env\.sh)/.test(
source,
),
});
}
const metadata = JSON.parse(await fs.readFile('package.json', 'utf8'));
for (const name of Object.values(metadata.pnpm?.patchedDependencies || {})) await copy(name);
for (const name of Object.values(metadata.pnpm?.patchedDependencies || {}))
await copy(name);
// The structural test stays offline; full production installation and service
// upgrades run against the unmodified package in verify-panel-package.cjs.
metadata.dependencies = {};
@@ -38,13 +57,50 @@ 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/shared/managedExit.cjs', '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/cron/settlement/exitReceipt.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.mkdir(path.dirname(path.join(root, 'static', name)), {
recursive: true,
});
await fs.writeFile(path.join(root, 'static', name), bytes);
files[name] = createHash('sha256').update(bytes).digest('hex');
}
for (const name of ['.env', '.env.local', '.env.production', '.aws/credentials', '.ssh/id_rsa', '.vscode/settings.json', '.github/workflows/private.yml', '.tmp/private.json', '.DS_Store', 'output/private.json', 'data/config/auth.json', 'back/private.json', 'back/private.ts', 'sample/tool.ts', 'sample/private.json', 'sample/__pycache__/notify.pyc', 'shell/preload/env.js', 'shell/preload/env.py', 'shell/preload/notify.js', 'shell/preload/__ql_notify__.js', 'shell/preload/lang_env.sh', 'shell/preload/task-notify.json', 'shell/preload/__pycache__/env.pyc', 'cli/dist/npm/ql.js', 'cli/src/internal/private.cjs']) {
for (const name of [
'.env',
'.env.local',
'.env.production',
'.aws/credentials',
'.ssh/id_rsa',
'.vscode/settings.json',
'.github/workflows/private.yml',
'.tmp/private.json',
'.DS_Store',
'output/private.json',
'data/config/auth.json',
'back/private.json',
'back/private.ts',
'sample/tool.ts',
'sample/private.json',
'sample/__pycache__/notify.pyc',
'shell/preload/env.js',
'shell/preload/env.py',
'shell/preload/notify.js',
'shell/preload/__ql_notify__.js',
'shell/preload/lang_env.sh',
'shell/preload/task-notify.json',
'shell/preload/__pycache__/env.pyc',
'cli/dist/npm/ql.js',
'cli/src/internal/private.cjs',
]) {
await fs.mkdir(path.dirname(path.join(root, name)), { recursive: true });
await fs.writeFile(path.join(root, name), 'DO_NOT_PUBLISH');
}
@@ -52,65 +108,177 @@ async function packageFixture(t) {
const env = { ...process.env, HOME: temp, NODE_ENV: 'production' };
await execute('git', ['init', '-q'], { cwd: root, env });
await execute('git', ['add', '-A'], { cwd: root, env });
await execute('git', ['-c', 'user.name=Package Test', '-c', 'user.email=test@example.invalid', '-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'fixture'], { cwd: root, env });
await fs.writeFile(path.join(root, 'static/build-info.json'), JSON.stringify({
version: 1, dirty: false, sourceCommit: (await execute('git', ['rev-parse', 'HEAD'], { cwd: root })).stdout.trim(), files,
lockfileSha256: createHash('sha256').update(lock).digest('hex'),
}));
const pack = () => execute('npm', ['pack', '--json', '--cache', path.join(temp, 'cache'), '--pack-destination', output], { cwd: root, env, timeout: 60000, maxBuffer: 4 * 1024 * 1024 });
await execute(
'git',
[
'-c',
'user.name=Package Test',
'-c',
'user.email=test@example.invalid',
'-c',
'core.hooksPath=/dev/null',
'commit',
'-qm',
'fixture',
],
{ cwd: root, env },
);
await fs.writeFile(
path.join(root, 'static/build-info.json'),
JSON.stringify({
version: 1,
dirty: false,
sourceCommit: (
await execute('git', ['rev-parse', 'HEAD'], { cwd: root })
).stdout.trim(),
files,
lockfileSha256: createHash('sha256').update(lock).digest('hex'),
}),
);
const pack = () =>
execute(
'npm',
[
'pack',
'--json',
'--cache',
path.join(temp, 'cache'),
'--pack-destination',
output,
],
{ cwd: root, env, timeout: 60000, maxBuffer: 4 * 1024 * 1024 },
);
return { root, output, temp, env, lock, files, pack };
}
test('real npm pack excludes local state and its installed lifecycle restores verified runtime files', async (t) => {
const { root, output, temp, env, lock, files, pack } = await packageFixture(t);
const { root, output, temp, env, lock, files, pack } = await packageFixture(
t,
);
// The whitelist must work by itself, even for artifacts ignored by Git.
await assert.rejects(fs.access(path.join(root, '.npmignore')), { code: 'ENOENT' });
await assert.rejects(fs.access(path.join(root, '.npmignore')), {
code: 'ENOENT',
});
const packed = await pack();
const [archive] = JSON.parse(packed.stdout);
checkPackedFiles(archive.files);
const patches = Object.values(JSON.parse(await fs.readFile(path.join(root, 'package.json'), 'utf8')).pnpm?.patchedDependencies || {});
const patches = Object.values(
JSON.parse(await fs.readFile(path.join(root, 'package.json'), 'utf8')).pnpm
?.patchedDependencies || {},
);
for (const patch of patches) {
assert.throws(() => checkPackedFiles(archive.files.filter((file) => file.path !== patch)), /Missing npm runtime/);
assert.throws(
() =>
checkPackedFiles(archive.files.filter((file) => file.path !== patch)),
/Missing npm runtime/,
);
}
assert.throws(() => checkPackedFiles([...archive.files, { path: 'patches/undeclared.patch' }]), /Unexpected npm file/);
assert.throws(
() =>
checkPackedFiles([
...archive.files,
{ path: 'patches/undeclared.patch' },
]),
/Unexpected npm file/,
);
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' });
await assert.rejects(fs.access(path.join(root, 'shell/upgrade-lock.yaml')), {
code: 'ENOENT',
});
const prefix = path.join(temp, 'installed');
await execute('npm', ['install', '--offline', '--omit=dev', '--no-audit', '--no-fund', '--cache', path.join(temp, 'cache'), '--prefix', prefix, path.join(output, archive.filename)], { cwd: temp, env, timeout: 60000 });
await execute(
'npm',
[
'install',
'--offline',
'--omit=dev',
'--no-audit',
'--no-fund',
'--cache',
path.join(temp, 'cache'),
'--prefix',
prefix,
path.join(output, archive.filename),
],
{ cwd: temp, env, timeout: 60000 },
);
const installed = path.join(prefix, 'node_modules/@whyour/qinglong');
for (const patch of patches) assert.deepEqual(await fs.readFile(path.join(installed, patch)), await fs.readFile(path.join(root, patch)));
for (const patch of patches)
assert.deepEqual(
await fs.readFile(path.join(installed, patch)),
await fs.readFile(path.join(root, patch)),
);
for (const { path: name } of archive.files)
assert.equal((await fs.readFile(path.join(installed, name))).includes(Buffer.from('DO_NOT_PUBLISH')), false, `Private fixture content in npm package: ${name}`);
await assert.rejects(fs.access(path.join(installed, '.env')), { code: 'ENOENT' });
assert.equal(await fs.readFile(path.join(installed, 'pnpm-lock.yaml'), 'utf8'), lock);
assert.equal(typeof require(path.join(installed, 'shell/upgrade.cjs')).stageUpgrade, 'function');
assert.ok((await fs.stat(path.join(installed, 'shell/update.sh'))).mode & 0o111);
for (const [name, file] of Object.entries(JSON.parse(await fs.readFile(path.join(installed, 'package.json'), 'utf8')).bin)) {
assert.equal(
(await fs.readFile(path.join(installed, name))).includes(
Buffer.from('DO_NOT_PUBLISH'),
),
false,
`Private fixture content in npm package: ${name}`,
);
await assert.rejects(fs.access(path.join(installed, '.env')), {
code: 'ENOENT',
});
assert.equal(
await fs.readFile(path.join(installed, 'pnpm-lock.yaml'), 'utf8'),
lock,
);
assert.equal(
typeof require(path.join(installed, 'shell/upgrade.cjs')).stageUpgrade,
'function',
);
assert.ok(
(await fs.stat(path.join(installed, 'shell/update.sh'))).mode & 0o111,
);
for (const [name, file] of Object.entries(
JSON.parse(await fs.readFile(path.join(installed, 'package.json'), 'utf8'))
.bin,
)) {
await fs.access(path.join(prefix, 'node_modules/.bin', name));
assert.ok((await fs.stat(path.join(installed, file))).mode & 0o111, file);
}
await fs.writeFile(path.join(installed, 'shell/upgrade-lock.yaml'), 'tampered');
await fs.writeFile(
path.join(installed, 'shell/upgrade-lock.yaml'),
'tampered',
);
assert.throws(() => restorePackageLock(installed), /does not match/);
assert.equal(await fs.readFile(path.join(installed, 'pnpm-lock.yaml'), 'utf8'), lock);
assert.ok(!(await fs.readdir(installed)).some((name) => name.startsWith('.upgrade-lock-')));
assert.equal(
await fs.readFile(path.join(installed, 'pnpm-lock.yaml'), 'utf8'),
lock,
);
assert.ok(
!(await fs.readdir(installed)).some((name) =>
name.startsWith('.upgrade-lock-'),
),
);
});
test('postinstall still supports minimal Docker dependency stages before shell files are copied', async (t) => {
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-builder-'));
t.after(() => fs.rm(temp, { recursive: true, force: true }));
const metadata = JSON.parse(await fs.readFile('package.json', 'utf8'));
await fs.writeFile(path.join(temp, 'package.json'), JSON.stringify({ scripts: { postinstall: metadata.scripts.postinstall } }));
await fs.writeFile(
path.join(temp, 'package.json'),
JSON.stringify({ scripts: { postinstall: metadata.scripts.postinstall } }),
);
await fs.writeFile(path.join(temp, 'pnpm-lock.yaml'), 'source lock');
await execute('npm', ['run', 'postinstall', '--cache', path.join(temp, 'cache')], { cwd: temp, timeout: 30000 });
await execute(
'npm',
['run', 'postinstall', '--cache', path.join(temp, 'cache')],
{ cwd: temp, timeout: 30000 },
);
});
test('a missing npm runtime lockfile fails instead of claiming an installed package is ready', async (t) => {
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-lock-missing-'));
t.after(() => fs.rm(temp, { recursive: true, force: true }));
assert.throws(() => restorePackageLock(temp), /Missing npm package upgrade lockfile/);
assert.throws(
() => restorePackageLock(temp),
/Missing npm package upgrade lockfile/,
);
});
test('real npm overwrites preserve .env automatically and failed installs restore the old package', async (t) => {
@@ -119,62 +287,165 @@ test('real npm overwrites preserve .env automatically and failed installs restor
const archive = path.join(output, packed.filename);
const legacy = path.join(temp, 'legacy');
await fs.mkdir(legacy);
await fs.writeFile(path.join(legacy, 'package.json'), JSON.stringify({ name: '@whyour/qinglong', version: '2.22.0' }));
await fs.writeFile(
path.join(legacy, 'package.json'),
JSON.stringify({ name: '@whyour/qinglong', version: '2.22.0' }),
);
await fs.writeFile(path.join(legacy, 'old-package-marker'), 'legacy');
const [old] = JSON.parse((await execute('npm', ['pack', '--ignore-scripts', '--json', '--cache', path.join(temp, 'cache')], { cwd: legacy, env })).stdout);
const [old] = JSON.parse(
(
await execute(
'npm',
[
'pack',
'--ignore-scripts',
'--json',
'--cache',
path.join(temp, 'cache'),
],
{ cwd: legacy, env },
)
).stdout,
);
const broken = path.join(temp, 'broken');
await fs.mkdir(broken);
await fs.cp(root, broken, { recursive: true });
await fs.writeFile(path.join(broken, 'shell/upgrade-lock.yaml'), 'invalid lock');
const [bad] = JSON.parse((await execute('npm', ['pack', '--ignore-scripts', '--json', '--cache', path.join(temp, 'cache')], { cwd: broken, env })).stdout);
await fs.writeFile(
path.join(broken, 'shell/upgrade-lock.yaml'),
'invalid lock',
);
const [bad] = JSON.parse(
(
await execute(
'npm',
[
'pack',
'--ignore-scripts',
'--json',
'--cache',
path.join(temp, 'cache'),
],
{ cwd: broken, env },
)
).stdout,
);
for (const global of [false, true]) {
await t.test(global ? 'global npm install' : 'local npm install', async () => {
const prefix = path.join(temp, global ? 'global' : 'local');
const linkedPrefix = prefix + '-link';
await fs.mkdir(prefix);
await fs.symlink(prefix, linkedPrefix);
const installed = path.join(prefix, global ? 'lib/node_modules/@whyour/qinglong' : 'node_modules/@whyour/qinglong');
const install = (file) => execute('npm', ['install', ...(global ? ['--global'] : []), '--prefix', linkedPrefix, '--force', '--offline', '--omit=dev', '--no-audit', '--no-fund', '--cache', path.join(temp, 'cache'), file], { cwd: temp, env, timeout: 60000 });
await install(path.join(legacy, old.filename));
const bytes = Buffer.from('QL_DATA_DIR=/external/data\r\nSECRET="配置 test"\r\n# no trailing newline');
const external = path.join(prefix, 'external.env');
await fs.writeFile(external, bytes);
await fs.symlink(external, path.join(installed, '.env'));
await assert.rejects(install(archive), (error) => {
assert.match(error.stderr, /must be a regular file/);
return true;
});
assert.equal(JSON.parse(await fs.readFile(path.join(installed, 'package.json'))).version, '2.22.0');
assert.equal(await fs.readlink(path.join(installed, '.env')), external);
assert.deepEqual(await fs.readFile(external), bytes);
await fs.rm(path.join(installed, '.env'));
await fs.writeFile(path.join(installed, '.env'), bytes, { mode: 0o644 });
await assert.rejects(install(path.join(broken, bad.filename)), (error) => {
assert.match(error.stderr, /does not match its build manifest/);
return true;
});
assert.equal(JSON.parse(await fs.readFile(path.join(installed, 'package.json'))).version, '2.22.0');
assert.equal(await fs.readFile(path.join(installed, 'old-package-marker'), 'utf8'), 'legacy');
assert.deepEqual(await fs.readFile(path.join(installed, '.env')), bytes);
await install(archive);
assert.deepEqual(await fs.readFile(path.join(installed, '.env')), bytes);
assert.equal((await fs.stat(path.join(installed, '.env'))).mode & 0o777, 0o600);
await assert.rejects(fs.access(path.join(installed, 'old-package-marker')), { code: 'ENOENT' });
// Same-version forced reinstall must also retain custom configuration.
await install(archive);
assert.deepEqual(await fs.readFile(path.join(installed, '.env')), bytes);
assert.ok(!(await fs.readdir(installed)).some((name) => name.startsWith('.upgrade-env-')));
});
await t.test(
global ? 'global npm install' : 'local npm install',
async () => {
const prefix = path.join(temp, global ? 'global' : 'local');
const linkedPrefix = prefix + '-link';
await fs.mkdir(prefix);
await fs.symlink(prefix, linkedPrefix);
const installed = path.join(
prefix,
global
? 'lib/node_modules/@whyour/qinglong'
: 'node_modules/@whyour/qinglong',
);
const install = (file) =>
execute(
'npm',
[
'install',
...(global ? ['--global'] : []),
'--prefix',
linkedPrefix,
'--force',
'--offline',
'--omit=dev',
'--no-audit',
'--no-fund',
'--cache',
path.join(temp, 'cache'),
file,
],
{ cwd: temp, env, timeout: 60000 },
);
await install(path.join(legacy, old.filename));
const bytes = Buffer.from(
'QL_DATA_DIR=/external/data\r\nSECRET="配置 test"\r\n# no trailing newline',
);
const external = path.join(prefix, 'external.env');
await fs.writeFile(external, bytes);
await fs.symlink(external, path.join(installed, '.env'));
await assert.rejects(install(archive), (error) => {
assert.match(error.stderr, /must be a regular file/);
return true;
});
assert.equal(
JSON.parse(await fs.readFile(path.join(installed, 'package.json')))
.version,
'2.22.0',
);
assert.equal(await fs.readlink(path.join(installed, '.env')), external);
assert.deepEqual(await fs.readFile(external), bytes);
await fs.rm(path.join(installed, '.env'));
await fs.writeFile(path.join(installed, '.env'), bytes, {
mode: 0o644,
});
await assert.rejects(
install(path.join(broken, bad.filename)),
(error) => {
assert.match(error.stderr, /does not match its build manifest/);
return true;
},
);
assert.equal(
JSON.parse(await fs.readFile(path.join(installed, 'package.json')))
.version,
'2.22.0',
);
assert.equal(
await fs.readFile(path.join(installed, 'old-package-marker'), 'utf8'),
'legacy',
);
assert.deepEqual(
await fs.readFile(path.join(installed, '.env')),
bytes,
);
await install(archive);
assert.deepEqual(
await fs.readFile(path.join(installed, '.env')),
bytes,
);
assert.equal(
(await fs.stat(path.join(installed, '.env'))).mode & 0o777,
0o600,
);
await assert.rejects(
fs.access(path.join(installed, 'old-package-marker')),
{ code: 'ENOENT' },
);
// Same-version forced reinstall must also retain custom configuration.
await install(archive);
assert.deepEqual(
await fs.readFile(path.join(installed, '.env')),
bytes,
);
assert.ok(
!(await fs.readdir(installed)).some((name) =>
name.startsWith('.upgrade-env-'),
),
);
},
);
}
});
test('environment recovery uses only the exact retired package and never overwrites existing configuration', async (t) => {
const temp = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-env-')));
const temp = await fs.realpath(
await fs.mkdtemp(path.join(os.tmpdir(), 'ql-npm-env-')),
);
t.after(() => fs.rm(temp, { recursive: true, force: true }));
const root = path.join(temp, 'node_modules/@whyour/qinglong');
await fs.mkdir(root, { recursive: true });
const suffix = createHash('sha1').update(root).digest('base64').replace(/[^a-zA-Z0-9]+/g, '').slice(0, 8);
const suffix = createHash('sha1')
.update(root)
.digest('base64')
.replace(/[^a-zA-Z0-9]+/g, '')
.slice(0, 8);
const retired = path.join(path.dirname(root), `.qinglong-${suffix}`);
const destination = path.join(root, '.env');
const other = path.join(path.dirname(root), '.qinglong-unrelated');
@@ -183,10 +454,19 @@ test('environment recovery uses only the exact retired package and never overwri
restoreEnvironment(root);
await assert.rejects(fs.access(destination), { code: 'ENOENT' });
await fs.mkdir(retired);
await fs.writeFile(path.join(retired, 'package.json'), JSON.stringify({ name: 'another-package' }));
await fs.writeFile(
path.join(retired, 'package.json'),
JSON.stringify({ name: 'another-package' }),
);
await fs.writeFile(path.join(retired, '.env'), 'private');
assert.throws(() => restoreEnvironment(root), /Unexpected retired npm package/);
await fs.writeFile(path.join(retired, 'package.json'), JSON.stringify({ name: '@whyour/qinglong' }));
assert.throws(
() => restoreEnvironment(root),
/Unexpected retired npm package/,
);
await fs.writeFile(
path.join(retired, 'package.json'),
JSON.stringify({ name: '@whyour/qinglong' }),
);
await fs.rm(path.join(retired, '.env'));
restoreEnvironment(root);
await assert.rejects(fs.access(destination), { code: 'ENOENT' });
@@ -203,62 +483,159 @@ test('environment recovery uses only the exact retired package and never overwri
await fs.writeFile(destination, 'new custom configuration');
await fs.writeFile(path.join(retired, '.env'), 'old configuration');
restoreEnvironment(root);
assert.equal(await fs.readFile(destination, 'utf8'), 'new custom configuration');
assert.ok(!(await fs.readdir(root)).some((name) => name.startsWith('.upgrade-env-')));
assert.equal(
await fs.readFile(destination, 'utf8'),
'new custom configuration',
);
assert.ok(
!(await fs.readdir(root)).some((name) => name.startsWith('.upgrade-env-')),
);
});
test('npm publication consumes the exact archive whose isolated installation passed', () => {
const yaml = require('js-yaml');
const sync = require('node:fs');
const workflow = yaml.load(sync.readFileSync('.github/workflows/build-docker-image.yml', 'utf8'));
const workflow = yaml.load(
sync.readFileSync('.github/workflows/build-docker-image.yml', 'utf8'),
);
const verify = workflow.jobs['verify-npm-package'];
assert.deepEqual(verify.needs, ['build-static', 'build-npm-migration-bundle']);
assert.ok(verify.steps.some((step) => step.with?.name === 'npm-migration-bundle-${{ github.sha }}'));
assert.deepEqual(verify.needs, [
'build-static',
'build-npm-migration-bundle',
]);
assert.ok(
verify.steps.some(
(step) => step.with?.name === 'npm-migration-bundle-${{ github.sha }}',
),
);
const migration = workflow.jobs['build-npm-migration-bundle'];
assert.equal(migration.needs, 'build-debian');
assert.ok(migration.steps.some((step) => /Dockerfile.upgrade-bundle/.test(step.run || '')));
assert.ok(!migration.steps.some((step) => /publish-upgrade-bundles/.test(step.run || '')));
assert.ok(
migration.steps.some((step) =>
/Dockerfile.upgrade-bundle/.test(step.run || ''),
),
);
assert.ok(
!migration.steps.some((step) =>
/publish-upgrade-bundles/.test(step.run || ''),
),
);
assert.deepEqual(verify.strategy.matrix.node, ['20.18.1', '24']);
assert.match(verify.container, /node:.*bookworm/);
const tools = verify.steps.find((step) => step.name === 'Install isolated service test tools');
assert.match(tools.run, /npm install --global --prefix \/usr\/local.*pm2@6\.0\.14/);
const service = verify.steps.find((step) => step.name === 'Install and upgrade the exact npm archive');
const tools = verify.steps.find(
(step) => step.name === 'Install isolated service test tools',
);
assert.match(
tools.run,
/npm install --global --prefix \/usr\/local.*pm2@6\.0\.14/,
);
const service = verify.steps.find(
(step) => step.name === 'Install and upgrade the exact npm archive',
);
assert.equal(service.env.QL_PANEL_TEST_PM2, '/usr/local/bin/pm2');
assert.ok(workflow.jobs.publish.needs.includes('verify-npm-package'));
const download = workflow.jobs.publish.steps.find((step) => step.uses?.startsWith('actions/download-artifact@'));
const download = workflow.jobs.publish.steps.find((step) =>
step.uses?.startsWith('actions/download-artifact@'),
);
assert.equal(download.with.name, 'qinglong-npm-${{ github.sha }}');
const publication = workflow.jobs.publish.steps.find((step) => step.name === 'Publish npm package with OIDC');
const publication = workflow.jobs.publish.steps.find(
(step) => step.name === 'Publish npm package with OIDC',
);
assert.match(publication.run, /npm publish "\.\/\$archive" --ignore-scripts/);
assert.ok(!workflow.jobs.publish.steps.some((step) => /pnpm build/.test(step.run || '')));
assert.ok(
!workflow.jobs.publish.steps.some((step) =>
/pnpm build/.test(step.run || ''),
),
);
});
for (const scenario of ['dirty-source', 'stale-commit', 'dirty-build', 'changed-lock', 'changed-output', 'missing-output', 'extra-output']) {
for (const scenario of [
'dirty-source',
'stale-commit',
'dirty-build',
'changed-lock',
'changed-output',
'missing-output',
'extra-output',
]) {
test(`native npm pack rejects ${scenario} before producing an archive`, async (t) => {
const { root, output, pack } = await packageFixture(t);
const manifestFile = path.join(root, 'static/build-info.json');
const manifest = JSON.parse(await fs.readFile(manifestFile, 'utf8'));
if (scenario === 'dirty-source') await fs.appendFile(path.join(root, 'shell/start.sh'), '\n# uncommitted change\n');
if (scenario === 'dirty-source')
await fs.appendFile(
path.join(root, 'shell/start.sh'),
'\n# uncommitted change\n',
);
if (scenario === 'stale-commit') {
await fs.appendFile(path.join(root, 'shell/start.sh'), '\n# committed change after build\n');
await fs.appendFile(
path.join(root, 'shell/start.sh'),
'\n# committed change after build\n',
);
await execute('git', ['add', '-A'], { cwd: root });
await execute('git', ['-c', 'user.name=Package Test', '-c', 'user.email=test@example.invalid', '-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'new source'], { cwd: root });
await execute(
'git',
[
'-c',
'user.name=Package Test',
'-c',
'user.email=test@example.invalid',
'-c',
'core.hooksPath=/dev/null',
'commit',
'-qm',
'new source',
],
{ cwd: root },
);
}
if (scenario === 'dirty-build') { manifest.dirty = true; await fs.writeFile(manifestFile, JSON.stringify(manifest)); }
if (scenario === 'changed-lock') {
await fs.appendFile(path.join(root, 'pnpm-lock.yaml'), '# changed lock\n');
await execute('git', ['add', '-A'], { cwd: root });
await execute('git', ['-c', 'user.name=Package Test', '-c', 'user.email=test@example.invalid', '-c', 'core.hooksPath=/dev/null', 'commit', '-qm', 'new lock'], { cwd: root });
manifest.sourceCommit = (await execute('git', ['rev-parse', 'HEAD'], { cwd: root })).stdout.trim();
if (scenario === 'dirty-build') {
manifest.dirty = true;
await fs.writeFile(manifestFile, JSON.stringify(manifest));
}
if (scenario === 'changed-output') await fs.appendFile(path.join(root, 'static/build/app.js'), 'changed');
if (scenario === 'missing-output') await fs.rm(path.join(root, 'static/build/app.js'));
if (scenario === 'extra-output') await fs.writeFile(path.join(root, 'static/build/leftover.js'), 'old');
if (scenario === 'changed-lock') {
await fs.appendFile(
path.join(root, 'pnpm-lock.yaml'),
'# changed lock\n',
);
await execute('git', ['add', '-A'], { cwd: root });
await execute(
'git',
[
'-c',
'user.name=Package Test',
'-c',
'user.email=test@example.invalid',
'-c',
'core.hooksPath=/dev/null',
'commit',
'-qm',
'new lock',
],
{ cwd: root },
);
manifest.sourceCommit = (
await execute('git', ['rev-parse', 'HEAD'], { cwd: root })
).stdout.trim();
await fs.writeFile(manifestFile, JSON.stringify(manifest));
}
if (scenario === 'changed-output')
await fs.appendFile(path.join(root, 'static/build/app.js'), 'changed');
if (scenario === 'missing-output')
await fs.rm(path.join(root, 'static/build/app.js'));
if (scenario === 'extra-output')
await fs.writeFile(path.join(root, 'static/build/leftover.js'), 'old');
await assert.rejects(pack(), (error) => {
assert.match(error.stderr, /clean source|do not match|checksum mismatch|file set mismatch/i);
assert.match(
error.stderr,
/clean source|do not match|checksum mismatch|file set mismatch/i,
);
return true;
});
assert.deepEqual(await fs.readdir(output), []);
await assert.rejects(fs.access(path.join(root, 'shell/upgrade-lock.yaml')), { code: 'ENOENT' });
await assert.rejects(
fs.access(path.join(root, 'shell/upgrade-lock.yaml')),
{ code: 'ENOENT' },
);
});
}
+16 -8
View File
@@ -13,10 +13,7 @@ const publication = workflow.jobs.publish.steps.find(
).run;
test('npm publication waits for every supported release image', () => {
for (const name of [
'build-alpine',
'build-debian',
])
for (const name of ['build-alpine', 'build-debian'])
assert.ok(workflow.jobs.publish.needs.includes(name), name);
});
@@ -42,7 +39,11 @@ for (const [scenario, expectedStatus, published] of [
path.join(root, 'package/package.json'),
JSON.stringify({ name: '@whyour/qinglong', version: '2.22.0' }),
);
const packed = spawnSync('tar', ['-czf', 'npm-panel/verified.tgz', 'package'], { cwd: root });
const packed = spawnSync(
'tar',
['-czf', 'npm-panel/verified.tgz', 'package'],
{ cwd: root },
);
assert.equal(packed.status, 0, String(packed.stderr));
fs.writeFileSync(
path.join(bin, 'npm'),
@@ -77,8 +78,15 @@ case 'network': console.log('upstream unavailable'); process.exit(1);
assert.equal(result.status, expectedStatus, result.stdout + result.stderr);
assert.equal(fs.existsSync(path.join(root, 'published')), published);
if (published)
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(root, 'published'), 'utf8')), [
'./npm-panel/verified.tgz', '--ignore-scripts', '--access', 'public', '--registry=https://registry.npmjs.org',
]);
assert.deepEqual(
JSON.parse(fs.readFileSync(path.join(root, 'published'), 'utf8')),
[
'./npm-panel/verified.tgz',
'--ignore-scripts',
'--access',
'public',
'--registry=https://registry.npmjs.org',
],
);
});
}
+22 -8
View File
@@ -9,22 +9,36 @@ const artifacts = require('../../cli/src/internal/maintenance/upgradeArtifacts.c
const { installBundle } = require('../../shell/install-bundle.cjs');
test('offline environment loading treats installation paths as data and preserves the caller directory', async (t) => {
const directory = await fs.mkdtemp(path.join(require('node:os').tmpdir(), 'ql-offline-path-'));
const directory = await fs.mkdtemp(
path.join(require('node:os').tmpdir(), 'ql-offline-path-'),
);
t.after(() => fs.rm(directory, { recursive: true, force: true }));
const root = path.join(directory, 'panel space \' " $(echo injected) `echo injected`;');
const root = path.join(
directory,
'panel space \' " $(echo injected) `echo injected`;',
);
await fs.mkdir(path.join(root, 'shell'), { recursive: true });
await fs.writeFile(path.join(root, 'shell/share.sh'), 'import_config() { ql_port=5789; ql_base_url=/panel/; }\n');
await fs.writeFile(path.join(root, 'shell/env.sh'), 'export QL_BRANCH=develop\n');
await fs.writeFile(
path.join(root, 'shell/share.sh'),
'import_config() { ql_port=5789; ql_base_url=/panel/; }\n',
);
await fs.writeFile(
path.join(root, 'shell/env.sh'),
'export QL_BRANCH=develop\n',
);
const cwd = process.cwd();
let captured;
t.mock.method(artifacts, 'stageUpgrade', async ({ env }) => {
captured = env;
throw new Error('reached staging');
});
await assert.rejects(installBundle(
['--file', path.join(root, 'unused.tar.gz'), '--download-only'],
{ ...process.env, QL_DIR: root },
), /reached staging/);
await assert.rejects(
installBundle(
['--file', path.join(root, 'unused.tar.gz'), '--download-only'],
{ ...process.env, QL_DIR: root },
),
/reached staging/,
);
assert.equal(captured.QL_DIR, root);
assert.equal(captured.QlPort, '5789');
assert.equal(captured.QlBaseUrl, '/panel/');
+6 -1
View File
@@ -245,7 +245,12 @@ test('a terminal state published between the status read and PID probe wins', as
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 };
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) => {
+111 -34
View File
@@ -9,14 +9,29 @@ function fixture(t, language) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-lazy-notify-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const extension = language === 'python' ? 'py' : 'js';
fs.copyFileSync(`shell/preload/sitecustomize.${extension}`, path.join(root, `sitecustomize.${extension}`));
fs.copyFileSync(
`shell/preload/sitecustomize.${extension}`,
path.join(root, `sitecustomize.${extension}`),
);
fs.writeFileSync(path.join(root, `env.${extension}`), '');
fs.writeFileSync(path.join(root, 'before.sh'), 'export FROM_SHELL=before\n');
fs.writeFileSync(path.join(root, 'before.js'), 'process.env.FROM_LANGUAGE = "javascript";\n');
fs.writeFileSync(path.join(root, 'task_before.py'), 'import os\nos.environ["FROM_LANGUAGE"] = "python"\n');
fs.writeFileSync(path.join(root, 'client.js'), 'module.exports = { getEnvs: () => "client-ready" };\n');
fs.writeFileSync(
path.join(root, 'before.js'),
'process.env.FROM_LANGUAGE = "javascript";\n',
);
fs.writeFileSync(
path.join(root, 'task_before.py'),
'import os\nos.environ["FROM_LANGUAGE"] = "python"\n',
);
fs.writeFileSync(
path.join(root, 'client.js'),
'module.exports = { getEnvs: () => "client-ready" };\n',
);
fs.copyFileSync('shell/preload/client.py', path.join(root, 'client.py'));
fs.copyFileSync('shell/preload/esm-loader.mjs', path.join(root, 'esm-loader.mjs'));
fs.copyFileSync(
'shell/preload/esm-loader.mjs',
path.join(root, 'esm-loader.mjs'),
);
const env = {
...process.env,
PYTHONPATH: root,
@@ -37,9 +52,13 @@ function fixture(t, language) {
const entry = path.join(root, `entry.${extensionOverride}`);
write(path.basename(entry), body);
const python = language === 'python';
const result = spawnSync(python ? 'python3' : process.execPath,
python ? [entry] : ['--require', path.join(root, 'sitecustomize.js'), entry],
{ cwd: root, env, encoding: 'utf8', timeout: 15000 });
const result = spawnSync(
python ? 'python3' : process.execPath,
python
? [entry]
: ['--require', path.join(root, 'sitecustomize.js'), entry],
{ cwd: root, env, encoding: 'utf8', timeout: 15000 },
);
assert.equal(result.status, 0, result.stderr + result.stdout);
return result.stdout;
};
@@ -49,29 +68,42 @@ function fixture(t, language) {
for (const extension of ['js', 'mjs']) {
test(`${extension} startup preserves hooks, environment selection and client without importing notifications`, (t) => {
const f = fixture(t, 'javascript');
f.write('__ql_notify__.js', 'throw Error("notification dependencies must not load at startup");');
f.run(`
const assert = ${extension === 'mjs' ? '(await import("node:assert/strict")).default' : 'require("node:assert/strict")'};
f.write(
'__ql_notify__.js',
'throw Error("notification dependencies must not load at startup");',
);
f.run(
`
const assert = ${
extension === 'mjs'
? '(await import("node:assert/strict")).default'
: 'require("node:assert/strict")'
};
assert.equal(process.env.FROM_SHELL, 'before');
assert.equal(process.env.FROM_LANGUAGE, 'javascript');
assert.equal(process.env.FROM_COMMAND, 'command');
assert.equal(process.env.ACCOUNTS, 'second&third');
assert.equal(QLAPI.getEnvs(), 'client-ready');
assert.equal(typeof QLAPI.notify, 'function');
`, extension);
`,
extension,
);
});
}
test('JavaScript first notification imports once and preserves arguments, this, promises and errors', (t) => {
const f = fixture(t, 'javascript');
f.write('__ql_notify__.js', `
f.write(
'__ql_notify__.js',
`
global.notificationLoads = (global.notificationLoads || 0) + 1;
exports.sendNotify = function (...args) {
if (args[0] === 'fail') throw new Error('send failed');
global.notificationResult = Promise.resolve({ args, receiver: this });
return global.notificationResult;
};
`);
`,
);
f.run(`
const assert = require('node:assert/strict');
assert.equal(global.notificationLoads, undefined);
@@ -91,10 +123,13 @@ test('JavaScript first notification imports once and preserves arguments, this,
test('JavaScript reports import failures on notify and permits a later retry', (t) => {
const f = fixture(t, 'javascript');
f.write('__ql_notify__.js', `
f.write(
'__ql_notify__.js',
`
if (!process.env.NOTIFY_READY) throw Error('notification dependency unavailable');
exports.sendNotify = (...args) => args;
`);
`,
);
f.run(`
const assert = require('node:assert/strict');
assert.equal(QLAPI.getEnvs(), 'client-ready');
@@ -106,7 +141,10 @@ test('JavaScript reports import failures on notify and permits a later retry', (
test('Python startup preserves hooks, environment selection and client without importing notifications', (t) => {
const f = fixture(t, 'python');
f.write('__ql_notify__.py', 'raise RuntimeError("notification dependencies must not load at startup")\n');
f.write(
'__ql_notify__.py',
'raise RuntimeError("notification dependencies must not load at startup")\n',
);
f.run(`
import os, sys
assert os.environ['FROM_SHELL'] == 'before'
@@ -121,14 +159,17 @@ assert callable(QLAPI.getEnvs)
test('Python first notification imports once and preserves args, kwargs, return values and errors', (t) => {
const f = fixture(t, 'python');
f.write('__ql_notify__.py', `
f.write(
'__ql_notify__.py',
`
import builtins
builtins.notification_loads = getattr(builtins, 'notification_loads', 0) + 1
def send(*args, **kwargs):
if args[0] == 'fail':
raise ValueError('send failed')
return args, kwargs
`);
`,
);
f.run(`
import builtins, sys
assert '__ql_notify__' not in sys.modules
@@ -146,13 +187,16 @@ else:
test('Python reports import failures on notify and permits a later retry', (t) => {
const f = fixture(t, 'python');
f.write('__ql_notify__.py', `
f.write(
'__ql_notify__.py',
`
import os
if not os.environ.get('NOTIFY_READY'):
raise RuntimeError('notification dependency unavailable')
def send(*args, **kwargs):
return args
`);
`,
);
f.run(`
import os, sys
assert '__ql_notify__' not in sys.modules
@@ -172,16 +216,37 @@ for (const extension of ['js', 'mjs', 'py']) {
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');";
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");
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);
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);
}
@@ -199,14 +264,25 @@ test('the panel client defers gRPC until an API call, uses panel dependencies an
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', `
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', `
`,
);
packageFile(
f.root,
'@grpc/grpc-js',
`
global.grpcLoads = (global.grpcLoads || 0) + 1;
exports.credentials = { createInsecure: () => ({}) };
exports.Metadata = class {};
@@ -216,7 +292,8 @@ test('the panel client defers gRPC until an API call, uses panel dependencies an
close() { global.closes = (global.closes || 0) + 1; }
}
exports.loadPackageDefinition = () => ({com: { ql: { api: {Api} }}});
`);
`,
);
f.run(`
const assert = require('node:assert/strict');
(async () => {
+62 -14
View File
@@ -2,24 +2,72 @@ const test = require('node:test');
const assert = require('node:assert/strict');
const vm = require('node:vm');
const fs = require('node:fs');
const configRequire = require('node:module').createRequire(require('node:path').resolve('ecosystem.config.js'));
const configRequire = require('node:module').createRequire(
require('node:path').resolve('ecosystem.config.js'),
);
const source = fs.readFileSync('ecosystem.config.js', 'utf8');
const appSource = fs.readFileSync('back/app.ts', 'utf8');
const ts = require('typescript');
const compiled = ts.transpileModule(appSource.slice(0, appSource.indexOf('\nconst app = new Application();')) + '\nmodule.exports = Application;', {compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022,esModuleInterop:true}}).outputText;
function config(env) {const module={exports:{}};vm.runInNewContext(source,{module,process:{env},require:configRequire});return module.exports.apps[0];}
const compiled = ts.transpileModule(
appSource.slice(0, appSource.indexOf('\nconst app = new Application();')) +
'\nmodule.exports = Application;',
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2022,
esModuleInterop: true,
},
},
).outputText;
function config(env) {
const module = { exports: {} };
vm.runInNewContext(source, {
module,
process: { env },
require: configRequire,
});
return module.exports.apps[0];
}
test('container APM policy keeps worker isolation and can restore all inherited probes', () => {
for (const primary of [undefined, 'true']) for (const workers of [undefined, 'true']) {
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},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');
assert.equal(conf.max_restarts,5);assert.equal(conf.script,'static/build/app.js');
}
for (const primary of [undefined, 'true'])
for (const workers of [undefined, 'true']) {
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 }, 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',
);
assert.equal(conf.max_restarts, 5);
assert.equal(conf.script, 'static/build/app.js');
}
});
test('standalone PM2 monitoring stays enabled', () => {
for(const QL_PRIMARY_APM of [undefined,'true','false']) assert.equal(config({QL_PRIMARY_APM}).pmx,true);
for (const QL_PRIMARY_APM of [undefined, 'true', 'false'])
assert.equal(config({ QL_PRIMARY_APM }).pmx, true);
});
+91 -31
View File
@@ -8,12 +8,14 @@ test('BSD identity and parent lookups distinguish a vanished PID from ps failure
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;
} },
const probes = load('back/cron/execution/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 {
@@ -30,7 +32,12 @@ test('BSD identity and parent lookups distinguish a vanished PID from ps failure
{ 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));
assert.throws(
probe,
(error) =>
!['ESRCH', 'ENOENT'].includes(error.code) &&
/ps|PID/.test(error.message),
);
}
}
} finally {
@@ -51,7 +58,16 @@ function fixture(descendants, probe = () => {}, birth, descendant) {
}).outputText;
const signals = [];
const exports = {};
new Function('exports', 'process', 'psTree', 'fs', 'setTimeout', 'systemOwner', 'isProcessDescendant', code)(
new Function(
'exports',
'process',
'psTree',
'fs',
'setTimeout',
'systemOwner',
'isProcessDescendant',
code,
)(
exports,
{
platform: 'linux',
@@ -63,7 +79,9 @@ function fixture(descendants, probe = () => {}, birth, descendant) {
},
async () => [...descendants],
{},
setTimeout, birth, descendant,
setTimeout,
birth,
descendant,
);
return { killTask: exports.killTask, signals };
}
@@ -114,41 +132,83 @@ test('a leaf retains SIGINT and a process tree retains child-first SIGTERM', asy
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' });
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());
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);
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' });
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']]);
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'],
]);
});
+2 -3
View File
@@ -1,9 +1,8 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const protectedPathCase = require(
'../../back/middlewares/protectedPathCase',
).default;
const protectedPathCase =
require('../../back/middlewares/protectedPathCase').default;
function runMiddleware(path) {
let status;
+3 -1
View File
@@ -77,7 +77,9 @@ test('ql log reads the requested system log history without PM2', () => {
test('ql log follows the current Winston system log without PM2', () => {
const { binDir, shellDir, testRoot } = prepareFixture('container');
const systemLogDir = path.join(testRoot, 'data/syslog');
const currentDate = spawnSync('date', ['+%F'], { encoding: 'utf8' }).stdout.trim();
const currentDate = spawnSync('date', ['+%F'], {
encoding: 'utf8',
}).stdout.trim();
const currentLog = path.join(systemLogDir, `${currentDate}.log`);
fs.mkdirSync(systemLogDir, { recursive: true });
fs.writeFileSync(currentLog, 'system-one\n');
+203 -59
View File
@@ -2,97 +2,241 @@ const test = require('node:test');
const assert = require('node:assert/strict');
const load = require('../helpers/load-security-module.cjs');
const tick = () => new Promise(setImmediate);
function gate() { let release; const promise = new Promise(r => release = r); return { promise, release }; }
async function fixture() {
const logger = { info() {}, error() {}, warn() {} }, notices = [];
const limit = load('back/shared/pLimit.ts', {
'../data/system': { AuthDataType: { systemConfig: 'systemConfig' }, SystemModel: { sync: async () => {}, findOne: async () => ({ info: { cronConcurrency: 1 } }) } },
'../loaders/logger': logger,
'../services/notify': class {},
'../shared/i18n': { t: s => s, tf: s => s },
'../config': { grpcPort: 1 },
'../protos/api': { ApiClient: class { systemNotify(value, cb) { notices.push(value); cb(); } } },
'../config/grpcCerts': { getGrpcCerts: () => null },
}).default;
await tick();
const spawned = [], records = new Map(), jobs = new Map();
let readGate, killGate;
const { runCron } = load('back/shared/runCron.ts', {
'cross-spawn': { spawn: command => { spawned.push(command); return {}; } },
'./pLimit': limit,
'../loaders/logger': logger,
'../data/cron': { CrontabModel: { findOne: async ({ where }) => { const row = records.get(String(where.id)); if (readGate) await readGate.promise; return row; }, update: async () => {} }, CrontabStatus: { running: 0, queued: 3, idle: 1 } },
'../data/runningInstance': { RunningInstanceModel: { update: async () => {} }, InstanceStatus: { running: 0, stopped: 2 } },
'../config/util': { killTask: async () => { if (killGate) await killGate.promise; } },
'./childProcess': { observeChildProcess: () => ({ completed: Promise.resolve({ code: 0 }) }), asError: e => e },
});
const { addCron } = load('back/schedule/addCron.ts', {
'../shared/cronScheduler': { createCronJob: (schedule, callback) => ({ start() {}, cancel() {}, fire: callback }) },
'../shared/cronSchedule': { isValidCronSchedule: x => x !== 'invalid' },
'./data': { scheduleStacks: jobs }, '../shared/runCron': { runCron }, '../loaders/logger': logger,
'../shared/i18n': { t: (s) => s, tf: s => s },
});
const { delCron } = load('back/schedule/delCron.ts', { './data': { scheduleStacks: jobs }, '../loaders/logger': logger });
function add(id = '1', command = 'old', replace = false) {
records.set(id, { isDisabled: 0, allow_multiple_instances: 1 });
addCron({ request: { crons: [{ id, command, schedule: '* * * * * *' }], replace } }, err => assert.ifError(err));
return jobs.get(id)[0];
}
function remove(id = '1') { delCron({ request: { ids: [id] } }, err => assert.ifError(err)); }
async function block() { const g = gate(); const done = limit.runWithCronLimit({ id: 'blocker' }, async () => { await g.promise; }); await tick(); return { release: async () => { g.release(); await done; } }; }
return { limit, spawned, records, jobs, add, remove, block, notices, setReadGate: g => readGate = g, setKillGate: g => killGate = g };
function gate() {
let release;
const promise = new Promise((r) => (release = r));
return { promise, release };
}
for (const operation of ['disable', 'delete', 'update', 'replace', 'disable-enable']) {
async function fixture() {
const logger = { info() {}, error() {}, warn() {} },
notices = [];
const limit = load('back/cron/execution/cronLimit.ts', {
'../../data/system': {
AuthDataType: { systemConfig: 'systemConfig' },
SystemModel: {
sync: async () => {},
findOne: async () => ({ info: { cronConcurrency: 1 } }),
},
},
'../../loaders/logger': logger,
'../../services/notify': class {},
'../../shared/i18n': { t: (s) => s, tf: (s) => s },
'../../config': { grpcPort: 1 },
'../../protos/api': {
ApiClient: class {
systemNotify(value, cb) {
notices.push(value);
cb();
}
},
},
'../../config/grpcCerts': { getGrpcCerts: () => null },
}).default;
await tick();
const spawned = [],
records = new Map(),
jobs = new Map();
let readGate, killGate;
const { runCron } = load('back/cron/execution/runCron.ts', {
'cross-spawn': {
spawn: (command) => {
spawned.push(command);
return {};
},
},
'./cronLimit': limit,
'../../loaders/logger': logger,
'../../data/cron': {
CrontabModel: {
findOne: async ({ where }) => {
const row = records.get(String(where.id));
if (readGate) await readGate.promise;
return row;
},
update: async () => {},
},
CrontabStatus: { running: 0, queued: 3, idle: 1 },
},
'../../data/runningInstance': {
RunningInstanceModel: { update: async () => {} },
InstanceStatus: { running: 0, stopped: 2 },
},
'../../config/util': {
killTask: async () => {
if (killGate) await killGate.promise;
},
},
'../../shared/childProcess': {
observeChildProcess: () => ({ completed: Promise.resolve({ code: 0 }) }),
asError: (e) => e,
},
});
const { addCron } = load('back/schedule/addCron.ts', {
'../cron/scheduling/cronScheduler': {
createCronJob: (schedule, callback) => ({
start() {},
cancel() {},
fire: callback,
}),
},
'../cron/scheduling/cronSchedule': {
isValidCronSchedule: (x) => x !== 'invalid',
},
'./data': { scheduleStacks: jobs },
'../cron/execution/runCron': { runCron },
'../loaders/logger': logger,
'../shared/i18n': { t: (s) => s, tf: (s) => s },
});
const { delCron } = load('back/schedule/delCron.ts', {
'./data': { scheduleStacks: jobs },
'../loaders/logger': logger,
});
function add(id = '1', command = 'old', replace = false) {
records.set(id, { isDisabled: 0, allow_multiple_instances: 1 });
addCron(
{
request: { crons: [{ id, command, schedule: '* * * * * *' }], replace },
},
(err) => assert.ifError(err),
);
return jobs.get(id)[0];
}
function remove(id = '1') {
delCron({ request: { ids: [id] } }, (err) => assert.ifError(err));
}
async function block() {
const g = gate();
const done = limit.runWithCronLimit({ id: 'blocker' }, async () => {
await g.promise;
});
await tick();
return {
release: async () => {
g.release();
await done;
},
};
}
return {
limit,
spawned,
records,
jobs,
add,
remove,
block,
notices,
setReadGate: (g) => (readGate = g),
setKillGate: (g) => (killGate = g),
};
}
for (const operation of [
'disable',
'delete',
'update',
'replace',
'disable-enable',
]) {
test(`queued scheduled execution is invalidated by ${operation}`, async () => {
const f = await fixture(), old = f.add(), blocker = await f.block();
const f = await fixture(),
old = f.add(),
blocker = await f.block();
const queued = old.fire();
if (operation === 'disable' || operation === 'disable-enable') { f.records.get('1').isDisabled = 1; f.remove(); }
if (operation === 'delete') { f.records.delete('1'); f.remove(); }
if (operation === 'disable' || operation === 'disable-enable') {
f.records.get('1').isDisabled = 1;
f.remove();
}
if (operation === 'delete') {
f.records.delete('1');
f.remove();
}
if (operation === 'update') f.add('1', 'new');
if (operation === 'replace') f.add('1', 'new', true);
if (operation === 'disable-enable') f.add('1', 'old');
const next = f.jobs.get('1')?.[0].fire();
await blocker.release(); await queued; await next;
assert.deepEqual(f.spawned, ['update', 'replace'].includes(operation) ? ['new'] : operation === 'disable-enable' ? ['old'] : []);
await blocker.release();
await queued;
await next;
assert.deepEqual(
f.spawned,
['update', 'replace'].includes(operation)
? ['new']
: operation === 'disable-enable'
? ['old']
: [],
);
assert.equal(f.limit.cronLimitPendingCount, 0);
assert.equal(f.limit.cronLimitActiveCount, 0);
});
}
test('stale callbacks cannot re-enqueue after cancellation', async () => {
const f = await fixture(), old = f.add(); f.remove(); await old.fire();
const f = await fixture(),
old = f.add();
f.remove();
await old.fire();
assert.deepEqual(f.spawned, []);
});
test('invalidation during an asynchronous database read prevents spawning', async () => {
const f = await fixture(), old = f.add(), pending = gate(); f.setReadGate(pending);
const run = old.fire(); await tick(); f.remove(); pending.release(); await run;
const f = await fixture(),
old = f.add(),
pending = gate();
f.setReadGate(pending);
const run = old.fire();
await tick();
f.remove();
pending.release();
await run;
assert.deepEqual(f.spawned, []);
});
test('invalidation while replacing a running instance prevents the old spawn', async () => {
const f = await fixture(), old = f.add(), pending = gate();
f.records.set('1', { isDisabled: 0, allow_multiple_instances: 0, pid: 10, status: 0 }); f.setKillGate(pending);
const run = old.fire(); await tick(); f.remove(); pending.release(); await run;
const f = await fixture(),
old = f.add(),
pending = gate();
f.records.set('1', {
isDisabled: 0,
allow_multiple_instances: 0,
pid: 10,
status: 0,
});
f.setKillGate(pending);
const run = old.fire();
await tick();
f.remove();
pending.release();
await run;
assert.deepEqual(f.spawned, []);
});
test('database removal or disable is respected before scheduler RPC arrives', async () => {
for (const disabled of [true, false]) {
const f = await fixture(), old = f.add(), blocker = await f.block(); const run = old.fire();
if (disabled) f.records.get('1').isDisabled = 1; else f.records.delete('1');
await blocker.release(); await run; assert.deepEqual(f.spawned, []);
const f = await fixture(),
old = f.add(),
blocker = await f.block();
const run = old.fire();
if (disabled) f.records.get('1').isDisabled = 1;
else f.records.delete('1');
await blocker.release();
await run;
assert.deepEqual(f.spawned, []);
}
});
test('five stale runs do not suppress the new revision or erase its repeat accounting', async () => {
const f = await fixture(), old = f.add(), blocker = await f.block();
const f = await fixture(),
old = f.add(),
blocker = await f.block();
const pending = Array.from({ length: 5 }, () => old.fire());
const current = f.add('1', 'new'); pending.push(...Array.from({ length: 5 }, () => current.fire()));
const current = f.add('1', 'new');
pending.push(...Array.from({ length: 5 }, () => current.fire()));
assert.equal(f.notices.length, 0);
await blocker.release(); await Promise.all(pending);
await blocker.release();
await Promise.all(pending);
assert.deepEqual(f.spawned, Array(5).fill('new'));
await current.fire(); assert.equal(f.spawned.length, 6);
await current.fire();
assert.equal(f.spawned.length, 6);
});
+106 -25
View File
@@ -18,43 +18,82 @@ test('CI uses the pinned production Node, retaining explicit compatibility cover
for (const file of ['docker/Dockerfile', 'docker/Dockerfile.310']) {
const versions = [...read(file).matchAll(/\bnode:(\d+\.\d+\.\d+)-alpine/g)];
assert.ok(versions.length >= 2, file);
for (const [, version] of versions) assert.equal(version, productionNode, file);
for (const [, version] of versions)
assert.equal(version, productionNode, file);
const packageVersion = read(file).match(/\bnodejs=(\d+\.\d+\.\d+)-r\d+/);
assert.ok(packageVersion, `${file}: pin the Alpine Node package`);
assert.equal(packageVersion[1], productionNode, file);
assert.ok(read(file).includes(`test "$(node --version)" = "v${productionNode}"`), file);
assert.ok(
read(file).includes(`test "$(node --version)" = "v${productionNode}"`),
file,
);
}
assert.equal(read('docker/install-node-debian.sh').match(/^version=(.*)$/m)[1], productionNode);
for (const file of ['docker/Dockerfile.debian', 'docker/Dockerfile.debian310']) {
assert.equal(
read('docker/install-node-debian.sh').match(/^version=(.*)$/m)[1],
productionNode,
);
for (const file of [
'docker/Dockerfile.debian',
'docker/Dockerfile.debian310',
]) {
const versions = [...read(file).matchAll(/"v(\d+\.\d+\.\d+)"/g)];
assert.ok(versions.length >= 2, file);
for (const [, version] of versions) assert.equal(version, productionNode, file);
for (const [, version] of versions)
assert.equal(version, productionNode, file);
}
for (const name of ['validate', 'release-readiness', 'build-docker-image', 'cli-package']) {
for (const name of [
'validate',
'release-readiness',
'build-docker-image',
'cli-package',
]) {
for (const [jobName, job] of Object.entries(workflow(name).jobs)) {
const steps = job.steps || [];
for (const [index, step] of steps.entries()) {
if (!step.uses?.startsWith('actions/setup-node@')) continue;
assert.equal(step.with['node-version-file'], '.nvmrc', `${name}/${jobName}`);
assert.ok(steps.slice(0, index).some((s) => s.uses?.startsWith('actions/checkout@')), `${name}/${jobName}: checkout before version file`);
assert.equal(
step.with['node-version-file'],
'.nvmrc',
`${name}/${jobName}`,
);
assert.ok(
steps
.slice(0, index)
.some((s) => s.uses?.startsWith('actions/checkout@')),
`${name}/${jobName}: checkout before version file`,
);
const version = step.with['node-version'];
if (!version) continue;
assert.equal(name, 'cli-package');
assert.equal(jobName, 'package');
for (const node of job.strategy.matrix.node) {
const resolved = vm.runInNewContext(version.slice(3, -2), { matrix: { node } });
assert.equal(resolved || productionNode, node === '22.12.0' ? node : productionNode);
const resolved = vm.runInNewContext(version.slice(3, -2), {
matrix: { node },
});
assert.equal(
resolved || productionNode,
node === '22.12.0' ? node : productionNode,
);
}
}
}
}
const build = workflow('build-docker-image');
const runtime = build.jobs['build-static'].steps.find((s) => s.id === 'runtime');
const runtime = build.jobs['build-static'].steps.find(
(s) => s.id === 'runtime',
);
assert.match(runtime.run, /cat \.nvmrc/);
assert.equal(build.jobs['build-static'].outputs['node-version'], '${{ steps.runtime.outputs.node-version }}');
assert.equal(
build.jobs['build-static'].outputs['node-version'],
'${{ steps.runtime.outputs.node-version }}',
);
const verify = build.jobs['verify-npm-package'];
const expression = verify.container.match(/\$\{\{(.*?)\}\}/)[1]
.replace('needs.build-static.outputs.node-version', JSON.stringify(productionNode));
const expression = verify.container
.match(/\$\{\{(.*?)\}\}/)[1]
.replace(
'needs.build-static.outputs.node-version',
JSON.stringify(productionNode),
);
for (const node of verify.strategy.matrix.node) {
const version = vm.runInNewContext(expression, { matrix: { node } });
assert.equal(version, node === '20.18.1' ? node : productionNode);
@@ -63,10 +102,19 @@ test('CI uses the pinned production Node, retaining explicit compatibility cover
test('release readiness runs the source verifier offline and watches its inputs', () => {
const readiness = workflow('release-readiness');
for (const file of ['.nvmrc', '.github/workflows/validate.yml', 'docker/install-node-debian.sh', 'scripts/verify-runtime-dependencies.cjs', 'test/back/release-runtime-alignment.test.cjs']) {
for (const file of [
'.nvmrc',
'.github/workflows/validate.yml',
'docker/install-node-debian.sh',
'scripts/verify-runtime-dependencies.cjs',
'test/back/release-runtime-alignment.test.cjs',
]) {
assert.ok(readiness.on.pull_request.paths.includes(file), file);
}
const step = readiness.jobs.images.steps.find((s) => s.name === 'Verify native production runtime without external networking');
const step = readiness.jobs.images.steps.find(
(s) =>
s.name === 'Verify native production runtime without external networking',
);
assert.match(step.run, /docker run --rm -i --network none --entrypoint node/);
assert.match(step.run, /< scripts\/verify-runtime-dependencies\.cjs/);
});
@@ -79,33 +127,56 @@ function fixture(t) {
const write = (file, data) => {
const target = path.join(directory, file);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, typeof data === 'string' ? data : JSON.stringify(data));
fs.writeFileSync(
target,
typeof data === 'string' ? data : JSON.stringify(data),
);
};
const install = (name, version, parent) => {
const prefix = `node_modules/${parent ? `${parent}/node_modules/` : ''}${name}`;
const prefix = `node_modules/${
parent ? `${parent}/node_modules/` : ''
}${name}`;
write(`${prefix}/package.json`, { name, version, main: 'index.js' });
write(`${prefix}/index.js`, 'module.exports = {};');
};
for (const name of ['@grpc/grpc-js', 'compression', 'multer', 'sequelize', 'express', 'sockjs']) {
for (const name of [
'@grpc/grpc-js',
'compression',
'multer',
'sequelize',
'express',
'sockjs',
]) {
manifest.dependencies[name] = '1.0.0';
lock.dependencies[name] = { specifier: '1.0.0', version: '1.0.0' };
install(name, '1.0.0');
}
for (const [parent, name] of [['express', 'proxy-addr'], ['sockjs', 'websocket-driver']]) {
for (const [parent, name] of [
['express', 'proxy-addr'],
['sockjs', 'websocket-driver'],
]) {
lock.packages[`/${parent}@1.0.0`] = { dependencies: { [name]: '1.0.0' } };
install(name, '1.0.0', parent);
// A healthy root copy must not mask a stale copy resolved by the parent.
install(name, '1.0.0');
}
for (const name of ['sqlite3', 'nodemailer', 'undici']) install(name, '1.0.0');
for (const name of ['sqlite3', 'nodemailer', 'undici'])
install(name, '1.0.0');
write('.nvmrc', process.versions.node);
lock.dependencies.sequelize.version = '1.0.0(@whyour/sqlite3@1.1.5)';
const run = (stdin = false) => {
write('package.json', manifest);
write('pnpm-lock.yaml', yaml.dump(lock));
return spawnSync(process.execPath, stdin ? [] : [verifier], {
cwd: directory, encoding: 'utf8', timeout: 10000,
...(stdin ? { input: fs.readFileSync(verifier, 'utf8'), env: { ...process.env, NODE_PATH: path.join(root, 'node_modules') } } : {}),
cwd: directory,
encoding: 'utf8',
timeout: 10000,
...(stdin
? {
input: fs.readFileSync(verifier, 'utf8'),
env: { ...process.env, NODE_PATH: path.join(root, 'node_modules') },
}
: {}),
});
};
return { manifest, lock, install, run, write };
@@ -124,7 +195,14 @@ test('runtime verification follows dependency upgrades without a second version
}
});
for (const scenario of ['node-version', 'manifest', 'direct', 'transitive', 'missing-lock', 'missing-import']) {
for (const scenario of [
'node-version',
'manifest',
'direct',
'transitive',
'missing-lock',
'missing-import',
]) {
test(`runtime verification rejects ${scenario} drift`, (t) => {
const f = fixture(t);
let expected;
@@ -144,7 +222,10 @@ for (const scenario of ['node-version', 'manifest', 'direct', 'transitive', 'mis
delete f.lock.packages['/sockjs@1.0.0'];
expected = /sockjs > websocket-driver: missing lock entry/;
} else {
f.write('node_modules/sqlite3/index.js', 'throw new Error("native binding unavailable")');
f.write(
'node_modules/sqlite3/index.js',
'throw new Error("native binding unavailable")',
);
expected = /native binding unavailable/;
}
const result = f.run();
+48 -15
View File
@@ -19,26 +19,42 @@ test('startup closes interrupted instances without inventing exit codes or rewri
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 });
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 db.transaction((tx) =>
require('../../back/cron/history').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 { TriggerHistory, systemOwner } = require('../../back/cron/history');
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 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 = {
set_envs: async () => { startupEvents.push('environment'); },
set_envs: async () => {
startupEvents.push('environment');
},
getAuthInfo: async () => ({}),
initializeSystemApp: async () => {},
refreshApps: async () => {},
@@ -52,7 +68,11 @@ test('startup closes interrupted instances without inventing exit codes or rewri
'../services/user': class {},
'../services/open': class {},
'../data/cron': {
CrontabModel: { sequelize: db, update: async () => {}, findAll: async () => [] },
CrontabModel: {
sequelize: db,
update: async () => {},
findAll: async () => [],
},
CrontabStatus: { idle: 1 },
},
'../data/dependence': {
@@ -85,7 +105,9 @@ test('startup closes interrupted instances without inventing exit codes or rewri
'../schedule/client': {
readiness: {
configure() {},
recover: async () => { startupEvents.push('scheduler'); },
recover: async () => {
startupEvents.push('scheduler');
},
},
},
}).default;
@@ -99,9 +121,13 @@ test('startup closes interrupted instances without inventing exit codes or rewri
global.setTimeout = originalTimeout;
}
assert.deepEqual(startupEvents, ['environment', 'scheduler']);
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((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 &&
@@ -129,10 +155,17 @@ test('startup closes interrupted instances without inventing exit codes or rewri
global.setTimeout = originalTimeout;
}
assert.deepEqual(startupEvents, [
'environment', 'scheduler', 'environment', 'scheduler',
'environment',
'scheduler',
'environment',
'scheduler',
]);
assert.deepEqual(
await instances.findAll({ where:{id:[1,2,3,4]}, order: [['id', 'ASC']], raw: true }),
await instances.findAll({
where: { id: [1, 2, 3, 4] },
order: [['id', 'ASC']],
raw: true,
}),
rows,
);
});
+2 -1
View File
@@ -107,7 +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('SELECT COUNT(*) AS count FROM CronTriggers'))
return [{ count: 4 }];
if (query.startsWith('DELETE FROM CronTriggers')) return 4;
vacuumed = query === 'VACUUM';
return [];
+92 -28
View File
@@ -2,39 +2,103 @@ const test = require('node:test');
const assert = require('node:assert/strict');
const grpc = require('@grpc/grpc-js');
const load = require('../helpers/load-security-module.cjs');
const { SchedulerReadiness } = require('../../back/shared/schedulerReadiness');
const {
SchedulerReadiness,
} = require('../../back/cron/scheduling/schedulerReadiness');
for (const [name, rows, delay, succeeds] of [
['large distinct snapshot', Array.from({length:10000}, (_, i) => ({id:String(i), schedule:`${i%60} ${Math.floor(i/60)%60} ${Math.floor(i/3600)} * * *`})), 10000, true],
['extra schedules', [{id:'extra', schedule:'* * * * *', extra_schedules:Array.from({length:2000},()=>({schedule:'0 * * * *'}))}], 10000, true],
['unresponsive small write', [{id:'small', schedule:'* * * * *'}], 30000, false],
['unresponsive large write remains bounded', Array.from({length:30000},()=>({schedule:'* * * * *'})), 180000, false],
[
'large distinct snapshot',
Array.from({ length: 10000 }, (_, i) => ({
id: String(i),
schedule: `${i % 60} ${Math.floor(i / 60) % 60} ${Math.floor(
i / 3600,
)} * * *`,
})),
10000,
true,
],
[
'extra schedules',
[
{
id: 'extra',
schedule: '* * * * *',
extra_schedules: Array.from({ length: 2000 }, () => ({
schedule: '0 * * * *',
})),
},
],
10000,
true,
],
[
'unresponsive small write',
[{ id: 'small', schedule: '* * * * *' }],
30000,
false,
],
[
'unresponsive large write remains bounded',
Array.from({ length: 30000 }, () => ({ schedule: '* * * * *' })),
180000,
false,
],
]) {
test(`recovery deadline: ${name}`, async (t) => {
t.mock.timers.enable({apis:['Date','setTimeout'], now:0});
let calls=0, deadline;
const fake={waitForReady:(_,cb)=>cb(), addCron:(_req,_meta,options,cb)=>{
calls++; deadline=options.deadline;
const budget=deadline-Date.now();
setTimeout(()=>cb(delay<=budget ? null : Object.assign(Error('deadline'),{code:grpc.status.DEADLINE_EXCEEDED}), {}), Math.min(delay,budget));
}};
const client=load('back/schedule/client.ts', {
'../protos/cron':{...require('../../back/protos/cron'),CronClient:class{constructor(){return fake}}},
'../config':{grpcPort:5500},
'../config/grpcCerts':{getGrpcCerts:()=>({caCert:'ca',clientKey:'key',clientCert:'cert'})},
'@grpc/grpc-js':{...grpc,credentials:{createSsl:()=>({})}},
t.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 0 });
let calls = 0,
deadline;
const fake = {
waitForReady: (_, cb) => cb(),
addCron: (_req, _meta, options, cb) => {
calls++;
deadline = options.deadline;
const budget = deadline - Date.now();
setTimeout(
() =>
cb(
delay <= budget
? null
: Object.assign(Error('deadline'), {
code: grpc.status.DEADLINE_EXCEEDED,
}),
{},
),
Math.min(delay, budget),
);
},
};
const client = load('back/schedule/client.ts', {
'../protos/cron': {
...require('../../back/protos/cron'),
CronClient: class {
constructor() {
return fake;
}
},
},
'../config': { grpcPort: 5500 },
'../config/grpcCerts': {
getGrpcCerts: () => ({
caCert: 'ca',
clientKey: 'key',
clientCert: 'cert',
}),
},
'@grpc/grpc-js': { ...grpc, credentials: { createSsl: () => ({}) } },
}).default;
const readiness=new SchedulerReadiness(async()=>{}, 60000);
t.after(()=>clearTimeout(readiness.retry));
client.readiness=readiness;
readiness.configure(()=>client.addCron(rows,true));
const recovering=readiness.recover();
const readiness = new SchedulerReadiness(async () => {}, 60000);
t.after(() => clearTimeout(readiness.retry));
client.readiness = readiness;
readiness.configure(() => client.addCron(rows, true));
const recovering = readiness.recover();
await new Promise(setImmediate);
assert.equal(calls,1);
assert.ok(deadline<=120000);
t.mock.timers.tick(Math.min(delay,deadline));
assert.equal(await recovering,succeeds);
assert.equal(calls,1,'uncertain writes are not replayed inline');
assert.equal(await readiness.check(),succeeds);
assert.equal(calls, 1);
assert.ok(deadline <= 120000);
t.mock.timers.tick(Math.min(delay, deadline));
assert.equal(await recovering, succeeds);
assert.equal(calls, 1, 'uncertain writes are not replayed inline');
assert.equal(await readiness.check(), succeeds);
});
}
+14 -14
View File
@@ -8,20 +8,20 @@ const load = require('../helpers/load-security-module.cjs');
const logger = { info() {}, debug() {}, warn() {}, error() {} };
const tick = () => new Promise(setImmediate);
function createLimit() {
return load('back/shared/pLimit.ts', {
'../data/system': {
return load('back/cron/execution/cronLimit.ts', {
'../../data/system': {
AuthDataType: { systemConfig: 'systemConfig' },
SystemModel: {
sync: async () => {},
findOne: async () => ({ info: { cronConcurrency: 1 } }),
},
},
'../loaders/logger': logger,
'../services/notify': class {},
'../shared/i18n': { t: (x) => x, tf: (x) => x },
'../config': {},
'../config/grpcCerts': { getGrpcCerts: () => null },
'../protos/api': {},
'../../loaders/logger': logger,
'../../services/notify': class {},
'../../shared/i18n': { t: (x) => x, tf: (x) => x },
'../../config': {},
'../../config/grpcCerts': { getGrpcCerts: () => null },
'../../protos/api': {},
}).default;
}
function createSystem(client, limit, options = {}) {
@@ -35,9 +35,9 @@ function createSystem(client, limit, options = {}) {
const writes = [];
const Service = load('back/services/system.ts', {
'../config': options.config || {},
'../shared/schedulerMutationLock': options.config
? load('back/shared/schedulerMutationLock.ts', {
'../config': options.config,
'../cron/scheduling/schedulerMutationLock': options.config
? load('back/cron/scheduling/schedulerMutationLock.ts', {
'../../config/index': options.config,
})
: { withSchedulerMutation: (operation) => operation() },
'../config/const': {},
@@ -57,7 +57,7 @@ function createSystem(client, limit, options = {}) {
},
},
},
'../shared/pLimit': limit,
'../cron/execution/cronLimit': limit,
'../schedule/client': client,
'../shared/i18n': { t: (x) => x },
'./notify': class {},
@@ -82,7 +82,7 @@ async function rpcFixture(t) {
apiLimit = createLimit();
await tick();
const handler = load('back/schedule/setConcurrency.ts', {
'../shared/pLimit': schedulerLimit,
'../cron/execution/cronLimit': schedulerLimit,
});
let port;
const Grpc = load('back/services/grpc.ts', {
@@ -214,7 +214,7 @@ test('invalid concurrency is rejected before configuration writes or queue chang
assert.deepEqual(f.writes, []);
assert.deepEqual(mutations, []);
const handler = load('back/schedule/setConcurrency.ts', {
'../shared/pLimit': {
'../cron/execution/cronLimit': {
setCustomLimit: async (value) => mutations.push(value),
},
}).setConcurrency;
+2 -2
View File
@@ -17,9 +17,9 @@ for (const failOperation of [false, true]) {
const config = { crontabFile: path.join(root, 'crontab.list') };
await fs.writeFile(config.crontabFile, '');
const { withSchedulerMutation } = load(
'back/shared/schedulerMutationLock.ts',
'back/cron/scheduling/schedulerMutationLock.ts',
{
'../config': config,
'../../config/index': config,
},
);
const { writeFileWithLock } = load('back/shared/utils.ts', {
+20 -10
View File
@@ -66,7 +66,7 @@ async function fixture(t) {
'../config/util': { isDemoEnv: () => false },
'../config/const': {},
'../schedule/client': client,
'../shared/pLimit': {},
'../cron/execution/cronLimit': {},
'../shared/utils': {},
'../shared/i18n': { t: (s) => s },
'../shared/logReader': {},
@@ -179,7 +179,8 @@ for (const operation of ['create', 'update', 'enabled']) {
await assert.rejects(
mutation,
(err) =>
err.status === 503 && err.cause === cause &&
err.status === 503 &&
err.cause === cause &&
(operation === 'update' ? /原调度未能恢复/ : /回滚/).test(err.message),
);
if (operation === 'create') assert.equal(await crons.count(), 0);
@@ -204,8 +205,8 @@ test(
t.after(() => fs.rm(root, { recursive: true, force: true }));
const config = { crontabFile: path.join(root, 'crontab.list') };
const { withSchedulerMutation } = load(
'back/shared/schedulerMutationLock.ts',
{ '../config': config },
'back/cron/scheduling/schedulerMutationLock.ts',
{ '../../config/index': config },
);
const entered = gate(),
release = gate();
@@ -220,7 +221,7 @@ test(
'-e',
`
const load = require('./test/helpers/load-security-module.cjs');
const { withSchedulerMutation } = load('back/shared/schedulerMutationLock.ts', {'../config': JSON.parse(process.argv[1])});
const { withSchedulerMutation } = load('back/cron/scheduling/schedulerMutationLock.ts', {"../../config/index": JSON.parse(process.argv[1])});
process.send('attempting');
withSchedulerMutation(async () => process.send('entered')).then(() => process.disconnect()).catch(err => { console.error(err); process.exit(1); });
`,
@@ -257,13 +258,20 @@ for (const operation of ['update', 'remove', 'disabled']) {
test(`${operation} aborts on RPC ${code} with deletion applied=${applied} and reconciles the original DB`, async (t) => {
const { service, crons, client, jobs } = await fixture(t);
await crons.create({
id: 1, command: 'old', schedule: '* * * * *', isDisabled: 0,
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';
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 });
const failure = Object.assign(Error('uncertain deletion'), {
code,
status: 503,
});
let deletes = 0;
client.delCron = async (ids) => {
deletes++;
@@ -271,8 +279,10 @@ for (const operation of ['update', 'remove', 'disabled']) {
throw failure;
};
const add = client.addCron;
client.addCron = async () => assert.fail('must not register after failed deletion');
service.setCrontab = async () => assert.fail('must not publish after failed deletion');
client.addCron = async () =>
assert.fail('must not register after failed deletion');
service.setCrontab = async () =>
assert.fail('must not publish after failed deletion');
await assert.rejects(
operation === 'update'
? service.update({ id: 1, command: 'new', schedule: '@once' })
+240 -88
View File
@@ -1,98 +1,250 @@
const test=require('node:test');
const assert=require('node:assert/strict');
const {setTimeout:sleep}=require('node:timers/promises');
const {SchedulerReadiness}=require('../../back/shared/schedulerReadiness');
const load=require('../helpers/load-security-module.cjs');
const fs=require('node:fs');
const ts=require('typescript');
const test = require('node:test');
const assert = require('node:assert/strict');
const { setTimeout: sleep } = require('node:timers/promises');
const {
SchedulerReadiness,
} = require('../../back/cron/scheduling/schedulerReadiness');
const load = require('../helpers/load-security-module.cjs');
const fs = require('node:fs');
const ts = require('typescript');
test('readiness stays false through failed restoration and retries without idle polling',async()=>{
let probes=0,restores=0,fail=true;
const state=new SchedulerReadiness(async()=>{probes++;},10);
state.configure(async()=>{restores++;if(fail)throw Error('registration failed');});
assert.equal(await state.recover(),false);assert.equal(await state.check(),false);
fail=false;await sleep(40);assert.equal(await state.check(),true);assert.ok(restores>=2);
const before=probes;await sleep(40);assert.equal(probes,before);
test('readiness stays false through failed restoration and retries without idle polling', async () => {
let probes = 0,
restores = 0,
fail = true;
const state = new SchedulerReadiness(async () => {
probes++;
}, 10);
state.configure(async () => {
restores++;
if (fail) throw Error('registration failed');
});
assert.equal(await state.recover(), false);
assert.equal(await state.check(), false);
fail = false;
await sleep(40);
assert.equal(await state.check(), true);
assert.ok(restores >= 2);
const before = probes;
await sleep(40);
assert.equal(probes, before);
});
test('single-flight recovery cannot mark an invalidated generation ready',async()=>{
let release,restores=0;
const state=new SchedulerReadiness(async()=>{},10);
state.configure(async()=>{if(++restores===1)await new Promise(r=>release=r);});
const a=state.recover();assert.equal(state.recover(),a);await sleep(1);
state.invalidate();release();assert.equal(await a,false);assert.equal(await state.check(),false);
await sleep(30);assert.equal(await state.check(),true);assert.equal(restores,2);
test('single-flight recovery cannot mark an invalidated generation ready', async () => {
let release,
restores = 0;
const state = new SchedulerReadiness(async () => {}, 10);
state.configure(async () => {
if (++restores === 1) await new Promise((r) => (release = r));
});
const a = state.recover();
assert.equal(state.recover(), a);
await sleep(1);
state.invalidate();
release();
assert.equal(await a, false);
assert.equal(await state.check(), false);
await sleep(30);
assert.equal(await state.check(), true);
assert.equal(restores, 2);
});
test('mutation waiting is bounded, a later recovery can succeed',async()=>{
let release;
const state=new SchedulerReadiness(async()=>{},10);state.configure(()=>new Promise(r=>release=r));
await assert.rejects(state.ensureReady(15),e=>e.status===503);
release();await sleep(1);assert.equal(await state.check(),true);
test('mutation waiting is bounded, a later recovery can succeed', async () => {
let release;
const state = new SchedulerReadiness(async () => {}, 10);
state.configure(() => new Promise((r) => (release = r)));
await assert.rejects(state.ensureReady(15), (e) => e.status === 503);
release();
await sleep(1);
assert.equal(await state.check(), true);
});
test('probe failure immediately invalidates a previously ready scheduler',async()=>{
let fail=false;
const state=new SchedulerReadiness(async()=>{if(fail)throw Error('unavailable');},10);
state.configure(async()=>{});assert.equal(await state.recover(),true);
fail=true;assert.equal(await state.check(),false);
fail=false;await sleep(40);assert.equal(await state.check(),true);
test('probe failure immediately invalidates a previously ready scheduler', async () => {
let fail = false;
const state = new SchedulerReadiness(async () => {
if (fail) throw Error('unavailable');
}, 10);
state.configure(async () => {});
assert.equal(await state.recover(), true);
fail = true;
assert.equal(await state.check(), false);
fail = false;
await sleep(40);
assert.equal(await state.check(), true);
});
test('health uses actual readiness and returns HTTP 503 until recovery',async(t)=>{
let ready=false;const express=require('express');
const {HealthService}=load('back/services/health.ts',{
typedi:{Service:()=>x=>x},'../loaders/logger':{error(){}},'./http':{},
'../schedule/client':{readiness:{check:async()=>ready}},
});
const service=new HealthService({getServer:()=>({})});
const app=express();load('back/api/health.ts',{
typedi:{get:()=>service},'../services/health':{HealthService},'../loaders/logger':{error(){}},
}).default(app);
const server=app.listen(0,'127.0.0.1');await new Promise(r=>server.once('listening',r));
t.after(()=>new Promise(r=>{server.close(r);server.closeAllConnections();}));
for(const expected of [503,200,503]){
ready=expected===200;const r=await fetch(`http://127.0.0.1:${server.address().port}/health`);const b=await r.json();
assert.equal(r.status,expected);assert.equal(b.code,expected);assert.equal(b.data.services.grpc,ready);
}
test('health uses actual readiness and returns HTTP 503 until recovery', async (t) => {
let ready = false;
const express = require('express');
const { HealthService } = load('back/services/health.ts', {
typedi: { Service: () => (x) => x },
'../loaders/logger': { error() {} },
'./http': {},
'../schedule/client': { readiness: { check: async () => ready } },
});
const service = new HealthService({ getServer: () => ({}) });
const app = express();
load('back/api/health.ts', {
typedi: { get: () => service },
'../services/health': { HealthService },
'../loaders/logger': { error() {} },
}).default(app);
const server = app.listen(0, '127.0.0.1');
await new Promise((r) => server.once('listening', r));
t.after(
() =>
new Promise((r) => {
server.close(r);
server.closeAllConnections();
}),
);
for (const expected of [503, 200, 503]) {
ready = expected === 200;
const r = await fetch(`http://127.0.0.1:${server.address().port}/health`);
const b = await r.json();
assert.equal(r.status, expected);
assert.equal(b.code, expected);
assert.equal(b.data.services.grpc, ready);
}
});
test('health failure does not reveal internal error details',async(t)=>{
const express=require('express');
const HealthService=class{};
const app=express();load('back/api/health.ts',{
typedi:{get:()=>({check:async()=>{throw Error('sensitive health detail');}})},
'../services/health':{HealthService},'../loaders/logger':{error(){}},
}).default(app);
const server=app.listen(0,'127.0.0.1');await new Promise(r=>server.once('listening',r));
t.after(()=>new Promise(r=>{server.close(r);server.closeAllConnections();}));
const response=await fetch(`http://127.0.0.1:${server.address().port}/health`);
assert.equal(response.status,500);
assert.deepEqual(await response.json(),{code:500,message:'Health check failed'});
test('health failure does not reveal internal error details', async (t) => {
const express = require('express');
const HealthService = class {};
const app = express();
load('back/api/health.ts', {
typedi: {
get: () => ({
check: async () => {
throw Error('sensitive health detail');
},
}),
},
'../services/health': { HealthService },
'../loaders/logger': { error() {} },
}).default(app);
const server = app.listen(0, '127.0.0.1');
await new Promise((r) => server.once('listening', r));
t.after(
() =>
new Promise((r) => {
server.close(r);
server.closeAllConnections();
}),
);
const response = await fetch(
`http://127.0.0.1:${server.address().port}/health`,
);
assert.equal(response.status, 500);
assert.deepEqual(await response.json(), {
code: 500,
message: 'Health check failed',
});
});
test('recovery registration errors propagate while ordinary autosave retains file synchronization',async()=>{
const source=fs.readFileSync('back/services/cron.ts','utf8');const a=source.indexOf(' public async autosave_crontab('),z=source.indexOf(' public async bootTask',a);
const js=ts.transpileModule('class Fixture {\n'+source.slice(a,z)+'}\nmodule.exports=Fixture;', {compilerOptions:{target:ts.ScriptTarget.ES2020}}).outputText;
const module={exports:{}};let files=0;
new Function('module','isDemoEnv','cronClient','withSchedulerMutation',js)(module,()=>false,{addCron:async()=>{throw Error('registration unavailable');}},fn=>fn());
const fixture=new module.exports();fixture.crontabs=async()=>({data:[]});fixture.setCrontab=async()=>{files++;};fixture.logger={warn(){}};
await fixture.autosave_crontab();assert.equal(files,1);
await assert.rejects(fixture.autosave_crontab(true),/registration unavailable/);assert.equal(files,2);
test('recovery registration errors propagate while ordinary autosave retains file synchronization', async () => {
const source = fs.readFileSync('back/services/cron.ts', 'utf8');
const a = source.indexOf(' public async autosave_crontab('),
z = source.indexOf(' public async bootTask', a);
const js = ts.transpileModule(
'class Fixture {\n' + source.slice(a, z) + '}\nmodule.exports=Fixture;',
{ compilerOptions: { target: ts.ScriptTarget.ES2020 } },
).outputText;
const module = { exports: {} };
let files = 0;
new Function(
'module',
'isDemoEnv',
'cronClient',
'withSchedulerMutation',
js,
)(
module,
() => false,
{
addCron: async () => {
throw Error('registration unavailable');
},
},
(fn) => fn(),
);
const fixture = new module.exports();
fixture.crontabs = async () => ({ data: [] });
fixture.setCrontab = async () => {
files++;
};
fixture.logger = { warn() {} };
await fixture.autosave_crontab();
assert.equal(files, 1);
await assert.rejects(
fixture.autosave_crontab(true),
/registration unavailable/,
);
assert.equal(files, 2);
});
test('scheduler probe uses the cron channel and failed writes are not replayed',async()=>{
const calls=[];const fake={
waitForReady(deadline,cb){calls.push(['wait',deadline]);cb();},
makeUnaryRequest(path,serialize,deserialize,request,options,cb){calls.push(['probe',path,request,options]);cb(null,{status:1});},
addCron(request,metadata,options,cb){calls.push(['add',request,options]);cb(Object.assign(Error('invalid'),{code:3}));},
};
const client=load('back/schedule/client.ts',{
'../protos/cron':{...require('../../back/protos/cron'),CronClient:class{constructor(){return fake;}}},
'../config':{grpcPort:5500},'../config/grpcCerts':{getGrpcCerts:()=>({caCert:'ca',clientKey:'key',clientCert:'cert'})},
'@grpc/grpc-js':{...require('@grpc/grpc-js'),credentials:{createSsl:()=>({})},status:{UNAVAILABLE:14},Metadata:class{}},
}).default;
client.readiness.configure(async()=>{});assert.equal(await client.readiness.recover(),true);
assert.ok(calls.filter(x=>x[0]==='probe').every(x=>x[1]==='/com.ql.health.Health/Check'&&x[2].service==='scheduler'&&x[3].deadline>Date.now()));
await assert.rejects(client.addCron([]),/invalid/);assert.equal(calls.filter(x=>x[0]==='add').length,1);
test('scheduler probe uses the cron channel and failed writes are not replayed', async () => {
const calls = [];
const fake = {
waitForReady(deadline, cb) {
calls.push(['wait', deadline]);
cb();
},
makeUnaryRequest(path, serialize, deserialize, request, options, cb) {
calls.push(['probe', path, request, options]);
cb(null, { status: 1 });
},
addCron(request, metadata, options, cb) {
calls.push(['add', request, options]);
cb(Object.assign(Error('invalid'), { code: 3 }));
},
};
const client = load('back/schedule/client.ts', {
'../protos/cron': {
...require('../../back/protos/cron'),
CronClient: class {
constructor() {
return fake;
}
},
},
'../config': { grpcPort: 5500 },
'../config/grpcCerts': {
getGrpcCerts: () => ({
caCert: 'ca',
clientKey: 'key',
clientCert: 'cert',
}),
},
'@grpc/grpc-js': {
...require('@grpc/grpc-js'),
credentials: { createSsl: () => ({}) },
status: { UNAVAILABLE: 14 },
Metadata: class {},
},
}).default;
client.readiness.configure(async () => {});
assert.equal(await client.readiness.recover(), true);
assert.ok(
calls
.filter((x) => x[0] === 'probe')
.every(
(x) =>
x[1] === '/com.ql.health.Health/Check' &&
x[2].service === 'scheduler' &&
x[3].deadline > Date.now(),
),
);
await assert.rejects(client.addCron([]), /invalid/);
assert.equal(calls.filter((x) => x[0] === 'add').length, 1);
});
test('scheduler health probe never calls back into HTTP health',async()=>{
const {check}=load('back/schedule/health.ts',{
'../config':{},undici:{request:()=>{throw Error('recursive HTTP health call');}},
});
const result=await new Promise(resolve=>check({request:{service:'scheduler'}},(error,response)=>resolve({error,response})));
assert.equal(result.error,null);assert.deepEqual(result.response,{status:1});
test('scheduler health probe never calls back into HTTP health', async () => {
const { check } = load('back/schedule/health.ts', {
'../config': {},
undici: {
request: () => {
throw Error('recursive HTTP health call');
},
},
});
const result = await new Promise((resolve) =>
check({ request: { service: 'scheduler' } }, (error, response) =>
resolve({ error, response }),
),
);
assert.equal(result.error, null);
assert.deepEqual(result.response, { status: 1 });
});
+62 -19
View File
@@ -3,9 +3,14 @@ const assert = require('node:assert/strict');
const fs = require('node:fs');
const ts = require('typescript');
const load = require('../helpers/load-security-module.cjs');
const { SchedulerReadiness } = require('../../back/shared/schedulerReadiness');
const {
SchedulerReadiness,
} = require('../../back/cron/scheduling/schedulerReadiness');
const { AddCronRequest } = require('../../back/protos/cron');
const { getInvalidCronSchedules } = require('../../back/shared/cronSchedule');
const {
getInvalidCronSchedules,
} = require('../../back/cron/scheduling/cronSchedule');
const { nodeCron } = require('../../back/cron/scheduling/cronScheduling');
function fixture(client) {
const source = fs.readFileSync('back/services/cron.ts', 'utf8');
@@ -16,12 +21,21 @@ function fixture(client) {
{ compilerOptions: { target: ts.ScriptTarget.ES2020 } },
).outputText;
const module = { exports: {} };
new Function('module', 'isDemoEnv', 'cronClient', 'withSchedulerMutation', 'getInvalidCronSchedules', js)(
new Function(
'module',
'isDemoEnv',
'cronClient',
'withSchedulerMutation',
'getInvalidCronSchedules',
'nodeCron',
js,
)(
module,
() => false,
client,
(fn) => fn(),
getInvalidCronSchedules,
nodeCron,
);
const service = new module.exports();
service.setCrontab = async () => {};
@@ -42,12 +56,13 @@ test('recovery reconciles a surviving scheduler after missed deletes and disable
);
const { addCron } = load('back/schedule/addCron.ts', {
'./data': { scheduleStacks: stacks },
'../shared/cronScheduler': {
'../cron/scheduling/cronScheduler': {
createCronJob: (_schedule, _callback, options) => ({
start() {}, cancel: () => cancelled.push(options.name.split(':')[0]),
start() {},
cancel: () => cancelled.push(options.name.split(':')[0]),
}),
},
'../shared/runCron': {},
'../cron/execution/runCron': {},
'../loaders/logger': { info() {}, warn() {} },
'../shared/i18n': { t: (s) => s, tf: (s) => s },
});
@@ -96,7 +111,7 @@ test('invalid replacement leaves the previous schedule intact', async () => {
]);
const { addCron } = load('back/schedule/addCron.ts', {
'./data': { scheduleStacks: stacks },
'../shared/runCron': {},
'../cron/execution/runCron': {},
'../loaders/logger': {},
'../shared/i18n': { t: (s) => s, tf: (s) => s },
});
@@ -121,22 +136,41 @@ test('invalid persisted schedules cannot block recovery, valid jobs or HTTP heal
const warnings = [];
const { addCron } = load('back/schedule/addCron.ts', {
'./data': { scheduleStacks: stacks },
'../shared/runCron': {},
'../cron/execution/runCron': {},
'../loaders/logger': { info() {}, warn() {} },
'../shared/i18n': { t: (s) => s, tf: require('node:util').format },
});
const client = { addCron: (crons, replace) => new Promise((resolve, reject) => {
addCron({ request: { crons, replace } }, (error) => error ? reject(error) : resolve());
}) };
const client = {
addCron: (crons, replace) =>
new Promise((resolve, reject) => {
addCron({ request: { crons, replace } }, (error) =>
error ? reject(error) : resolve(),
);
}),
};
const service = fixture(client);
let snapshot;
service.setCrontab = async (tabs) => { snapshot = tabs.data; };
service.logger.warn = (...args) => warnings.push(require('node:util').format(...args));
service.setCrontab = async (tabs) => {
snapshot = tabs.data;
};
service.logger.warn = (...args) =>
warnings.push(require('node:util').format(...args));
let rows = [
{ id: 'good', name: 'valid', schedule: '0 0/30 * * * ?', isDisabled: 0 },
{ id: 'bad-main', name: 'bad main', schedule: 'not a cron', isDisabled: 0 },
{ id: 'bad-extra', name: 'bad extra', schedule: '* * * * *', extra_schedules: [{ schedule: '0 70 * * * ?' }], isDisabled: 0 },
{ id: 'unsupported', name: 'unsupported', schedule: 'H * * * *', isDisabled: 0 },
{
id: 'bad-extra',
name: 'bad extra',
schedule: '* * * * *',
extra_schedules: [{ schedule: '0 70 * * * ?' }],
isDisabled: 0,
},
{
id: 'unsupported',
name: 'unsupported',
schedule: 'H * * * *',
isDisabled: 0,
},
{ id: 'disabled', name: 'disabled', schedule: 'bad', isDisabled: 1 },
];
service.crontabs = async () => ({ data: rows });
@@ -148,20 +182,29 @@ test('invalid persisted schedules cannot block recovery, valid jobs or HTTP heal
state.configure(() => service.autosave_crontab(true));
assert.equal(await state.recover(), true);
assert.deepEqual([...stacks.keys()], ['good']);
assert.deepEqual(snapshot.map((x) => x.id), ['good', 'disabled']);
assert.deepEqual(
snapshot.map((x) => x.id),
['good', 'disabled'],
);
assert.equal(rows.length, 5, 'persisted rows are preserved for editing');
assert.equal(rows[1].isDisabled, 0);
assert.equal(warnings.length, 3);
assert.match(warnings.join('\n'), /bad-main.*bad main.*not a cron/);
assert.match(warnings.join('\n'), /bad-extra.*0 70/);
const { HealthService } = load('back/services/health.ts', {
typedi: { Service: () => (x) => x }, './http': {},
'../schedule/client': { readiness: state }, '../loaders/logger': { error() {} },
typedi: { Service: () => (x) => x },
'./http': {},
'../schedule/client': { readiness: state },
'../loaders/logger': { error() {} },
});
const health = new HealthService({ getServer: () => ({}) });
assert.equal((await health.check()).status, 'ok');
rows = rows.filter((x) => x.id !== 'good');
assert.equal(await state.recover(), true, 'even all-invalid snapshots can recover');
assert.equal(
await state.recover(),
true,
'even all-invalid snapshots can recover',
);
assert.equal(stacks.size, 0);
assert.equal((await health.check()).status, 'ok');
});
+15 -4
View File
@@ -61,13 +61,24 @@ test('registration serializes nullable SQLite scheduling fields as absent', asyn
},
};
const legacy = {
id: '1', extra_schedules: null, max_queue_wait: null, catchup_seconds: null, recovery_from: null,
id: '1',
extra_schedules: null,
max_queue_wait: null,
catchup_seconds: null,
recovery_from: null,
};
const configured = {
id: '2', schedule: '* * * * *', extra_schedules: [{ schedule: '0 1 * * *' }],
max_queue_wait: 0, catchup_seconds: 60, recovery_from: 1700000000000,
id: '2',
schedule: '* * * * *',
extra_schedules: [{ schedule: '0 1 * * *' }],
max_queue_wait: 0,
catchup_seconds: 60,
recovery_from: 1700000000000,
};
await client.addCron([legacy, configured], true);
assert.equal(received.replace, true);
assert.deepEqual(received.crons, [ICron.create({ id: '1' }), ICron.create(configured)]);
assert.deepEqual(received.crons, [
ICron.create({ id: '1' }),
ICron.create(configured),
]);
});
+246 -110
View File
@@ -4,7 +4,7 @@ const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const { Sequelize, DataTypes, QueryTypes, Transaction } = require('sequelize');
const { migrateSchema } = require('../../back/shared/schemaMigrations');
const { migrateSchema } = require('../../back/data/schemaMigrations');
const load = require('../helpers/load-security-module.cjs');
async function createLegacy(storage = ':memory:', omitEnvs = false) {
@@ -27,8 +27,12 @@ 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');
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();
@@ -50,7 +54,12 @@ test('legacy database upgrades without losing rows and repeated migration is ide
type: QueryTypes.SELECT,
});
assert.equal(applied.length, 27);
assert.ok(Object.hasOwn(await database.getQueryInterface().describeTable('CrontabStats'), 'fixed_max_time'));
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);
@@ -67,26 +76,40 @@ test('migration repairs malformed environment labels before ORM reads', async (t
[4, '{}'],
[5, '["keep"]'],
]) {
await database.query('INSERT INTO "Envs" (id, name, labels) VALUES (?, ?, ?)', {
replacements: [id, `env-${id}`, labels],
});
await database.query(
'INSERT INTO "Envs" (id, name, labels) VALUES (?, ?, ?)',
{
replacements: [id, `env-${id}`, labels],
},
);
}
const EnvModel = database.define('Env', {
name: DataTypes.STRING,
labels: DataTypes.JSON,
}, { timestamps: false });
const EnvModel = database.define(
'Env',
{
name: DataTypes.STRING,
labels: DataTypes.JSON,
},
{ timestamps: false },
);
await assert.rejects(EnvModel.findAll(), /Unexpected end of JSON input/);
await migrateSchema(database);
const rows = await EnvModel.findAll({ order: [['id', 'ASC']] });
assert.deepEqual(rows.map((row) => row.labels), [[], [], [], [], ['keep']]);
assert.deepEqual(
rows.map((row) => row.labels),
[[], [], [], [], ['keep']],
);
await migrateSchema(database);
const repaired = await database.query('SELECT id, labels FROM "Envs" ORDER BY id', {
type: QueryTypes.SELECT,
});
assert.deepEqual(repaired.map(({ labels }) => labels), [
'[]', '[]', '[]', '[]', '["keep"]',
]);
const repaired = await database.query(
'SELECT id, labels FROM "Envs" ORDER BY id',
{
type: QueryTypes.SELECT,
},
);
assert.deepEqual(
repaired.map(({ labels }) => labels),
['[]', '[]', '[]', '[]', '["keep"]'],
);
});
test('migration failure rolls back added columns and can be retried after repair', async (t) => {
@@ -160,7 +183,7 @@ test('database loader rejects initialization failure rather than allowing worker
])
mocks[`../data/${file}`] = { [model]: { sync: async () => {} } };
mocks['../data'] = { sequelize: {} };
mocks['../shared/schemaMigrations'] = {
mocks['../data/schemaMigrations'] = {
migrateSchema: async () => {
throw new Error('SQLITE_FULL');
},
@@ -169,121 +192,234 @@ test('database loader rejects initialization failure rather than allowing worker
await assert.rejects(initialize(), /SQLITE_FULL/);
});
test('upgrading stop batches preserves completed and pending idempotency bindings', async t => {
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 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 });
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 => {
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(
"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 }), []);
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));
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 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 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'), []);
});
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/cron/settlement/exitReceipt.cjs');
const { TriggerHistory } = require('../../back/cron/history');
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'), []);
},
);
}
+1 -1
View File
@@ -47,7 +47,7 @@ test('script file operations allow token.json while protecting panel configurati
'./sock': {},
'./cron': {},
'./schedule': {},
'../shared/pLimit': {},
'../cron/execution/cronLimit': {},
typedi: { Service: () => (x) => x, Inject: () => () => {} },
};
const cache = new Map();
+5 -1
View File
@@ -131,7 +131,11 @@ assert len(children[0])==3,children
.filter((x) => x.title === 'Concurrent cold startup')
.map((x) => [x.notifyType, x.success])
.sort(),
[['accepted', true], ['no_result', false], ['rejected', false]],
[
['accepted', true],
['no_result', false],
['rejected', false],
],
);
// Missing certificates and an older/unavailable backend must not kill scripts.
await run(
+27 -21
View File
@@ -183,7 +183,7 @@ 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 => {
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
@@ -203,29 +203,35 @@ test('Shell retries the same identified receipt after a timeout and starts the n
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);
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.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 => {
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'));
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'),
);
});
+74 -30
View File
@@ -54,7 +54,8 @@ for (const [label, args] of [
f.write(`shell/${name}`, source(`shell/${name}`));
f.write(
'shell/api.sh',
extract('shell/api.sh', 'init_execution_id') + '\nupdate_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');
@@ -557,46 +558,89 @@ 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 => {
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(
'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),
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`);
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";
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",
});
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');
assert.equal(
fs.readFileSync(path.join(f.root, 'scripts', file), 'utf8'),
'body',
);
});
+13 -4
View File
@@ -3,14 +3,23 @@ const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
test('shell translations print leading dashes, placeholders and newlines', () => {
const result = spawnSync('bash', ['-c', String.raw`
const result = spawnSync(
'bash',
[
'-c',
String.raw`
source shell/share.sh
t '---> 服务诊断信息'
t '---> 最近的系统日志: %s' '/tmp/test.log'
t 'first\nsecond'
`], { encoding: 'utf8', env: { ...process.env, QL_DIR: process.cwd() } });
`,
],
{ encoding: 'utf8', env: { ...process.env, QL_DIR: process.cwd() } },
);
assert.equal(result.status, 0, result.stderr);
assert.equal(result.stderr, '');
assert.equal(result.stdout,
'---> 服务诊断信息\n---> 最近的系统日志: /tmp/test.log\nfirst\nsecond\n');
assert.equal(
result.stdout,
'---> 服务诊断信息\n---> 最近的系统日志: /tmp/test.log\nfirst\nsecond\n',
);
});
+4 -1
View File
@@ -225,7 +225,10 @@ for (const branch of ['master', 'develop', 'debian', 'debian-dev'])
const f = await fixture(t, { branch, lockChange: true, tee: true });
let result = await f.execute('update', 'false');
assert.equal(result.code, 0, result.stdout + result.stderr);
assert.ok(result.stdout.includes('     '), 'update logs retain the completion marker');
assert.ok(
result.stdout.includes('     '),
'update logs retain the completion marker',
);
assert.equal(f.read('version.yaml'), 'version: 2.21.0');
assert.equal(fs.existsSync(path.join(f.root, 'stops')), false);
assert.match(
+131 -42
View File
@@ -9,47 +9,84 @@ const apiFile = path.resolve(__dirname, '../../shell/api.sh');
const endpoints = {
status: {
method: 'PUT', url: /\/open\/crons\/status\?t=\d+$/,
body: { ids: ['37'], status: '1', pid: '4321', log_path: 'task/run.log',
last_execution_time: 1787004000, last_running_time: 90, exit_code: 0 },
success: '', failure: (message) => message,
method: 'PUT',
url: /\/open\/crons\/status\?t=\d+$/,
body: {
ids: ['37'],
status: '1',
pid: '4321',
log_path: 'task/run.log',
last_execution_time: 1787004000,
last_running_time: 90,
exit_code: 0,
},
success: '',
failure: (message) => message,
},
statistics: {
method: 'POST', url: /\/open\/dashboard\/record$/,
method: 'POST',
url: /\/open\/dashboard\/record$/,
body: { ref_id: 37, code: 0, elapsed: 90 },
success: '', failure: (message) => message,
success: '',
failure: (message) => message,
},
add: {
method: 'POST', url: /\/open\/crons\?t=\d+$/,
body: { name: 'sample job', command: 'task job.py', schedule: '0 * * * *', sub_id: null },
success: 'sample job -> 添加成功', failure: (message) => `sample job -> 添加失败(${message})`,
method: 'POST',
url: /\/open\/crons\?t=\d+$/,
body: {
name: 'sample job',
command: 'task job.py',
schedule: '0 * * * *',
sub_id: null,
},
success: 'sample job -> 添加成功',
failure: (message) => `sample job -> 添加失败(${message})`,
},
update: {
method: 'PUT', url: /\/open\/crons\?t=\d+$/,
body: { name: 'sample job', command: 'task job.py', schedule: '0 * * * *', id: '37' },
success: 'sample job -> 更新成功', failure: (message) => `sample job -> 更新失败(${message})`,
method: 'PUT',
url: /\/open\/crons\?t=\d+$/,
body: {
name: 'sample job',
command: 'task job.py',
schedule: '0 * * * *',
id: '37',
},
success: 'sample job -> 更新成功',
failure: (message) => `sample job -> 更新失败(${message})`,
},
command: {
method: 'PUT', url: /\/open\/crons\?t=\d+$/,
method: 'PUT',
url: /\/open\/crons\?t=\d+$/,
body: { command: 'task job.py', id: '37' },
success: 'task job.py -> 更新成功', failure: (message) => `task job.py -> 更新失败(${message})`,
success: 'task job.py -> 更新成功',
failure: (message) => `task job.py -> 更新失败(${message})`,
},
delete: {
method: 'DELETE', url: /\/open\/crons\?t=\d+$/,
body: [37, 38], success: '成功', failure: (message) => `失败(${message})`,
method: 'DELETE',
url: /\/open\/crons\?t=\d+$/,
body: [37, 38],
success: '成功',
failure: (message) => `失败(${message})`,
},
notify: {
method: 'PUT', url: /\/open\/system\/notify\?t=\d+$/,
method: 'PUT',
url: /\/open\/system\/notify\?t=\d+$/,
body: { title: 'title', content: 'body' },
success: '通知发送成功🎉', failure: (message) => `通知失败(${message})`,
success: '通知发送成功🎉',
failure: (message) => `通知失败(${message})`,
},
find: {
method: 'GET', url: /\/open\/crons\/detail\?log_path=task\/run.log&t=\d+$/,
body: null, success: 'sample job', failure: () => '',
method: 'GET',
url: /\/open\/crons\/detail\?log_path=task\/run.log&t=\d+$/,
body: null,
success: 'sample job',
failure: () => '',
},
auth: {
method: 'PUT', url: /\/open\/system\/auth\/reset\?t=\d+$/,
body: { retries: 0 }, success: '重置登录错误次数成功🎉',
method: 'PUT',
url: /\/open\/system\/auth\/reset\?t=\d+$/,
body: { retries: 0 },
success: '重置登录错误次数成功🎉',
failure: (message) => `重置登录错误次数失败(${message})`,
},
};
@@ -58,10 +95,18 @@ function runCallback(endpoint, scenario) {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-api-token-'));
try {
const tokenFile = path.join(directory, 'token.json');
fs.writeFileSync(tokenFile, JSON.stringify({
value: 'initial-token', expiration: Math.floor(Date.now() / 1000) + 3600,
}));
const child = spawnSync('bash', ['-c', `
fs.writeFileSync(
tokenFile,
JSON.stringify({
value: 'initial-token',
expiration: Math.floor(Date.now() / 1000) + 3600,
}),
);
const child = spawnSync(
'bash',
[
'-c',
`
. "$API_FILE"
create_token() {
printf 'refresh\\n' >> "$CAPTURE"
@@ -106,22 +151,46 @@ function runCallback(endpoint, scenario) {
find) find_cron_api 'log_path=task/run.log' ;;
auth) update_auth_config '"retries":0' '重置登录错误次数' ;;
esac
`], {
env: { ...process.env, PATH: `/usr/bin:/bin:${process.env.PATH}`, API_FILE: apiFile, file_auth_token: tokenFile,
CAPTURE: path.join(directory, 'requests'), SCENARIO: scenario,
ENDPOINT: endpoint, ql_port: '5700' },
encoding: 'utf8', timeout: 10_000,
});
const denied = ['persistent', 'forbidden', 'unavailable'].includes(scenario);
assert.equal(child.status, denied && ['add', 'delete'].includes(endpoint) ? 1 : 0, child.stderr);
`,
],
{
env: {
...process.env,
PATH: `/usr/bin:/bin:${process.env.PATH}`,
API_FILE: apiFile,
file_auth_token: tokenFile,
CAPTURE: path.join(directory, 'requests'),
SCENARIO: scenario,
ENDPOINT: endpoint,
ql_port: '5700',
},
encoding: 'utf8',
timeout: 10_000,
},
);
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 lines = fs
.readFileSync(path.join(directory, 'requests'), 'utf8')
.trim()
.split('\n');
const refreshes = lines.filter((line) => line === 'refresh').length;
const requests = lines.filter((line) => line !== 'refresh');
const captures = [];
for (let i = 0; i < requests.length; i += 4) {
captures.push({ auth: requests[i], method: requests[i + 1],
url: requests[i + 2], body: JSON.parse(requests[i + 3]) });
captures.push({
auth: requests[i],
method: requests[i + 1],
url: requests[i + 2],
body: JSON.parse(requests[i + 3]),
});
}
return { output: child.stdout, refreshes, captures };
} finally {
@@ -130,12 +199,23 @@ function runCallback(endpoint, scenario) {
}
for (const [endpoint, expected] of Object.entries(endpoints)) {
for (const scenario of ['valid', 'expired', 'replaced', 'rejected', 'persistent', 'forbidden', 'unavailable']) {
for (const scenario of [
'valid',
'expired',
'replaced',
'rejected',
'persistent',
'forbidden',
'unavailable',
]) {
test(`${endpoint} API handles ${scenario} token without unbounded retries`, () => {
const { output, refreshes, captures } = runCallback(endpoint, scenario);
const retries = ['rejected', 'persistent'].includes(scenario);
assert.equal(captures.length, retries ? 2 : 1);
assert.equal(refreshes, ['expired', 'rejected', 'persistent'].includes(scenario) ? 1 : 0);
assert.equal(
refreshes,
['expired', 'rejected', 'persistent'].includes(scenario) ? 1 : 0,
);
for (const capture of captures) {
assert.deepEqual(capture.body, expected.body);
assert.equal(capture.method, expected.method);
@@ -144,9 +224,18 @@ for (const [endpoint, expected] of Object.entries(endpoints)) {
if (['expired', 'replaced', 'rejected'].includes(scenario)) {
assert.equal(captures.at(-1).auth, 'Authorization: Bearer fresh-token');
}
const error = scenario === 'persistent' ? 'Token 已失效'
: scenario === 'forbidden' ? 'forbidden' : scenario === 'unavailable' ? 'unavailable' : '';
assert.equal(output.trim(), error ? expected.failure(error) : expected.success);
const error =
scenario === 'persistent'
? 'Token 已失效'
: scenario === 'forbidden'
? 'forbidden'
: scenario === 'unavailable'
? 'unavailable'
: '';
assert.equal(
output.trim(),
error ? expected.failure(error) : expected.success,
);
});
}
}
+7 -7
View File
@@ -8,8 +8,8 @@ function fixture(row, { claim = true, onSpawn = () => {} } = {}) {
cronWrites = [],
instanceWrites = [],
instanceReads = [];
const { runCron } = load('back/shared/runCron.ts', {
'./i18n': { t: (s) => s },
const { runCron } = load('back/cron/execution/runCron.ts', {
'../../shared/i18n': { t: (s) => s },
'cross-spawn': {
spawn: (cmd) => {
spawned.push(cmd);
@@ -17,12 +17,12 @@ function fixture(row, { claim = true, onSpawn = () => {} } = {}) {
return { pid: process.pid };
},
},
'./pLimit': {
'./cronLimit': {
runWithCronLimit: (_cron, execute) => execute(),
removeQueuedCron() {},
},
'../loaders/logger': { info() {}, error() {} },
'../data/cron': {
'../../loaders/logger': { info() {}, error() {} },
'../../data/cron': {
CrontabModel: {
findOne: async () => row,
update: async (...args) => {
@@ -34,7 +34,7 @@ function fixture(row, { claim = true, onSpawn = () => {} } = {}) {
},
CrontabStatus: { running: 0, idle: 1, queued: 3 },
},
'../data/runningInstance': {
'../../data/runningInstance': {
RunningInstanceModel: {
findAll: async (options) => {
instanceReads.push(options);
@@ -45,7 +45,7 @@ function fixture(row, { claim = true, onSpawn = () => {} } = {}) {
InstanceStatus: { running: 0, stopped: 2 },
},
dayjs: () => ({ unix: () => 123 }),
'./childProcess': {
'../../shared/childProcess': {
observeChildProcess: () => ({ completed: Promise.resolve({ code: 0 }) }),
asError: (e) => e,
},
@@ -6,12 +6,15 @@ const path = require('node:path');
const { spawnSync } = require('node:child_process');
const startup = fs.readFileSync('shell/start-simplify.sh', 'utf8');
const runtimeLoader = fs.readFileSync('shell/share.sh', 'utf8')
const runtimeLoader = fs
.readFileSync('shell/share.sh', 'utf8')
.match(/^load_node_runtime_args\(\) \{[\s\S]*?^\}/m)[0];
const preparation = `${runtimeLoader}\ndir_root="$QL_DIR"\n` + startup.slice(
startup.indexOf('\nfix_config\n'),
startup.indexOf('log_with_style "INFO" "$(t \'🔄'),
);
const preparation =
`${runtimeLoader}\ndir_root="$QL_DIR"\n` +
startup.slice(
startup.indexOf('\nfix_config\n'),
startup.indexOf('log_with_style "INFO" "$(t \'🔄'),
);
for (const fails of [false, true]) {
test(`manual startup ${
fails
+1 -1
View File
@@ -56,7 +56,7 @@ function scriptFixture(killTask, pid = 100) {
'../config': { scriptPath: '/scripts' },
'../config/const': { TASK_COMMAND: 'task' },
'../config/util': { killTask, getPid: async () => pid },
'../shared/pLimit': { removeQueuedCron() {} },
'../cron/execution/cronLimit': { removeQueuedCron() {} },
'./sock': {},
'./cron': {},
'./schedule': {},
+142 -57
View File
@@ -35,7 +35,9 @@ async function fixture(t, onKill = async () => {}) {
});
load('back/data/cronStats.ts', { '.': { sequelize: db } });
await db.sync();
await db.transaction(tx => require('../../back/shared/triggerHistory').installTriggerHistory(db, tx));
await db.transaction((tx) =>
require('../../back/cron/history').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' },
@@ -59,8 +61,9 @@ 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,
'../cron/execution/cronProcess': {
pidNamespaceOwner: require('../../back/cron/execution/cronProcess')
.pidNamespaceOwner,
verifyCronProcess() {},
},
'../config/util': {
@@ -75,7 +78,7 @@ async function fixture(t, onKill = async () => {}) {
},
'../config/const': {},
'../schedule/client': {},
'../shared/pLimit': {},
'../cron/execution/cronLimit': {},
'../shared/utils': {},
'../shared/i18n': { t: (s) => s },
'../shared/logReader': {},
@@ -180,19 +183,21 @@ test('failed termination is not finalized as stopped', async (t) => {
});
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);
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);
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 => {
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);
@@ -200,40 +205,68 @@ test('legacy instances sharing a numeric PID cannot be individually signalled',
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; });
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'); }
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));
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']);
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 => {
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 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; }
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 batchJoined = new Promise((resolve) => {
captured = resolve;
});
const stopInstance = f.service.stopInstance.bind(f.service);
f.service.stopInstance = (cronId, id) => {
if (id === 1) captured();
@@ -241,24 +274,41 @@ test('single and batch stop share the in-flight termination and keep the batch s
};
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]);
const history = new (require('../../back/cron/history').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 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 => {
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'); });
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 history = new (require('../../back/cron/history').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]]);
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);
@@ -267,10 +317,14 @@ test('a single stop is durable before asynchronous tree traversal and a replacem
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 => {
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 f = await fixture(t, async ({ pid }) => {
if (pid === 102 && blocked) throw Error('interrupted');
});
const history = new (require('../../back/cron/history').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/);
@@ -278,10 +332,18 @@ test('an interrupted batch replays its original instances and leaves later queue
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 } });
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);
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 });
@@ -290,14 +352,17 @@ test('an interrupted batch replays its original instances and leaves later queue
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');
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');
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 => {
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);
@@ -309,12 +374,16 @@ test('replaying an empty original snapshot never targets the first later run', a
assert.deepEqual(f.killed, [301]);
});
test('a second restart rolls back receipt deletion when settling a legacy instance fails', async t => {
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);
const history = new (require('../../back/cron/history').TriggerHistory)(
f.crons.sequelize,
);
await history.queueInstanceStop(1, 1, 101);
const stop = () => f.service.stopInstance(1, 1);
const transactionError = () => { throw Error('interrupted during settlement'); };
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');
@@ -324,31 +393,47 @@ test('a second restart rolls back receipt deletion when settling a legacy instan
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; });
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'); }
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 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/);
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)]);
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 => {
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();
+221 -79
View File
@@ -305,7 +305,11 @@ 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, dir_shell: path.resolve('shell'), QA_ROOT: root },
env: {
...process.env,
dir_shell: path.resolve('shell'),
QA_ROOT: root,
},
encoding: 'utf8',
timeout: 5000,
});
@@ -457,7 +461,11 @@ function cancellationFixture(t, subscriptions) {
events.push(['createInterval', doc.command, interval, immediately]),
};
const service = new Subscription(
{}, schedule, {}, { removeSSHKey: async () => {} }, {},
{},
schedule,
{},
{ removeSSHKey: async () => {} },
{},
);
service.setSshConfig = async () => {};
return { service, docs, events };
@@ -466,25 +474,44 @@ function cancellationFixture(t, subscriptions) {
async function sshLifecycleFixture(t, initial) {
const root = temporary(t);
const ssh = sshService(root);
let docs = [{ ...initial, get() { return { ...this }; } }];
const SubscriptionService = load(path.resolve('back/services/subscription.ts'), {
'../config': { scriptPath: root, repoPath: root },
'../data/subscription': {
Subscription: class { constructor(value) { Object.assign(this, value); } },
SubscriptionModel: {
findAll: async () => docs,
destroy: async () => { docs = []; },
let docs = [
{
...initial,
get() {
return { ...this };
},
},
'../data/cron': { CrontabModel: { findAll: async () => [] } },
'../config/util': {
rmPath: (p) => fs.promises.rm(p, { recursive: true, force: true }),
];
const SubscriptionService = load(
path.resolve('back/services/subscription.ts'),
{
'../config': { scriptPath: root, repoPath: root },
'../data/subscription': {
Subscription: class {
constructor(value) {
Object.assign(this, value);
}
},
SubscriptionModel: {
findAll: async () => docs,
destroy: async () => {
docs = [];
},
},
},
'../data/cron': { CrontabModel: { findAll: async () => [] } },
'../config/util': {
rmPath: (p) => fs.promises.rm(p, { recursive: true, force: true }),
},
'../config/const': {},
'../shared/i18n': { t: (x) => x, tf: (x) => x },
'../shared/pLimit': {},
'./schedule': {},
'./sock': {},
'./sshKey': {},
'./cron': {},
},
'../config/const': {},
'../shared/i18n': { t: (x) => x, tf: (x) => x },
'../shared/pLimit': {},
'./schedule': {}, './sock': {}, './sshKey': {}, './cron': {},
}).default;
).default;
const service = new SubscriptionService({}, {}, {}, ssh, {});
service.handleTask = async () => {};
service.getDb = async () => ({ ...docs[0] });
@@ -503,8 +530,14 @@ test('editing an SSH subscription removes the old alias key and configuration',
await f.service.update({ ...initial, alias });
const mapped = paths.getSubscriptionSshAlias(alias);
assert.equal(fs.existsSync(path.join(f.root, initial.alias)), false);
assert.equal(fs.existsSync(path.join(f.root, initial.alias + '.config')), false);
assert.equal(fs.readFileSync(path.join(f.root, mapped), 'utf8').trim(), 'fixture-key');
assert.equal(
fs.existsSync(path.join(f.root, initial.alias + '.config')),
false,
);
assert.equal(
fs.readFileSync(path.join(f.root, mapped), 'utf8').trim(),
'fixture-key',
);
assert.ok(fs.existsSync(path.join(f.root, mapped + '.config')));
});
@@ -606,112 +639,202 @@ test('valid subscription scheduling still creates quoted commands for both sched
}
});
test('repeated subscription sync recognizes installed system-wrapper and legacy rules', t => {
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 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'), '');
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 => {
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'));
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']);
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 => {
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',
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');
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));
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 => {
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),
} });
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');
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 => {
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 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]);
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.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']) {
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');
@@ -723,22 +846,41 @@ test('subscription writes reject destination links and replace hardlinks without
assert.equal(fs.readFileSync(file, 'utf8'), 'protected');
});
test('a rejected guarded deletion preserves its file and propagates failure to subscription sync', t => {
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";
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, '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(){ :; }',
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 },
});
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');
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',
);
});
@@ -478,7 +478,12 @@ test('an unrelated dangling or outside symlink reference does not block safe cle
});
test('URL-derived storage accepts legal directory names longer than user aliases and containing spaces', async (t) => {
const doc = { ...cases[0], id: 1, alias: 'short-alias', url: `/tmp/owner/${'r'.repeat(205)} repo.git` };
const doc = {
...cases[0],
id: 1,
alias: 'short-alias',
url: `/tmp/owner/${'r'.repeat(205)} repo.git`,
};
const f = fixture(t, [doc]);
const files = f.paths(doc).map((p) => path.join(p, 'job.js'));
files.forEach(f.write);
@@ -506,7 +511,12 @@ test('an unrepresentable unused Shell filename does not block valid CLI raw clea
});
test('cleanup retains each representable path when only its prefixed Shell script name is too long', async (t) => {
const doc = { id: 1, alias: 'partial-raw', type: 'file', url: 'https://example.com/job.js?token=' };
const doc = {
id: 1,
alias: 'partial-raw',
type: 'file',
url: 'https://example.com/job.js?token=',
};
const prefix = getSubscriptionStorageNames(doc).raw;
doc.url += 'a'.repeat(255 - Buffer.byteLength(prefix));
const shell = getSubscriptionStorageNames(doc);
@@ -536,7 +546,12 @@ test('a legal Unicode alias with an unrepresentable unused directory does not bl
});
test('Unicode storage follows filesystem limits rather than imposing a UTF-8 byte cap', async (t) => {
const doc = { ...cases[0], id: 1, alias: 'short-alias', url: `/tmp/owner/${'中'.repeat(86)}.git` };
const doc = {
...cases[0],
id: 1,
alias: 'short-alias',
url: `/tmp/owner/${'中'.repeat(86)}.git`,
};
const f = fixture(t, [doc]);
const files = f.paths(doc).map((p) => path.join(p, 'job.js'));
for (const file of files) {
+1 -1
View File
@@ -60,7 +60,7 @@ test('clearing a dependency cache marks installed entries for reinstall', async
SystemModel: {},
});
stubModule('../../back/schedule/client', { __esModule: true, default: {} });
stubModule('../../back/shared/pLimit', {
stubModule('../../back/cron/execution/cronLimit', {
__esModule: true,
default: {},
});
+1 -1
View File
@@ -23,7 +23,7 @@ async function fixture(t) {
'../data/dependence': {},
'../data/notify': {},
'../data/system': {},
'../shared/pLimit': {},
'../cron/execution/cronLimit': {},
'../schedule/client': {},
'../shared/i18n': { t: (x) => x },
'./notify': class {},
+5 -2
View File
@@ -19,7 +19,7 @@ async function fixture(t) {
'../data/dependence': {},
'../data/notify': {},
'../data/system': {},
'../shared/pLimit': {},
'../cron/execution/cronLimit': {},
'../schedule/client': {},
'../shared/i18n': { t: (x) => x },
'./notify': class {},
@@ -36,7 +36,10 @@ test('clearing system logs preserves append handles used by existing workers', a
await fs.writeFile(active, 'old active logs\n');
await fs.writeFile(rotated, 'old rotated logs\n');
await fs.writeFile(path.join(root, 'audit.json'), 'rotation metadata');
const workers = await Promise.all([fs.open(active, 'a'), fs.open(active, 'a')]);
const workers = await Promise.all([
fs.open(active, 'a'),
fs.open(active, 'a'),
]);
t.after(async () => {
await Promise.all(workers.map((worker) => worker.close()));
});
+289 -86
View File
@@ -37,12 +37,17 @@ function fixture(t, initialTokens = []) {
});
let now = START;
let app = {
name: 'system', client_id: 'system-client', client_secret: 'system-secret',
scopes: ['crons', 'system', 'dashboard'], tokens: initialTokens,
name: 'system',
client_id: 'system-client',
client_secret: 'system-secret',
scopes: ['crons', 'system', 'dashboard'],
tokens: initialTokens,
};
t.mock.method(Date, 'now', () => now * 1000);
t.mock.method(shareStore, 'getApps', async () => [app]);
t.mock.method(shareStore, 'updateApps', async (apps) => { [app] = apps; });
t.mock.method(shareStore, 'updateApps', async (apps) => {
[app] = apps;
});
t.mock.method(AppModel, 'findOne', async ({ where }) => {
if (where.name) assert.equal(where.name, app.name);
else {
@@ -58,8 +63,12 @@ function fixture(t, initialTokens = []) {
t.mock.method(AppModel, 'findAll', async () => [{ get: () => app }]);
return {
service: new OpenService({}),
atDay(day) { now = START + day * DAY; },
tokens() { return app.tokens; },
atDay(day) {
now = START + day * DAY;
},
tokens() {
return app.tokens;
},
};
}
@@ -93,7 +102,8 @@ test('startup generation renews before a restarted 28-day interval', async (t) =
test('generation at the five-token limit extends the reused token without revoking active tokens', async (t) => {
const initial = Array.from({ length: 5 }, (_, index) => ({
value: `token-${index}`, expiration: START + 2 * DAY,
value: `token-${index}`,
expiration: START + 2 * DAY,
}));
const state = fixture(t, initial);
const renewed = await state.service.generateSystemToken(true);
@@ -117,7 +127,9 @@ test('ordinary acquisition reuses the newest valid database token and republishe
assert.equal(token.value, 'newer-token');
assert.deepEqual(state.tokens(), initial);
assert.deepEqual(
JSON.parse(fs.readFileSync(path.join(config.configPath, 'token.json'), 'utf8')),
JSON.parse(
fs.readFileSync(path.join(config.configPath, 'token.json'), 'utf8'),
),
token,
);
});
@@ -125,10 +137,21 @@ test('ordinary acquisition reuses the newest valid database token and republishe
test('a failed generation releases its lock and does not publish a token', async (t) => {
const state = fixture(t);
const update = AppModel.update;
AppModel.update = async () => { throw new Error('generation failed'); };
await assert.rejects(state.service.generateSystemToken(), /generation failed/);
assert.equal(fs.existsSync(path.join(config.configPath, 'token.json')), false);
assert.equal(fs.existsSync(path.join(config.configPath, 'token.json.refresh.lock')), false);
AppModel.update = async () => {
throw new Error('generation failed');
};
await assert.rejects(
state.service.generateSystemToken(),
/generation failed/,
);
assert.equal(
fs.existsSync(path.join(config.configPath, 'token.json')),
false,
);
assert.equal(
fs.existsSync(path.join(config.configPath, 'token.json.refresh.lock')),
false,
);
AppModel.update = update;
const token = await state.service.generateSystemToken();
assert.ok(state.tokens().some((current) => current.value === token.value));
@@ -142,8 +165,14 @@ test('acquisition recovers an authentication cache failure after the database co
if (++attempts === 1) throw new Error('authentication cache failed');
return updateCache(apps);
};
await assert.rejects(state.service.generateSystemToken(), /authentication cache failed/);
assert.equal(fs.existsSync(path.join(config.configPath, 'token.json')), false);
await assert.rejects(
state.service.generateSystemToken(),
/authentication cache failed/,
);
assert.equal(
fs.existsSync(path.join(config.configPath, 'token.json')),
false,
);
const committed = state.tokens()[0];
const token = await state.service.generateSystemToken();
assert.equal(token.value, committed.value);
@@ -156,12 +185,20 @@ async function processFixture(t, initialTokens = []) {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-token-process-'));
t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
const databaseFile = path.join(directory, 'database.json');
fs.writeFileSync(databaseFile, JSON.stringify({
name: 'system', client_id: 'system-client', client_secret: 'system-secret',
scopes: ['crons', 'system', 'dashboard'], tokens: initialTokens,
}));
fs.writeFileSync(
databaseFile,
JSON.stringify({
name: 'system',
client_id: 'system-client',
client_secret: 'system-secret',
scopes: ['crons', 'system', 'dashboard'],
tokens: initialTokens,
}),
);
const worker = path.join(directory, 'worker.cjs');
fs.writeFileSync(worker, `
fs.writeFileSync(
worker,
`
const fs = require('node:fs/promises');
const path = require('node:path');
const root = process.cwd();
@@ -195,26 +232,46 @@ async function processFixture(t, initialTokens = []) {
shareStore.getApps = async () => { throw new Error('stale cache must not be read'); };
shareStore.updateApps = async () => {};
require(path.join(root, 'back/token'));
`);
`,
);
return {
directory,
run(renew = false, fail = false, hold = false) {
return execute(process.execPath, [
'-r', require.resolve('ts-node/register/transpile-only'), worker,
...(renew ? ['--renew'] : []),
], {
cwd: root, timeout: 20_000,
env: { ...process.env, QL_TOKEN_TEST_FAIL: fail ? '1' : '0', QL_TOKEN_TEST_HOLD: hold ? '1' : '0' },
});
return execute(
process.execPath,
[
'-r',
require.resolve('ts-node/register/transpile-only'),
worker,
...(renew ? ['--renew'] : []),
],
{
cwd: root,
timeout: 20_000,
env: {
...process.env,
QL_TOKEN_TEST_FAIL: fail ? '1' : '0',
QL_TOKEN_TEST_HOLD: hold ? '1' : '0',
},
},
);
},
tokens() {
return JSON.parse(fs.readFileSync(databaseFile, 'utf8')).tokens;
},
cached() {
return JSON.parse(
fs.readFileSync(path.join(directory, 'token.json'), 'utf8'),
);
},
tokens() { return JSON.parse(fs.readFileSync(databaseFile, 'utf8')).tokens; },
cached() { return JSON.parse(fs.readFileSync(path.join(directory, 'token.json'), 'utf8')); },
};
}
test('four independent token processes converge on one usable token when the cache is missing', async (t) => {
const state = await processFixture(t);
const results = await Promise.all(Array.from({ length: 4 }, () => state.run()));
const results = await Promise.all(
Array.from({ length: 4 }, () => state.run()),
);
const issued = results.map(({ stdout, stderr }) => {
assert.equal(stderr, '');
return stdout.trim();
@@ -223,13 +280,24 @@ test('four independent token processes converge on one usable token when the cac
assert.equal(state.tokens().length, 1);
assert.equal(state.tokens()[0].value, issued[0]);
assert.equal(state.cached().value, issued[0]);
assert.equal(fs.existsSync(path.join(state.directory, 'token.json.refresh.lock')), false);
assert.equal(
fs.existsSync(path.join(state.directory, 'token.json.refresh.lock')),
false,
);
});
test('concurrent scheduled renewal and ordinary acquisition preserve all returned tokens', async (t) => {
const original = { value: 'original-token', expiration: Math.round(Date.now() / 1000) + DAY };
const original = {
value: 'original-token',
expiration: Math.round(Date.now() / 1000) + DAY,
};
const state = await processFixture(t, [original]);
const results = await Promise.all([state.run(true), state.run(), state.run(true), state.run()]);
const results = await Promise.all([
state.run(true),
state.run(),
state.run(true),
state.run(),
]);
const tokens = state.tokens();
assert.equal(tokens.length, 3);
assert.ok(tokens.some((token) => token.value === original.value));
@@ -258,16 +326,23 @@ test('startup configures the 28-day token task with explicit renewal', async (t)
const initialize = require('../../back/loaders/initTask').default;
const SystemService = require('../../back/services/system').default;
const ScheduleService = require('../../back/services/schedule').default;
const SubscriptionService = require('../../back/services/subscription').default;
const SubscriptionService =
require('../../back/services/subscription').default;
const SshKeyService = require('../../back/services/sshKey').default;
const scheduled = [];
const services = new Map([
[SystemService, { getSystemConfig: async () => undefined }],
[ScheduleService, {
cancelIntervalTask: async () => {},
createIntervalTask: (...args) => scheduled.push(args),
}],
[SubscriptionService, { setSshConfig: async () => {}, list: async () => [] }],
[
ScheduleService,
{
cancelIntervalTask: async () => {},
createIntervalTask: (...args) => scheduled.push(args),
},
],
[
SubscriptionService,
{ setSshConfig: async () => {}, list: async () => [] },
],
[SshKeyService, {}],
]);
t.mock.method(Container, 'get', (service) => {
@@ -285,7 +360,9 @@ test('startup configures the 28-day token task with explicit renewal', async (t)
function appsFixture(t) {
const previousConfigPath = config.configPath;
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-apps-concurrency-'));
const directory = fs.mkdtempSync(
path.join(os.tmpdir(), 'ql-apps-concurrency-'),
);
config.configPath = directory;
t.after(() => {
config.configPath = previousConfigPath;
@@ -294,14 +371,28 @@ function appsFixture(t) {
t.mock.method(Date, 'now', () => START * 1000);
const clone = (value) => JSON.parse(JSON.stringify(value));
let apps = [
{ id: 1, name: 'system', client_id: 'system-client', client_secret: 'system-secret',
scopes: ['crons', 'system', 'dashboard'], tokens: [{ value: 'system-token', expiration: START + DAY }] },
{ id: 2, name: 'external', client_id: 'external-client', client_secret: 'external-secret',
scopes: ['crons'], tokens: [] },
{
id: 1,
name: 'system',
client_id: 'system-client',
client_secret: 'system-secret',
scopes: ['crons', 'system', 'dashboard'],
tokens: [{ value: 'system-token', expiration: START + DAY }],
},
{
id: 2,
name: 'external',
client_id: 'external-client',
client_secret: 'external-secret',
scopes: ['crons'],
tokens: [],
},
];
let cached = clone(apps);
const matches = (app, where) => Object.entries(where).every(([key, value]) =>
Array.isArray(value) ? value.includes(app[key]) : app[key] === value);
const matches = (app, where) =>
Object.entries(where).every(([key, value]) =>
Array.isArray(value) ? value.includes(app[key]) : app[key] === value,
);
t.mock.method(AppModel, 'findOne', async ({ where }) => {
const app = apps.find((app) => matches(app, where));
if (!app) return null;
@@ -309,22 +400,36 @@ function appsFixture(t) {
await new Promise((resolve) => setTimeout(resolve, 10));
return { ...snapshot, get: () => snapshot };
});
t.mock.method(AppModel, 'findAll', async () => clone(apps).map((app) => ({ get: () => app })));
t.mock.method(AppModel, 'findAll', async () =>
clone(apps).map((app) => ({ get: () => app })),
);
t.mock.method(AppModel, 'update', async (values, { where }) => {
apps = apps.map((app) => matches(app, where) ? { ...app, ...clone(values) } : app);
apps = apps.map((app) =>
matches(app, where) ? { ...app, ...clone(values) } : app,
);
return [1];
});
t.mock.method(AppModel, 'destroy', async ({ where }) => {
apps = apps.filter((app) => !matches(app, where));
});
t.mock.method(AppModel, 'create', async (values) => {
const app = { id: Math.max(0, ...apps.map((app) => app.id)) + 1, tokens: [], ...values };
const app = {
id: Math.max(0, ...apps.map((app) => app.id)) + 1,
tokens: [],
...values,
};
apps.push(app);
return { get: () => clone(app) };
});
t.mock.method(shareStore, 'updateApps', async (values) => { cached = clone(values); });
t.mock.method(shareStore, 'updateApps', async (values) => {
cached = clone(values);
});
t.mock.method(shareStore, 'getApps', async () => clone(cached));
return { service: new OpenService({}), apps: () => clone(apps), cached: () => clone(cached) };
return {
service: new OpenService({}),
apps: () => clone(apps),
cached: () => clone(cached),
};
}
for (const operation of ['acquisition', 'startup refresh']) {
@@ -332,8 +437,12 @@ for (const operation of ['acquisition', 'startup refresh']) {
const state = appsFixture(t);
let resume;
let entered;
const paused = new Promise((resolve) => { entered = resolve; });
const barrier = new Promise((resolve) => { resume = resolve; });
const paused = new Promise((resolve) => {
entered = resolve;
});
const barrier = new Promise((resolve) => {
resume = resolve;
});
const findAll = AppModel.findAll;
let first = true;
AppModel.findAll = async (...args) => {
@@ -345,30 +454,48 @@ for (const operation of ['acquisition', 'startup refresh']) {
}
return snapshot;
};
const publication = operation === 'acquisition'
? state.service.generateSystemToken() : state.service.refreshApps();
const publication =
operation === 'acquisition'
? state.service.generateSystemToken()
: state.service.refreshApps();
await paused;
const issuance = state.service.authToken({ client_id: 'external-client', client_secret: 'external-secret' });
const issuance = state.service.authToken({
client_id: 'external-client',
client_secret: 'external-secret',
});
await new Promise((resolve) => setTimeout(resolve, 150));
resume();
const [, response] = await Promise.all([publication, issuance]);
assert.equal(response.code, 200);
assert.ok(state.apps()[1].tokens.some((token) => token.value === response.data.token));
assert.ok(
state
.apps()[1]
.tokens.some((token) => token.value === response.data.token),
);
assert.deepEqual(state.cached(), state.apps());
});
}
test('concurrent token API calls and scheduled generation preserve every issued token', async (t) => {
const state = appsFixture(t);
const credentials = { client_id: 'system-client', client_secret: 'system-secret' };
const credentials = {
client_id: 'system-client',
client_secret: 'system-secret',
};
const results = await Promise.all([
state.service.authToken(credentials), state.service.generateSystemToken(true),
state.service.authToken(credentials), state.service.generateSystemToken(true),
state.service.authToken(credentials),
state.service.generateSystemToken(true),
state.service.authToken(credentials),
state.service.generateSystemToken(true),
]);
const tokens = state.apps()[0].tokens;
assert.equal(tokens.length, 5);
for (const response of results) {
assert.ok(tokens.some((token) => token.value === (response.value || response.data.token)));
assert.ok(
tokens.some(
(token) => token.value === (response.value || response.data.token),
),
);
}
assert.deepEqual(state.cached(), state.apps());
});
@@ -376,17 +503,40 @@ test('concurrent token API calls and scheduled generation preserve every issued
for (const mutation of ['resetSecret', 'remove', 'update', 'create']) {
test(`concurrent cache refresh and ${mutation} retain the latest application state`, async (t) => {
const state = appsFixture(t);
await state.service.authToken({ client_id: 'external-client', client_secret: 'external-secret' });
const change = () => mutation === 'resetSecret' ? state.service.resetSecret(2)
: mutation === 'remove' ? state.service.remove([2])
: mutation === 'update' ? state.service.update({ id: 2, name: 'external', scopes: ['dashboard'] })
: state.service.create({ name: 'created', scopes: ['crons'] });
await Promise.all([state.service.refreshApps(), change(), state.service.generateSystemToken()]);
await state.service.authToken({
client_id: 'external-client',
client_secret: 'external-secret',
});
const change = () =>
mutation === 'resetSecret'
? state.service.resetSecret(2)
: mutation === 'remove'
? state.service.remove([2])
: mutation === 'update'
? state.service.update({
id: 2,
name: 'external',
scopes: ['dashboard'],
})
: state.service.create({ name: 'created', scopes: ['crons'] });
await Promise.all([
state.service.refreshApps(),
change(),
state.service.generateSystemToken(),
]);
assert.deepEqual(state.cached(), state.apps());
if (mutation === 'resetSecret') {
assert.equal(state.cached()[1].tokens.length, 0);
assert.notEqual(state.cached()[1].client_secret, 'external-secret');
assert.equal((await state.service.authToken({ client_id: 'external-client', client_secret: 'external-secret' })).code, 400);
assert.equal(
(
await state.service.authToken({
client_id: 'external-client',
client_secret: 'external-secret',
})
).code,
400,
);
} else if (mutation === 'remove') {
assert.equal(state.cached().length, 1);
} else if (mutation === 'update') {
@@ -416,7 +566,10 @@ test('application mutations cannot change or expose the built-in system app', as
test('system initialization preserves active tokens while migrating dashboard scope', async (t) => {
const state = appsFixture(t);
await AppModel.update({ scopes: ['crons', 'system'] }, { where: { id: 1 } });
await Promise.all([state.service.initializeSystemApp(), state.service.generateSystemToken(true)]);
await Promise.all([
state.service.initializeSystemApp(),
state.service.generateSystemToken(true),
]);
assert.deepEqual(state.cached(), state.apps());
assert.deepEqual(state.apps()[0].scopes, ['crons', 'system', 'dashboard']);
assert.equal(state.apps()[0].tokens.length, 2);
@@ -424,13 +577,19 @@ test('system initialization preserves active tokens while migrating dashboard sc
test('failed atomic token-file publication releases the application lock for recovery', async (t) => {
const state = appsFixture(t);
const temporary = path.join(config.configPath, `token.json.${process.pid}.tmp`);
const temporary = path.join(
config.configPath,
`token.json.${process.pid}.tmp`,
);
fs.mkdirSync(temporary);
await assert.rejects(state.service.generateSystemToken(), /EISDIR/);
fs.rmSync(temporary, { recursive: true });
const token = await state.service.generateSystemToken();
assert.equal(token.value, 'system-token');
assert.equal(fs.existsSync(path.join(config.configPath, '.apps-state.lock')), false);
assert.equal(
fs.existsSync(path.join(config.configPath, '.apps-state.lock')),
false,
);
});
test('real SQLite and authentication cache retain concurrent process updates', async (t) => {
@@ -438,10 +597,15 @@ test('real SQLite and authentication cache retain concurrent process updates', a
await AppModel.sync({ force: true });
const service = new OpenService({});
await service.initializeSystemApp();
const external = await service.create({ name: 'sqlite-external', scopes: ['crons'] });
const external = await service.create({
name: 'sqlite-external',
scopes: ['crons'],
});
const worker = path.join(environment, 'sqlite-worker.cjs');
const root = path.resolve(__dirname, '../..');
fs.writeFileSync(worker, `
fs.writeFileSync(
worker,
`
require(${JSON.stringify(require.resolve('reflect-metadata'))});
const path = require('node:path');
const root = process.cwd();
@@ -458,12 +622,33 @@ test('real SQLite and authentication cache retain concurrent process updates', a
console.log(JSON.stringify(result || {}));
})().catch(error => { console.error(error); process.exitCode = 1; })
.finally(async () => { await keyvStore.disconnect(); await sequelize.close(); });
`);
const actions = ['renew', 'acquire', 'auth', 'refresh', 'renew', 'auth', 'auth'];
const outcomes = await Promise.allSettled(actions.map((action) => execute(process.execPath, [
'-r', require.resolve('ts-node/register/transpile-only'), worker, action,
external.client_id, external.client_secret,
], { cwd: root, timeout: 20_000, env: process.env })));
`,
);
const actions = [
'renew',
'acquire',
'auth',
'refresh',
'renew',
'auth',
'auth',
];
const outcomes = await Promise.allSettled(
actions.map((action) =>
execute(
process.execPath,
[
'-r',
require.resolve('ts-node/register/transpile-only'),
worker,
action,
external.client_id,
external.client_secret,
],
{ cwd: root, timeout: 20_000, env: process.env },
),
),
);
const results = outcomes.map((outcome) => {
assert.equal(outcome.status, 'fulfilled', outcome.reason?.stderr);
return outcome.value;
@@ -475,14 +660,27 @@ test('real SQLite and authentication cache retain concurrent process updates', a
assert.equal(results[index].stderr, '');
const result = JSON.parse(results[index].stdout.trim());
const value = result.value || result.data?.token;
if (value) assert.ok(cached.some((app) => app.tokens?.some((token) => token.value === value)));
if (value)
assert.ok(
cached.some((app) =>
app.tokens?.some((token) => token.value === value),
),
);
}
assert.equal(database.find((app) => app.name === 'sqlite-external').tokens.length, 3);
const file = JSON.parse(fs.readFileSync(path.join(config.configPath, 'token.json'), 'utf8'));
assert.ok(cached.find((app) => app.name === 'system').tokens.some((token) => token.value === file.value));
assert.equal(
database.find((app) => app.name === 'sqlite-external').tokens.length,
3,
);
const file = JSON.parse(
fs.readFileSync(path.join(config.configPath, 'token.json'), 'utf8'),
);
assert.ok(
cached
.find((app) => app.name === 'system')
.tokens.some((token) => token.value === file.value),
);
});
test('atomic publication preserves restricted token-file permissions', async (t) => {
const state = fixture(t, [{ value: 'current', expiration: START + DAY }]);
const file = path.join(config.configPath, 'token.json');
@@ -493,7 +691,6 @@ test('atomic publication preserves restricted token-file permissions', async (t)
assert.equal(fs.statSync(file).mode & 0o777, 0o640);
});
test('a SIGKILLed generator leaves a lock that the next acquisition recovers', async (t) => {
const state = await processFixture(t);
const running = state.run(false, false, true);
@@ -505,9 +702,15 @@ test('a SIGKILLed generator leaves a lock that the next acquisition recovers', a
}
running.child.kill('SIGKILL');
assert.equal((await stopped).signal, 'SIGKILL');
assert.equal(fs.existsSync(path.join(state.directory, '.apps-state.lock')), true);
assert.equal(
fs.existsSync(path.join(state.directory, '.apps-state.lock')),
true,
);
const recovered = await state.run();
assert.equal(recovered.stderr, '');
assert.equal(recovered.stdout.trim(), state.cached().value);
assert.equal(fs.existsSync(path.join(state.directory, '.apps-state.lock')), false);
assert.equal(
fs.existsSync(path.join(state.directory, '.apps-state.lock')),
false,
);
});
+179 -54
View File
@@ -13,8 +13,17 @@ function extract(file, name) {
}
const helpers = [
fs.readFileSync('shell/task-timeout.sh', 'utf8'),
...['handle_task_start', 'handle_task_end', 'run_task_before', 'run_task_after', 'get_env_array', 'clear_env'].map(n => extract('shell/share.sh', n)),
...['run_shell_script', 'define_program', 'format_params'].map(n => extract('shell/task.sh', n)),
...[
'handle_task_start',
'handle_task_end',
'run_task_before',
'run_task_after',
'get_env_array',
'clear_env',
].map((n) => extract('shell/share.sh', n)),
...['run_shell_script', 'define_program', 'format_params'].map((n) =>
extract('shell/task.sh', n),
),
].join('\n');
const taskSource = path.resolve('shell/otask.sh');
@@ -23,10 +32,21 @@ function fixture(t) {
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const write = (name, body) => fs.writeFileSync(path.join(root, name), body);
write('env.sh', 'export QA_PANEL="alpha&beta&gamma"\n');
write('before.sh', 'export QA_BEFORE=ready\nqa_function() { printf "HOOK_FUNCTION\\n"; }\n');
write('after.sh', 'printf "AFTER:%s:%s\\n" "$QA_PANEL" "$QA_BEFORE" >> "$QA_ROOT/events"\n');
write(
'before.sh',
'export QA_BEFORE=ready\nqa_function() { printf "HOOK_FUNCTION\\n"; }\n',
);
write(
'after.sh',
'printf "AFTER:%s:%s\\n" "$QA_PANEL" "$QA_BEFORE" >> "$QA_ROOT/events"\n',
);
const run = (args, timeout = '') => {
const r = spawnSync('/bin/bash', ['-c', helpers + `
const r = spawnSync(
'/bin/bash',
[
'-c',
helpers +
`
dir_scripts=$QA_ROOT; dir_shell=$QA_ROOT; dir_dep=$QA_ROOT
file_env=$QA_ROOT/env.sh; file_task_before=$QA_ROOT/before.sh; file_task_after=$QA_ROOT/after.sh
ID=42; log_path=fixture.log; is_macos=0
@@ -41,32 +61,76 @@ function fixture(t) {
format_params "$@"; define_program "${'${task_shell_params[@]}'}"
. "$QA_TASK_SOURCE"
printf 'WRAPPER_FINISHED\\n' >> "$QA_ROOT/events"
`, 'fixture', ...args], { cwd: root, env: { ...process.env, command_timeout_time: timeout, QA_ROOT: root, QA_TASK_SOURCE: taskSource }, encoding: 'utf8', timeout: 10000 });
`,
'fixture',
...args,
],
{
cwd: root,
env: {
...process.env,
command_timeout_time: timeout,
QA_ROOT: root,
QA_TASK_SOURCE: taskSource,
},
encoding: 'utf8',
timeout: 10000,
},
);
assert.equal(r.status, 0, r.stdout + r.stderr);
return { stdout: r.stdout, events: fs.readFileSync(path.join(root, 'events'), 'utf8').trim().split('\n') };
return {
stdout: r.stdout,
events: fs
.readFileSync(path.join(root, 'events'), 'utf8')
.trim()
.split('\n'),
};
};
return { write, run };
}
test('managed task propagates the sourced script status through direct output, redirection and tee', t => {
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, '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',
});
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/);
@@ -81,20 +145,33 @@ for (const [label, body, code] of [
['errexit failure', 'set -e\nfalse\necho SHOULD_NOT_RUN', 1],
['script EXIT trap', `trap 'echo SCRIPT_EXIT_TRAP' EXIT\nexit 4`, 4],
]) {
test(`sourced shell ${label} still runs after hook and reports exactly one completion`, t => {
test(`sourced shell ${label} still runs after hook and reports exactly one completion`, (t) => {
const f = fixture(t);
f.write('probe.sh', `[[ "$QA_PANEL" == 'alpha&beta&gamma' && "$QA_BEFORE" == ready ]] || exit 99\nqa_function\n${body}\n`);
f.write(
'probe.sh',
`[[ "$QA_PANEL" == 'alpha&beta&gamma' && "$QA_BEFORE" == ready ]] || exit 99\nqa_function\n${body}\n`,
);
const r = f.run(['probe.sh']);
assert.match(r.stdout, /HOOK_FUNCTION/);
assert.doesNotMatch(r.stdout, /SHOULD_NOT_RUN/);
if (label === 'script EXIT trap') assert.match(r.stdout, /SCRIPT_EXIT_TRAP/);
assert.deepEqual(r.events, ['STATUS:0:', 'AFTER:alpha&beta&gamma:ready', `STATUS:1:${code}`, `STAT:${code}`, 'WRAPPER_FINISHED']);
if (label === 'script EXIT trap')
assert.match(r.stdout, /SCRIPT_EXIT_TRAP/);
assert.deepEqual(r.events, [
'STATUS:0:',
'AFTER:alpha&beta&gamma:ready',
`STATUS:1:${code}`,
`STAT:${code}`,
'WRAPPER_FINISHED',
]);
});
}
test('shell arguments and before-hook functions survive isolation while script state stays in the child', t => {
test('shell arguments and before-hook functions survive isolation while script state stays in the child', (t) => {
const f = fixture(t);
f.write('probe.sh', '[[ "$1" == "arg with spaces" ]] || exit 99\nqa_function\nexport QA_BEFORE=changed\ncd /\nexit 5\n');
f.write(
'probe.sh',
'[[ "$1" == "arg with spaces" ]] || exit 99\nqa_function\nexport QA_BEFORE=changed\ncd /\nexit 5\n',
);
const r = f.run(['probe.sh', '--', 'arg with spaces']);
assert.match(r.stdout, /HOOK_FUNCTION/);
assert.ok(r.events.includes('AFTER:alpha&beta&gamma:ready'));
@@ -105,42 +182,60 @@ for (const [label, args] of [
['explicit shell interpreter', ['bash', 'probe.sh', 'argument']],
['shell script with positional args', ['probe.sh', 'argument']],
]) {
test(`${label} preserves generated environment and reports failure`, t => {
test(`${label} preserves generated environment and reports failure`, (t) => {
const f = fixture(t);
f.write('probe.sh', '[[ "$QA_PANEL" == "alpha&beta&gamma" && "$QA_BEFORE" == ready && "$1" == argument ]] || exit 99\nexit 6\n');
f.write(
'probe.sh',
'[[ "$QA_PANEL" == "alpha&beta&gamma" && "$QA_BEFORE" == ready && "$1" == argument ]] || exit 99\nexit 6\n',
);
const r = f.run(args);
assert.ok(r.events.includes('STATUS:1:6'));
assert.equal(r.events.filter(x => x.startsWith('STATUS:1:')).length, 1);
assert.equal(r.events.filter((x) => x.startsWith('STATUS:1:')).length, 1);
});
}
test('explicit Python interpreter receives panel and before-hook environment', t => {
test('explicit Python interpreter receives panel and before-hook environment', (t) => {
const f = fixture(t);
f.write('probe.py', 'import os,sys\nassert os.environ["QA_PANEL"] == "alpha&beta&gamma"\nassert os.environ["QA_BEFORE"] == "ready"\nassert sys.argv[1] == "argument"\nsys.exit(8)\n');
assert.ok(f.run(['python3', 'probe.py', 'argument']).events.includes('STATUS:1:8'));
f.write(
'probe.py',
'import os,sys\nassert os.environ["QA_PANEL"] == "alpha&beta&gamma"\nassert os.environ["QA_BEFORE"] == "ready"\nassert sys.argv[1] == "argument"\nsys.exit(8)\n',
);
assert.ok(
f.run(['python3', 'probe.py', 'argument']).events.includes('STATUS:1:8'),
);
});
test('explicit Node interpreter retains generated environment', t => {
test('explicit Node interpreter retains generated environment', (t) => {
const f = fixture(t);
f.write('probe.cjs', 'if (process.env.QA_PANEL !== "alpha&beta&gamma" || process.env.QA_BEFORE !== "ready") process.exit(99); process.exit(8);\n');
f.write(
'probe.cjs',
'if (process.env.QA_PANEL !== "alpha&beta&gamma" || process.env.QA_BEFORE !== "ready") process.exit(99); process.exit(8);\n',
);
assert.ok(f.run(['node', 'probe.cjs']).events.includes('STATUS:1:8'));
});
test('plain commands retain generated environment', t => {
test('plain commands retain generated environment', (t) => {
const f = fixture(t);
assert.match(f.run(['printenv', 'QA_PANEL']).stdout, /alpha&beta&gamma/);
});
for (const mode of ['desi', 'conc']) {
test(`shell ${mode} keeps selected account values and completion reporting`, t => {
test(`shell ${mode} keeps selected account values and completion reporting`, (t) => {
const f = fixture(t);
f.write('probe.sh', 'printf "ACCOUNT=%s\\n" "$QA_PANEL"\nexit 0\n');
const r = f.run(['probe.sh', mode, 'QA_PANEL', '2-3']);
assert.match(r.stdout, mode === 'desi' ? /ACCOUNT=beta&gamma/ : /ACCOUNT=beta\nACCOUNT=gamma/);
assert.match(
r.stdout,
mode === 'desi' ? /ACCOUNT=beta&gamma/ : /ACCOUNT=beta\nACCOUNT=gamma/,
);
assert.doesNotMatch(r.stdout, /ACCOUNT=alpha/);
assert.ok(r.events.includes(`AFTER:${mode === 'desi' ? 'beta&gamma' : 'gamma'}:ready`));
assert.equal(r.events.filter(x => x === 'STATUS:1:0').length, 1);
assert.equal(r.events.filter(x => x.startsWith('AFTER:')).length, 1);
assert.ok(
r.events.includes(
`AFTER:${mode === 'desi' ? 'beta&gamma' : 'gamma'}:ready`,
),
);
assert.equal(r.events.filter((x) => x === 'STATUS:1:0').length, 1);
assert.equal(r.events.filter((x) => x.startsWith('AFTER:')).length, 1);
});
}
@@ -148,20 +243,36 @@ for (const [label, args] of [
['sourced shell', ['probe.sh', '--', 'space value']],
['explicit bash', ['bash', 'probe.sh', 'space value']],
]) {
test(`${label} timeout stops descendants and finalizes once with 124`, t => {
test(`${label} timeout stops descendants and finalizes once with 124`, (t) => {
const f = fixture(t);
f.write('before.sh', 'export QA_BEFORE=ready\nprivate_value=private\nprivate_array=(one "two words")\nqa_function() { printf "HOOK_FUNCTION\\n"; }\n');
f.write('probe.sh', `[[ "$QA_PANEL" == 'alpha&beta&gamma' && "$QA_BEFORE" == ready && "$1" == 'space value' ]] || exit 91\n${label === 'sourced shell' ? '[[ "$private_value" = private && "${private_array[1]}" = "two words" ]] || exit 92\nqa_function\n' : ''}trap 'echo EXIT_TRAP' EXIT\nsleep 3\necho SHOULD_NOT_RUN\n`);
f.write(
'before.sh',
'export QA_BEFORE=ready\nprivate_value=private\nprivate_array=(one "two words")\nqa_function() { printf "HOOK_FUNCTION\\n"; }\n',
);
f.write(
'probe.sh',
`[[ "$QA_PANEL" == 'alpha&beta&gamma' && "$QA_BEFORE" == ready && "$1" == 'space value' ]] || exit 91\n${
label === 'sourced shell'
? '[[ "$private_value" = private && "${private_array[1]}" = "two words" ]] || exit 92\nqa_function\n'
: ''
}trap 'echo EXIT_TRAP' EXIT\nsleep 3\necho SHOULD_NOT_RUN\n`,
);
const before = Date.now();
const r = f.run(args, '0.2s');
assert.ok(Date.now() - before < 2500, r.stdout);
assert.doesNotMatch(r.stdout, /SHOULD_NOT_RUN/);
assert.match(r.stdout, /EXIT_TRAP/);
assert.deepEqual(r.events, ['STATUS:0:', 'AFTER:alpha&beta&gamma:ready', 'STATUS:1:124', 'STAT:124', 'WRAPPER_FINISHED']);
assert.deepEqual(r.events, [
'STATUS:0:',
'AFTER:alpha&beta&gamma:ready',
'STATUS:1:124',
'STAT:124',
'WRAPPER_FINISHED',
]);
});
}
test('timeout escalates when a shell and its children ignore TERM', t => {
test('timeout escalates when a shell and its children ignore TERM', (t) => {
const f = fixture(t);
f.write('probe.sh', 'trap "" TERM\nsleep 3\necho SHOULD_NOT_RUN\n');
const before = Date.now();
@@ -171,7 +282,7 @@ test('timeout escalates when a shell and its children ignore TERM', t => {
assert.ok(r.events.includes('STATUS:1:124'));
});
test('completed timed tasks keep their exit code and do not wait for the timer', t => {
test('completed timed tasks keep their exit code and do not wait for the timer', (t) => {
const f = fixture(t);
f.write('probe.sh', 'exit 7\n');
const before = Date.now();
@@ -180,7 +291,7 @@ test('completed timed tasks keep their exit code and do not wait for the timer',
assert.ok(r.events.includes('STATUS:1:7'));
});
test('zero disables the deadline and invalid durations never start the script', t => {
test('zero disables the deadline and invalid durations never start the script', (t) => {
const f = fixture(t);
f.write('probe.sh', 'echo DID_RUN\n');
assert.match(f.run(['probe.sh'], '0s').stdout, /DID_RUN/);
@@ -191,28 +302,42 @@ test('zero disables the deadline and invalid durations never start the script',
});
for (const [runtime, filename, body] of [
['python3', 'timed.py', 'import time\nprint("STARTED", flush=True)\ntime.sleep(3)\nprint("SHOULD_NOT_RUN", flush=True)\n'],
['node', 'timed.cjs', 'console.log("STARTED"); setTimeout(() => console.log("SHOULD_NOT_RUN"), 3000);\n'],
[
'python3',
'timed.py',
'import time\nprint("STARTED", flush=True)\ntime.sleep(3)\nprint("SHOULD_NOT_RUN", flush=True)\n',
],
[
'node',
'timed.cjs',
'console.log("STARTED"); setTimeout(() => console.log("SHOULD_NOT_RUN"), 3000);\n',
],
]) {
test(`${runtime} timeout stops execution and reports 124`, t => {
test(`${runtime} timeout stops execution and reports 124`, (t) => {
const f = fixture(t);
f.write(filename, body);
const r = f.run([runtime, filename], '0.5s');
assert.match(r.stdout, /STARTED/);
assert.doesNotMatch(r.stdout, /SHOULD_NOT_RUN/);
assert.ok(r.events.includes('STATUS:1:124'));
assert.equal(r.events.filter(x => x.startsWith('AFTER:')).length, 1);
assert.equal(r.events.filter((x) => x.startsWith('AFTER:')).length, 1);
});
}
for (const mode of ['desi', 'conc']) {
test(`timed shell ${mode} preserves selected accounts and terminates every worker`, t => {
test(`timed shell ${mode} preserves selected accounts and terminates every worker`, (t) => {
const f = fixture(t);
f.write('probe.sh', 'echo "ACCOUNT=$QA_PANEL"\nsleep 3\necho SHOULD_NOT_RUN\n');
f.write(
'probe.sh',
'echo "ACCOUNT=$QA_PANEL"\nsleep 3\necho SHOULD_NOT_RUN\n',
);
const r = f.run(['probe.sh', mode, 'QA_PANEL', '2-3'], '0.2s');
assert.match(r.stdout, mode === 'desi' ? /ACCOUNT=beta&gamma/ : /ACCOUNT=beta\nACCOUNT=gamma/);
assert.match(
r.stdout,
mode === 'desi' ? /ACCOUNT=beta&gamma/ : /ACCOUNT=beta\nACCOUNT=gamma/,
);
assert.doesNotMatch(r.stdout, /SHOULD_NOT_RUN/);
assert.equal(r.events.filter(x => x.startsWith('AFTER:')).length, 1);
assert.equal(r.events.filter((x) => x.startsWith('AFTER:')).length, 1);
// Concurrent mode retains its existing aggregate wait status behavior.
assert.ok(r.events.includes(`STATUS:1:${mode === 'desi' ? 124 : 0}`));
});
+6 -3
View File
@@ -115,12 +115,15 @@ handle_task_end
);
});
test('scheduled tasks starting in the same millisecond write different files', t => {
run(t, `log_name=common
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 ]]`);
[[ "$log_path" == common/2026-09-12-23-59-59-999.log ]]`,
);
});
+187
View File
@@ -0,0 +1,187 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { Sequelize, QueryTypes } = require('sequelize');
const load = require('../helpers/load-security-module.cjs');
const { installTriggerHistory } = require('../../back/cron/history');
const {
TriggerLifecycle,
} = require('../../back/cron/execution/triggerLifecycle');
async function fixture(t) {
const db = new Sequelize({
dialect: 'sqlite',
storage: ':memory:',
logging: false,
});
t.after(() => db.close());
const tasks = load('back/data/cron.ts', { './index': { sequelize: db } });
const instances = load('back/data/runningInstance.ts', {
'./index': { sequelize: db },
});
load('back/data/cronStats.ts', { './index': { sequelize: db } });
await db.sync();
await db.transaction((tx) => installTriggerHistory(db, tx));
await tasks.CrontabModel.create({ id: 1, command: 'true', status: 1 });
const unexpected = async () =>
assert.fail('unexpected exit evidence operation');
const evidence = {
exitBeforeStop: unexpected,
completeCommandExit: unexpected,
recoverScriptSample: unexpected,
// This fixture has no receipts to replay, but recovery must pass its transaction.
replayPublishedExits: async (tx) => assert.ok(tx && !tx.finished),
};
const lifecycle = new TriggerLifecycle(db, evidence);
const rows = () =>
db.query('SELECT * FROM CronTriggers ORDER BY id', {
type: QueryTypes.SELECT,
});
return { db, lifecycle, evidence, rows, instances };
}
test('lifecycle admission, start and terminal writes roll back with the caller transaction', async (t) => {
const { db, lifecycle, rows } = await fixture(t);
await assert.rejects(
db.transaction(async (tx) => {
assert.equal(
await lifecycle.enqueue('rolled-back', 1, 'manual', null, 100, tx),
true,
);
assert.equal(await lifecycle.start('rolled-back', 200, false, tx), true);
await lifecycle.finish('rolled-back', 'failed', 'spawn', 1, tx, 300);
throw Error('caller rollback');
}),
/caller rollback/,
);
assert.deepEqual(await rows(), []);
await lifecycle.enqueue('queued', 1, 'manual', null, 100);
await lifecycle.enqueue('claimed', 1, 'manual', null, 100);
await lifecycle.start('claimed', 200);
await assert.rejects(
db.transaction(async (tx) => {
assert.deepEqual(await lifecycle.cancelQueuedInTransaction([1], tx), [
'queued',
]);
await lifecycle.queueInstanceStop(10, 1, 12345, tx);
throw Error('stop snapshot rollback');
}),
/stop snapshot rollback/,
);
assert.deepEqual(
(await rows()).map((row) => [row.id, row.state, row.stop_requested]),
[
['claimed', 'running', null],
['queued', 'queued', null],
],
);
assert.deepEqual(await lifecycle.pendingStops(), []);
});
test('restart recovery requeues only unstarted slots and leaves unknown and terminal results deduplicated', async (t) => {
const { lifecycle, rows } = await fixture(t);
assert.equal(await lifecycle.enqueue('uncertain', 1, 'node', 100, 100), true);
assert.equal(
await lifecycle.enqueue('uncertain', 1, 'node', 100, 100),
false,
);
assert.equal(await lifecycle.start('uncertain', 200), true);
await lifecycle.enqueue('unstarted', 1, 'node', 100, 100);
await lifecycle.interrupt(process.env.SERVICE_TYPE || 'http');
assert.deepEqual(
(await rows()).map((row) => [row.id, row.state, row.reason, row.exit_code]),
[
['uncertain', 'unknown', 'restart', null],
['unstarted', 'skipped', 'restart', null],
],
);
assert.equal(
await lifecycle.enqueue('uncertain', 1, 'recovery', 100, 300),
false,
);
assert.equal(await lifecycle.start('uncertain', 300), false);
assert.equal(
await lifecycle.enqueue('unstarted', 1, 'recovery', 100, 300),
true,
);
assert.equal(
await lifecycle.enqueue('unstarted', 1, 'recovery', 100, 300),
false,
);
assert.equal(await lifecycle.start('unstarted', 400), true);
await lifecycle.finish('unstarted', 'finished', null, 0, undefined, 500);
assert.equal(
await lifecycle.enqueue('unstarted', 1, 'recovery', 100, 600),
false,
);
await lifecycle.finish(
'unstarted',
'failed',
'late retry',
1,
undefined,
700,
);
const results = await rows();
assert.deepEqual(
results.map((row) => [row.id, row.state, row.exit_code]),
[
['uncertain', 'unknown', null],
['unstarted', 'finished', 0],
],
);
assert.equal(results[1].finished_at, 500);
});
test('failed exit settlement preserves the durable stop snapshot and rolls back state before any signal', async (t) => {
const { db, lifecycle, evidence, rows, instances } = await fixture(t);
await lifecycle.enqueue('run', 1, 'manual', null, 100);
await lifecycle.start('run', 200);
const instance = await instances.RunningInstanceModel.create({
cron_id: 1,
pid: 12345,
status: 0,
started_at: 1,
});
await db.query('UPDATE CronTriggers SET instance_id=$instance WHERE id=$id', {
bind: { instance: instance.id, id: 'run' },
});
evidence.exitBeforeStop = async () => ({
canonical: {
version: 1,
code: 0,
signal: null,
time: 300,
file: '/fixture/receipt',
},
recovered: [],
published: true,
unreadable: false,
});
let attempts = 0;
evidence.completeCommandExit = async (id, state, reason, code, tx) => {
attempts++;
assert.equal(state, 'unknown');
assert.ok(tx && !tx.finished);
await lifecycle.finish(id, 'finished', null, 0, tx, 300);
throw Error('ledger unavailable');
};
const targets = ['crond:12345:fixture-birth'];
await assert.rejects(
lifecycle.requestInstanceStop(
instance.id,
12345,
() => assert.fail('must not signal before evidence is settled'),
targets,
),
/ledger unavailable/,
);
assert.equal(attempts, 1);
const [row] = await rows();
assert.equal(row.state, 'running');
assert.equal(row.exit_code, null);
assert.equal(row.stop_requested, null);
const pending = await lifecycle.pendingStop(instance.id);
assert.equal(pending.signalled, 0);
assert.deepEqual(JSON.parse(pending.targets), targets);
});
+86
View File
@@ -0,0 +1,86 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { Sequelize, QueryTypes } = require('sequelize');
const load = require('../helpers/load-security-module.cjs');
const { TriggerQueries } = require('../../back/cron/queries/triggerQueries');
const {
TriggerHistory,
installTriggerHistory,
} = require('../../back/cron/history');
test('history queries work on a read-only database without resolving uncertain exits', async (t) => {
// The in-memory database shares one connection, including audit snapshots,
// so query_only prevents writes throughout the complete read path.
const db = new Sequelize({
dialect: 'sqlite',
storage: ':memory:',
logging: false,
});
t.after(() => db.close());
load('back/data/cron.ts', { './index': { sequelize: db } });
load('back/data/runningInstance.ts', { './index': { sequelize: db } });
load('back/data/cronStats.ts', { './index': { sequelize: db } });
await db.sync();
await db.transaction((tx) => installTriggerHistory(db, tx));
await db.query(`INSERT INTO CronTriggers
(id,cron_id,source,state,reason,exit_code,finished_at,exit_pending,observed_at)
VALUES ('a-restart',1,'manual','unknown','restart',0,200,0,100),
('b-pending',1,'legacy','unknown','restart',0,200,1,100),
('c-conflict',1,'legacy','unknown','restart',0,200,1,100),
('d-finished',1,'manual','finished',NULL,0,200,0,100),
('other-task',2,'manual','finished',NULL,0,200,0,100)`);
await db.query(`INSERT INTO CronExitObservations VALUES
('c-conflict','0',200), ('c-conflict','1',200)`);
const storedRows = () =>
db.query('SELECT * FROM CronTriggers ORDER BY id', {
type: QueryTypes.SELECT,
});
const before = await storedRows();
await db.query('PRAGMA query_only=ON');
await assert.rejects(
db.query("UPDATE CronTriggers SET state='finished'"),
/readonly/i,
);
const queries = new TriggerQueries(db);
const compatibility = new TriggerHistory(db);
const ids = before.map((row) => row.id);
const selected = await queries.visibleTriggers(1, ids);
assert.deepEqual(
selected.map((row) => [
row.id,
row.state,
row.reason,
row.exit_code,
row.finished_at,
]),
[
['a-restart', 'unknown', 'restart', null, null],
['b-pending', 'unknown', 'exit_pending', null, null],
['c-conflict', 'unknown', 'exit_conflict', null, null],
['d-finished', 'finished', null, 0, 200],
],
);
assert.deepEqual(await compatibility.visibleTriggers(1, ids), selected);
const first = await queries.recent(1, 0, 2);
assert.deepEqual(
first.map((row) => row.id),
['d-finished', 'c-conflict'],
);
const cursor = { time: first[1].observed_at, id: first[1].id };
const older = await queries.recent(1, 0, 2, cursor);
assert.deepEqual(
older.map((row) => row.id),
['b-pending', 'a-restart'],
);
assert.deepEqual(await queries.recent(1, 2, 2), older);
assert.deepEqual(await compatibility.recent(1, 0, 2, cursor), older);
const metrics = await queries.metrics(0);
assert.equal(metrics.observed, 5);
assert.equal(metrics.planned, 0);
assert.equal(metrics.waitP95, null);
assert.deepEqual(await compatibility.metrics(0), metrics);
assert.deepEqual(await storedRows(), before);
});
+275
View File
@@ -0,0 +1,275 @@
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 { QueryTypes } = require('sequelize');
const load = require('../helpers/load-security-module.cjs');
const { installTriggerHistory } = require('../../back/cron/history');
const {
TriggerLifecycle,
} = require('../../back/cron/execution/triggerLifecycle');
const {
TriggerSettlement,
} = require('../../back/cron/settlement/triggerSettlement');
const {
readExit,
writeExit,
receiptPath,
} = require('../../back/cron/settlement/exitReceipt.cjs');
async function fixture(t) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-settlement-'));
const db = load('back/data/index.ts', {
'../config/index': { dbPath: root },
}).sequelize;
const models = load('back/data/cron.ts', { './index': { sequelize: db } });
const instances = load('back/data/runningInstance.ts', {
'./index': { sequelize: db },
});
load('back/data/cronStats.ts', { './index': { sequelize: db } });
for (const key of ['QL_DIR', 'QL_DATA_DIR']) {
const previous = process.env[key];
process.env[key] = root;
t.after(() => {
if (previous === undefined) delete process.env[key];
else process.env[key] = previous;
});
}
t.after(async () => {
await db.close();
await fs.rm(root, { recursive: true, force: true });
});
await db.sync();
await db.transaction((tx) => installTriggerHistory(db, tx));
await models.CrontabModel.create({
id: 1,
command: 'true',
status: 1,
allow_multiple_instances: 1,
});
// Compose the two modules directly, without a TriggerHistory instance.
function components() {
let lifecycle;
const settlement = new TriggerSettlement(db, {
finish: (...args) => lifecycle.finish(...args),
shouldStop: (...args) => lifecycle.shouldStop(...args),
});
lifecycle = new TriggerLifecycle(db, settlement);
return { lifecycle, settlement };
}
const { lifecycle, settlement } = components();
const start = new Date().setHours(0, 0, 0, 0) - 60_000;
async function seed(id) {
await lifecycle.enqueue(id, 1, 'manual', null, start);
assert.equal(await lifecycle.start(id, start, true), true);
assert.equal(
await lifecycle.bindCommand(id, process.pid, id + '.log'),
true,
);
}
const rows = () =>
db.query('SELECT * FROM CronTriggers ORDER BY id', {
type: QueryTypes.SELECT,
});
const stats = () =>
db.query(
'SELECT run_count,success_count,fail_count,total_time,max_time FROM CrontabStats',
{ type: QueryTypes.SELECT },
);
return {
db,
seed,
start,
lifecycle,
settlement,
components,
rows,
stats,
instances,
};
}
test('caller rollback preserves exit evidence, state and statistics; a fresh settlement books the replay once', async (t) => {
const { db, seed, start, settlement, components, rows, stats, instances } =
await fixture(t);
await seed('rollback');
writeExit('rollback', 17, null, start + 1000);
await assert.rejects(
db.transaction(async (tx) => {
await settlement.completeCommandExit('rollback', 'finished', null, 0, tx);
const [row] = await db.query('SELECT counted FROM CronTriggers', {
transaction: tx,
type: QueryTypes.SELECT,
});
assert.equal(row.counted, 1);
throw Error('caller rollback');
}),
/caller rollback/,
);
assert.deepEqual(
(await rows()).map((r) => [r.state, r.exit_code, r.counted]),
[['running', null, 0]],
);
assert.deepEqual(await stats(), []);
assert.equal((await instances.RunningInstanceModel.findOne()).status, 0);
assert.equal((await readExit('rollback')).code, 17);
const restarted = components().settlement;
await db.transaction((tx) => restarted.replayPublishedExits(tx));
writeExit('rollback', 17, null, start + 1000);
await restarted.retryPendingExits();
await restarted.complete('rollback', 'finished', null, 0);
assert.deepEqual(
(await rows()).map((r) => [r.state, r.exit_code, r.counted]),
[['failed', 17, 1]],
);
assert.deepEqual(await stats(), [
{
run_count: 1,
success_count: 0,
fail_count: 1,
total_time: 1000,
max_time: 1000,
},
]);
assert.equal((await instances.RunningInstanceModel.findOne()).status, 3);
assert.equal(await readExit('rollback'), undefined);
});
test('failed COMMIT keeps the receipt despite afterCommit hooks and allows exactly one later booking', async (t) => {
const { db, seed, start, settlement, rows, stats } = await fixture(t);
await seed('commit-failure');
writeExit('commit-failure', 0, null, start + 2000);
await db.query('CREATE TABLE required_parent(id INTEGER PRIMARY KEY)');
await db.query(
'CREATE TABLE deferred_child(id INTEGER REFERENCES required_parent(id) DEFERRABLE INITIALLY DEFERRED)',
);
await db.query(
'CREATE TRIGGER fail_settlement_commit AFTER INSERT ON CrontabStats BEGIN INSERT INTO deferred_child VALUES (1); END',
);
await assert.rejects(
settlement.complete('commit-failure', 'failed', null, 1),
/constraint|foreign key/i,
);
assert.deepEqual(
(await rows()).map((r) => [r.state, r.counted]),
[['running', 0]],
);
assert.deepEqual(await stats(), []);
assert.equal((await readExit('commit-failure')).code, 0);
await db.query('DROP TRIGGER fail_settlement_commit');
await settlement.complete('commit-failure', 'unknown', 'restart', null);
await settlement.complete('commit-failure', 'unknown', 'restart', null);
assert.deepEqual(await stats(), [
{
run_count: 1,
success_count: 1,
fail_count: 0,
total_time: 2000,
max_time: 2000,
},
]);
assert.equal(await readExit('commit-failure'), undefined);
});
for (const conflict of ['code', 'time']) {
test(`conflicting bound ${conflict} withdraws only its own booking and remains unknown through replay`, async (t) => {
const { seed, start, lifecycle, settlement, rows, stats, db } =
await fixture(t);
for (const [id, duration] of [
['disputed', 3000],
['sibling', 1000],
]) {
await seed(id);
writeExit(id, 0, null, start + duration);
await settlement.complete(id, 'finished', null, 0);
}
writeExit(
'disputed',
conflict === 'code' ? 23 : 0,
null,
start + (conflict === 'time' ? 4000 : 3000),
);
await settlement.retryPendingExits();
await settlement.retryPendingExits();
await settlement.recordShellResult('disputed', 1, 0, 3000, start + 3000);
assert.deepEqual(
(await rows()).map((r) => [r.id, r.state, r.exit_code, r.counted]),
[
['disputed', 'unknown', null, 0],
['sibling', 'finished', 0, 1],
],
);
assert.deepEqual(await stats(), [
{
run_count: 1,
success_count: 1,
fail_count: 0,
total_time: 1000,
max_time: 1000,
},
]);
assert.equal(
await lifecycle.enqueue('disputed', 1, 'recovery', null, start + 5000),
false,
);
const conflicts = await db.query('SELECT * FROM CronBoundExitConflicts', {
type: QueryTypes.SELECT,
});
assert.equal(conflicts.length, 2);
assert.ok(
await readExit('disputed'),
'conflicting durable evidence must remain available',
);
});
}
test('a damaged receipt stays unknown and uncounted until verified evidence repairs the result', async (t) => {
const { seed, start, lifecycle, settlement, rows, stats } = await fixture(t);
await seed('damaged');
const file = receiptPath('damaged');
await fs.mkdir(path.dirname(file), { recursive: true });
await fs.writeFile(file, '{"version":1');
await settlement.complete(
'damaged',
'finished',
null,
0,
start + 1000,
'legacy',
);
await settlement.retryPendingExits();
assert.deepEqual(
(await rows()).map((r) => [
r.state,
r.exit_code,
r.counted,
r.exit_pending,
]),
[['unknown', null, 0, 1]],
);
assert.deepEqual(await stats(), []);
assert.equal(
await lifecycle.enqueue('damaged', 1, 'recovery', null, start + 2000),
false,
);
assert.equal(await fs.readFile(file, 'utf8'), '{"version":1');
await fs.unlink(file);
writeExit('damaged', 23, null, start + 1000);
await settlement.retryPendingExits();
await settlement.retryPendingExits();
assert.deepEqual(
(await rows()).map((r) => [r.state, r.exit_code, r.counted]),
[['failed', 23, 1]],
);
assert.deepEqual(await stats(), [
{
run_count: 1,
success_count: 0,
fail_count: 1,
total_time: 1000,
max_time: 1000,
},
]);
});
+1 -1
View File
@@ -17,7 +17,7 @@ function service(request) {
'../data/dependence': {},
'../data/notify': {},
'../data/system': {},
'../shared/pLimit': {},
'../cron/execution/cronLimit': {},
'../schedule/client': {},
'../shared/i18n': { t: (key) => key },
'./notify': class {},
+4 -1
View File
@@ -107,7 +107,10 @@ test('explicit CLI GitHub selection does not switch providers', async (t) => {
});
test('checksum validation failure never retries from another mirror', async (t) => {
const f = await fixture(t, () => false, 'gitee', true);
await assert.rejects(f.operation, /checksum mismatch|构建文件缺失、损坏或混入旧文件/);
await assert.rejects(
f.operation,
/checksum mismatch|构建文件缺失、损坏或混入旧文件/,
);
assert.equal(f.urls.length, 2);
assert.deepEqual(fs.readdirSync(f.tmp), []);
});
+12 -3
View File
@@ -88,7 +88,10 @@ for (const legacy of [true, false])
try {
await entered;
const contender = await Promise.race(attempts);
assert.match(contender.error?.message || '', /Another upgrade|已有更新或重载/);
assert.match(
contender.error?.message || '',
/Another upgrade|已有更新或重载/,
);
assert.equal(maximum, 1);
assert.equal((await original.readdir(lock)).length, 1);
} finally {
@@ -235,7 +238,10 @@ test(
res.once('close', () => clearInterval(timer));
});
const began = Date.now();
await assert.rejects(waitForHealth({ QlPort: port }, 80), /health check|后端启动检查失败/);
await assert.rejects(
waitForHealth({ QlPort: port }, 80),
/health check|后端启动检查失败/,
);
assert.ok(
Date.now() - began < 1000,
'deadline must not depend on socket inactivity',
@@ -280,7 +286,10 @@ for (const streaming of [false, true])
test('unhealthy, malformed and oversized health responses fail within the deadline', async (t) => {
for (const body of ['{}', '{', ' '.repeat(65537)]) {
const port = await healthServer(t, (req, res) => res.end(body));
await assert.rejects(waitForHealth({ QlPort: port }, 20), /health check|后端启动检查失败/);
await assert.rejects(
waitForHealth({ QlPort: port }, 20),
/health check|后端启动检查失败/,
);
}
});
+20 -6
View File
@@ -14,10 +14,17 @@ 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]);
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');
assert.equal(
new Set(groups).size,
groups.length,
'a retired process group was signalled twice',
);
};
}
@@ -34,7 +41,10 @@ for (const [version, exitCode] of [
survivor = path.join(root, 'survivor');
await fs.mkdir(path.join(source, 'node_modules'), { recursive: true });
await fs.mkdir(path.join(statics, 'build/bootstrap'), { recursive: true });
await fs.writeFile(path.join(source, 'version.yaml'), `version: ${version}`);
await fs.writeFile(
path.join(source, 'version.yaml'),
`version: ${version}`,
);
await fs.writeFile(path.join(statics, 'build/app.js'), 'backend');
await fs.writeFile(
path.join(statics, 'build-info.json'),
@@ -49,7 +59,9 @@ for (const [version, exitCode] of [
${JSON.stringify(survivor)}],{stdio:'inherit'});
process.send({type:'upgrade-probe',ok:${
exitCode === 0
},message:'simulated prestart failure',build:{sourceCommit:'a'.repeat(40),version:${JSON.stringify(version)},backendSha256:crypto.createHash('sha256').update('backend').digest('hex')}},()=>process.exit(${exitCode}));
},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);
@@ -148,7 +160,9 @@ test('cancelled dependency repair kills descendants and retains the original tre
if(process.argv[2]==='--version'){console.log('8.3.1');process.exit(0);}
require('node:child_process').spawn(process.execPath,['-e',
"process.on('SIGTERM',()=>{});require('node:fs').writeFileSync(process.argv[1],'started');setTimeout(()=>require('node:fs').writeFileSync(process.argv[2],'escaped'),1400);",
${JSON.stringify(started)},${JSON.stringify(survivor)}],{stdio:'inherit'});
${JSON.stringify(started)},${JSON.stringify(
survivor,
)}],{stdio:'inherit'});
setInterval(()=>{},1000);
`,
{ mode: 0o755 },
+190 -72
View File
@@ -5,27 +5,52 @@ const vm = require('node:vm');
const { EventEmitter } = require('node:events');
const ts = require('typescript');
const load = require('../helpers/load-security-module.cjs');
const { SchedulerReadiness } = load('back/shared/schedulerReadiness.ts');
const { SchedulerReadiness } = load(
'back/cron/scheduling/schedulerReadiness.ts',
);
const { outputText } = ts.transpileModule(
fs.readFileSync('back/bootstrap/upgradeProbe.ts', 'utf8'),
{ compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020, esModuleInterop: true } },
{
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2020,
esModuleInterop: true,
},
},
);
// Run the real probe entry point, including its lifecycle and IPC reporting.
// Only external services and the clock are replaced; no test exports are needed.
async function runProbe({ readiness, arch = 'x64', armVersion, supervised = true }) {
async function runProbe({
readiness,
arch = 'x64',
armVersion,
supervised = true,
}) {
let now = 0;
const events = [], waits = [], messages = [];
const events = [],
waits = [],
messages = [];
const build = { sourceCommit: 'a'.repeat(40) };
let finish;
const completed = new Promise((resolve) => { finish = resolve; });
const completed = new Promise((resolve) => {
finish = resolve;
});
const listener = { address: () => ({ port: 12345 }) };
const server = {
initialize: async () => { events.push('http'); return listener; },
shutdown: async () => { events.push('http-close'); },
initialize: async () => {
events.push('http');
return listener;
},
shutdown: async () => {
events.push('http-close');
},
};
const grpc = {
initialize: async () => { events.push('grpc'); return 12346; },
initialize: async () => {
events.push('grpc');
return 12346;
},
getServer: () => ({ forceShutdown: () => events.push('grpc-close') }),
};
class GrpcServerService {}
@@ -34,13 +59,23 @@ async function runProbe({ readiness, arch = 'x64', armVersion, supervised = true
'reflect-metadata': {},
dns: { setDefaultResultOrder: () => {} },
'../config': {},
'../data': { sequelize: {
transaction: async (action) => action({}),
query: async () => [[{ value: 42 }]],
close: async () => { events.push('db-close'); },
} },
'../loaders/db': async () => { events.push('db'); },
typedi: { Container: { get: (service) => service === GrpcServerService ? grpc : server } },
'../data': {
sequelize: {
transaction: async (action) => action({}),
query: async () => [[{ value: 42 }]],
close: async () => {
events.push('db-close');
},
},
},
'../loaders/db': async () => {
events.push('db');
},
typedi: {
Container: {
get: (service) => (service === GrpcServerService ? grpc : server),
},
},
'../services/grpc': { GrpcServerService },
'../services/http': { HttpServerService },
'../loaders/httpApplication': { createHttpApplication: async () => ({}) },
@@ -48,86 +83,154 @@ async function runProbe({ readiness, arch = 'x64', armVersion, supervised = true
'../loaders/express': () => {},
'../loaders/app': {},
'../loaders/depInjector': () => {},
'../schedule/client': { readiness: {
configure: (restore) => readiness.configure(restore),
recover: async () => {
const ready = await readiness.recover();
if (ready) events.push('ready');
return ready;
'../schedule/client': {
readiness: {
configure: (restore) => readiness.configure(restore),
recover: async () => {
const ready = await readiness.recover();
if (ready) events.push('ready');
return ready;
},
},
} },
http: { get: (url, respond) => {
events.push('health');
const request = new EventEmitter();
request.setTimeout = () => {};
queueMicrotask(() => {
const response = new EventEmitter();
response.statusCode = 200;
respond(response);
response.emit('data', JSON.stringify({ code: 200, data: { status: 'ok', services: { grpc: true, http: true }, build } }));
response.emit('end');
});
return request;
} },
},
http: {
get: (url, respond) => {
events.push('health');
const request = new EventEmitter();
request.setTimeout = () => {};
queueMicrotask(() => {
const response = new EventEmitter();
response.statusCode = 200;
respond(response);
response.emit(
'data',
JSON.stringify({
code: 200,
data: {
status: 'ok',
services: { grpc: true, http: true },
build,
},
}),
);
response.emit('end');
});
return request;
},
},
};
vm.runInNewContext(outputText, {
exports: {},
require: (name) => {
assert.ok(Object.hasOwn(modules, name), `Unexpected probe dependency: ${name}`);
return modules[name];
vm.runInNewContext(
outputText,
{
exports: {},
require: (name) => {
assert.ok(
Object.hasOwn(modules, name),
`Unexpected probe dependency: ${name}`,
);
return modules[name];
},
process: {
env: { QL_UPGRADE_PROBE: supervised ? '1' : '0' },
arch,
config: { variables: { arm_version: armVersion } },
pid: 123,
once: () => {},
memoryUsage: () => ({}),
send: (message) => {
messages.push(message);
events.push('report');
},
exit: finish,
},
Date: { now: () => now },
setTimeout: (callback, ms) => {
assert.ok(ms > 0 && ms <= 250);
waits.push(ms);
now += ms;
queueMicrotask(callback);
},
console: { error: () => {} },
},
process: {
env: { QL_UPGRADE_PROBE: supervised ? '1' : '0' }, arch,
config: { variables: { arm_version: armVersion } }, pid: 123,
once: () => {}, memoryUsage: () => ({}),
send: (message) => { messages.push(message); events.push('report'); },
exit: finish,
},
Date: { now: () => now },
setTimeout: (callback, ms) => {
assert.ok(ms > 0 && ms <= 250);
waits.push(ms);
now += ms;
queueMicrotask(callback);
},
console: { error: () => {} },
}, { filename: 'upgradeProbe.js' });
{ filename: 'upgradeProbe.js' },
);
const exitCode = await completed;
return { exitCode, events, waits, messages, elapsed: now, build };
}
test('upgrade probe survives cold scheduler recovery before checking HTTP and reporting readiness', async () => {
let attempts = 0, restored = false;
let attempts = 0,
restored = false;
const readiness = new SchedulerReadiness(async () => {
if (++attempts < 3) throw new Error('Failed to connect before the deadline');
if (++attempts < 3)
throw new Error('Failed to connect before the deadline');
});
// The probe must configure and finish restoration before reporting readiness.
const configure = readiness.configure.bind(readiness);
readiness.configure = (restore) => configure(async () => { await restore(); restored = true; });
readiness.configure = (restore) =>
configure(async () => {
await restore();
restored = true;
});
const result = await runProbe({ readiness });
assert.equal(result.exitCode, 0);
assert.equal(restored, true);
assert.equal(await readiness.check(), true);
assert.deepEqual(result.waits, [250, 250]);
assert.deepEqual(result.events, ['db', 'grpc', 'ready', 'http', 'health', 'report', 'http-close', 'grpc-close', 'db-close']);
assert.deepEqual(result.events, [
'db',
'grpc',
'ready',
'http',
'health',
'report',
'http-close',
'grpc-close',
'db-close',
]);
assert.equal(result.messages.length, 1);
assert.equal(result.messages[0].ok, true);
assert.equal(result.messages[0].build.sourceCommit, result.build.sourceCommit);
assert.equal(
result.messages[0].build.sourceCommit,
result.build.sourceCommit,
);
});
for (const [arch, armVersion, timeout] of [['x64', undefined, 10000], ['arm', 7, 10000], ['arm', '6', 60000]]) {
for (const [arch, armVersion, timeout] of [
['x64', undefined, 10000],
['arm', 7, 10000],
['arm', '6', 60000],
]) {
test(`unavailable ${arch}/v${armVersion} scheduler fails at its startup budget and cleans up`, async () => {
let attempts = 0;
const result = await runProbe({ arch, armVersion, readiness: {
configure: () => {}, recover: async () => { attempts++; return false; },
} });
const result = await runProbe({
arch,
armVersion,
readiness: {
configure: () => {},
recover: async () => {
attempts++;
return false;
},
},
});
assert.equal(result.exitCode, 1);
assert.equal(result.elapsed, timeout);
assert.equal(attempts, timeout / 250);
assert.deepEqual(result.events, ['db', 'grpc', 'http-close', 'grpc-close', 'db-close', 'report']);
assert.deepEqual(result.events, [
'db',
'grpc',
'http-close',
'grpc-close',
'db-close',
'report',
]);
assert.equal(result.messages.length, 1);
assert.equal(result.messages[0].ok, false);
assert.match(result.messages[0].message, /Upgrade scheduler readiness failed/);
assert.match(
result.messages[0].message,
/Upgrade scheduler readiness failed/,
);
await new Promise((resolve) => setImmediate(resolve));
assert.equal(attempts, timeout / 250, 'no retries after failure');
});
@@ -135,20 +238,35 @@ for (const [arch, armVersion, timeout] of [['x64', undefined, 10000], ['arm', 7,
test('unexpected scheduler recovery errors fail prestart without retries or a success report', async () => {
let attempts = 0;
const result = await runProbe({ readiness: {
configure: () => {}, recover: async () => { attempts++; throw new Error('broken scheduler configuration'); },
} });
const result = await runProbe({
readiness: {
configure: () => {},
recover: async () => {
attempts++;
throw new Error('broken scheduler configuration');
},
},
});
assert.equal(attempts, 1);
assert.equal(result.exitCode, 1);
assert.deepEqual(result.waits, []);
assert.deepEqual(result.events, ['db', 'grpc', 'http-close', 'grpc-close', 'db-close', 'report']);
assert.deepEqual(result.events, [
'db',
'grpc',
'http-close',
'grpc-close',
'db-close',
'report',
]);
assert.equal(result.messages.length, 1);
assert.equal(result.messages[0].ok, false);
assert.match(result.messages[0].message, /broken scheduler configuration/);
});
test('an already ready scheduler reaches health without waiting', async () => {
const result = await runProbe({ readiness: { configure: () => {}, recover: async () => true } });
const result = await runProbe({
readiness: { configure: () => {}, recover: async () => true },
});
assert.equal(result.exitCode, 0);
assert.deepEqual(result.waits, []);
assert.equal(result.messages[0].ok, true);
+12 -9
View File
@@ -46,7 +46,12 @@ test('decoded SystemNotify requests reach WPUSH with explicit or saved configura
const decorators = { Service: () => (x) => x, Inject: () => () => {} };
const NotificationService = load(back('services/notify.ts'), {
typedi: decorators,
'./user': {},
'../data/notificationSettings': {
readNotificationMode: async () => ({
type: 'wpush',
wpushApiKey: 'saved-key',
}),
},
'../config/util': {},
'../shared/i18n': { t: (x) => x },
'../config/http': {
@@ -64,8 +69,12 @@ test('decoded SystemNotify requests reach WPUSH with explicit or saved configura
'../config/const': constants,
'../config/util': {},
'../data/dependence': {},
'../data/system': { AuthDataType: { notifyLog: 'notifyLog' }, NotifyStatus: { success: 0, fail: 1 }, SystemModel: { create: async () => {}, findAll: async () => [] } },
'../shared/pLimit': {},
'../data/system': {
AuthDataType: { notifyLog: 'notifyLog' },
NotifyStatus: { success: 0, fail: 1 },
SystemModel: { create: async () => {}, findAll: async () => [] },
},
'../cron/execution/cronLimit': {},
'../schedule/client': {},
'../shared/i18n': { t: (x) => x },
'./notify': {},
@@ -73,12 +82,6 @@ test('decoded SystemNotify requests reach WPUSH with explicit or saved configura
'./sock': {},
}).default;
const notification = new NotificationService();
notification.userService = {
getNotificationMode: async () => ({
type: 'wpush',
wpushApiKey: 'saved-key',
}),
};
const system = new SystemService({ error() {} });
system.notificationService = notification;
+104 -26
View File
@@ -6,38 +6,91 @@ const ts = require('typescript');
// Exercise the real list effect while explicitly releasing each HTTP response.
function listEffect() {
const source = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/index.tsx'), 'utf8');
const ast = ts.createSourceFile('index.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const source = fs.readFileSync(
path.join(__dirname, '../../src/pages/crontab/index.tsx'),
'utf8',
);
const ast = ts.createSourceFile(
'index.tsx',
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
const effects = [];
function visit(node) {
if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect' &&
node.arguments[1]?.getText(ast).includes('searchText')) effects.push(node.arguments[0]);
if (
ts.isCallExpression(node) &&
node.expression.getText(ast) === 'useEffect' &&
node.arguments[1]?.getText(ast).includes('searchText')
)
effects.push(node.arguments[0]);
ts.forEachChild(node, visit);
}
visit(ast);
assert.equal(effects.length, 1);
const js = ts.transpile('const effect = ' + effects[0].getText(ast), {target: ts.ScriptTarget.ES2022});
const requests = [], timers = new Set(), rows = [], totals = [], failures = [];
const js = ts.transpile('const effect = ' + effects[0].getText(ast), {
target: ts.ScriptTarget.ES2022,
});
const requests = [],
timers = new Set(),
rows = [],
totals = [],
failures = [];
const bindings = {
pageConf: { page: 1, size: 20 }, viewConf: null, config: {apiPrefix: '/api/'},
request: { get(url, options) {
return new Promise((resolve, reject) => requests.push({url, options, resolve, reject}));
} }, setValue: value => rows.push(value), setTotal: value => totals.push(value),
setLoading() {}, setListFailed(failed) { failures.push(failed); },
setTimeout(fn) { timers.add(fn); return fn; }, clearTimeout(fn) { timers.delete(fn); },
pageConf: { page: 1, size: 20 },
viewConf: null,
config: { apiPrefix: '/api/' },
request: {
get(url, options) {
return new Promise((resolve, reject) =>
requests.push({ url, options, resolve, reject }),
);
},
},
setValue: (value) => rows.push(value),
setTotal: (value) => totals.push(value),
setLoading() {},
setListFailed(failed) {
failures.push(failed);
},
setTimeout(fn) {
timers.add(fn);
return fn;
},
clearTimeout(fn) {
timers.delete(fn);
},
};
return {
requests,
timers,
rows,
totals,
failures,
start(searchText) {
return Function(
'searchText',
...Object.keys(bindings),
js + '\nreturn effect();',
)(searchText, ...Object.values(bindings));
},
};
return { requests, timers, rows, totals, failures, start(searchText) {
return Function('searchText', ...Object.keys(bindings), js + '\nreturn effect();')(searchText, ...Object.values(bindings));
} };
}
const flush = () => new Promise(resolve => setImmediate(resolve));
const page = (id, sub_id) => ({code: 200, data: {data: [{id, sub_id}], total: 1}});
const flush = () => new Promise((resolve) => setImmediate(resolve));
const page = (id, sub_id) => ({
code: 200,
data: { data: [{ id, sub_id }], total: 1 },
});
test('switching searches discards stale list and subscription responses and cancels old polling', async () => {
for (const delaySubscription of [false, true]) {
const view = listEffect();
const closeA = view.start('A');
if (delaySubscription) { view.requests[0].resolve(page(1, 7)); await flush(); }
if (delaySubscription) {
view.requests[0].resolve(page(1, 7));
await flush();
}
const stale = view.requests.at(-1);
closeA();
assert.ok(stale.options.signal.aborted);
@@ -46,9 +99,14 @@ test('switching searches discards stale list and subscription responses and canc
assert.equal(fresh.options.params.searchValue, 'B&+');
fresh.resolve(page(2));
await flush();
stale.resolve(delaySubscription ? {code: 200, data: [{id: 7}]} : page(1, 7));
stale.resolve(
delaySubscription ? { code: 200, data: [{ id: 7 }] } : page(1, 7),
);
await flush();
assert.deepEqual(view.rows.map(rows => rows.map(r => r.id)), [[2]]);
assert.deepEqual(
view.rows.map((rows) => rows.map((r) => r.id)),
[[2]],
);
assert.deepEqual(view.totals, [1]);
assert.equal(view.requests.length, delaySubscription ? 3 : 2);
assert.equal(view.timers.size, 1);
@@ -75,18 +133,35 @@ test('list polling recovers on the next tick after a network failure', async ()
});
test('the next search can be submitted while the table request is in flight', () => {
const source = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/index.tsx'), 'utf8');
const ast = ts.createSourceFile('index.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const source = fs.readFileSync(
path.join(__dirname, '../../src/pages/crontab/index.tsx'),
'utf8',
);
const ast = ts.createSourceFile(
'index.tsx',
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
const controls = [];
function visit(node) {
if (ts.isJsxSelfClosingElement(node) && node.tagName.getText(ast) === 'Search') controls.push(node);
if (
ts.isJsxSelfClosingElement(node) &&
node.tagName.getText(ast) === 'Search'
)
controls.push(node);
ts.forEachChild(node, visit);
}
visit(ast);
assert.equal(controls.length, 1);
const attributes = controls[0].attributes.properties.map(p => p.name?.getText(ast));
const attributes = controls[0].attributes.properties.map((p) =>
p.name?.getText(ast),
);
assert.ok(attributes.includes('onSearch'));
assert.ok(!attributes.includes('loading') && !attributes.includes('disabled'));
assert.ok(
!attributes.includes('loading') && !attributes.includes('disabled'),
);
});
test('a failed subscription lookup still displays the current task list', async () => {
@@ -96,7 +171,10 @@ test('a failed subscription lookup still displays the current task list', async
await flush();
view.requests[1].reject(Error('offline'));
await flush();
assert.deepEqual(view.rows[0].map(row => row.id), [42]);
assert.deepEqual(
view.rows[0].map((row) => row.id),
[42],
);
assert.deepEqual(view.totals, [1]);
stop();
});
+129 -48
View File
@@ -40,7 +40,12 @@ function fixture(get) {
config: { apiPrefix: '/api/' },
cron: { id: 1 },
session: { current: new AbortController() },
pinnedTrigger: {}, reading: {current: false}, drained: {}, lastPath: {}, lastCursor: {}, scrollTimer: {},
pinnedTrigger: {},
reading: { current: false },
drained: {},
lastPath: {},
lastCursor: {},
scrollTimer: {},
LOG_CHUNK_BYTES: 256 * 1024,
MAX_LOG_VIEW_CHARS: 1024 * 1024,
logOffsetRef: { current: undefined },
@@ -54,8 +59,12 @@ function fixture(get) {
},
},
intl: { get: (value) => value },
setLoading(value) { values.loading = value; },
setReadFailed(value) { values.failed = value; },
setLoading(value) {
values.loading = value;
},
setReadFailed(value) {
values.failed = value;
},
autoScroll() {},
handleCancel() {},
setValue(value) {
@@ -87,7 +96,9 @@ function fixture(get) {
return {
values,
timers,
retry() { context.getCronLog(context.logOffsetRef.current === undefined); },
retry() {
context.getCronLog(context.logOffsetRef.current === undefined);
},
start() {
context.getCronLog(true);
},
@@ -228,12 +239,17 @@ test('first log read failure is recoverable on retry', async () => {
test('independent log readers can receive responses in reverse order across close and reopen', async () => {
let resolveOld;
const old = fixture(() => new Promise(resolve => { resolveOld = resolve; }));
const old = fixture(
() =>
new Promise((resolve) => {
resolveOld = resolve;
}),
);
old.start();
old.close();
const current = fixture(async () => ({code: 200, data: 'new log'}));
const current = fixture(async () => ({ code: 200, data: 'new log' }));
await current.read();
resolveOld({code: 200, data: 'old log', logStatus: 'running'});
resolveOld({ code: 200, data: 'old log', logStatus: 'running' });
await old.settle();
assert.equal(current.values.content, 'new log');
assert.equal(old.values.content, '');
@@ -242,7 +258,10 @@ test('independent log readers can receive responses in reverse order across clos
test('repeated retries share one in-flight read and closing aborts its transport', async () => {
const pending = [];
const view = fixture((url, { signal }) => new Promise(resolve => pending.push({ signal, resolve })));
const view = fixture(
(url, { signal }) =>
new Promise((resolve) => pending.push({ signal, resolve })),
);
view.start();
view.retry();
assert.equal(pending.length, 1);
@@ -257,25 +276,43 @@ test('repeated retries share one in-flight read and closing aborts its transport
test('polling a missing log displays its status once and retries from the last confirmed byte', async () => {
const calls = [];
const responses = [
{data: 'waiting', total: 0, nextOffset: 0}, {data: 'waiting', total: 0, nextOffset: 0},
{data: 'abc', total: 3, nextOffset: 3, logPath: 'a'}, null,
{data: 'd', total: 4, nextOffset: 4, logPath: 'a'},
{data: 'new!', total: 4, nextOffset: 4, logPath: 'b', logStatus: 'completed'},
{ data: 'waiting', total: 0, nextOffset: 0 },
{ data: 'waiting', total: 0, nextOffset: 0 },
{ data: 'abc', total: 3, nextOffset: 3, logPath: 'a' },
null,
{ data: 'd', total: 4, nextOffset: 4, logPath: 'a' },
{
data: 'new!',
total: 4,
nextOffset: 4,
logPath: 'b',
logStatus: 'completed',
},
];
const view = fixture(async url => {
const view = fixture(async (url) => {
calls.push(new URL(url, 'http://localhost').searchParams);
const r = responses.shift();
if (!r) throw Error('offline');
return {code: 200, logStatus: 'running', ...r};
return { code: 200, logStatus: 'running', ...r };
});
await view.read(); await view.tick();
await view.read();
await view.tick();
assert.equal(view.values.content, 'waiting');
await view.tick(); await view.tick();
await view.tick();
await view.tick();
assert.equal(view.values.failed, true);
assert.equal(view.values.content, 'abc');
view.retry(); view.retry(); await view.settle();
view.retry();
view.retry();
await view.settle();
assert.equal(view.values.content, 'abcd');
assert.deepEqual(calls.slice(3).map(p => [p.get('offset'), p.get('previousPath')]), [['3','a'],['3','a']]);
assert.deepEqual(
calls.slice(3).map((p) => [p.get('offset'), p.get('previousPath')]),
[
['3', 'a'],
['3', 'a'],
],
);
await view.tick();
assert.equal(view.values.content, 'new!');
assert.equal(view.timers.size, 0);
@@ -283,21 +320,28 @@ test('polling a missing log displays its status once and retries from the last c
test('a shortened file during a retry is reread from its new tail', async () => {
const responses = [
{data: 'previous log', nextOffset: 12, total: 12}, {data: '', nextOffset: 3, total: 3},
{data: 'new', nextOffset: 3, total: 3},
{ data: 'previous log', nextOffset: 12, total: 12 },
{ data: '', nextOffset: 3, total: 3 },
{ data: 'new', nextOffset: 3, total: 3 },
];
const calls = [];
const view = fixture(async url => {
const view = fixture(async (url) => {
calls.push(url);
return {code: 200, logStatus: responses.length === 3 ? 'running' : 'completed', ...responses.shift()};
return {
code: 200,
logStatus: responses.length === 3 ? 'running' : 'completed',
...responses.shift(),
};
});
await view.read(); await view.tick(); await view.tick();
await view.read();
await view.tick();
await view.tick();
assert.match(calls[2], /tail=true/);
assert.equal(view.values.content, 'new');
assert.equal(view.timers.size, 0);
});
test('retry after a truncate and regrow replaces displayed bytes and drains all pages exactly once', async t => {
test('retry after a truncate and regrow replaces displayed bytes and drains all pages exactly once', async (t) => {
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'ql-log-regrow-'));
t.after(() => fsp.rm(dir, { recursive: true, force: true }));
const file = path.join(dir, 'run.log');
@@ -305,23 +349,34 @@ test('retry after a truncate and regrow replaces displayed bytes and drains all
let running = true;
let fail = false;
const offsets = [];
const view = fixture(async url => {
const view = fixture(async (url) => {
const p = new URL(url, 'http://localhost').searchParams;
const offset = p.has('offset') ? Number(p.get('offset')) : undefined;
offsets.push(offset);
if (fail) throw Error('timeout');
const chunk = await readLogChunk(file, {
offset, follow: p.get('follow') === 'true', cursor: p.get('cursor'),
tail: p.get('tail') === 'true', limit: Number(p.get('limit')),
offset,
follow: p.get('follow') === 'true',
cursor: p.get('cursor'),
tail: p.get('tail') === 'true',
limit: Number(p.get('limit')),
});
return { ...chunk, code: 200, data: chunk.content, logPath: 'run.log',
logStatus: running ? 'running' : 'completed' };
return {
...chunk,
code: 200,
data: chunk.content,
logPath: 'run.log',
logStatus: running ? 'running' : 'completed',
};
});
await view.read();
fail = true;
await view.tick();
assert.equal(view.values.failed, true);
const current = Array.from({ length: 16000 }, (_, i) => `${i} · 中文日志🚀\n`).join('');
const current = Array.from(
{ length: 16000 },
(_, i) => `${i} · 中文日志🚀\n`,
).join('');
await fsp.writeFile(file, current);
fail = running = false;
view.retry();
@@ -338,42 +393,68 @@ test('retry after a truncate and regrow replaces displayed bytes and drains all
test('a fresh list snapshot wakes a drained live viewer only for a new path or active task', () => {
const effects = [];
function visitEffect(node) {
if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect' &&
node.arguments[1]?.getText(ast) === '[cron]') effects.push(node.arguments[0]);
if (
ts.isCallExpression(node) &&
node.expression.getText(ast) === 'useEffect' &&
node.arguments[1]?.getText(ast) === '[cron]'
)
effects.push(node.arguments[0]);
ts.forEachChild(node, visitEffect);
}
visitEffect(ast);
assert.equal(effects.length, 1);
const wake = ts.transpile('var wake = ' + effects[0].getText(ast), {target: ts.ScriptTarget.ES2020});
const wake = ts.transpile('var wake = ' + effects[0].getText(ast), {
target: ts.ScriptTarget.ES2020,
});
let calls = 0;
const context = { cron: { log_path: 'old', status: 1 }, lastPath: {current: 'old'},
drained: {current: true}, pinnedTrigger: {}, logUrl: undefined,
CrontabStatus: {running: 0, queued: 3}, getCronLog: () => calls++ };
const context = {
cron: { log_path: 'old', status: 1 },
lastPath: { current: 'old' },
drained: { current: true },
pinnedTrigger: {},
logUrl: undefined,
CrontabStatus: { running: 0, queued: 3 },
getCronLog: () => calls++,
};
const update = () => vm.runInNewContext(wake + '\nwake()', context);
update(); assert.equal(calls, 0);
context.cron = {log_path: 'new', status: 1};
update(); assert.equal(calls, 1);
context.cron = {log_path: 'old', status: 3};
update(); assert.equal(calls, 2);
update();
assert.equal(calls, 0);
context.cron = { log_path: 'new', status: 1 };
update();
assert.equal(calls, 1);
context.cron = { log_path: 'old', status: 3 };
update();
assert.equal(calls, 2);
context.drained.current = false;
update(); assert.equal(calls, 2);
update();
assert.equal(calls, 2);
context.drained.current = true;
context.logUrl = '/api/logs/detail?file=old';
update(); assert.equal(calls, 2);
update();
assert.equal(calls, 2);
});
test('concurrent live log polling and retries stay scoped to the initially selected trigger', async () => {
const calls = [];
const view = fixture(async url => {
const view = fixture(async (url) => {
const p = new URL(url, 'http://localhost').searchParams;
calls.push(p.get('triggerId'));
if (calls.length === 2) throw Error('timeout');
const selected = p.get('triggerId') || (calls.length === 1 ? 'a' : 'b');
return { code: 200, triggerId: selected, logPath: selected + '.log', total: calls.length === 1 ? 1 : 2,
nextOffset: calls.length === 1 ? 1 : 2, logStatus: calls.length < 3 ? 'running' : 'completed',
data: calls.length === 1 ? 'A' : selected === 'a' ? '!' : 'B!' };
return {
code: 200,
triggerId: selected,
logPath: selected + '.log',
total: calls.length === 1 ? 1 : 2,
nextOffset: calls.length === 1 ? 1 : 2,
logStatus: calls.length < 3 ? 'running' : 'completed',
data: calls.length === 1 ? 'A' : selected === 'a' ? '!' : 'B!',
};
});
await view.read(); await view.tick(); view.retry(); await view.settle();
await view.read();
await view.tick();
view.retry();
await view.settle();
assert.deepEqual(calls, [null, 'a', 'a']);
assert.equal(view.values.content, 'A!');
assert.equal(view.timers.size, 0);
+478 -141
View File
@@ -4,51 +4,107 @@ const fs = require('node:fs');
const ts = require('typescript');
function dashboard(anomaly) {
const source = fs.readFileSync(require.resolve('../../src/pages/dashboard/index.tsx'), 'utf8');
const ast = ts.createSourceFile('dashboard.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const source = fs.readFileSync(
require.resolve('../../src/pages/dashboard/index.tsx'),
'utf8',
);
const ast = ts.createSourceFile(
'dashboard.tsx',
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
let effect;
function visit(node) {
if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect' &&
node.arguments[0].getText(ast).includes('setOverview')) effect = node.arguments[0].getText(ast);
if (
ts.isCallExpression(node) &&
node.expression.getText(ast) === 'useEffect' &&
node.arguments[0].getText(ast).includes('setOverview')
)
effect = node.arguments[0].getText(ast);
ts.forEachChild(node, visit);
}
visit(ast);
assert.ok(effect);
const requests = [], results = [], failures = [], timers = new Set();
const requests = [],
results = [],
failures = [],
timers = new Set();
const noop = () => {};
const bindings = {
performance: { now: () => 1000 },
anomaly, config: { apiPrefix: '/api/' }, REFRESH_INTERVAL: 30000,
setOverview: value => results.push(value), setOverviewFailed: value => failures.push(value),
setLoading: noop, setTrend: noop, setSystem: noop, setTopTime: noop, setTopCount: noop, setLabels: noop, setRuntime: noop,
setInterval(fn) { timers.add(fn); return fn; }, clearInterval(fn) { timers.delete(fn); },
request: { get(url, options) {
return new Promise((resolve, reject) => requests.push({ url, options, resolve, reject }));
} },
anomaly,
config: { apiPrefix: '/api/' },
REFRESH_INTERVAL: 30000,
setOverview: (value) => results.push(value),
setOverviewFailed: (value) => failures.push(value),
setLoading: noop,
setTrend: noop,
setSystem: noop,
setTopTime: noop,
setTopCount: noop,
setLabels: noop,
setRuntime: noop,
setInterval(fn) {
timers.add(fn);
return fn;
},
clearInterval(fn) {
timers.delete(fn);
},
request: {
get(url, options) {
return new Promise((resolve, reject) =>
requests.push({ url, options, resolve, reject }),
);
},
},
};
const js = ts.transpile('const start = ' + effect, { target: ts.ScriptTarget.ES2022 });
const js = ts.transpile('const start = ' + effect, {
target: ts.ScriptTarget.ES2022,
});
return {
start: Function(...Object.keys(bindings), js + '\nreturn start;')(...Object.values(bindings)),
tick() { for (const fn of timers) fn(); }, timers, results, failures,
requests: section => requests.filter(r => r.url === '/api/dashboard/' + section),
start: Function(
...Object.keys(bindings),
js + '\nreturn start;',
)(...Object.values(bindings)),
tick() {
for (const fn of timers) fn();
},
timers,
results,
failures,
requests: (section) =>
requests.filter((r) => r.url === '/api/dashboard/' + section),
};
}
const flush = () => new Promise(resolve => setImmediate(resolve));
const flush = () => new Promise((resolve) => setImmediate(resolve));
test('a first anomaly request that never succeeds still expires using the overview deadline', async () => {
const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100, deadline: 10000 };
const v = anomalies(),
selection = { source: 'panel', kind: 'missing', at: 100, deadline: 10000 };
const close = v.start(selection, { page: 1 });
v.tick(10000);
assert.deepEqual(v.invalidated, [{ selection, reason: 'expired' }]);
assert.equal(v.requests[0].signal.aborted, true);
v.requests[0].resolve({ code: 200, data: { rows: ['yesterday'], summary: {} } });
v.requests[0].resolve({
code: 200,
data: { rows: ['yesterday'], summary: {} },
});
await flush();
assert.deepEqual(v.received, []);
close();
});
test('a first failure and manual retry cannot reset the overview deadline', async () => {
const v = anomalies(), selection = { source: 'system', kind: 'unconfirmed', at: 100, deadline: 10000 };
const v = anomalies(),
selection = {
source: 'system',
kind: 'unconfirmed',
at: 100,
deadline: 10000,
};
const close = v.start(selection, { page: 1 });
v.requests[0].reject(new Error('offline'));
await flush();
@@ -62,7 +118,8 @@ test('a first failure and manual retry cannot reset the overview deadline', asyn
});
test('opening an already expired overview does not send an obsolete detail request', () => {
const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100, deadline: 1000 };
const v = anomalies(),
selection = { source: 'panel', kind: 'missing', at: 100, deadline: 1000 };
v.advance(1001);
const close = v.start(selection, { page: 1 });
assert.equal(v.requests.length, 0);
@@ -71,16 +128,21 @@ test('opening an already expired overview does not send an obsolete detail reque
});
test('overview deadlines use server time and request start, independent of the browser wall clock', async () => {
const v = dashboard(), close = v.start();
const v = dashboard(),
close = v.start();
const serverNow = 1795017590000;
v.requests('overview')[0].resolve({ code: 200, data: { serverNow, expiresAt: serverNow + 10000 } });
v.requests('overview')[0].resolve({
code: 200,
data: { serverNow, expiresAt: serverNow + 10000 },
});
await flush();
assert.equal(v.results[0].anomalyDeadline, 11000);
close();
});
test('slow dashboard cards do not block crond counts, overlap a pending refresh or restart polling after unmount', async () => {
const view = dashboard(), leave = view.start();
const view = dashboard(),
leave = view.start();
view.tick();
assert.equal(view.requests('overview').length, 1);
view.requests('overview')[0].resolve({ code: 200, data: { actualSkips: 0 } });
@@ -107,7 +169,11 @@ test('slow dashboard cards do not block crond counts, overlap a pending refresh
await flush();
stale.resolve({ code: 200, data: { actualSkips: 0 } });
await flush();
assert.deepEqual(view.results, [{ actualSkips: 0 }, { actualSkips: 1 }, { actualSkips: 2 }]);
assert.deepEqual(view.results, [
{ actualSkips: 0 },
{ actualSkips: 1 },
{ actualSkips: 2 },
]);
assert.deepEqual(view.failures, [false, true, false, false]);
assert.equal(view.timers.size, 1);
closeAgain();
@@ -117,47 +183,114 @@ test('system crond results distinguish missing records, unknown exits and record
const intl = require('react-intl-universal');
const messages = require('../../src/locales/zh-CN.json');
await intl.init({ currentLocale: 'zh-CN', locales: { 'zh-CN': messages } });
const source = fs.readFileSync(require.resolve('../../src/pages/dashboard/index.tsx'), 'utf8');
const ast = ts.createSourceFile('dashboard.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const source = fs.readFileSync(
require.resolve('../../src/pages/dashboard/index.tsx'),
'utf8',
);
const ast = ts.createSourceFile(
'dashboard.tsx',
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
let renderer;
function visit(node) {
if (ts.isObjectLiteralExpression(node) && node.properties.some(p =>
ts.isPropertyAssignment(p) && p.name.getText(ast) === 'title' &&
p.initializer.getText(ast) === "intl.get('执行情况')")) {
renderer = node.properties.find(p => p.name.getText(ast) === 'render').initializer;
if (
ts.isObjectLiteralExpression(node) &&
node.properties.some(
(p) =>
ts.isPropertyAssignment(p) &&
p.name.getText(ast) === 'title' &&
p.initializer.getText(ast) === "intl.get('执行情况')",
)
) {
renderer = node.properties.find(
(p) => p.name.getText(ast) === 'render',
).initializer;
}
ts.forEachChild(node, visit);
}
visit(ast);
assert.ok(renderer);
const js = ts.transpileModule('const render = ' + renderer.getText(ast), {
fileName: 'cell.tsx', compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 },
fileName: 'cell.tsx',
compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 },
}).outputText;
const cell = Function('React', 'intl', js + '\nreturn render;')(require('react'), intl);
const html = row => require('react-dom/server').renderToStaticMarkup(cell(null, row));
const cell = Function(
'React',
'intl',
js + '\nreturn render;',
)(require('react'), intl);
const html = (row) =>
require('react-dom/server').renderToStaticMarkup(cell(null, row));
assert.equal(html({ status: 'missing', triggerCount: 0 }), '未收到触发记录');
assert.equal(html({ status: 'skipped', triggerCount: 1, skipCount: 1 }), '已跳过');
assert.equal(
html({ status: 'skipped', triggerCount: 1, skipCount: 1 }),
'已跳过',
);
assert.equal(html({ status: 'started' }), '命令已启动');
assert.equal(html({ status: 'started', triggerCount: 1, startCount: 1, unknownExitCount: 1 }),
'命令已启动 · 结果未知');
assert.equal(html({ status: 'started', triggerCount: 2, startCount: 1, skipCount: 1, unknownExitCount: 1 }),
'启动 1 次 · 跳过 1 次 · 其中 1 次执行结果未知');
assert.equal(
html({
status: 'started',
triggerCount: 1,
startCount: 1,
unknownExitCount: 1,
}),
'命令已启动 · 结果未知',
);
assert.equal(
html({
status: 'started',
triggerCount: 2,
startCount: 1,
skipCount: 1,
unknownExitCount: 1,
}),
'启动 1 次 · 跳过 1 次 · 其中 1 次执行结果未知',
);
});
test('dashboard timing preserves millisecond precision, rounds long waits and distinguishes zero from no samples', async () => {
const intl = require('react-intl-universal');
const locales = { 'zh-CN': require('../../src/locales/zh-CN.json'), 'en-US': require('../../src/locales/en-US.json') };
const source = fs.readFileSync(require.resolve('../../src/pages/dashboard/timingStatistic.tsx'), 'utf8');
const { outputText } = ts.transpileModule(source, { compilerOptions: {
jsx: ts.JsxEmit.ReactJSX, module: ts.ModuleKind.CommonJS, esModuleInterop: true,
} });
const locales = {
'zh-CN': require('../../src/locales/zh-CN.json'),
'en-US': require('../../src/locales/en-US.json'),
};
const source = fs.readFileSync(
require.resolve('../../src/pages/dashboard/timingStatistic.tsx'),
'utf8',
);
const { outputText } = ts.transpileModule(source, {
compilerOptions: {
jsx: ts.JsxEmit.ReactJSX,
module: ts.ModuleKind.CommonJS,
esModuleInterop: true,
},
});
const component = {};
Function('require', 'exports', outputText)(require, component);
await intl.init({ currentLocale: 'zh-CN', locales });
assert.deepEqual([null, 0, 136, 1000, 5989, 59999, 60000, 119999, 1703994].map(component.formatTiming),
['—', '0 ms', '136 ms', '1 秒', '5.989 秒', '59.999 秒', '1 分 0 秒', '2 分 0 秒', '28 分 24 秒']);
const render = ms => require('react-dom/server').renderToStaticMarkup(
require('react').createElement(component.default, { title: 'P95', ms }));
assert.deepEqual(
[null, 0, 136, 1000, 5989, 59999, 60000, 119999, 1703994].map(
component.formatTiming,
),
[
'—',
'0 ms',
'136 ms',
'1 秒',
'5.989 秒',
'59.999 秒',
'1 分 0 秒',
'2 分 0 秒',
'28 分 24 秒',
],
);
const render = (ms) =>
require('react-dom/server').renderToStaticMarkup(
require('react').createElement(component.default, { title: 'P95', ms }),
);
assert.match(render(1703994), /title="1703994 ms">28 分 24 秒/);
assert.match(render(null), /—/);
assert.doesNotMatch(render(136), /个样本/);
@@ -166,56 +299,127 @@ test('dashboard timing preserves millisecond precision, rounds long waits and di
});
function anomalies() {
const filename = require.resolve('../../src/pages/dashboard/scheduleAnomalies.tsx');
const filename = require.resolve(
'../../src/pages/dashboard/scheduleAnomalies.tsx',
);
const source = fs.readFileSync(filename, 'utf8');
const ast = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const ast = ts.createSourceFile(
filename,
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
let effect;
function visit(node) {
if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect')
if (
ts.isCallExpression(node) &&
node.expression.getText(ast) === 'useEffect'
)
effect = node.arguments[0].getText(ast);
ts.forEachChild(node, visit);
}
visit(ast);
const js = ts.transpile('const start = ' + effect, { target: ts.ScriptTarget.ES2022 });
const requests = [], received = [], failed = [], summaries = [], invalidated = [], timers = new Map();
const js = ts.transpile('const start = ' + effect, {
target: ts.ScriptTarget.ES2022,
});
const requests = [],
received = [],
failed = [],
summaries = [],
invalidated = [],
timers = new Map();
let now = 0;
const bindings = {
expiresAt: { current: undefined },
config: { apiPrefix: '/api/' },
request: { get(url, options) {
assert.equal(url, '/api/dashboard/schedule-anomalies');
return new Promise((resolve, reject) => requests.push({ ...options, resolve, reject }));
} },
setResponse: data => received.push(data.result), setFailed: flag => failed.push(flag), setLoading() {},
request: {
get(url, options) {
assert.equal(url, '/api/dashboard/schedule-anomalies');
return new Promise((resolve, reject) =>
requests.push({ ...options, resolve, reject }),
);
},
},
setResponse: (data) => received.push(data.result),
setFailed: (flag) => failed.push(flag),
setLoading() {},
onUpdate: (selection, summary) => summaries.push(summary),
onInvalidate: (selection, reason) => invalidated.push({ selection, reason }),
onInvalidate: (selection, reason) =>
invalidated.push({ selection, reason }),
performance: { now: () => now },
setTimeout(fn, ms) { timers.set(fn, ms); return fn; }, clearTimeout(fn) { timers.delete(fn); },
setTimeout(fn, ms) {
timers.set(fn, ms);
return fn;
},
clearTimeout(fn) {
timers.delete(fn);
},
};
return {
start: (selection, query) => Function(...Object.keys(bindings), 'selection', 'query',
js + '\nreturn start();')(...Object.values(bindings), selection, query),
requests, received, failed, summaries, invalidated, timers,
advance(ms) { now += ms; },
tick(delay = 5000) { for (const [fn, ms] of [...timers]) if (ms === delay) { timers.delete(fn); fn(); } },
start: (selection, query) =>
Function(
...Object.keys(bindings),
'selection',
'query',
js + '\nreturn start();',
)(...Object.values(bindings), selection, query),
requests,
received,
failed,
summaries,
invalidated,
timers,
advance(ms) {
now += ms;
},
tick(delay = 5000) {
for (const [fn, ms] of [...timers])
if (ms === delay) {
timers.delete(fn);
fn();
}
},
};
}
test('anomaly pagination pins its plan window, advances revisions after resets and stops old polling across source changes', async () => {
const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100 };
const v = anomalies(),
selection = { source: 'panel', kind: 'missing', at: 100 };
const close = v.start(selection, { page: 2, revision: 'old' });
assert.deepEqual(v.requests[0].params, { ...selection, live: true, page: 2, revision: 'old' });
const updated = { rows: ['remaining'], page: 1, revision: 'new', total: 26, changed: true, summary: { audit: { missing: 26 } } };
assert.deepEqual(v.requests[0].params, {
...selection,
live: true,
page: 2,
revision: 'old',
});
const updated = {
rows: ['remaining'],
page: 1,
revision: 'new',
total: 26,
changed: true,
summary: { audit: { missing: 26 } },
};
v.requests[0].resolve({ code: 200, data: updated });
await flush();
assert.deepEqual(v.received, [updated]);
assert.deepEqual(v.summaries, [updated.summary]);
v.tick(); v.tick();
v.tick();
v.tick();
assert.equal(v.requests.length, 2);
assert.deepEqual(v.requests[1].params, { ...selection, live: true, page: 1, revision: 'new' });
assert.deepEqual(v.requests[1].params, {
...selection,
live: true,
page: 1,
revision: 'new',
});
close();
assert.equal(v.requests[1].signal.aborted, true);
const leave = v.start({ source: 'system', kind: 'unconfirmed', at: 200 }, { page: 1 });
const leave = v.start(
{ source: 'system', kind: 'unconfirmed', at: 200 },
{ page: 1 },
);
v.requests[1].resolve({ code: 200, data: { ...updated, total: 99 } });
v.requests[2].reject(new Error('timeout'));
await flush();
@@ -223,8 +427,17 @@ test('anomaly pagination pins its plan window, advances revisions after resets a
assert.equal(v.received.length, 1);
assert.equal(v.timers.size, 0);
leave();
const finish = v.start({ source: 'system', kind: 'unconfirmed', at: 200 }, { page: 1 });
const empty = { rows: [], page: 1, revision: 'empty', total: 0, summary: { systemAudit: { actualUnconfirmed: 0 } } };
const finish = v.start(
{ source: 'system', kind: 'unconfirmed', at: 200 },
{ page: 1 },
);
const empty = {
rows: [],
page: 1,
revision: 'empty',
total: 0,
summary: { systemAudit: { actualUnconfirmed: 0 } },
};
v.requests[3].resolve({ code: 200, data: empty });
await flush();
assert.equal(v.failed.at(-1), false);
@@ -235,48 +448,90 @@ test('anomaly pagination pins its plan window, advances revisions after resets a
});
test('opening anomaly details cancels older overview responses and keeps its counts owned by the detail snapshot', async () => {
const v = dashboard(), close = v.start();
const v = dashboard(),
close = v.start();
close();
v.requests('overview')[0].resolve({ code: 200, data: { triggers: { audit: { missing: 55 } } } });
v.requests('overview')[0].resolve({
code: 200,
data: { triggers: { audit: { missing: 55 } } },
});
await flush();
assert.deepEqual(v.results, []);
const opened = dashboard({ source: 'panel' }), leave = opened.start();
const opened = dashboard({ source: 'panel' }),
leave = opened.start();
opened.tick();
assert.equal(opened.requests('overview').length, 0);
assert.equal(opened.requests('runtime').length, 1);
leave();
});
for (const source of ['panel', 'system']) test(source + ' partial cleanup resets pagination and abandoned page replies cannot restore deleted rows after switching source', async () => {
const v = anomalies(), selection = { source, kind: 'unconfirmed', at: 100, session: 1 };
const stop = v.start(selection, { page: 3, revision: 'before-cleanup' });
const retained = { page: 1, total: 40, revision: 'after-cleanup', changed: true,
rows: [{ trigger: 'retained', hasLog: true }], summary: source === 'panel'
? { audit: { unconfirmed: 40 } } : { systemAudit: { actualUnconfirmed: 40 } } };
v.requests[0].resolve({ code: 200, data: retained });
await flush();
v.tick();
assert.equal(v.requests[1].params.page, 1);
assert.equal(v.requests[1].params.revision, 'after-cleanup');
stop();
const next = { ...selection, source: source === 'panel' ? 'system' : 'panel', session: 2 };
const close = v.start(next, { page: 1 });
const fresh = { ...retained, rows: [{ trigger: 'other-source', hasLog: true }], total: 1, revision: 'fresh',
summary: next.source === 'panel' ? { audit: { unconfirmed: 1 } } : { systemAudit: { actualUnconfirmed: 1 } } };
v.requests[2].resolve({ code: 200, data: fresh });
await flush();
v.requests[1].resolve({ code: 200, data: { ...retained, total: 60, rows: [{ trigger: 'deleted' }] } });
await flush();
assert.deepEqual(v.received, [retained, fresh]);
assert.deepEqual(v.summaries, [retained.summary, fresh.summary]);
close();
assert.equal(v.timers.size, 0);
});
for (const source of ['panel', 'system'])
test(
source +
' partial cleanup resets pagination and abandoned page replies cannot restore deleted rows after switching source',
async () => {
const v = anomalies(),
selection = { source, kind: 'unconfirmed', at: 100, session: 1 };
const stop = v.start(selection, { page: 3, revision: 'before-cleanup' });
const retained = {
page: 1,
total: 40,
revision: 'after-cleanup',
changed: true,
rows: [{ trigger: 'retained', hasLog: true }],
summary:
source === 'panel'
? { audit: { unconfirmed: 40 } }
: { systemAudit: { actualUnconfirmed: 40 } },
};
v.requests[0].resolve({ code: 200, data: retained });
await flush();
v.tick();
assert.equal(v.requests[1].params.page, 1);
assert.equal(v.requests[1].params.revision, 'after-cleanup');
stop();
const next = {
...selection,
source: source === 'panel' ? 'system' : 'panel',
session: 2,
};
const close = v.start(next, { page: 1 });
const fresh = {
...retained,
rows: [{ trigger: 'other-source', hasLog: true }],
total: 1,
revision: 'fresh',
summary:
next.source === 'panel'
? { audit: { unconfirmed: 1 } }
: { systemAudit: { actualUnconfirmed: 1 } },
};
v.requests[2].resolve({ code: 200, data: fresh });
await flush();
v.requests[1].resolve({
code: 200,
data: { ...retained, total: 60, rows: [{ trigger: 'deleted' }] },
});
await flush();
assert.deepEqual(v.received, [retained, fresh]);
assert.deepEqual(v.summaries, [retained.summary, fresh.summary]);
close();
assert.equal(v.timers.size, 0);
},
);
test('midnight cancels a hung anomaly refresh and a late reply cannot publish yesterday counts', async () => {
const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100, session: 1 };
const v = anomalies(),
selection = { source: 'panel', kind: 'missing', at: 100, session: 1 };
const leave = v.start(selection, { page: 1 });
const data = { page: 1, revision: 'before-midnight', rows: ['old'], summary: { audit: { missing: 1 } }, serverNow: 1000, expiresAt: 11000 };
const data = {
page: 1,
revision: 'before-midnight',
rows: ['old'],
summary: { audit: { missing: 1 } },
serverNow: 1000,
expiresAt: 11000,
};
v.requests[0].resolve({ code: 200, data });
await flush();
v.tick();
@@ -292,9 +547,17 @@ test('midnight cancels a hung anomaly refresh and a late reply cannot publish ye
});
test('pagination and retry preserve the midnight deadline while their requests remain hung', async () => {
const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100, session: 1 };
const v = anomalies(),
selection = { source: 'panel', kind: 'missing', at: 100, session: 1 };
const leave = v.start(selection, { page: 1 });
const data = { page: 1, revision: 'old', rows: ['old'], summary: { audit: { missing: 30 } }, serverNow: 1000, expiresAt: 11000 };
const data = {
page: 1,
revision: 'old',
rows: ['old'],
summary: { audit: { missing: 30 } },
serverNow: 1000,
expiresAt: 11000,
};
v.requests[0].resolve({ code: 200, data });
await flush();
v.advance(3000);
@@ -316,28 +579,56 @@ test('pagination and retry preserve the midnight deadline while their requests r
cancelRetry();
});
for (const status of ['expired', 'unavailable']) test('anomaly ' + status + ' closes the old session without republishing old rows or retrying', async () => {
const v = anomalies(), selection = { source: 'system', kind: 'unconfirmed', at: 100, session: 1 };
const leave = v.start(selection, { page: 2, revision: 'old' });
v.requests[0].resolve({ code: 200, data: { status } });
await flush();
assert.deepEqual(v.invalidated, [{ selection, reason: status }]);
assert.deepEqual(v.received, []);
assert.deepEqual(v.summaries, []);
assert.equal(v.timers.size, 0);
leave();
const next = { ...selection, session: 2 }, close = v.start(next, { page: 1 });
const data = { page: 1, revision: 'new', rows: [], total: 0, summary: { systemAudit: { actualUnconfirmed: 0 } } };
v.requests[1].resolve({ code: 200, data });
await flush();
assert.deepEqual(v.received, [data]);
close();
});
for (const status of ['expired', 'unavailable'])
test(
'anomaly ' +
status +
' closes the old session without republishing old rows or retrying',
async () => {
const v = anomalies(),
selection = {
source: 'system',
kind: 'unconfirmed',
at: 100,
session: 1,
};
const leave = v.start(selection, { page: 2, revision: 'old' });
v.requests[0].resolve({ code: 200, data: { status } });
await flush();
assert.deepEqual(v.invalidated, [{ selection, reason: status }]);
assert.deepEqual(v.received, []);
assert.deepEqual(v.summaries, []);
assert.equal(v.timers.size, 0);
leave();
const next = { ...selection, session: 2 },
close = v.start(next, { page: 1 });
const data = {
page: 1,
revision: 'new',
rows: [],
total: 0,
summary: { systemAudit: { actualUnconfirmed: 0 } },
};
v.requests[1].resolve({ code: 200, data });
await flush();
assert.deepEqual(v.received, [data]);
close();
},
);
test('an expired response that arrived across midnight cannot be rendered for even one poll', async () => {
const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100 };
const v = anomalies(),
selection = { source: 'panel', kind: 'missing', at: 100 };
const close = v.start(selection, { page: 1 });
v.requests[0].resolve({ code: 200, data: { serverNow: 1000, expiresAt: 999, summary: { audit: { missing: 7 } }, rows: ['old'] } });
v.requests[0].resolve({
code: 200,
data: {
serverNow: 1000,
expiresAt: 999,
summary: { audit: { missing: 7 } },
rows: ['old'],
},
});
await flush();
assert.equal(v.invalidated[0].reason, 'expired');
assert.deepEqual(v.received, []);
@@ -347,18 +638,37 @@ test('an expired response that arrived across midnight cannot be rendered for ev
test('a queued summary update is fenced even when closing and reopening happens before effect cleanup', () => {
const file = require.resolve('../../src/pages/dashboard/index.tsx');
const source = fs.readFileSync(file, 'utf8'), ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const source = fs.readFileSync(file, 'utf8'),
ast = ts.createSourceFile(
file,
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
let callback;
function visit(node) {
if (ts.isVariableDeclaration(node) && node.name.getText(ast) === 'updateAnomalySummary')
if (
ts.isVariableDeclaration(node) &&
node.name.getText(ast) === 'updateAnomalySummary'
)
callback = node.initializer.arguments[0].getText(ast);
ts.forEachChild(node, visit);
}
visit(ast);
assert.ok(callback);
const old = { session: 1 }, next = { session: 2 }, anomalySession = { current: old }, queued = [];
const js = ts.transpile('const update = ' + callback, { target: ts.ScriptTarget.ES2022 });
const update = Function('anomalySession', 'setOverview', js + '\nreturn update;')(anomalySession, updater => queued.push(updater));
const old = { session: 1 },
next = { session: 2 },
anomalySession = { current: old },
queued = [];
const js = ts.transpile('const update = ' + callback, {
target: ts.ScriptTarget.ES2022,
});
const update = Function(
'anomalySession',
'setOverview',
js + '\nreturn update;',
)(anomalySession, (updater) => queued.push(updater));
update(old, { audit: { missing: 8 } });
anomalySession.current = next;
update(old, { audit: { missing: 9 } });
@@ -369,26 +679,52 @@ test('a queued summary update is fenced even when closing and reopening happens
test('an old invalidation cannot close a reopened session or clear its freshly queued summary', () => {
const file = require.resolve('../../src/pages/dashboard/index.tsx');
const source = fs.readFileSync(file, 'utf8'), ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const source = fs.readFileSync(file, 'utf8'),
ast = ts.createSourceFile(
file,
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
let callback;
function visit(node) {
if (ts.isVariableDeclaration(node) && node.name.getText(ast) === 'invalidateAnomaly')
if (
ts.isVariableDeclaration(node) &&
node.name.getText(ast) === 'invalidateAnomaly'
)
callback = node.initializer.arguments[0].getText(ast);
ts.forEachChild(node, visit);
}
visit(ast);
assert.ok(callback);
const old = { session: 1 }, current = { session: 2 };
const anomalySession = { current }, anomalyVersion = { current: 2 };
const summaries = [], logs = [], messages = [];
const old = { session: 1 },
current = { session: 2 };
const anomalySession = { current },
anomalyVersion = { current: 2 };
const summaries = [],
logs = [],
messages = [];
let closes = 0;
const bindings = { anomalySession, anomalyVersion,
closeAnomaly() { closes++; anomalySession.current = undefined; },
setOverview: update => summaries.push(update), setLogCron: update => logs.push(update),
message: { info: text => messages.push(text) }, intl: { get: text => text },
const bindings = {
anomalySession,
anomalyVersion,
closeAnomaly() {
closes++;
anomalySession.current = undefined;
},
setOverview: (update) => summaries.push(update),
setLogCron: (update) => logs.push(update),
message: { info: (text) => messages.push(text) },
intl: { get: (text) => text },
};
const js = ts.transpile('const invalidate = ' + callback, { target: ts.ScriptTarget.ES2022 });
const invalidate = Function(...Object.keys(bindings), js + '\nreturn invalidate;')(...Object.values(bindings));
const js = ts.transpile('const invalidate = ' + callback, {
target: ts.ScriptTarget.ES2022,
});
const invalidate = Function(
...Object.keys(bindings),
js + '\nreturn invalidate;',
)(...Object.values(bindings));
invalidate(old, 'unavailable');
assert.equal(closes, 0);
assert.equal(summaries.length, 0);
@@ -398,7 +734,8 @@ test('an old invalidation cannot close a reopened session or clear its freshly q
const next = { session: 3 };
anomalySession.current = next;
anomalyVersion.current = 3;
const fresh = { triggers: { audit: { missing: 0 } } }, freshLog = { anomalySession: 3 };
const fresh = { triggers: { audit: { missing: 0 } } },
freshLog = { anomalySession: 3 };
assert.strictEqual(summaries[0](fresh), fresh);
assert.strictEqual(logs[0](freshLog), freshLog);
assert.equal(messages.length, 1);
+268 -65
View File
@@ -46,29 +46,64 @@ const flush = () => new Promise((resolve) => setImmediate(resolve));
const pastCursor = action('components/fileBrowser/index.tsx', 'pastCursor', {});
test('a retry at the top restores the next visible file when the first file was deleted', () => {
const row = (title, top) => ({ title, getBoundingClientRect: () => ({ top, bottom: top + 24 }) });
const row = (title, top) => ({
title,
getBoundingClientRect: () => ({ top, bottom: top + 24 }),
});
const element = {
scrollTop: 0, clientHeight: 48, getBoundingClientRect: () => ({ top: 100 }),
querySelectorAll: () => [row('gone', 100), row('survivor', 124), row('below', 148)],
querySelector: selector => selector === 'button[title="survivor"]' ? row('survivor', 364) : null,
scrollTop: 0,
clientHeight: 48,
getBoundingClientRect: () => ({ top: 100 }),
querySelectorAll: () => [
row('gone', 100),
row('survivor', 124),
row('below', 148),
],
querySelector: (selector) =>
selector === 'button[title="survivor"]' ? row('survivor', 364) : null,
};
const viewport = { current: element }, position = {};
action('components/fileBrowser/index.tsx', 'rememberPosition', { viewport, position })();
assert.deepEqual([...position.current.offsets], [['gone', 0], ['survivor', 24]]);
const viewport = { current: element },
position = {};
action('components/fileBrowser/index.tsx', 'rememberPosition', {
viewport,
position,
})();
assert.deepEqual(
[...position.current.offsets],
[
['gone', 0],
['survivor', 24],
],
);
const emptyListing = { rows: [], next: '', versions: new Map() };
action('components/fileBrowser/index.tsx', 'Entries', {
React: require('react'), emptyListing, Spin: 'i', CSS: { escape: key => key },
useRef: value => value === null ? viewport : value === undefined ? position : { current: value },
useState: value => [value, () => {}], useEffect() {}, useLayoutEffect: effect => effect(),
React: require('react'),
emptyListing,
Spin: 'i',
CSS: { escape: (key) => key },
useRef: (value) =>
value === null
? viewport
: value === undefined
? position
: { current: value },
useState: (value) => [value, () => {}],
useEffect() {},
useLayoutEffect: (effect) => effect(),
})({ source: 'logs', path: '', search: '' });
assert.equal(element.scrollTop, 240);
assert.equal(position.current, undefined);
});
test('a new execution has its own title before its log path arrives', () => {
const readableLogName = action('components/fileBrowser/name.ts', 'readableLogName', {});
const readableLogName = action(
'components/fileBrowser/name.ts',
'readableLogName',
{},
);
const title = action('pages/crontab/detail.tsx', 'instanceTitle', {
readableLogName, intl: { get: (key, { id }) => key.replace('{id}', id) },
readableLogName,
intl: { get: (key, { id }) => key.replace('{id}', id) },
});
const next = { id: 34834, status: 0, log_path: null };
const stopped = { id: 34814, status: 2, log_path: 'task/old.log' };
@@ -79,17 +114,34 @@ test('a new execution has its own title before its log path arrives', () => {
test('file rows preserve meaningful suffixes, separate the search directory and expose the full path', () => {
const React = require('react');
const names = ['async_components___init__', 'async_components_register.js', '中文任务_同步明细.log'];
const rows = names.map(title => ({ title, parent: 'workers', key: 'workers/' + title, type: 'file' }));
const names = [
'async_components___init__',
'async_components_register.js',
'中文任务_同步明细.log',
];
const rows = names.map((title) => ({
title,
parent: 'workers',
key: 'workers/' + title,
type: 'file',
}));
const emptyListing = { rows, next: '', versions: new Map() };
const entries = action('components/fileBrowser/index.tsx', 'Entries', {
React, useRef: current => ({ current }), useState: value => [value, () => {}], useEffect() {}, useLayoutEffect() {},
emptyListing, FileOutlined: 'i', Spin: 'i', Typography: { Text: 'span' }, readableLogName: value => value,
React,
useRef: (current) => ({ current }),
useState: (value) => [value, () => {}],
useEffect() {},
useLayoutEffect() {},
emptyListing,
FileOutlined: 'i',
Spin: 'i',
Typography: { Text: 'span' },
readableLogName: (value) => value,
})({ source: 'logs', path: '', search: 'work' }).props.children[0];
const tails = ['___init__', '_register.js', '_同步明细.log'];
for (const [i, button] of entries.entries()) {
const [name, parent] = button.props.children[1].props.children;
const parts = name.props.children.map(span => span.props.children);
const parts = name.props.children.map((span) => span.props.children);
assert.equal(parts.join(''), names[i]);
assert.equal(parts[1], tails[i]);
assert.equal(parent.props.children, 'workers');
@@ -101,24 +153,53 @@ test('file rows preserve meaningful suffixes, separate the search directory and
for (const remaining of [0, 2, 8]) {
test(`manual retry retains the requested depth through churn and a network error with ${remaining} files left`, async () => {
const emptyListing = { rows: [], next: '', versions: new Map() };
const listing = { current: { rows: [0, 1, 2, 3], next: '4', versions: new Map([['a', '1']]) } };
const states = [], failures = [];
let checks = 0, reads = 0, phase = 'churn';
const listing = {
current: {
rows: [0, 1, 2, 3],
next: '4',
versions: new Map([['a', '1']]),
},
};
const states = [],
failures = [];
let checks = 0,
reads = 0,
phase = 'churn';
const read = action('components/fileBrowser/index.tsx', 'read', {
pastCursor, rememberPosition() {},
listing, emptyListing, pending: {}, path: 'a', source: 'scripts', search: '', folders: false,
config: { apiPrefix: '/api/' }, setLoading() {}, setFailed: v => failures.push(v),
setListing: page => states.push(page.rows),
pastCursor,
rememberPosition() {},
listing,
emptyListing,
pending: {},
path: 'a',
source: 'scripts',
search: '',
folders: false,
config: { apiPrefix: '/api/' },
setLoading() {},
setFailed: (v) => failures.push(v),
setListing: (page) => states.push(page.rows),
request: {
async get(_url, { params }) {
reads++;
if (phase === 'offline') throw new Error('network unavailable');
const count = phase === 'churn' ? 8 : remaining;
const offset = Number(params.after);
const data = Array.from({ length: Math.min(2, count - offset) }, (_, i) => offset + i);
return { code: 200, data, next: offset + 2 < count ? String(offset + 2) : null, versions: [['a', '1']] };
const data = Array.from(
{ length: Math.min(2, count - offset) },
(_, i) => offset + i,
);
return {
code: 200,
data,
next: offset + 2 < count ? String(offset + 2) : null,
versions: [['a', '1']],
};
},
async post() {
checks++;
return { code: 200, current: phase === 'stable' };
},
async post() { checks++; return { code: 200, current: phase === 'stable' }; },
},
});
await read(listing.current);
@@ -135,7 +216,10 @@ for (const remaining of [0, 2, 8]) {
phase = 'stable';
await Promise.all([read(retry), read(retry)]);
const count = Math.min(6, remaining);
assert.deepEqual(listing.current.rows, Array.from({ length: count }, (_, i) => i));
assert.deepEqual(
listing.current.rows,
Array.from({ length: count }, (_, i) => i),
);
assert.equal(listing.current.next, remaining > count ? String(count) : '');
const completedReads = reads;
await read(retry);
@@ -149,21 +233,44 @@ for (const [source, search, boundary, cursors] of [
// DFS enters directory "a" before visiting sibling "a-".
['logs', 'needle', 'a-', ['a/1', 'a/2', 'a/3', 'a/x', 'a.', 'z']],
]) {
test(`retry traverses the old boundary after earlier inserts and deletion of the cursor (${source}, ${search || 'directory'})`, async () => {
test(`retry traverses the old boundary after earlier inserts and deletion of the cursor (${source}, ${
search || 'directory'
})`, async () => {
const emptyListing = { rows: [], next: '', versions: new Map() };
const listing = { current: { rows: ['old1', 'old2'], next: boundary, versions: new Map() } };
const listing = {
current: { rows: ['old1', 'old2'], next: boundary, versions: new Map() },
};
const failures = [];
let stable = false;
const read = action('components/fileBrowser/index.tsx', 'read', {
pastCursor, rememberPosition() {}, listing, emptyListing, pending: {}, source, path: '', search, folders: false,
config: { apiPrefix: '/api/' }, setLoading() {}, setFailed: v => failures.push(v), setListing() {},
pastCursor,
rememberPosition() {},
listing,
emptyListing,
pending: {},
source,
path: '',
search,
folders: false,
config: { apiPrefix: '/api/' },
setLoading() {},
setFailed: (v) => failures.push(v),
setListing() {},
request: {
async get(_url, { params }) {
const index = params.after === boundary ? 4 : cursors.indexOf(params.after) + 1;
const index =
params.after === boundary ? 4 : cursors.indexOf(params.after) + 1;
assert.ok(index < cursors.length);
return { code: 200, next: cursors[index], data: search && index === 3 ? [] : [cursors[index]], versions: [['', '1']] };
return {
code: 200,
next: cursors[index],
data: search && index === 3 ? [] : [cursors[index]],
versions: [['', '1']],
};
},
async post() {
return { code: 200, current: stable };
},
async post() { return { code: 200, current: stable }; },
},
});
await read(listing.current);
@@ -173,53 +280,119 @@ for (const [source, search, boundary, cursors] of [
await read(listing.current);
assert.equal(failures.at(-1), false);
assert.equal(listing.current.next, cursors[4]);
assert.deepEqual(listing.current.rows, cursors.slice(0, 5).filter((_, i) => !search || i !== 3));
assert.deepEqual(
listing.current.rows,
cursors.slice(0, 5).filter((_, i) => !search || i !== 3),
);
});
}
test('loading more rebuilds the original depth if a delayed last page missed a move into a previous directory', async () => {
const pages = [
{ data: ['c/old'], next: null, versions: [['c', '1']] },
{ data: ['a/moved', 'b/kept'], next: 'b/kept', versions: [['a', '2'], ['b', '1']] },
{
data: ['a/moved', 'b/kept'],
next: 'b/kept',
versions: [
['a', '2'],
['b', '1'],
],
},
{ data: ['c/new'], next: null, versions: [['c', '2']] },
];
const cursors = [], checks = [], commits = [], emptyListing = { rows: [], next: '', versions: new Map() };
const listing = { current: { rows: ['a/deleted', 'b/kept'], next: 'b/kept', versions: new Map([['a', '1'], ['b', '1']]) } };
const cursors = [],
checks = [],
commits = [],
emptyListing = { rows: [], next: '', versions: new Map() };
const listing = {
current: {
rows: ['a/deleted', 'b/kept'],
next: 'b/kept',
versions: new Map([
['a', '1'],
['b', '1'],
]),
},
};
const read = action('components/fileBrowser/index.tsx', 'read', {
pastCursor, rememberPosition() {},
pending: {}, listing, emptyListing, source: 'logs', path: '', search: 'match',
folders: false, config: { apiPrefix: '/api/' }, setListing: value => commits.push(value.rows),
setLoading() {}, setFailed(value) { assert.equal(value, false); },
pastCursor,
rememberPosition() {},
pending: {},
listing,
emptyListing,
source: 'logs',
path: '',
search: 'match',
folders: false,
config: { apiPrefix: '/api/' },
setListing: (value) => commits.push(value.rows),
setLoading() {},
setFailed(value) {
assert.equal(value, false);
},
request: {
async get(_url, { params }) { cursors.push(params.after); return { code: 200, ...pages.shift() }; },
async post(_url, stamps) { checks.push(Object.fromEntries(stamps)); return { code: 200, current: checks.length > 1 }; },
async get(_url, { params }) {
cursors.push(params.after);
return { code: 200, ...pages.shift() };
},
async post(_url, stamps) {
checks.push(Object.fromEntries(stamps));
return { code: 200, current: checks.length > 1 };
},
},
});
const previous = listing.current;
await read(previous);
await read(previous); // A late second click from the previous render.
assert.deepEqual(cursors, ['b/kept', '', 'b/kept']);
assert.deepEqual(checks, [{ a: '1', b: '1', c: '1' }, { a: '2', b: '1', c: '2' }]);
assert.deepEqual(checks, [
{ a: '1', b: '1', c: '1' },
{ a: '2', b: '1', c: '2' },
]);
assert.deepEqual(commits, [[], ['a/moved', 'b/kept', 'c/new']]);
});
for (const retrying of [false, true]) {
test(`abandoning a search discards its delayed validation during ${retrying ? 'manual retry' : 'initial load'}`, async () => {
const pending = {}, commits = [];
test(`abandoning a search discards its delayed validation during ${
retrying ? 'manual retry' : 'initial load'
}`, async () => {
const pending = {},
commits = [];
const emptyListing = { rows: [], next: '', versions: new Map() };
const previous = retrying ? { ...emptyListing, retryMinimum: 2 } : emptyListing;
let finish, reads = 0;
const previous = retrying
? { ...emptyListing, retryMinimum: 2 }
: emptyListing;
let finish,
reads = 0;
const read = action('components/fileBrowser/index.tsx', 'read', {
pastCursor, rememberPosition() {},
pending, listing: { current: previous }, emptyListing, source: 'scripts', path: '', search: 'old',
folders: false, config: { apiPrefix: '/api/' }, setListing: value => commits.push(value),
setLoading() {}, setFailed() {},
pastCursor,
rememberPosition() {},
pending,
listing: { current: previous },
emptyListing,
source: 'scripts',
path: '',
search: 'old',
folders: false,
config: { apiPrefix: '/api/' },
setListing: (value) => commits.push(value),
setLoading() {},
setFailed() {},
request: {
async get() {
reads++;
return { code: 200, data: [`old-${reads}.js`], next: reads === 1 ? 'more' : null, versions: [['', '1']] };
return {
code: 200,
data: [`old-${reads}.js`],
next: reads === 1 ? 'more' : null,
versions: [['', '1']],
};
},
post() {
return new Promise((resolve) => {
finish = resolve;
});
},
post() { return new Promise(resolve => { finish = resolve; }); },
},
});
const loading = read(previous);
@@ -237,11 +410,27 @@ test('directory navigation shows the current path separately and returns exactly
for (const source of ['scripts', 'logs']) {
let directory = 'parent/child';
const render = (input = '') => {
const states = [[directory, next => { directory = next; }], [input, () => {}], [input, () => {}]];
const states = [
[
directory,
(next) => {
directory = next;
},
],
[input, () => {}],
[input, () => {}],
];
return action('components/fileBrowser/index.tsx', 'FileBrowser', {
React, Entries: 'div', Spin: 'span', ArrowUpOutlined: 'i', Button: 'button',
Input: { Search: 'input' }, Typography: { Text: 'span' }, intl: { get: key => key },
useEffect() {}, useState: () => states.shift(),
React,
Entries: 'div',
Spin: 'span',
ArrowUpOutlined: 'i',
Button: 'button',
Input: { Search: 'input' },
Typography: { Text: 'span' },
intl: { get: (key) => key },
useEffect() {},
useState: () => states.shift(),
})({ source }).props.children[1];
};
assert.ok(!render('query'));
@@ -336,7 +525,7 @@ test('expanded history retains its cursor and original head during inserts and r
pending,
paging,
visibleIds,
list: { current: { scrollTo: position => scrolls.push(position) } },
list: { current: { scrollTo: (position) => scrolls.push(position) } },
pageSize: 2,
config: { apiPrefix: '/api/' },
id: 1,
@@ -356,13 +545,20 @@ test('expanded history retains its cursor and original head during inserts and r
await reading;
reading = load('older');
await load('older');
assert.deepEqual(request.calls.at(-1).config.params, { paged: true, limit: 2, before: 3 });
assert.deepEqual(request.calls.at(-1).config.params, {
paged: true,
limit: 2,
before: 3,
});
assert.equal(request.calls.length, 2);
request.calls.at(-1).reject(new Error('older request interrupted'));
await reading;
assert.equal(failure, 'older');
reading = load('refresh');
assert.deepEqual(request.calls.at(-1).config.params, { paged: true, limit: 1 });
assert.deepEqual(request.calls.at(-1).config.params, {
paged: true,
limit: 1,
});
answer([5], null);
await flush();
answer([3], null);
@@ -370,13 +566,20 @@ test('expanded history retains its cursor and original head during inserts and r
assert.equal(state.current.hasNew, true);
assert.equal(failure, 'older');
reading = load(failure);
assert.deepEqual(request.calls.at(-1).config.params, { paged: true, limit: 2, before: 3 });
assert.deepEqual(request.calls.at(-1).config.params, {
paged: true,
limit: 2,
before: 3,
});
answer([2, 1], null);
await reading;
reading = load('refresh');
answer([6], null);
await flush();
assert.deepEqual(request.calls.at(-1).config.params, { paged: true, ids: '3' });
assert.deepEqual(request.calls.at(-1).config.params, {
paged: true,
ids: '3',
});
answer([3], null);
await reading;
assert.deepEqual(
+21 -6
View File
@@ -152,12 +152,27 @@ test('healthy bootstrap continues loading system information', async () => {
});
test('retryable panel reads retain their route on gateway failures and still enforce login expiry', async () => {
for (const [status, retryInPlace, expected] of [[502, true, []], [504, true, []],
[502, false, ['/error']], [401, true, ['/login']]]) {
const {request, pushes} = fixture('/crontab');
await assert.rejects(request.get('/api/crons/1/triggers', {retryInPlace, adapter: async config => {
throw new axios.AxiosError('failed', 'ERR_BAD_RESPONSE', config, null, {status, config, data: {}});
}}));
for (const [status, retryInPlace, expected] of [
[502, true, []],
[504, true, []],
[502, false, ['/error']],
[401, true, ['/login']],
]) {
const { request, pushes } = fixture('/crontab');
await assert.rejects(
request.get('/api/crons/1/triggers', {
retryInPlace,
adapter: async (config) => {
throw new axios.AxiosError(
'failed',
'ERR_BAD_RESPONSE',
config,
null,
{ status, config, data: {} },
);
},
}),
);
assert.deepEqual(pushes, expected);
}
});
+32 -7
View File
@@ -6,19 +6,44 @@ const load = require('../helpers/load-security-module.cjs');
test('debugger keeps the selected script when an older read completes after it', async () => {
const ts = require('typescript');
const file = path.resolve(__dirname, '../../src/pages/script/editModal.tsx');
const source = ts.createSourceFile(file, require('fs').readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
const source = ts.createSourceFile(
file,
require('fs').readFileSync(file, 'utf8'),
ts.ScriptTarget.Latest,
true,
);
let read;
function visit(node) {
if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'getDetail')
if (
ts.isVariableDeclaration(node) &&
node.name.getText(source) === 'getDetail'
)
read = node.initializer.getText(source);
ts.forEachChild(node, visit);
}
visit(source);
const js = ts.transpile('const read = ' + read, { target: ts.ScriptTarget.ES2022 });
const responses = [], ready = [], contents = [];
const get = Function('request', 'pendingFile', 'setFileReady', 'setValue', 'config', js + '\nreturn read;')(
{ get: (_url, { signal }) => new Promise(resolve => responses.push({ resolve, signal })) },
{ current: undefined }, state => ready.push(state), text => contents.push(text), { apiPrefix: '/api/' },
const js = ts.transpile('const read = ' + read, {
target: ts.ScriptTarget.ES2022,
});
const responses = [],
ready = [],
contents = [];
const get = Function(
'request',
'pendingFile',
'setFileReady',
'setValue',
'config',
js + '\nreturn read;',
)(
{
get: (_url, { signal }) =>
new Promise((resolve) => responses.push({ resolve, signal })),
},
{ current: undefined },
(state) => ready.push(state),
(text) => contents.push(text),
{ apiPrefix: '/api/' },
);
get({ title: 'slow.js' });
get({ title: 'current.js' });
File diff suppressed because it is too large. Load diff
+175 -58
View File
@@ -9,20 +9,37 @@ const zh = require('../../src/locales/zh-CN.json');
const en = require('../../src/locales/en-US.json');
// Render the actual TSX, including disclosure markup and translated field names.
const source = fs.readFileSync(require.resolve('../../src/pages/crontab/triggerTiming.tsx'), 'utf8');
const { outputText } = ts.transpileModule(source, { compilerOptions: {
jsx: ts.JsxEmit.ReactJSX, module: ts.ModuleKind.CommonJS, esModuleInterop: true,
target: ts.ScriptTarget.ES2022,
}});
const source = fs.readFileSync(
require.resolve('../../src/pages/crontab/triggerTiming.tsx'),
'utf8',
);
const { outputText } = ts.transpileModule(source, {
compilerOptions: {
jsx: ts.JsxEmit.ReactJSX,
module: ts.ModuleKind.CommonJS,
esModuleInterop: true,
target: ts.ScriptTarget.ES2022,
},
});
const output = {};
Function('require', 'exports', outputText)(require, output);
const base = new Date(2026, 10, 16, 14, 55).getTime();
before(() => intl.init({currentLocale: 'zh-CN', locales: {'zh-CN': zh, 'en-US': en}}));
before(() =>
intl.init({ currentLocale: 'zh-CN', locales: { 'zh-CN': zh, 'en-US': en } }),
);
function render(fields) {
const html = renderToStaticMarkup(React.createElement(output.default, { row: {
observed_at: base, state: 'running', source: 'node', exit_code: null, ...fields,
}}));
const html = renderToStaticMarkup(
React.createElement(output.default, {
row: {
observed_at: base,
state: 'running',
source: 'node',
exit_code: null,
...fields,
},
}),
);
const [summary, details] = html.split(/<details[^>]*>/);
assert.doesNotMatch(html, /<details[^>]* open/);
assert.match(details, /<summary>时间明细<\/summary>/);
@@ -31,8 +48,12 @@ function render(fields) {
}
test('summary separates 57 ms in queue from 158 ms to command start and optional script entry', () => {
const fields = { scheduled_at: base, queued_at: base + 10, started_at: base + 67,
command_started_at: base + 158 };
const fields = {
scheduled_at: base,
queued_at: base + 10,
started_at: base + 67,
command_started_at: base + 158,
};
for (const script_started_at of [null, base + 201]) {
const { summary, details } = render({ ...fields, script_started_at });
assert.match(summary, /排队等待 <b>57 ms/);
@@ -46,59 +67,103 @@ test('summary separates 57 ms in queue from 158 ms to command start and optional
assert.match(details, /计划到脚本开始 <b>201 ms/);
}
}
const {summary} = render({...fields, state:'finished', finished_at:base+3158});
const { summary } = render({
...fields,
state: 'finished',
finished_at: base + 3158,
});
assert.match(summary, /计划到命令启动 <b>158 ms/);
assert.match(summary, /结束时间 <b>14:55:03/);
});
test('only a currently queued run accumulates wait; skip or stop freezes the wait', (t) => {
t.mock.method(Date, 'now', () => base + 7000);
const fields = { queued_at:base, scheduled_at:base, started_at:null };
assert.match(render({...fields, state:'queued'}).summary, /已排队 <b>7 s/);
const { summary, details } = render({...fields, state:'skipped', finished_at:base+12});
const fields = { queued_at: base, scheduled_at: base, started_at: null };
assert.match(render({ ...fields, state: 'queued' }).summary, /已排队 <b>7 s/);
const { summary, details } = render({
...fields,
state: 'skipped',
finished_at: base + 12,
});
assert.doesNotMatch(summary, /已排队|计划到命令启动|排队等待/);
assert.match(details, /跳过前等待 <b>12 ms/);
const stopped = render({...fields,state:'stopped',finished_at:base+2100});
assert.match(stopped.summary,/排队等待 <b>2.1 s/);
const unknown = render({...fields,state:'unknown',finished_at:base+6000});
assert.doesNotMatch(unknown.summary,/排队等待|结束时间|已排队/);
assert.match(unknown.details,/状态记录时间/);
const stopped = render({
...fields,
state: 'stopped',
finished_at: base + 2100,
});
assert.match(stopped.summary, /排队等待 <b>2.1 s/);
const unknown = render({
...fields,
state: 'unknown',
finished_at: base + 6000,
});
assert.doesNotMatch(unknown.summary, /排队等待|结束时间|已排队/);
assert.match(unknown.details, /状态记录时间/);
});
test('manual and legacy rows never synthesize a schedule, queue time, command start or sample', () => {
const manual=render({source:'manual',queued_at:base, started_at:base+30,command_started_at:base+51});
assert.match(manual.summary,/进入队列/);
assert.match(manual.summary,/命令启动 <b>14:55:00/);
assert.doesNotMatch(manual.summary,/计划到命令启动/);
for (const source of ['system','legacy','client']) {
const {summary,details}=render({source,started_at:base, state:'failed',exit_code:17});
assert.match(summary,/记录启动/);
assert.match(summary,/退出码 <b>17/);
assert.doesNotMatch(summary,/计划运行|排队等待|计划到命令启动/);
assert.match(details,/记录启动<\/dt><dd>14:55:00.000/);
assert.match(details,/命令启动<\/dt><dd>未记录/);
const manual = render({
source: 'manual',
queued_at: base,
started_at: base + 30,
command_started_at: base + 51,
});
assert.match(manual.summary, /进入队列/);
assert.match(manual.summary, /命令启动 <b>14:55:00/);
assert.doesNotMatch(manual.summary, /计划到命令启动/);
for (const source of ['system', 'legacy', 'client']) {
const { summary, details } = render({
source,
started_at: base,
state: 'failed',
exit_code: 17,
});
assert.match(summary, /记录启动/);
assert.match(summary, /退出码 <b>17/);
assert.doesNotMatch(summary, /计划运行|排队等待|计划到命令启动/);
assert.match(details, /记录启动<\/dt><dd>14:55:00.000/);
assert.match(details, /命令启动<\/dt><dd>未记录/);
}
});
test('retain precision and dates across midnight, accept zero latency, omit reversed timestamps', () => {
const scheduled = new Date(2026, 11, 31, 23, 59, 59, 900).getTime();
const {summary,details}=render({state:'finished',scheduled_at:scheduled,queued_at:scheduled,
started_at:scheduled,command_started_at:scheduled+150,finished_at:scheduled+3100});
assert.match(summary,/2026-12-31 23:59:59/);
assert.match(summary,/排队等待 <b>0 ms/);
assert.match(summary,/结束时间 <b>2027-01-01 00:00:03/);
assert.match(details,/命令启动<\/dt><dd>2027-01-01 00:00:00.050/);
assert.doesNotMatch(render({scheduled_at:base, command_started_at:base-1}).summary,/计划到命令启动/);
const { summary, details } = render({
state: 'finished',
scheduled_at: scheduled,
queued_at: scheduled,
started_at: scheduled,
command_started_at: scheduled + 150,
finished_at: scheduled + 3100,
});
assert.match(summary, /2026-12-31 23:59:59/);
assert.match(summary, /排队等待 <b>0 ms/);
assert.match(summary, /结束时间 <b>2027-01-01 00:00:03/);
assert.match(details, /命令启动<\/dt><dd>2027-01-01 00:00:00.050/);
assert.doesNotMatch(
render({ scheduled_at: base, command_started_at: base - 1 }).summary,
/计划到命令启动/,
);
});
test('an entry sample with no schedule names the measured starting point and keeps millisecond precision', () => {
const script_started_at = base + 1635;
const manual = render({source:'manual', queued_at:base, started_at:base+10, script_started_at});
assert.match(manual.details,/入队到脚本开始 <b>1.635 s/);
const client = render({source:'client', started_at:base, script_started_at});
assert.match(client.details,/启动记录到脚本开始 <b>1.635 s/);
for (const {summary,details} of [manual,client]) {
assert.doesNotMatch(summary + details,/计划到脚本开始|计划到命令启动/);
const manual = render({
source: 'manual',
queued_at: base,
started_at: base + 10,
script_started_at,
});
assert.match(manual.details, /入队到脚本开始 <b>1.635 s/);
const client = render({
source: 'client',
started_at: base,
script_started_at,
});
assert.match(client.details, /启动记录到脚本开始 <b>1.635 s/);
for (const { summary, details } of [manual, client]) {
assert.doesNotMatch(summary + details, /计划到脚本开始|计划到命令启动/);
}
});
@@ -106,23 +171,75 @@ test('an expanded queued row uses its server snapshot even when the browser cloc
t.mock.method(Date, 'now', () => base + 600000);
const queued = { queued_at: base, queue_wait_ms: 375, state: 'queued' };
assert.match(render(queued).summary, /已排队 <b>375 ms/);
assert.match(render({...queued, queue_wait_ms:0}).summary, /已排队 <b>0 ms/);
assert.match(render({...queued, state:'running', started_at:base+812}).summary, /排队等待 <b>812 ms/);
assert.match(
render({ ...queued, queue_wait_ms: 0 }).summary,
/已排队 <b>0 ms/,
);
assert.match(
render({ ...queued, state: 'running', started_at: base + 812 }).summary,
/排队等待 <b>812 ms/,
);
});
test('expanded wait reasons retain the actual slot holders after the timer freezes', () => {
const queue_context=JSON.stringify({queue:'manual',limit:2,occupied:2,holders:[{id:'instance-101',name:'长任务 A'},{id:'instance-102',name:'长任务 B'}]});
const {summary,details}=render({state:'finished',queued_at:base,started_at:base+3712,finished_at:base+5000,queue_context});
assert.match(summary,/排队等待 <b>3.712 s/);
assert.match(details,/手动执行队列/);assert.match(details,/入队时已达并发上限(运行 2,上限 2)/);
assert.match(details,/长任务 A/);assert.match(details,/长任务 B/);
assert.match(render({state:'queued',queued_at:base}).details,/尚无同时运行的任务记录/);
const queue_context = JSON.stringify({
queue: 'manual',
limit: 2,
occupied: 2,
holders: [
{ id: 'instance-101', name: '长任务 A' },
{ id: 'instance-102', name: '长任务 B' },
],
});
const { summary, details } = render({
state: 'finished',
queued_at: base,
started_at: base + 3712,
finished_at: base + 5000,
queue_context,
});
assert.match(summary, /排队等待 <b>3.712 s/);
assert.match(details, /手动执行队列/);
assert.match(details, /入队时已达并发上限(运行 2,上限 2)/);
assert.match(details, /长任务 A/);
assert.match(details, /长任务 B/);
assert.match(
render({ state: 'queued', queued_at: base }).details,
/尚无同时运行的任务记录/,
);
});
test('a live queue shows the resampled holders and preserves the measured dequeue time after preparation',()=>{
const admission=JSON.stringify({queue:'manual',occupied:2,limit:2,holders:[{id:'a',name:'holder-A'},{id:'b',name:'holder-B'}]});
const live=JSON.stringify({queue:'manual',occupied:1,limit:1,holders:[{id:'b',name:'holder-B'}]});
const row={state:'queued',queued_at:base,queue_context:admission,queue_live_context:live};
assert.match(render(row).details,/最近一次检查(运行 1,上限 1)/);assert.doesNotMatch(render(row).details,/holder-A/);
assert.match(render({...row,state:'finished',dequeued_at:base+210,started_at:base+810}).summary,/排队等待 <b>210 ms/);
test('a live queue shows the resampled holders and preserves the measured dequeue time after preparation', () => {
const admission = JSON.stringify({
queue: 'manual',
occupied: 2,
limit: 2,
holders: [
{ id: 'a', name: 'holder-A' },
{ id: 'b', name: 'holder-B' },
],
});
const live = JSON.stringify({
queue: 'manual',
occupied: 1,
limit: 1,
holders: [{ id: 'b', name: 'holder-B' }],
});
const row = {
state: 'queued',
queued_at: base,
queue_context: admission,
queue_live_context: live,
};
assert.match(render(row).details, /最近一次检查(运行 1,上限 1)/);
assert.doesNotMatch(render(row).details, /holder-A/);
assert.match(
render({
...row,
state: 'finished',
dequeued_at: base + 210,
started_at: base + 810,
}).summary,
/排队等待 <b>210 ms/,
);
});
+4 -1
View File
@@ -456,7 +456,10 @@ test('sidebar and dialog use the same authoritative status even when old phase f
);
f.store.setJob({ status: 'ready', phase: 'downloading', percent: 62 });
notice.render();
assert.equal(notice.nodes('button')[0].props['aria-label'], '下载完成,等待重启');
assert.equal(
notice.nodes('button')[0].props['aria-label'],
'下载完成,等待重启',
);
f.store.setJob({ status: 'completed', phase: 'ready' });
assert.equal(notice.render(), null);
panel.render();
+26 -1
View File
@@ -3,22 +3,47 @@ const path = require('node:path');
const { createRequire } = require('node:module');
const ts = require('typescript');
function moduleFile(file, name) {
const target = path.resolve(path.dirname(file), name);
const resolved = [
target,
`${target}.ts`,
`${target}.js`,
`${target}.cjs`,
path.join(target, 'index.ts'),
path.join(target, 'index.js'),
].find(
(candidate) => fs.existsSync(candidate) && fs.statSync(candidate).isFile(),
);
return resolved;
}
module.exports = function loadSecurityModule(
file,
mocks = {},
cache = new Map(),
resolvedMocks,
) {
file = path.resolve(file);
// A dependency keeps its mock when a nested module imports it at another depth.
resolvedMocks ??= new Map(
Object.entries(mocks).flatMap(([name, value]) => {
const target = name.startsWith('.') ? moduleFile(file, name) : undefined;
return target ? [[target, value]] : [];
}),
);
if (cache.has(file)) return cache.get(file).exports;
const module = { exports: {} };
cache.set(file, module);
const localRequire = createRequire(file);
const requireModule = (name) => {
const resolved = name.startsWith('.') ? moduleFile(file, name) : undefined;
if (resolvedMocks.has(resolved)) return resolvedMocks.get(resolved);
if (Object.hasOwn(mocks, name)) return mocks[name];
if (name.startsWith('.')) {
const target = path.resolve(path.dirname(file), name);
if (fs.existsSync(`${target}.ts`)) {
return loadSecurityModule(`${target}.ts`, mocks, cache);
return loadSecurityModule(`${target}.ts`, mocks, cache, resolvedMocks);
}
}
return localRequire(name);
+43 -16
View File
@@ -7,7 +7,12 @@ const { LogStreamManager } = require('../../back/shared/logStreamManager');
const [root, command] = process.argv.slice(2);
process.env.QL_DATA_DIR = root;
const reporter = path.join(root, 'reporter.cjs');
fs.writeFileSync(reporter, `require('node:fs').writeFileSync(${JSON.stringify(path.join(root, 'receipt.json'))}, process.argv[2]);`);
fs.writeFileSync(
reporter,
`require('node:fs').writeFileSync(${JSON.stringify(
path.join(root, 'receipt.json'),
)}, process.argv[2]);`,
);
const Service = load('back/services/cron.ts', {
'../config': { logPath: root },
'../data/cron': {
@@ -17,22 +22,44 @@ const Service = load('back/services/cron.ts', {
'../data/runningInstance': {},
'../config/util': { getUniqPath: async () => "log's $directory" },
'../schedule/client': {},
'../shared/pLimit': { manualRunWithCronLimit: fn => fn() },
'../shared/triggerHistory': { TriggerHistory: class {
async bindCommand(_, pid, log) { process.send({ pid, log }); return true; }
async shouldStop() { return false; }
async complete() {}
} },
'../shared/logStreamManager': { logStreamManager: new LogStreamManager(root) },
'cross-spawn': { spawn: (file, args, options) => {
// Record the real supervisor's receipt without starting a panel database.
if (file === 'python3') args[7] = reporter;
return spawn(file, args, options);
} },
'../cron/execution/cronLimit': { manualRunWithCronLimit: (fn) => fn() },
'../cron/history': {
TriggerHistory: class {
async bindCommand(_, pid, log) {
process.send({ pid, log });
return true;
}
async shouldStop() {
return false;
}
async complete() {}
},
},
'../shared/logStreamManager': {
logStreamManager: new LogStreamManager(root),
},
'cross-spawn': {
spawn: (file, args, options) => {
// Record the real supervisor's receipt without starting a panel database.
if (file === 'python3') args[7] = reporter;
return spawn(file, args, options);
},
},
}).default;
const service = new Service({ info() {}, error(...args) { console.error(...args); } });
service.getDb = async () => ({ id: 1, status: 3, command, queued_token: 'test', log_path: '' });
const service = new Service({
info() {},
error(...args) {
console.error(...args);
},
});
service.getDb = async () => ({
id: 1,
status: 3,
command,
queued_token: 'test',
log_path: '',
});
service.makeCommand = () => command;
service.runSingle(1, 'test', 'manual-log-test').then(result => {
service.runSingle(1, 'test', 'manual-log-test').then((result) => {
process.send({ result }, () => process.disconnect());
});
+76 -37
View File
@@ -8,54 +8,93 @@ const { once } = require('node:events');
const { setTimeout: delay } = require('node:timers/promises');
const { createHash } = require('node:crypto');
const volume = '/ql/data/db';
const moduleFile = '/ql/static/build/shared/managedExit.cjs';
const moduleFile = '/ql/static/build/cron/settlement/exitReceipt.cjs';
const { receiptPath, readExit, retiringExits } = require(moduleFile);
(async () => {
const usage = await fs.statfs(volume);
assert.equal(usage.type,0xef53);
assert.ok(usage.blocks * usage.bsize <= 32 * 1024 * 1024 && usage.files <= 8192);
await fs.access(path.join(volume,'.qa-isolated-volume'));
const root = await fs.mkdtemp(path.join(volume,'.qa-slot-'));
assert.equal(usage.type, 0xef53);
assert.ok(
usage.blocks * usage.bsize <= 32 * 1024 * 1024 && usage.files <= 8192,
);
await fs.access(path.join(volume, '.qa-isolated-volume'));
const root = await fs.mkdtemp(path.join(volume, '.qa-slot-'));
const workers = [];
try {
process.env.QL_DATA_DIR = root;
const id = 'occupied-slot', directory = path.join(path.dirname(receiptPath(id)),'.claim.' + id + '.qaTest');
await fs.mkdir(directory,{recursive:true});
const slot = path.join(directory,'receipt');
const receipt = code => JSON.stringify({code, signal:null, time:1000, version:1,
checksum:createHash('sha256').update(JSON.stringify([id,code,null,1000])).digest('hex')});
await fs.writeFile(slot,receipt(17),{flag:'wx'});
for (const role of ['A','B']) {
const id = 'occupied-slot',
directory = path.join(
path.dirname(receiptPath(id)),
'.claim.' + id + '.qaTest',
);
await fs.mkdir(directory, { recursive: true });
const slot = path.join(directory, 'receipt');
const receipt = (code) =>
JSON.stringify({
code,
signal: null,
time: 1000,
version: 1,
checksum: createHash('sha256')
.update(JSON.stringify([id, code, null, 1000]))
.digest('hex'),
});
await fs.writeFile(slot, receipt(17), { flag: 'wx' });
for (const role of ['A', 'B']) {
const barrier = path.join(root, role);
const child = spawn(process.execPath,[path.join(__dirname,'receipt-claim-reuse-worker.cjs'),
moduleFile, slot, id, '17', '1000', barrier],{stdio:'inherit'});
workers.push({barrier,child,done:once(child,'exit')});
const child = spawn(
process.execPath,
[
path.join(__dirname, 'receipt-claim-reuse-worker.cjs'),
moduleFile,
slot,
id,
'17',
'1000',
barrier,
],
{ stdio: 'inherit' },
);
workers.push({ barrier, child, done: once(child, 'exit') });
}
const deadline = performance.now() + 10000;
const before = await Promise.all(workers.map(async ({barrier}) => {
while (performance.now() < deadline) {
try { return JSON.parse(await fs.readFile(barrier+'.ready','utf8')); }
catch (error) { if (error.code !== 'ENOENT') throw error; }
await delay(20);
}
throw Error('Both collectors must validate the original slot');
}));
assert.equal(before[0].fileInode,before[1].fileInode);
assert.equal(before[0].directoryInode,before[1].directoryInode);
await fs.writeFile(slot+'.new',receipt(42),{flag:'wx'});
await fs.rename(slot+'.new',slot);
const before = await Promise.all(
workers.map(async ({ barrier }) => {
while (performance.now() < deadline) {
try {
return JSON.parse(await fs.readFile(barrier + '.ready', 'utf8'));
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
await delay(20);
}
throw Error('Both collectors must validate the original slot');
}),
);
assert.equal(before[0].fileInode, before[1].fileInode);
assert.equal(before[0].directoryInode, before[1].directoryInode);
await fs.writeFile(slot + '.new', receipt(42), { flag: 'wx' });
await fs.rename(slot + '.new', slot);
const inode = (await fs.stat(slot)).ino;
assert.notEqual(inode,before[0].fileInode);
for (const {barrier} of workers) await fs.writeFile(barrier+'.go','');
for (const {done} of workers) assert.deepEqual(await done,[0,null]);
assert.notEqual(inode, before[0].fileInode);
for (const { barrier } of workers) await fs.writeFile(barrier + '.go', '');
for (const { done } of workers) assert.deepEqual(await done, [0, null]);
const captures = await retiringExits();
assert.equal(captures.length,1);
assert.equal((await fs.stat(captures[0].file)).ino,inode);
assert.equal((await readExit(id,captures[0].file)).code,42);
console.log(JSON.stringify({before,replacementInode:inode,retained:captures[0].file}));
assert.equal(captures.length, 1);
assert.equal((await fs.stat(captures[0].file)).ino, inode);
assert.equal((await readExit(id, captures[0].file)).code, 42);
console.log(
JSON.stringify({
before,
replacementInode: inode,
retained: captures[0].file,
}),
);
} finally {
for (const {child} of workers) if (child.exitCode === null) child.kill();
await fs.rm(root,{recursive:true,force:true});
for (const { child } of workers) if (child.exitCode === null) child.kill();
await fs.rm(root, { recursive: true, force: true });
}
})().catch(error => { console.error(error); process.exitCode=1; });
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Loaded 100 of 346 files, more files were not shown because too many files have changed in this diff. Show more