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

+18 -5
View File
@@ -4,7 +4,10 @@ const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const { execFileSync, spawnSync } = require('node:child_process');
const { createContext, sourceEnvironment } = require('../../dist/internal/runtime/context');
const {
createContext,
sourceEnvironment,
} = require('../../dist/internal/runtime/context');
const { executeTask } = require('../../dist/internal/execution/taskRunner');
test('Shell and CLI agree on isolated script state and account modes', async (t) => {
@@ -31,7 +34,14 @@ test('Shell and CLI agree on isolated script state and account modes', async (t)
path.join(root, 'static/build'),
])
await fs.mkdir(directory, { recursive: true });
for (const name of ['task.sh', 'task-timeout.sh', 'otask.sh', 'share.sh', 'api.sh', 'env.sh'])
for (const name of [
'task.sh',
'task-timeout.sh',
'otask.sh',
'share.sh',
'api.sh',
'env.sh',
])
await fs.copyFile(
path.resolve(__dirname, '../../../shell', name),
path.join(context.paths.dir_shell, name),
@@ -406,9 +416,12 @@ test('configuration shell options survive the environment bridge for pipeline an
assert.ok(env.SHELLOPTS.split(':').includes('pipefail'));
assert.ok(!env.SHELLOPTS.split(':').includes('allexport'));
// Bash 3.x cannot import BASHOPTS itself; exercise the actual CLI bridge.
const execution = await require('../../dist/internal/runtime/process').runProcess(
'bash', ['--noprofile', '--norc', '-c', probe], { env, capture: true },
);
const execution =
await require('../../dist/internal/runtime/process').runProcess(
'bash',
['--noprofile', '--norc', '-c', probe],
{ env, capture: true },
);
assert.equal(execution.code, 0);
const modern = execution.stdout;
assert.equal(modern, legacy);
+25 -6
View File
@@ -9,19 +9,38 @@ const { installCliEntrypoints } = require('../../dist/local/entrypoints');
test('generated entries treat quotes, newlines and code-like paths as data', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-entry-paths-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const cliRoot = path.join(root, "CLI '中文\n\");throw new Error('injected');//");
const cliRoot = path.join(
root,
"CLI '中文\n\");throw new Error('injected');//",
);
const bin = path.join(root, 'bin');
await fs.mkdir(path.join(cliRoot, 'dist'), { recursive: true });
await fs.writeFile(path.join(cliRoot, 'dist/ql.js'), 'exports.qlMain=async()=>{console.log(JSON.stringify(process.argv.slice(2)));return 7;};');
await fs.writeFile(path.join(cliRoot, 'dist/task.js'), 'exports.taskMain=async()=>{throw new Error("secret-value");};');
await fs.writeFile(
path.join(cliRoot, 'dist/ql.js'),
'exports.qlMain=async()=>{console.log(JSON.stringify(process.argv.slice(2)));return 7;};',
);
await fs.writeFile(
path.join(cliRoot, 'dist/task.js'),
'exports.taskMain=async()=>{throw new Error("secret-value");};',
);
await installCliEntrypoints(bin, cliRoot);
const ql = spawnSync(process.execPath, [path.join(bin, 'ql'), '--literal', 'value'], { encoding: 'utf8' });
const ql = spawnSync(
process.execPath,
[path.join(bin, 'ql'), '--literal', 'value'],
{ encoding: 'utf8' },
);
assert.equal(ql.status, 7, ql.stderr);
assert.deepEqual(JSON.parse(ql.stdout), ['--literal', 'value']);
for (const language of ['en', 'zh']) {
const result = spawnSync(process.execPath, [path.join(bin, 'task')], { encoding: 'utf8', env: { QL_LANG: language } });
const result = spawnSync(process.execPath, [path.join(bin, 'task')], {
encoding: 'utf8',
env: { QL_LANG: language },
});
assert.equal(result.status, 1);
assert.equal(result.stderr, language === 'en' ? 'CLI invocation failed.\n' : 'CLI 调用失败。\n');
assert.equal(
result.stderr,
language === 'en' ? 'CLI invocation failed.\n' : 'CLI 调用失败。\n',
);
assert.doesNotMatch(result.stderr, /secret-value/);
}
});
+136 -40
View File
@@ -5,23 +5,59 @@ const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
test('legacy Shell and TS resolve executable paths after selecting the working directory', t => {
const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ql-executable-')));
test('legacy Shell and TS resolve executable paths after selecting the working directory', (t) => {
const root = fs.realpathSync(
fs.mkdtempSync(path.join(os.tmpdir(), 'ql-executable-')),
);
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
for (const dir of ['shell/preload', 'shell/lang', 'data/config', 'data/scripts/bin', 'data/scripts/custom', 'data/log', 'static/build', 'bin'])
for (const dir of [
'shell/preload',
'shell/lang',
'data/config',
'data/scripts/bin',
'data/scripts/custom',
'data/log',
'static/build',
'bin',
])
fs.mkdirSync(path.join(root, dir), { recursive: true });
for (const name of ['task.sh', 'task-timeout.sh', 'otask.sh', 'share.sh', 'api.sh', 'env.sh'])
fs.copyFileSync(path.resolve(__dirname, '../../../shell', name), path.join(root, 'shell', name));
for (const name of [
'task.sh',
'task-timeout.sh',
'otask.sh',
'share.sh',
'api.sh',
'env.sh',
])
fs.copyFileSync(
path.resolve(__dirname, '../../../shell', name),
path.join(root, 'shell', name),
);
for (const name of ['zh.sh', 'en.sh'])
fs.copyFileSync(path.resolve(__dirname, '../../../shell/lang', name), path.join(root, 'shell/lang', name));
fs.copyFileSync(
path.resolve(__dirname, '../../../shell/lang', name),
path.join(root, 'shell/lang', name),
);
fs.symlinkSync(process.execPath, path.join(root, 'bin/node'));
fs.writeFileSync(path.join(root, 'bin/pnpm'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
fs.writeFileSync(path.join(root, 'static/build/token.js'), 'process.stdout.write("fixture")');
fs.writeFileSync(path.join(root, 'data/config/config.sh'),
'no_tee=true\nmy_task() { printf "%s\\n" "$PWD" "$@" > "$TRACE"; }\n');
fs.writeFileSync(path.join(root, 'bin/pnpm'), '#!/bin/sh\nexit 0\n', {
mode: 0o755,
});
fs.writeFileSync(
path.join(root, 'static/build/token.js'),
'process.stdout.write("fixture")',
);
fs.writeFileSync(
path.join(root, 'data/config/config.sh'),
'no_tee=true\nmy_task() { printf "%s\\n" "$PWD" "$@" > "$TRACE"; }\n',
);
fs.writeFileSync(path.join(root, 'data/config/crontab.list'), '');
const script = '#!/bin/sh\nprintf "%s\\n" "$PWD" "$@" > "$TRACE"\n';
for (const file of ['data/scripts/bin/tool', 'data/scripts/bin/tool.exe', 'data/scripts/custom/tool', 'bin/path-tool'])
for (const file of [
'data/scripts/bin/tool',
'data/scripts/bin/tool.exe',
'data/scripts/custom/tool',
'bin/path-tool',
])
fs.writeFileSync(path.join(root, file), script, { mode: 0o755 });
const cases = [
['bin/tool', '', 'bin'],
@@ -36,56 +72,116 @@ test('legacy Shell and TS resolve executable paths after selecting the working d
for (const [program, workDir, directory] of cases) {
for (const [label, command, prefix] of [
['shell', '/bin/bash', [path.join(root, 'shell/task.sh')]],
['ts', process.execPath, [path.resolve(__dirname, '../../dist/runner.js'), '--root', root]],
[
'ts',
process.execPath,
[path.resolve(__dirname, '../../dist/runner.js'), '--root', root],
],
]) {
const trace = path.join(root, `${label}.trace`);
fs.rmSync(trace, { force: true });
const result = spawnSync(command, [...prefix, program, 'first', 'two words'], {
env: { PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`, QL_DIR: root, work_dir: workDir, TRACE: trace },
encoding: 'utf8', timeout: 15000,
});
const result = spawnSync(
command,
[...prefix, program, 'first', 'two words'],
{
env: {
PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`,
QL_DIR: root,
work_dir: workDir,
TRACE: trace,
},
encoding: 'utf8',
timeout: 15000,
},
);
assert.equal(result.status, 0, `${label}/${program}: ${result.stderr}`);
assert.equal(fs.readFileSync(trace, 'utf8'),
`${path.join(root, 'data/scripts', directory)}\nfirst\ntwo words\n`, `${label}/${program}`);
assert.equal(
fs.readFileSync(trace, 'utf8'),
`${path.join(root, 'data/scripts', directory)}\nfirst\ntwo words\n`,
`${label}/${program}`,
);
}
}
// A builtin has no executable file. Function arguments must remain literal.
for (const args of [[':', 'unused'], ['my_task', '$(touch INJECTED)', '; exit 9']]) {
const result = spawnSync(process.execPath,
[path.resolve(__dirname, '../../dist/runner.js'), '--root', root, '--json', ...args], {
env: { PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`, TRACE: path.join(root, 'literal.trace') },
encoding: 'utf8', timeout: 15000,
});
for (const args of [
[':', 'unused'],
['my_task', '$(touch INJECTED)', '; exit 9'],
]) {
const result = spawnSync(
process.execPath,
[
path.resolve(__dirname, '../../dist/runner.js'),
'--root',
root,
'--json',
...args,
],
{
env: {
PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`,
TRACE: path.join(root, 'literal.trace'),
},
encoding: 'utf8',
timeout: 15000,
},
);
assert.equal(result.status, 0, result.stderr);
}
assert.equal(fs.readFileSync(path.join(root, 'literal.trace'), 'utf8'),
`${path.join(root, 'data/scripts')}\n$(touch INJECTED)\n; exit 9\n`);
assert.equal(
fs.readFileSync(path.join(root, 'literal.trace'), 'utf8'),
`${path.join(root, 'data/scripts')}\n$(touch INJECTED)\n; exit 9\n`,
);
assert.equal(fs.existsSync(path.join(root, 'data/scripts/INJECTED')), false);
fs.writeFileSync(path.join(root, 'data/config/config.sh'),
'no_tee=true\nSTATE=before\nmy_task() { export STATE=after; return 7; }\n');
fs.writeFileSync(path.join(root, 'data/config/task_after.sh'),
'printf "%s:%s" "$STATE" "$_task_exit_code" > "$TRACE.after"\n');
fs.writeFileSync(
path.join(root, 'data/config/config.sh'),
'no_tee=true\nSTATE=before\nmy_task() { export STATE=after; return 7; }\n',
);
fs.writeFileSync(
path.join(root, 'data/config/task_after.sh'),
'printf "%s:%s" "$STATE" "$_task_exit_code" > "$TRACE.after"\n',
);
for (const dir of ['', 'custom'])
fs.writeFileSync(path.join(root, 'data/scripts', dir, 'show.sh'),
'printf "%s" "$PWD" > "$TRACE"\n');
fs.writeFileSync(
path.join(root, 'data/scripts', dir, 'show.sh'),
'printf "%s" "$PWD" > "$TRACE"\n',
);
for (const scenario of ['function-state', 'hook-directory']) {
fs.writeFileSync(path.join(root, 'data/config/task_before.sh'),
scenario === 'hook-directory' ? 'work_dir=custom\n' : '');
const args = scenario === 'function-state' ? ['my_task'] : ['show.sh', 'now'];
fs.writeFileSync(
path.join(root, 'data/config/task_before.sh'),
scenario === 'hook-directory' ? 'work_dir=custom\n' : '',
);
const args =
scenario === 'function-state' ? ['my_task'] : ['show.sh', 'now'];
for (const [label, command, prefix] of [
['shell', '/bin/bash', [path.join(root, 'shell/task.sh')]],
['ts', process.execPath, [path.resolve(__dirname, '../../dist/runner.js'), '--root', root]],
[
'ts',
process.execPath,
[path.resolve(__dirname, '../../dist/runner.js'), '--root', root],
],
]) {
const trace = path.join(root, `${scenario}-${label}`);
const result = spawnSync(command, [...prefix, ...args], {
env: { PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`, QL_DIR: root, TRACE: trace },
encoding: 'utf8', timeout: 15000,
env: {
PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`,
QL_DIR: root,
TRACE: trace,
},
encoding: 'utf8',
timeout: 15000,
});
assert.equal(result.status, scenario === 'function-state' && label === 'ts' ? 7 : 0, result.stderr);
assert.equal(
result.status,
scenario === 'function-state' && label === 'ts' ? 7 : 0,
result.stderr,
);
if (scenario === 'function-state')
assert.equal(fs.readFileSync(`${trace}.after`, 'utf8'), 'after:7');
else
assert.equal(fs.readFileSync(trace, 'utf8'), path.join(root, 'data/scripts/custom'));
assert.equal(
fs.readFileSync(trace, 'utf8'),
path.join(root, 'data/scripts/custom'),
);
}
}
});
@@ -59,15 +59,21 @@ require(entry).main(JSON.parse(process.argv[2])).then(code => {
if (args.includes('--help'))
assert.ok(
!result.modules.some((module) =>
/^remote[/\\](commands[/\\](auth|open|task|subscription)\.js|api[/\\](client|download)\.js|auth[/\\])/.test(module),
/^remote[/\\](commands[/\\](auth|open|task|subscription)\.js|api[/\\](client|download)\.js|auth[/\\])/.test(
module,
),
),
'Help eagerly loaded command implementation',
);
if (args[0] === 'task' && !args.includes('--help'))
assert.ok(result.modules.includes(path.join('remote', 'commands', 'task.js')));
assert.ok(
result.modules.includes(path.join('remote', 'commands', 'task.js')),
);
if (args[0] === 'subscription')
assert.ok(
result.modules.includes(path.join('remote', 'commands', 'subscription.js')),
result.modules.includes(
path.join('remote', 'commands', 'subscription.js'),
),
);
}
});
+87 -26
View File
@@ -10,24 +10,41 @@ function invoke(args) {
require('./cli/dist/internal/commands/dispatch').dispatch = async command => ({code:200,data:command});
require('./cli/dist/ql').qlMain(JSON.parse(process.argv[1])).then(code=>{process.exitCode=code});`;
return spawnSync(process.execPath, ['-e', script, JSON.stringify(args)], {
cwd: path.resolve(__dirname, '../../..'), encoding: 'utf8',
env: { PATH: process.env.PATH, QL_LANG: 'en' }, timeout: 5000,
cwd: path.resolve(__dirname, '../../..'),
encoding: 'utf8',
env: { PATH: process.env.PATH, QL_LANG: 'en' },
timeout: 5000,
});
}
test('direct maintenance commands and local aliases accept modern and legacy options identically', () => {
for (const [args, name, values, positionals] of [
[['update', '--mirror', 'gitee', '--download-only', '--root', '/isolated'], 'update', {mirror:'gitee', 'download-only':true, root:'/isolated'}, []],
[['update', 'false', '--root', '/isolated'], 'update', {'download-only':true, root:'/isolated'}, []],
[['update', 'true'], 'update', {mirror:'github'}, []],
[['reload', 'system', '--root', '/isolated'], 'reload', {target:'system', root:'/isolated'}, []],
[['reload', '--target', 'data'], 'reload', {target:'data'}, []],
[
['update', '--mirror', 'gitee', '--download-only', '--root', '/isolated'],
'update',
{ mirror: 'gitee', 'download-only': true, root: '/isolated' },
[],
],
[
['update', 'false', '--root', '/isolated'],
'update',
{ 'download-only': true, root: '/isolated' },
[],
],
[['update', 'true'], 'update', { mirror: 'github' }, []],
[
['reload', 'system', '--root', '/isolated'],
'reload',
{ target: 'system', root: '/isolated' },
[],
],
[['reload', '--target', 'data'], 'reload', { target: 'data' }, []],
[['check'], 'check', {}, []],
[['rmlog', '7'], 'rmlog', {}, ['7']],
[['start', '--no-startup'], 'start', {'no-startup':true}, []],
[['start', '--no-startup'], 'start', { 'no-startup': true }, []],
[['repair-config'], 'repair-config', {}, []],
[['resetpwd', '--', '-literal-value'], 'resetpwd', {}, ['-literal-value']],
[['update', '--root', 'false'], 'update', {root:'false'}, []],
[['update', '--root', 'false'], 'update', { root: 'false' }, []],
]) {
const direct = invoke(['--json', ...args]);
const alias = invoke(['--json', 'local', ...args]);
@@ -37,15 +54,20 @@ test('direct maintenance commands and local aliases accept modern and legacy opt
const command = JSON.parse(direct.stdout).data;
assert.equal(command.name, `local ${name}`);
assert.deepEqual(command.positionals, positionals);
for (const [key, value] of Object.entries(values)) assert.equal(command.values[key], value);
for (const [key, value] of Object.entries(values))
assert.equal(command.values[key], value);
}
});
test('invalid maintenance options fail before dispatch; help recommends direct commands', () => {
for (const args of [
['update', 'invalid'], ['reload', 'invalid'], ['update', 'false', 'extra'],
['reload', 'system', '--target', 'data'], ['update', '--unknown'],
['update', '--', 'false'], ['rmlog', '-1'],
['update', 'invalid'],
['reload', 'invalid'],
['update', 'false', 'extra'],
['reload', 'system', '--target', 'data'],
['update', '--unknown'],
['update', '--', 'false'],
['rmlog', '-1'],
]) {
const result = invoke(['--json', ...args]);
assert.equal(result.status, 2, result.stderr);
@@ -62,11 +84,13 @@ test('invalid maintenance options fail before dispatch; help recommends direct c
}
});
test('direct and aliased maintenance preserve logs, lifecycle and single configuration evaluation', async t => {
test('direct and aliased maintenance preserve logs, lifecycle and single configuration evaluation', async (t) => {
const fs = require('node:fs/promises');
const os = require('node:os');
const http = require('node:http');
const exec = require('node:util').promisify(require('node:child_process').execFile);
const exec = require('node:util').promisify(
require('node:child_process').execFile,
);
for (const prefix of [[], ['local']]) {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-direct-extra-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
@@ -77,24 +101,61 @@ test('direct and aliased maintenance preserve logs, lifecycle and single configu
reports.push({ url: req.url, data: JSON.parse(body) });
res.end(JSON.stringify({ code: 200 }));
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
try {
await fs.mkdir(path.join(root, 'data/config'), { recursive: true });
await fs.writeFile(path.join(root, 'data/config/config.sh'), 'no_tee=true\nprintf x >> "$QL_DIR/loads"\n');
await fs.writeFile(path.join(root, 'data/config/token.json'), JSON.stringify({value:'fixture', expiration:Date.now()/1000+3600}));
await fs.writeFile(path.join(root, 'data/config/extra.sh'), 'printf "logged-extra\\n"\n');
const result = await exec(process.execPath, [path.resolve(__dirname, '../../dist/ql.js'), ...prefix, 'extra', '--root', root, '--json'], {
env: {PATH:process.env.PATH, QlPort:String(server.address().port), ID:'9'}, timeout:10000,
});
await fs.writeFile(
path.join(root, 'data/config/config.sh'),
'no_tee=true\nprintf x >> "$QL_DIR/loads"\n',
);
await fs.writeFile(
path.join(root, 'data/config/token.json'),
JSON.stringify({
value: 'fixture',
expiration: Date.now() / 1000 + 3600,
}),
);
await fs.writeFile(
path.join(root, 'data/config/extra.sh'),
'printf "logged-extra\\n"\n',
);
const result = await exec(
process.execPath,
[
path.resolve(__dirname, '../../dist/ql.js'),
...prefix,
'extra',
'--root',
root,
'--json',
],
{
env: {
PATH: process.env.PATH,
QlPort: String(server.address().port),
ID: '9',
},
timeout: 10000,
},
);
assert.equal(await fs.readFile(path.join(root, 'loads'), 'utf8'), 'x');
assert.equal(result.stderr, '');
const response = JSON.parse(result.stdout);
assert.match(response.logPath, /^extra\//);
assert.match(await fs.readFile(path.join(root, 'data/log', response.logPath), 'utf8'), /logged-extra/);
assert.deepEqual(reports.map(report => report.data.status), ['0', '1']);
assert.ok(reports.every(report => report.url === '/open/crons/status'));
assert.match(
await fs.readFile(
path.join(root, 'data/log', response.logPath),
'utf8',
),
/logged-extra/,
);
assert.deepEqual(
reports.map((report) => report.data.status),
['0', '1'],
);
assert.ok(reports.every((report) => report.url === '/open/crons/status'));
} finally {
await new Promise(resolve => server.close(resolve));
await new Promise((resolve) => server.close(resolve));
}
}
});
+60 -15
View File
@@ -5,23 +5,54 @@ const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
test('legacy Shell and TS preserve task stdin in each execution mode', t => {
test('legacy Shell and TS preserve task stdin in each execution mode', (t) => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-stdin-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
for (const dir of ['shell/preload', 'shell/lang', 'data/config', 'data/scripts', 'data/log', 'static/build', 'bin'])
for (const dir of [
'shell/preload',
'shell/lang',
'data/config',
'data/scripts',
'data/log',
'static/build',
'bin',
])
fs.mkdirSync(path.join(root, dir), { recursive: true });
for (const name of ['task.sh', 'task-timeout.sh', 'otask.sh', 'share.sh', 'api.sh', 'env.sh'])
fs.copyFileSync(path.resolve(__dirname, '../../../shell', name), path.join(root, 'shell', name));
for (const name of [
'task.sh',
'task-timeout.sh',
'otask.sh',
'share.sh',
'api.sh',
'env.sh',
])
fs.copyFileSync(
path.resolve(__dirname, '../../../shell', name),
path.join(root, 'shell', name),
);
for (const name of ['zh.sh', 'en.sh'])
fs.copyFileSync(path.resolve(__dirname, '../../../shell/lang', name), path.join(root, 'shell/lang', name));
fs.copyFileSync(
path.resolve(__dirname, '../../../shell/lang', name),
path.join(root, 'shell/lang', name),
);
fs.symlinkSync(process.execPath, path.join(root, 'bin/node'));
fs.writeFileSync(path.join(root, 'bin/pnpm'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
fs.writeFileSync(path.join(root, 'static/build/token.js'), 'process.stdout.write("fixture")');
fs.writeFileSync(path.join(root, 'bin/pnpm'), '#!/bin/sh\nexit 0\n', {
mode: 0o755,
});
fs.writeFileSync(
path.join(root, 'static/build/token.js'),
'process.stdout.write("fixture")',
);
fs.writeFileSync(path.join(root, 'data/config/config.sh'), 'no_tee=true\n');
fs.writeFileSync(path.join(root, 'data/config/crontab.list'), '');
fs.writeFileSync(path.join(root, 'shell/preload/env.sh'), 'export ACCOUNTS=one\n');
fs.writeFileSync(path.join(root, 'data/scripts/read.sh'),
'IFS= read -r value\nprintf "value=%s\\n" "$value" > "$TRACE"\n');
fs.writeFileSync(
path.join(root, 'shell/preload/env.sh'),
'export ACCOUNTS=one\n',
);
fs.writeFileSync(
path.join(root, 'data/scripts/read.sh'),
'IFS= read -r value\nprintf "value=%s\\n" "$value" > "$TRACE"\n',
);
const env = {
PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`,
QL_DIR: root,
@@ -29,18 +60,32 @@ test('legacy Shell and TS preserve task stdin in each execution mode', t => {
no_delay: 'true',
};
for (const mode of ['normal', 'now', 'desi', 'conc']) {
const args = ['read.sh', ...(mode === 'normal' ? [] : [mode]),
...(['desi', 'conc'].includes(mode) ? ['ACCOUNTS', '1'] : [])];
const args = [
'read.sh',
...(mode === 'normal' ? [] : [mode]),
...(['desi', 'conc'].includes(mode) ? ['ACCOUNTS', '1'] : []),
];
for (const [label, command, prefix] of [
['shell', '/bin/bash', [path.join(root, 'shell/task.sh')]],
['ts', process.execPath, [path.resolve(__dirname, '../../dist/runner.js'), '--root', root]],
[
'ts',
process.execPath,
[path.resolve(__dirname, '../../dist/runner.js'), '--root', root],
],
]) {
const trace = path.join(root, `${mode}-${label}`);
const result = spawnSync(command, [...prefix, ...args], {
env: { ...env, TRACE: trace }, input: 'hello\n', encoding: 'utf8', timeout: 15000,
env: { ...env, TRACE: trace },
input: 'hello\n',
encoding: 'utf8',
timeout: 15000,
});
assert.equal(result.status, 0, `${mode}/${label}: ${result.stderr}`);
assert.equal(fs.readFileSync(trace, 'utf8'), 'value=hello\n', `${mode}/${label}`);
assert.equal(
fs.readFileSync(trace, 'utf8'),
'value=hello\n',
`${mode}/${label}`,
);
}
}
});
+4 -1
View File
@@ -54,7 +54,10 @@ for (const [arch, arm, node] of [
);
const context = createContext(
{ root },
{ PATH: process.platform === 'linux' ? '' : '/usr/bin:/bin', QL_LANG: 'en' },
{
PATH: process.platform === 'linux' ? '' : '/usr/bin:/bin',
QL_LANG: 'en',
},
);
const entry = path.join(context.paths.dir_static, 'build/app.js');
let pid;
+3 -1
View File
@@ -240,7 +240,9 @@ for (const language of ['zh', 'en', 'unsupported']) {
return true;
},
);
const { runtimeEnvironment } = require('../../dist/internal/maintenance/bootstrap');
const {
runtimeEnvironment,
} = require('../../dist/internal/maintenance/bootstrap');
assert.throws(
() => runtimeEnvironment(ctx, 'bad'),
(error) => {
+16 -4
View File
@@ -6,14 +6,26 @@ const vm = require('node:vm');
test('bot integration failure does not print environment-derived error details', async () => {
const messages = [];
const childProcess = { env: { QL_PANEL_INTEGRATION: '1', QL_CLIENT_SECRET: 'sensitive-marker' }, exitCode: 0 };
const source = fs.readFileSync(path.join(__dirname, '../linux/bot-install.cjs'), 'utf8');
const childProcess = {
env: { QL_PANEL_INTEGRATION: '1', QL_CLIENT_SECRET: 'sensitive-marker' },
exitCode: 0,
};
const source = fs.readFileSync(
path.join(__dirname, '../linux/bot-install.cjs'),
'utf8',
);
vm.runInNewContext(source, {
process: childProcess,
console: { error: (message) => messages.push(message) },
require: (name) => {
if (name === 'node:fs/promises') return { mkdtemp: async () => '/fixture' };
if (name === '../../dist/internal/runtime/context') return { createContext: () => { throw new Error(childProcess.env.QL_CLIENT_SECRET); } };
if (name === 'node:fs/promises')
return { mkdtemp: async () => '/fixture' };
if (name === '../../dist/internal/runtime/context')
return {
createContext: () => {
throw new Error(childProcess.env.QL_CLIENT_SECRET);
},
};
if (name === '../../dist/internal/maintenance/bot') return {};
return require(name);
},
+6 -2
View File
@@ -5,7 +5,9 @@ const path = require('node:path');
const os = require('node:os');
const { setTimeout: delay } = require('node:timers/promises');
const { createContext } = require('../../dist/internal/runtime/context');
const { runContainer } = require('../../dist/internal/runtime/containerRuntime');
const {
runContainer,
} = require('../../dist/internal/runtime/containerRuntime');
async function fixture(t, mode = 'node') {
const root = await fs.mkdtemp(
@@ -180,7 +182,9 @@ test(
{ timeout: 20000 },
async (t) => {
const f = await fixture(t);
const { launchStartupHook } = require('../../dist/internal/maintenance/bootstrap');
const {
launchStartupHook,
} = require('../../dist/internal/maintenance/bootstrap');
const pidFile = path.join(f.root, 'extra-pid');
f.context.env.QL_TEST_EXTRA_PID = pidFile;
await fs.writeFile(
@@ -5,24 +5,35 @@ const { runProcess } = require('../../dist/internal/runtime/process');
test('environment transport preserves multiline values, empty values and exported functions', async () => {
const value = '中文\nsecond=line\r\n"quoted"\\literal';
const env = await sourceEnvironment({ PATH: process.env.PATH, VALUE: value }, [], [], {
command: 'export EMPTY=""; exported_fn() { printf "%s" "$VALUE"; }; export -f exported_fn; set -o pipefail; shopt -s nullglob; printf "user output"',
output: () => {},
});
const env = await sourceEnvironment(
{ PATH: process.env.PATH, VALUE: value },
[],
[],
{
command:
'export EMPTY=""; exported_fn() { printf "%s" "$VALUE"; }; export -f exported_fn; set -o pipefail; shopt -s nullglob; printf "user output"',
output: () => {},
},
);
assert.equal(env.VALUE, value);
assert.equal(env.EMPTY, '');
assert.ok(env.QL_CLI_SHELLOPTS.split(':').includes('pipefail'));
assert.ok(!env.QL_CLI_SHELLOPTS.split(':').includes('allexport'));
assert.ok(env.QL_CLI_BASHOPTS.split(':').includes('nullglob'));
assert.ok(!Object.keys(env).some(key => key.startsWith('__ql_')));
const child = await runProcess('bash', ['--noprofile', '--norc', '-c', 'exported_fn'], { env, capture: true });
assert.ok(!Object.keys(env).some((key) => key.startsWith('__ql_')));
const child = await runProcess(
'bash',
['--noprofile', '--norc', '-c', 'exported_fn'],
{ env, capture: true },
);
assert.equal(child.code, 0);
assert.equal(child.stdout, value);
});
test('environment transport does not execute a Node runtime from user configuration', async () => {
const env = await sourceEnvironment({ PATH: process.env.PATH }, [], [], {
command: 'export NODE_OPTIONS="--this-option-does-not-exist"; export PATH="/nonexistent"',
command:
'export NODE_OPTIONS="--this-option-does-not-exist"; export PATH="/nonexistent"',
});
assert.equal(env.NODE_OPTIONS, '--this-option-does-not-exist');
assert.equal(env.PATH, '/nonexistent');
+3 -1
View File
@@ -3,7 +3,9 @@ const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const { registerHostServices } = require('../../dist/internal/runtime/hostServices');
const {
registerHostServices,
} = require('../../dist/internal/runtime/hostServices');
const { createContext } = require('../../dist/internal/runtime/context');
for (const manager of ['openrc', 'systemd', 'missing']) {
+79 -27
View File
@@ -25,26 +25,42 @@ test('command log preserves scheduler path and rejects escaping the log director
);
});
test('managed CLI tasks and maintenance commands report against the parent receipt', async t => {
test('managed CLI tasks and maintenance commands report against the parent receipt', async (t) => {
const { LocalApi } = require('../../dist/internal/runtime/api');
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-managed-cli-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
const id = 'parent-receipt-7';
const context = createContext({ root }, {
PATH: process.env.PATH, ID: '7', no_tee: 'true', QL_TRIGGER_ID: id,
QL_CLI_LIFECYCLE: 'extended', QL_EXECUTION_ORIGIN: 'scheduled_system',
});
const context = createContext(
{ root },
{
PATH: process.env.PATH,
ID: '7',
no_tee: 'true',
QL_TRIGGER_ID: id,
QL_CLI_LIFECYCLE: 'extended',
QL_EXECUTION_ORIGIN: 'scheduled_system',
},
);
await fs.mkdir(context.paths.dir_scripts, { recursive: true });
await fs.writeFile(path.join(context.paths.dir_scripts, 'fixture.sh'), 'return 7');
await fs.writeFile(
path.join(context.paths.dir_scripts, 'fixture.sh'),
'return 7',
);
const calls = [];
t.mock.method(LocalApi.prototype, 'call', async (endpoint, method, body) => {
calls.push({ endpoint, body });
return { code: 200 };
});
const result = await executeTask(context, { argv: ['fixture.sh'], mode: 'now' });
const result = await executeTask(context, {
argv: ['fixture.sh'],
mode: 'now',
});
assert.equal(result.exitCode, 7);
assert.deepEqual(calls.map(r => r.endpoint), ['crons/status', 'crons/status', 'dashboard/record']);
assert.deepEqual(
calls.map((r) => r.endpoint),
['crons/status', 'crons/status', 'dashboard/record'],
);
await loggedOperation(context, 'extra', async () => true);
assert.equal(calls.length, 5);
for (const { body } of calls) {
@@ -55,23 +71,43 @@ test('managed CLI tasks and maintenance commands report against the parent recei
context.env.QL_CLI_LIFECYCLE = 'legacy';
await loggedOperation(context, 'extra', async () => true);
assert.ok(calls.length);
assert.ok(calls.every(r => !('trigger_id' in r.body)));
assert.ok(calls.every((r) => !('trigger_id' in r.body)));
});
test('distinct managed triggers in the same clock tick have separate maintenance and task logs', async t => {
test('distinct managed triggers in the same clock tick have separate maintenance and task logs', async (t) => {
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-same-tick-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
t.mock.method(Date, 'now', () => 1800000000000);
const run = async id => {
const context = createContext({ root }, { QL_CLI_LIFECYCLE: 'extended', QL_TRIGGER_ID: id,
PATH: process.env.PATH, no_tee: 'true', log_name: 'shared' });
const run = async (id) => {
const context = createContext(
{ root },
{
QL_CLI_LIFECYCLE: 'extended',
QL_TRIGGER_ID: id,
PATH: process.env.PATH,
no_tee: 'true',
log_name: 'shared',
},
);
await fs.mkdir(context.paths.dir_scripts, { recursive: true });
await fs.writeFile(path.join(context.paths.dir_scripts, id + '.sh'), 'echo ' + id);
await fs.writeFile(
path.join(context.paths.dir_scripts, id + '.sh'),
'echo ' + id,
);
const command = await loggedOperation(context, 'extra', async () => {});
const task = await executeTask(context, { argv: [id + '.sh'], mode: 'now' });
return { command: command.logPath, file: task.logPath,
content: await fs.readFile(path.join(context.paths.dir_log, task.logPath), 'utf8') };
const task = await executeTask(context, {
argv: [id + '.sh'],
mode: 'now',
});
return {
command: command.logPath,
file: task.logPath,
content: await fs.readFile(
path.join(context.paths.dir_log, task.logPath),
'utf8',
),
};
};
const [a, b] = await Promise.all([run('marker-alpha'), run('marker-bravo')]);
assert.notEqual(a.command, b.command);
@@ -82,25 +118,41 @@ test('distinct managed triggers in the same clock tick have separate maintenance
assert.doesNotMatch(b.content, /marker-alpha/);
});
test('same-tick standalone tasks and commands share a receipt only within one invocation', async t => {
test('same-tick standalone tasks and commands share a receipt only within one invocation', async (t) => {
const { LocalApi } = require('../../dist/internal/runtime/api');
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-client-receipts-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
t.mock.method(Date, 'now', () => 1800000000000);
const context = createContext({root}, {ID:'5', QL_CLI_LIFECYCLE:'extended', no_tee:'true',
real_log_path:'shared.log', PATH:process.env.PATH});
await fs.mkdir(context.paths.dir_scripts, {recursive:true});
await fs.writeFile(path.join(context.paths.dir_scripts, 'receipt.sh'), 'exit 0');
const context = createContext(
{ root },
{
ID: '5',
QL_CLI_LIFECYCLE: 'extended',
no_tee: 'true',
real_log_path: 'shared.log',
PATH: process.env.PATH,
},
);
await fs.mkdir(context.paths.dir_scripts, { recursive: true });
await fs.writeFile(
path.join(context.paths.dir_scripts, 'receipt.sh'),
'exit 0',
);
const groups = new Map();
t.mock.method(LocalApi.prototype, 'call', async (endpoint, method, body) => {
const id = body.execution_id;
assert.match(id, /^client-[0-9a-f-]{36}$/);
groups.set(id, [...(groups.get(id) || []), body.status ?? 'stat']);
return {code:200};
return { code: 200 };
});
await Promise.all([executeTask(context, {argv:['receipt.sh'], mode:'now'}),
executeTask(context, {argv:['receipt.sh'], mode:'now'}),
loggedOperation(context, 'extra', async () => {})]);
assert.deepEqual([...groups.values()].map(sequence => sequence.join(',')).sort(), ['0,1','0,1,stat','0,1,stat']);
await Promise.all([
executeTask(context, { argv: ['receipt.sh'], mode: 'now' }),
executeTask(context, { argv: ['receipt.sh'], mode: 'now' }),
loggedOperation(context, 'extra', async () => {}),
]);
assert.deepEqual(
[...groups.values()].map((sequence) => sequence.join(',')).sort(),
['0,1', '0,1,stat', '0,1,stat'],
);
});
+11 -7
View File
@@ -4,7 +4,10 @@ const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const http = require('node:http');
const { createContext, sourceEnvironment } = require('../../dist/internal/runtime/context');
const {
createContext,
sourceEnvironment,
} = require('../../dist/internal/runtime/context');
const { runProcess } = require('../../dist/internal/runtime/process');
const { pruneLogs } = require('../../dist/internal/maintenance/maintenance');
const { parse } = require('../helpers/commands.cjs');
@@ -276,7 +279,9 @@ test('concurrent accounts finish independently but merge logs in selection order
});
test('concurrent log spool waits for peers and cleans up on invocation failure', async (t) => {
const { orderedConcurrent } = require('../../dist/internal/execution/concurrent');
const {
orderedConcurrent,
} = require('../../dist/internal/execution/concurrent');
const root = sandbox(t);
const chunks = [];
let peerFinished = false;
@@ -485,10 +490,7 @@ test('shell tasks inherit before-hook state without leaking script state into af
path.join(context.paths.dir_log, result.logPath),
'utf8',
);
assert.match(
log,
/before:private\narg:space value\nafter:private:unset:7/,
);
assert.match(log, /before:private\narg:space value\nafter:private:unset:7/);
});
test('task resolves modules from pnpm global root and restores the previous path for after hooks', async (t) => {
@@ -538,7 +540,9 @@ test('task resolves modules from pnpm global root and restores the previous path
});
test('missing optional pnpm still provides user dependency resolution', async (t) => {
const { taskDependencyEnvironment } = require('../../dist/internal/execution/dependencies');
const {
taskDependencyEnvironment,
} = require('../../dist/internal/execution/dependencies');
const context = createContext(
{ root: sandbox(t) },
{
+134 -63
View File
@@ -184,8 +184,12 @@ test(
'cancelled local API requests do not replay mutations and final lifecycle still reports',
{ timeout: 5000 },
async (t) => {
const { cancellableOperation } = require('../../dist/internal/runtime/cancellation');
const { loggedOperation } = require('../../dist/internal/runtime/commandLog');
const {
cancellableOperation,
} = require('../../dist/internal/runtime/cancellation');
const {
loggedOperation,
} = require('../../dist/internal/runtime/commandLog');
for (const partialBody of [false, true]) {
const controller = new AbortController();
const calls = [];
@@ -288,22 +292,36 @@ for (const language of ['zh', 'en', 'unsupported']) {
});
}
test('a lifecycle timeout retries the identical payload once and other writes are not retried', async t => {
test('a lifecycle timeout retries the identical payload once and other writes are not retried', async (t) => {
const context = await fixture(t, () => {});
await token(context);
const requests = [];
const timer = global.setTimeout;
t.mock.method(global, 'setTimeout', (fn, ms, ...args) => timer(fn, ms === 30000 ? 5 : ms, ...args));
t.mock.method(global, 'fetch', async (_, {body, signal}) => {
t.mock.method(global, 'setTimeout', (fn, ms, ...args) =>
timer(fn, ms === 30000 ? 5 : ms, ...args),
);
t.mock.method(global, 'fetch', async (_, { body, signal }) => {
requests.push(body);
return new Promise((_, reject) => signal.addEventListener('abort', () => reject(signal.reason), {once:true}));
return new Promise((_, reject) =>
signal.addEventListener('abort', () => reject(signal.reason), {
once: true,
}),
);
});
const api = new LocalApi(context);
for (const [endpoint, method, body, attempts] of [
['crons/status','PUT',{ execution_id:'client-' + require('node:crypto').randomUUID(), status:'0' },2],
['dashboard/record','POST',{ trigger_id:'managed-fixture', code:0 },2],
['crons/status','PUT',{ status:'0' },1],
['crons','POST',{ trigger_id:'unrelated' },1],
[
'crons/status',
'PUT',
{
execution_id: 'client-' + require('node:crypto').randomUUID(),
status: '0',
},
2,
],
['dashboard/record', 'POST', { trigger_id: 'managed-fixture', code: 0 }, 2],
['crons/status', 'PUT', { status: '0' }, 1],
['crons', 'POST', { trigger_id: 'unrelated' }, 1],
]) {
requests.length = 0;
await assert.rejects(api.call(endpoint, method, body));
@@ -311,98 +329,151 @@ test('a lifecycle timeout retries the identical payload once and other writes ar
}
});
test('the live status schema selects every receipt on old, intermediate and upgraded panels', async t => {
test('the live status schema selects every receipt on old, intermediate and upgraded panels', async (t) => {
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const { loggedOperation } = require('../../dist/internal/runtime/commandLog');
let protocol;
const written = [], rejected = [];
const written = [],
rejected = [];
const context = await fixture(t, async (req, res) => {
let raw = '';
for await (const chunk of req) raw += chunk;
const body = JSON.parse(raw);
const forbidden = req.url.endsWith('/status') && Object.keys(body).find(field =>
(protocol !== 'identified' && ['execution_id','trigger_id'].includes(field)) ||
(protocol === 'legacy' && field === 'exit_code'));
const forbidden =
req.url.endsWith('/status') &&
Object.keys(body).find(
(field) =>
(protocol !== 'identified' &&
['execution_id', 'trigger_id'].includes(field)) ||
(protocol === 'legacy' && field === 'exit_code'),
);
if (forbidden) {
rejected.push(forbidden);
res.writeHead(400).end(JSON.stringify({validation:{body:{source:'body',keys:[forbidden]}}}));
res.writeHead(400).end(
JSON.stringify({
validation: { body: { source: 'body', keys: [forbidden] } },
}),
);
return;
}
written.push([req.url,body]);
written.push([req.url, body]);
res.end('{"code":200}');
});
await token(context);
Object.assign(context.env, { ID: '12', no_tee: 'true' });
await fs.mkdir(context.paths.dir_scripts, {recursive:true});
await fs.writeFile(path.join(context.paths.dir_scripts,'probe.sh'), 'return 7');
await fs.mkdir(context.paths.dir_scripts, { recursive: true });
await fs.writeFile(
path.join(context.paths.dir_scripts, 'probe.sh'),
'return 7',
);
// Even a full newer installation on disk cannot speak on behalf of the old process.
await fs.mkdir(path.join(context.root,'static/build/shared'), {recursive:true});
await fs.writeFile(path.join(context.root,'static/build/shared/executionIdentity.js'), '');
await fs.mkdir(path.join(context.root, 'static/build/cron'), {
recursive: true,
});
await fs.writeFile(
path.join(context.root, 'static/build/cron/identity.js'),
'',
);
for (protocol of ['legacy', 'exit-code', 'identified']) {
await fs.writeFile(path.join(context.root,'package.json'), JSON.stringify({version:protocol === 'identified' ? '2.20.1' : '2.25.0'}));
for (const managed of [false,true]) {
await fs.writeFile(
path.join(context.root, 'package.json'),
JSON.stringify({
version: protocol === 'identified' ? '2.20.1' : '2.25.0',
}),
);
for (const managed of [false, true]) {
if (managed) context.env.QL_TRIGGER_ID = 'parent-123';
else delete context.env.QL_TRIGGER_ID;
for (const task of [true,false]) {
for (const task of [true, false]) {
written.length = rejected.length = 0;
if (task) assert.equal((await executeTask(context,{argv:['probe.sh'],mode:'now'})).exitCode,7);
else await loggedOperation(context,'extra',async()=>{});
const [start,end] = written.map(r=>r[1]);
if (task)
assert.equal(
(await executeTask(context, { argv: ['probe.sh'], mode: 'now' }))
.exitCode,
7,
);
else await loggedOperation(context, 'extra', async () => {});
const [start, end] = written.map((r) => r[1]);
const key = managed ? 'trigger_id' : 'execution_id';
assert.deepEqual(rejected, protocol === 'legacy' ? [key,'exit_code'] : protocol === 'exit-code' ? [key] : []);
assert.equal(start.status,'0'); assert.equal(end.status,'1');
assert.equal(end.exit_code, protocol === 'legacy' ? undefined : task ? 7 : 0);
assert.deepEqual(
rejected,
protocol === 'legacy'
? [key, 'exit_code']
: protocol === 'exit-code'
? [key]
: [],
);
assert.equal(start.status, '0');
assert.equal(end.status, '1');
assert.equal(
end.exit_code,
protocol === 'legacy' ? undefined : task ? 7 : 0,
);
assert.equal(written.length, task && protocol !== 'legacy' ? 3 : 2);
for (const [,body] of written) assert.equal(body[key],start[key]);
if (protocol === 'identified') assert.ok(managed ? start[key] === 'parent-123' : /^client-/.test(start[key]));
else assert.equal(start[key],undefined);
for (const [, body] of written) assert.equal(body[key], start[key]);
if (protocol === 'identified')
assert.ok(
managed ? start[key] === 'parent-123' : /^client-/.test(start[key]),
);
else assert.equal(start[key], undefined);
}
}
}
});
test('a missing start response or a non-schema failure never switches a receipt to anonymous', async t => {
test('a missing start response or a non-schema failure never switches a receipt to anonymous', async (t) => {
const { LifecycleReceipt } = require('../../dist/internal/runtime/lifecycle');
const calls = [];
let rejectedField;
const ctx = await fixture(t, async (req,res) => {
let raw=''; for await (const chunk of req) raw+=chunk;
const ctx = await fixture(t, async (req, res) => {
let raw = '';
for await (const chunk of req) raw += chunk;
calls.push(JSON.parse(raw));
if (!rejectedField) { res.destroy(); return; }
res.writeHead(400).end(JSON.stringify({ validation: {body: {source:'body',keys:[rejectedField]}} }));
if (!rejectedField) {
res.destroy();
return;
}
res.writeHead(400).end(
JSON.stringify({
validation: { body: { source: 'body', keys: [rejectedField] } },
}),
);
});
await token(ctx);
const receipt = new LifecycleReceipt(ctx,10);
await assert.rejects(receipt.status({ids:[5],status:'0'}));
const receipt = new LifecycleReceipt(ctx, 10);
await assert.rejects(receipt.status({ ids: [5], status: '0' }));
rejectedField = 'execution_id';
await assert.rejects(receipt.status({ids:[5],status:'1'},7));
assert.equal(calls.length,2);
assert.equal(calls[0].execution_id,calls[1].execution_id);
await assert.rejects(receipt.status({ ids: [5], status: '1' }, 7));
assert.equal(calls.length, 2);
assert.equal(calls[0].execution_id, calls[1].execution_id);
rejectedField = 'pid';
await assert.rejects(new LifecycleReceipt(ctx,11).status({ids:[5],status:'0'}));
assert.equal(calls.length,3);
await assert.rejects(
new LifecycleReceipt(ctx, 11).status({ ids: [5], status: '0' }),
);
assert.equal(calls.length, 3);
});
test('dated status, statistics and retries share an exit instant without changing the identified body schema', async t => {
test('dated status, statistics and retries share an exit instant without changing the identified body schema', async (t) => {
const { LifecycleReceipt } = require('../../dist/internal/runtime/lifecycle');
const writes=[];
const ctx=await fixture(t,async(req,res)=>{
let raw=''; for await(const chunk of req)raw+=chunk;
const body=JSON.parse(raw);
writes.push({body, time:req.headers['x-ql-finished-at']});
res.end(JSON.stringify({code:200}));
const writes = [];
const ctx = await fixture(t, async (req, res) => {
let raw = '';
for await (const chunk of req) raw += chunk;
const body = JSON.parse(raw);
writes.push({ body, time: req.headers['x-ql-finished-at'] });
res.end(JSON.stringify({ code: 200 }));
});
await token(ctx);
const receipt=new LifecycleReceipt(ctx,Math.floor(Date.now()/1000));
await receipt.status({status:'0'});
await receipt.status({status:'1'},17);
await receipt.status({status:'1'},17);
await receipt.statistics(1,17,2);
assert.equal(writes[0].time,undefined);
assert.match(writes[1].time,/^\d{13}$/);
for (const {body,time} of writes.slice(1)) {
assert.equal(time,writes[1].time);
assert.equal(body.execution_id,writes[0].body.execution_id);
assert.equal(body.finished_at,undefined);
const receipt = new LifecycleReceipt(ctx, Math.floor(Date.now() / 1000));
await receipt.status({ status: '0' });
await receipt.status({ status: '1' }, 17);
await receipt.status({ status: '1' }, 17);
await receipt.statistics(1, 17, 2);
assert.equal(writes[0].time, undefined);
assert.match(writes[1].time, /^\d{13}$/);
for (const { body, time } of writes.slice(1)) {
assert.equal(time, writes[1].time);
assert.equal(body.execution_id, writes[0].body.execution_id);
assert.equal(body.finished_at, undefined);
}
});
+3 -1
View File
@@ -9,7 +9,9 @@ const net = require('node:net');
const { randomUUID } = require('node:crypto');
const { execFileSync, spawn } = require('node:child_process');
const { createContext } = require('../../dist/internal/runtime/context');
const { syncRepository } = require('../../dist/internal/subscription/subscriptionRunner');
const {
syncRepository,
} = require('../../dist/internal/subscription/subscriptionRunner');
const git = process.platform === 'darwin' ? '/usr/bin/git' : 'git';
for (const tls of [false, true])
@@ -5,7 +5,10 @@ const os = require('node:os');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const { createContext } = require('../../dist/internal/runtime/context');
const { replaceAndReload, reloadPanel } = require('../../dist/internal/maintenance/upgrade');
const {
replaceAndReload,
reloadPanel,
} = require('../../dist/internal/maintenance/upgrade');
const { installCronEntrypoint } = require('../../dist/local/cronEntrypoint');
for (const language of ['zh', 'en', 'unsupported']) {
+4 -1
View File
@@ -7,7 +7,10 @@ const { within } = require('../../dist/internal/runtime/files');
const { createContext } = require('../../dist/internal/runtime/context');
const { loggedOperation } = require('../../dist/internal/runtime/commandLog');
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const { syncRaw, repositoryName } = require('../../dist/internal/subscription/subscriptionRunner');
const {
syncRaw,
repositoryName,
} = require('../../dist/internal/subscription/subscriptionRunner');
const { LocalApi } = require('../../dist/internal/runtime/api');
const subprocess = require('../../dist/internal/runtime/process');
@@ -1,6 +1,9 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { runProcess, checkedProcess } = require('../../dist/internal/runtime/process');
const {
runProcess,
checkedProcess,
} = require('../../dist/internal/runtime/process');
for (const language of ['zh', 'en', 'unsupported']) {
test(`subprocess failures localize and reap failed writers: ${language}`, async () => {
+3 -1
View File
@@ -5,7 +5,9 @@ const path = require('node:path');
const os = require('node:os');
const { execFileSync } = require('node:child_process');
const { createContext } = require('../../dist/internal/runtime/context');
const { listTaskScripts } = require('../../dist/internal/execution/scriptInventory');
const {
listTaskScripts,
} = require('../../dist/internal/execution/scriptInventory');
test('no-argument runner lists legacy JS candidates without evaluating scripts or config', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-inventory-'));
@@ -4,7 +4,9 @@ const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { matchSubscriptionPaths } = require('../../dist/internal/subscription/subscriptionFilter');
const {
matchSubscriptionPaths,
} = require('../../dist/internal/subscription/subscriptionFilter');
test('subscription filters preserve legacy POSIX classes, escaping, anchors and option-like patterns', async (t) => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-filter-'));
+25 -8
View File
@@ -164,7 +164,14 @@ test('subscription reconciliation scopes removals to canonical paths and the cur
});
assert.equal(result.added, 1);
assert.equal(result.removed, 1);
assert.deepEqual(requests.find((r) => r.method === 'DELETE').body, [{ id: 1, script: 'owner_repository/old.js', command: rows[0].command, sub_id: 7 }]);
assert.deepEqual(requests.find((r) => r.method === 'DELETE').body, [
{
id: 1,
script: 'owner_repository/old.js',
command: rows[0].command,
sub_id: 7,
},
]);
assert.deepEqual(requests.find((r) => r.method === 'POST').body, {
name: 'New task',
schedule: '0 9 * * *',
@@ -180,7 +187,9 @@ test('subscription reconciliation scopes removals to canonical paths and the cur
});
test('raw download failure preserves the last script and does not reconcile tasks', async (t) => {
const { syncRaw } = require('../../dist/internal/subscription/subscriptionRunner');
const {
syncRaw,
} = require('../../dist/internal/subscription/subscriptionRunner');
const http = require('node:http');
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-raw-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
@@ -215,7 +224,9 @@ test('raw download failure preserves the last script and does not reconcile task
test('directory replacement stages on the destination filesystem before switching old files', async (t) => {
const fsp = require('node:fs/promises');
const { replaceDirectory } = require('../../dist/internal/subscription/subscriptionRunner');
const {
replaceDirectory,
} = require('../../dist/internal/subscription/subscriptionRunner');
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-cross-device-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const staged = path.join(root, 'staged'),
@@ -251,7 +262,9 @@ test('directory replacement stages on the destination filesystem before switchin
test('cross-filesystem preparation failure leaves the old subscription directory untouched', async (t) => {
const fsp = require('node:fs/promises');
const { replaceDirectory } = require('../../dist/internal/subscription/subscriptionRunner');
const {
replaceDirectory,
} = require('../../dist/internal/subscription/subscriptionRunner');
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-copy-failure-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const staged = path.join(root, 'staged'),
@@ -433,7 +446,7 @@ test('cron metadata precedence agrees with unchanged legacy add_cron', (t) => {
}
});
test('a slash in a branch cannot publish through a linked namespace parent', async t => {
test('a slash in a branch cannot publish through a linked namespace parent', async (t) => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-nested-namespace-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const context = createContext({ root }, { PATH: process.env.PATH });
@@ -444,9 +457,13 @@ test('a slash in a branch cannot publish through a linked namespace parent', asy
fs.mkdirSync(dir, { recursive: true });
const link = path.join(dir, 'owner_repo_feature');
fs.symlinkSync(outside, link);
await assert.rejects(syncRepository(context, {
url: 'https://example.invalid/owner/repo.git', branch: 'feature/branch',
}), /管理目录|managed directory/);
await assert.rejects(
syncRepository(context, {
url: 'https://example.invalid/owner/repo.git',
branch: 'feature/branch',
}),
/管理目录|managed directory/,
);
assert.deepEqual(fs.readdirSync(outside), ['sentinel']);
fs.unlinkSync(link);
}
+3 -1
View File
@@ -4,7 +4,9 @@ const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const { spawnSync } = require('node:child_process');
const { matchesDelayExtension } = require('../../dist/internal/execution/taskDelay');
const {
matchesDelayExtension,
} = require('../../dist/internal/execution/taskDelay');
const { createContext } = require('../../dist/internal/runtime/context');
const { executeTask } = require('../../dist/internal/execution/taskRunner');
+176 -45
View File
@@ -10,69 +10,200 @@ function fixture(t) {
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
for (const dir of ['data/config', 'data/scripts', 'bin'])
fs.mkdirSync(path.join(root, dir), { recursive: true });
fs.writeFileSync(path.join(root, 'bin/pnpm'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
fs.writeFileSync(path.join(root, 'bin/pnpm'), '#!/bin/sh\nexit 0\n', {
mode: 0o755,
});
const trace = path.join(root, 'trace');
return {
root, trace,
write(file, contents) { fs.writeFileSync(path.join(root, file), contents); },
args: [path.resolve(__dirname, '../../dist/runner.js'), '--root', root, '--json'],
root,
trace,
write(file, contents) {
fs.writeFileSync(path.join(root, file), contents);
},
args: [
path.resolve(__dirname, '../../dist/runner.js'),
'--root',
root,
'--json',
],
env: { PATH: `${path.join(root, 'bin')}:/usr/bin:/bin`, TRACE: trace },
events() { return fs.existsSync(trace) ? fs.readFileSync(trace, 'utf8').trim().split('\n') : []; },
events() {
return fs.existsSync(trace)
? fs.readFileSync(trace, 'utf8').trim().split('\n')
: [];
},
};
}
test('shared Shell lifecycle scopes timeouts to the task and runs cleanup exactly once', async t => {
test('shared Shell lifecycle scopes timeouts to the task and runs cleanup exactly once', async (t) => {
const cases = [
{ name: 'success', task: 'return 0', code: 0 },
{ name: 'failure', task: 'return 7', code: 7 },
{ name: 'function timeout preserves state', task: 'STATE=changed; sleep 10', code: 124, timeout: true, state: 'changed' },
{ name: 'external timeout', args: ['sleep', '10'], code: 124, timeout: true },
{ name: 'Shell script timeout preserves parent hook state', task: 'STATE=changed; sleep 10', shell: true, code: 124, timeout: true },
{ name: 'slow before is outside task timeout', before: 'sleep 0.2', task: 'return 0', code: 0 },
{ name: 'slow after is outside task timeout', after: 'sleep 0.2', task: 'return 0', code: 0 },
{ name: 'background child cannot hold pipes after timeout cleanup', task: '(trap "" INT; sleep 30) & sleep 30', after: 'sleep 0.3', code: 124, timeout: true },
{ name: 'script may redirect fd 3', shell: true, task: 'exec 3> "$TRACE.fd"; return 0', after: 'sleep 0.3', code: 0 },
{ name: 'before may close fd 3 and redirect fd 9', before: 'exec 3>&- 9> "$TRACE.lock"', task: 'return 0', after: 'sleep 0.3', code: 0 },
{ name: 'timeout cleanup survives script fd 3 redirection', shell: true, task: 'exec 3> "$TRACE.fd"; STATE=changed; sleep 30', after: 'sleep 0.3', code: 124, timeout: true },
{ name: 'Shell exit preserves user trap and runs after once', shell: true, task: 'trap \'printf "exit\\n" >> "$TRACE"\' EXIT; exit 9', code: 9, userExit: true },
{ name: 'explicit exit preserves user trap and skips after', task: 'trap \'printf "exit\\n" >> "$TRACE"\' EXIT; exit 9', code: 9, noAfter: true, userExit: true },
{ name: 'user EXIT trap survives timeout with parent cleanup', task: 'trap \'printf "exit\\n" >> "$TRACE"\' EXIT; sleep 10', code: 124, timeout: true, userExit: true },
{ name: 'forced termination falls back to cleanup', task: 'trap "" INT; sleep 30', code: 124, timeout: true },
{
name: 'function timeout preserves state',
task: 'STATE=changed; sleep 10',
code: 124,
timeout: true,
state: 'changed',
},
{
name: 'external timeout',
args: ['sleep', '10'],
code: 124,
timeout: true,
},
{
name: 'Shell script timeout preserves parent hook state',
task: 'STATE=changed; sleep 10',
shell: true,
code: 124,
timeout: true,
},
{
name: 'slow before is outside task timeout',
before: 'sleep 0.2',
task: 'return 0',
code: 0,
},
{
name: 'slow after is outside task timeout',
after: 'sleep 0.2',
task: 'return 0',
code: 0,
},
{
name: 'background child cannot hold pipes after timeout cleanup',
task: '(trap "" INT; sleep 30) & sleep 30',
after: 'sleep 0.3',
code: 124,
timeout: true,
},
{
name: 'script may redirect fd 3',
shell: true,
task: 'exec 3> "$TRACE.fd"; return 0',
after: 'sleep 0.3',
code: 0,
},
{
name: 'before may close fd 3 and redirect fd 9',
before: 'exec 3>&- 9> "$TRACE.lock"',
task: 'return 0',
after: 'sleep 0.3',
code: 0,
},
{
name: 'timeout cleanup survives script fd 3 redirection',
shell: true,
task: 'exec 3> "$TRACE.fd"; STATE=changed; sleep 30',
after: 'sleep 0.3',
code: 124,
timeout: true,
},
{
name: 'Shell exit preserves user trap and runs after once',
shell: true,
task: 'trap \'printf "exit\\n" >> "$TRACE"\' EXIT; exit 9',
code: 9,
userExit: true,
},
{
name: 'explicit exit preserves user trap and skips after',
task: 'trap \'printf "exit\\n" >> "$TRACE"\' EXIT; exit 9',
code: 9,
noAfter: true,
userExit: true,
},
{
name: 'user EXIT trap survives timeout with parent cleanup',
task: 'trap \'printf "exit\\n" >> "$TRACE"\' EXIT; sleep 10',
code: 124,
timeout: true,
userExit: true,
},
{
name: 'forced termination falls back to cleanup',
task: 'trap "" INT; sleep 30',
code: 124,
timeout: true,
},
];
for (const scenario of cases) await t.test(scenario.name, t => {
const f = fixture(t);
f.write('data/config/config.sh', `no_tee=true\nSTATE=original\nmy_task() { ${scenario.task || ':'}; }\n`);
f.write('data/config/task_before.sh', `printf 'before\\n' >> "$TRACE"\n${scenario.before || ':'}\n`);
f.write('data/config/task_after.sh', `${scenario.after || ':'}\nprintf 'after:%s:%s\\n' "$STATE" "$_task_exit_code" >> "$TRACE"\n`);
if (scenario.shell) f.write('data/scripts/task.sh', scenario.task + '\n');
const result = spawnSync(process.execPath, [...f.args, '-m', '0.1s', ...(scenario.args || [scenario.shell ? 'task.sh' : 'my_task'])], {
env: f.env, encoding: 'utf8', timeout: 15000,
for (const scenario of cases)
await t.test(scenario.name, (t) => {
const f = fixture(t);
f.write(
'data/config/config.sh',
`no_tee=true\nSTATE=original\nmy_task() { ${scenario.task || ':'}; }\n`,
);
f.write(
'data/config/task_before.sh',
`printf 'before\\n' >> "$TRACE"\n${scenario.before || ':'}\n`,
);
f.write(
'data/config/task_after.sh',
`${
scenario.after || ':'
}\nprintf 'after:%s:%s\\n' "$STATE" "$_task_exit_code" >> "$TRACE"\n`,
);
if (scenario.shell) f.write('data/scripts/task.sh', scenario.task + '\n');
const result = spawnSync(
process.execPath,
[
...f.args,
'-m',
'0.1s',
...(scenario.args || [scenario.shell ? 'task.sh' : 'my_task']),
],
{
env: f.env,
encoding: 'utf8',
timeout: 15000,
},
);
assert.equal(result.status, scenario.code, result.stderr);
const data = JSON.parse(result.stdout).data;
assert.equal(data.exitCode, scenario.code);
assert.equal(data.timedOut, !!scenario.timeout);
assert.deepEqual(f.events(), [
'before',
...(scenario.userExit ? ['exit'] : []),
...(scenario.noAfter
? []
: [`after:${scenario.state || 'original'}:${scenario.code}`]),
]);
});
assert.equal(result.status, scenario.code, result.stderr);
const data = JSON.parse(result.stdout).data;
assert.equal(data.exitCode, scenario.code);
assert.equal(data.timedOut, !!scenario.timeout);
assert.deepEqual(f.events(), [
'before', ...(scenario.userExit ? ['exit'] : []),
...(scenario.noAfter ? [] : [`after:${scenario.state || 'original'}:${scenario.code}`]),
]);
});
});
test('user cancellation remains cancellation, without timeout cleanup replay', async t => {
test('user cancellation remains cancellation, without timeout cleanup replay', async (t) => {
const f = fixture(t);
f.write('data/config/config.sh', 'my_task() { printf "READY\\n"; sleep 30; }\n');
f.write(
'data/config/config.sh',
'my_task() { printf "READY\\n"; sleep 30; }\n',
);
f.write('data/config/task_after.sh', 'printf "after\\n" >> "$TRACE"\n');
const child = spawn(process.execPath, [...f.args, '-m', '20s', 'my_task'], { env: f.env });
let out = '', err = '', sent = false;
const child = spawn(process.execPath, [...f.args, '-m', '20s', 'my_task'], {
env: f.env,
});
let out = '',
err = '',
sent = false;
const timer = setTimeout(() => child.kill('SIGKILL'), 15000);
t.after(() => { clearTimeout(timer); child.kill('SIGKILL'); });
child.stdout.on('data', chunk => out += chunk);
child.stderr.on('data', chunk => {
t.after(() => {
clearTimeout(timer);
child.kill('SIGKILL');
});
child.stdout.on('data', (chunk) => (out += chunk));
child.stderr.on('data', (chunk) => {
err += chunk;
if (!sent && err.includes('READY')) { sent = true; child.kill('SIGTERM'); }
if (!sent && err.includes('READY')) {
sent = true;
child.kill('SIGTERM');
}
});
const code = await new Promise((resolve, reject) => {
child.once('error', reject);
child.once('close', resolve);
});
const code = await new Promise((resolve, reject) => { child.once('error', reject); child.once('close', resolve); });
assert.equal(sent, true, err);
assert.equal(code, 143, err);
assert.equal(JSON.parse(out).data.timedOut, false);
+3 -1
View File
@@ -106,6 +106,8 @@ assert.equal(process.env.QL_PANEL_INTEGRATION, '1');
await fs.rm(foreignRoot, { recursive: true, force: true });
}
})().catch(() => {
console.error('Bot installation integration test failed; raw subprocess errors are omitted to protect environment credentials.');
console.error(
'Bot installation integration test failed; raw subprocess errors are omitted to protect environment credentials.',
);
process.exitCode = 1;
});
+6 -2
View File
@@ -5,8 +5,12 @@ const path = require('node:path');
const os = require('node:os');
const { setTimeout: delay } = require('node:timers/promises');
const { createContext } = require('../../dist/internal/runtime/context');
const { runContainer } = require('../../dist/internal/runtime/containerRuntime');
const { launchStartupHook } = require('../../dist/internal/maintenance/bootstrap');
const {
runContainer,
} = require('../../dist/internal/runtime/containerRuntime');
const {
launchStartupHook,
} = require('../../dist/internal/maintenance/bootstrap');
const { launchBot } = require('../../dist/internal/maintenance/bot');
const live = (pid) => {
+6 -1
View File
@@ -36,7 +36,12 @@ const { LocalApi } = require('../../dist/internal/runtime/api');
{ stdio: 'pipe' },
);
const nginxPid = Number(
(await fs.readFile(systemd ? '/run/nginx.pid' : '/run/nginx/nginx.pid', 'utf8')).trim(),
(
await fs.readFile(
systemd ? '/run/nginx.pid' : '/run/nginx/nginx.pid',
'utf8',
)
).trim(),
);
assert.ok(Number.isSafeInteger(nginxPid) && nginxPid > 1);
process.kill(nginxPid, 0);
+3 -1
View File
@@ -1,7 +1,9 @@
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const { spawnSync } = require('node:child_process');
const { createContext } = require('/opt/qinglong-cli/dist/internal/runtime/context');
const {
createContext,
} = require('/opt/qinglong-cli/dist/internal/runtime/context');
const { LocalApi } = require('/opt/qinglong-cli/dist/internal/runtime/api');
assert.equal(process.env.QL_PANEL_INTEGRATION, '1');
(async () => {
+4 -1
View File
@@ -2,7 +2,10 @@ process.channel.ref();
// Child fixture: real service startup pauses at a deterministic cancellation boundary.
const { createContext } = require('../../dist/internal/runtime/context');
const { replaceAndReload } = require('../../dist/internal/maintenance/upgrade');
const { startPanel, stopPanel } = require('../../dist/internal/maintenance/operator');
const {
startPanel,
stopPanel,
} = require('../../dist/internal/maintenance/operator');
const {
withCommandCancellation,
cancellableOperation,
+4 -1
View File
@@ -4,7 +4,10 @@ const fs = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { createContext } = require('../../dist/internal/runtime/context');
const { startPanel, stopPanel } = require('../../dist/internal/maintenance/operator');
const {
startPanel,
stopPanel,
} = require('../../dist/internal/maintenance/operator');
const { reloadPanel } = require('../../dist/internal/maintenance/upgrade');
test(
+181 -32
View File
@@ -9,53 +9,202 @@ const fs = require('node:fs/promises');
assert.equal(process.env.QL_PANEL_INTEGRATION, '1');
const url = 'http://127.0.0.1:5700';
const api = async (route, method = 'GET', body) => {
const response = await fetch(url + '/api/' + route, { method,
headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
const result = await response.json(); assert.equal(result.code, 200); return result.data;
const response = await fetch(url + '/api/' + route, {
method,
headers: { 'content-type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
});
const result = await response.json();
assert.equal(result.code, 200);
return result.data;
};
const info = await api('system');
assert.equal(info.isInitialized, false, 'Refuse initialized panels');
const credentials = {
username: 'fixture-' + randomUUID(),
password: randomUUID(),
};
const info = await api('system'); assert.equal(info.isInitialized, false, 'Refuse initialized panels');
const credentials = { username: 'fixture-' + randomUUID(), password: randomUUID() };
await api('user/init', 'PUT', credentials);
const owner = (await api('user/login', 'POST', credentials)).token;
const config = '/tmp/ql-openapi-auth.json';
const entry = path.resolve(__dirname, '../../dist/npm/ql.js');
const cli = (args, ownerMode = false, extra = {}) => {
const result = spawnSync(process.execPath, [entry, ...args, '--json'], {
encoding: 'utf8', timeout: 30000,
env: { ...process.env, QL_CLI_CONFIG: config, QL_URL: ownerMode ? url : '', QL_ACCESS_TOKEN: ownerMode ? owner : '', ...extra },
encoding: 'utf8',
timeout: 30000,
env: {
...process.env,
QL_CLI_CONFIG: config,
QL_URL: ownerMode ? url : '',
QL_ACCESS_TOKEN: ownerMode ? owner : '',
...extra,
},
});
// Report only the command name, never request bodies or application credentials.
assert.equal(result.status, 0, args.slice(0, 2).join(' ') + ': ' + result.stderr);
assert.equal(
result.status,
0,
args.slice(0, 2).join(' ') + ': ' + result.stderr,
);
return JSON.parse(result.stdout).data;
};
const app = cli(['app', 'create', '--name', 'cli-fixture', '--scopes', 'crons,subscriptions,envs,configs,scripts,logs,dependencies,system,dashboard', '--show-secrets'], true);
const app = cli(
[
'app',
'create',
'--name',
'cli-fixture',
'--scopes',
'crons,subscriptions,envs,configs,scripts,logs,dependencies,system,dashboard',
'--show-secrets',
],
true,
);
assert.ok(app.client_id && app.client_secret);
cli(['login', '--url', url], false, { QL_CLIENT_ID: app.client_id, QL_CLIENT_SECRET: app.client_secret });
cli(['login', '--url', url], false, {
QL_CLIENT_ID: app.client_id,
QL_CLIENT_SECRET: app.client_secret,
});
cli(['auth', 'status', '--scope', 'crons']);
cli(['app', 'update', String(app.id), '--name', 'cli-updated', '--scopes', 'crons,subscriptions,envs,configs,scripts,logs,dependencies,system,dashboard'], true);
assert.ok(cli(['app', 'list'], true).every(item => !('client_secret' in item) && !('tokens' in item)));
const task = cli(['task', 'create', '--name', 'cli-task', '--command', 'echo OPENAPI_FIXTURE', '--schedule', '0 0 * * *']);
cli(['task', 'update', String(task.id), '--name', 'cli-task-updated', '--command', 'echo OPENAPI_UPDATED', '--schedule', '0 1 * * *']);
cli(['task', 'disable', String(task.id)]); cli(['task', 'enable', String(task.id)]);
cli(
[
'app',
'update',
String(app.id),
'--name',
'cli-updated',
'--scopes',
'crons,subscriptions,envs,configs,scripts,logs,dependencies,system,dashboard',
],
true,
);
assert.ok(
cli(['app', 'list'], true).every(
(item) => !('client_secret' in item) && !('tokens' in item),
),
);
const task = cli([
'task',
'create',
'--name',
'cli-task',
'--command',
'echo OPENAPI_FIXTURE',
'--schedule',
'0 0 * * *',
]);
cli([
'task',
'update',
String(task.id),
'--name',
'cli-task-updated',
'--command',
'echo OPENAPI_UPDATED',
'--schedule',
'0 1 * * *',
]);
cli(['task', 'disable', String(task.id)]);
cli(['task', 'enable', String(task.id)]);
assert.equal(cli(['task', 'get', String(task.id)]).name, 'cli-task-updated');
const sub = cli(['subscription', 'create', '--type', 'file', '--url', url + '/fixture.js', '--alias', 'cli-sub', '--schedule-type', 'crontab', '--schedule', '0 0 * * *']);
cli(['subscription', 'update', String(sub.id), '--data', JSON.stringify({ type: 'file', url: url + '/fixture.js', alias: 'cli-sub', name: 'cli-sub-updated', schedule_type: 'crontab', schedule: '0 1 * * *' })]);
cli(['subscription', 'disable', String(sub.id)]); cli(['subscription', 'enable', String(sub.id)]);
assert.equal(cli(['subscription', 'get', String(sub.id)]).name, 'cli-sub-updated');
const env = cli(['env', 'create', '--data', '[{"name":"CLI_FIXTURE","value":"one"}]'])[0];
cli(['env', 'update', String(env.id), '--data', '{"name":"CLI_FIXTURE","value":"two"}']);
const sub = cli([
'subscription',
'create',
'--type',
'file',
'--url',
url + '/fixture.js',
'--alias',
'cli-sub',
'--schedule-type',
'crontab',
'--schedule',
'0 0 * * *',
]);
cli([
'subscription',
'update',
String(sub.id),
'--data',
JSON.stringify({
type: 'file',
url: url + '/fixture.js',
alias: 'cli-sub',
name: 'cli-sub-updated',
schedule_type: 'crontab',
schedule: '0 1 * * *',
}),
]);
cli(['subscription', 'disable', String(sub.id)]);
cli(['subscription', 'enable', String(sub.id)]);
assert.equal(
cli(['subscription', 'get', String(sub.id)]).name,
'cli-sub-updated',
);
const env = cli([
'env',
'create',
'--data',
'[{"name":"CLI_FIXTURE","value":"one"}]',
])[0];
cli([
'env',
'update',
String(env.id),
'--data',
'{"name":"CLI_FIXTURE","value":"two"}',
]);
assert.equal(cli(['env', 'get', String(env.id)]).value, 'two');
cli(['env', 'delete', String(env.id)]);
cli(['script', 'create', '--data', '{"filename":"cli-openapi.js","content":"console.log(1)","path":""}']);
assert.equal(cli(['script', 'get', '--query', '{"file":"cli-openapi.js"}']), 'console.log(1)');
cli(['config', 'save', '--data', '{"name":"cli-openapi.sh","content":"# fixture"}']);
assert.equal(cli(['config', 'get', '--query', '{"path":"cli-openapi.sh"}']), '# fixture');
cli(['log', 'list']); cli(['dependency', 'list']);
cli(['task', 'delete', String(task.id)]); cli(['subscription', 'delete', String(sub.id)]);
const reset = cli(['app', 'reset-secret', String(app.id), '--show-secrets'], true);
cli([
'script',
'create',
'--data',
'{"filename":"cli-openapi.js","content":"console.log(1)","path":""}',
]);
assert.equal(
cli(['script', 'get', '--query', '{"file":"cli-openapi.js"}']),
'console.log(1)',
);
cli([
'config',
'save',
'--data',
'{"name":"cli-openapi.sh","content":"# fixture"}',
]);
assert.equal(
cli(['config', 'get', '--query', '{"path":"cli-openapi.sh"}']),
'# fixture',
);
cli(['log', 'list']);
cli(['dependency', 'list']);
cli(['task', 'delete', String(task.id)]);
cli(['subscription', 'delete', String(sub.id)]);
const reset = cli(
['app', 'reset-secret', String(app.id), '--show-secrets'],
true,
);
assert.ok(reset.client_secret !== app.client_secret);
cli(['login', '--url', url], false, { QL_CLIENT_ID: app.client_id, QL_CLIENT_SECRET: reset.client_secret });
cli(['auth', 'status']); cli(['app', 'delete', String(app.id)], true);
cli(['login', '--url', url], false, {
QL_CLIENT_ID: app.client_id,
QL_CLIENT_SECRET: reset.client_secret,
});
cli(['auth', 'status']);
cli(['app', 'delete', String(app.id)], true);
await fs.rm(config, { force: true });
console.log(JSON.stringify({ panelVersion: info.version, taskCrud: true, subscriptionCrud: true, appCrudAndSecretRotation: true, envCrud: true, scriptCreateRead: true, configSaveRead: true, logAndDependencyRead: true }));
})().catch(error => { console.error(error.message); process.exitCode = 1; });
console.log(
JSON.stringify({
panelVersion: info.version,
taskCrud: true,
subscriptionCrud: true,
appCrudAndSecretRotation: true,
envCrud: true,
scriptCreateRead: true,
configSaveRead: true,
logAndDependencyRead: true,
}),
);
})().catch((error) => {
console.error(error.message);
process.exitCode = 1;
});
+11 -2
View File
@@ -38,7 +38,11 @@ exports.verifyAccountMaintenance = async function verifyAccountMaintenance(
assert.equal((await login()).code, 200, 'New credentials were not saved');
const incorrect = randomUUID();
for (let attempt = 0; attempt < 3; attempt++) {
assert.equal((await login(incorrect)).code, 400, 'Expected a rejected password before throttling');
assert.equal(
(await login(incorrect)).code,
400,
'Expected a rejected password before throttling',
);
}
assert.equal(
(await login()).code,
@@ -49,7 +53,12 @@ exports.verifyAccountMaintenance = async function verifyAccountMaintenance(
const session = await login();
assert.equal(session.code, 200, 'Login limit was not cleared');
assert.ok(session.data.token, 'Fresh owner session required');
await api('system/auth/reset', 'PUT', { twoFactorActivated: true }, session.data.token);
await api(
'system/auth/reset',
'PUT',
{ twoFactorActivated: true },
session.data.token,
);
assert.equal(
(await login()).code,
420,
+4 -1
View File
@@ -38,7 +38,10 @@ exports.verifyOperator = async function verifyOperator(api) {
last_execution_time: start,
log_path: 'cli-retention/2000-01-01-kept.log',
});
assert.equal((await api(`crons/${task.id}`)).data.log_path, 'cli-retention/2000-01-01-kept.log');
assert.equal(
(await api(`crons/${task.id}`)).data.log_path,
'cli-retention/2000-01-01-kept.log',
);
const result = invoke(['rmlog', '7']);
assert.ok(result.removed.includes('cli-retention/2000-01-01-unused.log'));
assert.ok(result.retained.includes('cli-retention/2000-01-01-kept.log'));
+3 -1
View File
@@ -2,7 +2,9 @@ const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const { randomUUID } = require('node:crypto');
const { createContext } = require('../../dist/internal/runtime/context');
const { installPanelDependencies } = require('../../dist/internal/maintenance/operator');
const {
installPanelDependencies,
} = require('../../dist/internal/maintenance/operator');
const { reloadPanel } = require('../../dist/internal/maintenance/upgrade');
assert.equal(process.env.QL_PANEL_INTEGRATION, '1');
(async () => {
+17 -4
View File
@@ -43,10 +43,21 @@ let restoreEntrypoints;
const switched = process.env.QL_PANEL_ENTRYPOINTS === '1';
if (switched && process.env.QL_PANEL_PACKAGED === '1') {
assert.equal(process.env.QL_CLI_ROOT, '/opt/qinglong-cli');
for (const [name, module] of [['task', 'task'], ['ql', 'ql']]) {
const target = require('node:path').join(require('node:os').homedir(), 'bin', name);
for (const [name, module] of [
['task', 'task'],
['ql', 'ql'],
]) {
const target = require('node:path').join(
require('node:os').homedir(),
'bin',
name,
);
assert.equal((await fs.lstat(target)).isSymbolicLink(), false);
assert.ok((await fs.readFile(target, 'utf8')).includes(Buffer.from(`/opt/qinglong-cli/dist/${module}.js`).toString('base64')));
assert.ok(
(await fs.readFile(target, 'utf8')).includes(
Buffer.from(`/opt/qinglong-cli/dist/${module}.js`).toString('base64'),
),
);
}
} else if (switched)
restoreEntrypoints =
@@ -214,7 +225,9 @@ let restoreEntrypoints;
})()
.catch(() => {
// Assertions can embed environment values or subprocess output in their message.
console.error('Disposable panel integration failed; inspect the failing scenario locally.');
console.error(
'Disposable panel integration failed; inspect the failing scenario locally.',
);
process.exitCode = 1;
})
.finally(async () => {
+6 -2
View File
@@ -7,7 +7,9 @@ const { createHash } = require('node:crypto');
const { createContext } = require('../../dist/internal/runtime/context');
const operator = require('../../dist/internal/maintenance/operator');
const { stageUpgrade } = require('../../dist/internal/maintenance/upgrade');
const { cancellableOperation } = require('../../dist/internal/runtime/cancellation');
const {
cancellableOperation,
} = require('../../dist/internal/runtime/cancellation');
test(
'published master archives pass actual HTTPS download and staging validation',
@@ -43,7 +45,9 @@ test(
context.paths.dir_tmp,
);
installations.push(directory);
await fs.mkdir(path.join(directory, 'node_modules'), { recursive: true });
await fs.mkdir(path.join(directory, 'node_modules'), {
recursive: true,
});
},
);
const controller = new AbortController();
+3 -1
View File
@@ -7,7 +7,9 @@ const net = require('node:net');
const { execFileSync, spawn } = require('node:child_process');
const { setTimeout: delay } = require('node:timers/promises');
const { createContext } = require('../../dist/internal/runtime/context');
const { syncRepository } = require('../../dist/internal/subscription/subscriptionRunner');
const {
syncRepository,
} = require('../../dist/internal/subscription/subscriptionRunner');
test(
'real SSH subscriptions require the configured identity and pinned host key',
+4 -1
View File
@@ -5,7 +5,10 @@ const os = require('node:os');
const path = require('node:path');
const { fork } = require('node:child_process');
const { createContext } = require('../../dist/internal/runtime/context');
const { startPanel, stopPanel } = require('../../dist/internal/maintenance/operator');
const {
startPanel,
stopPanel,
} = require('../../dist/internal/maintenance/operator');
const { runProcess } = require('../../dist/internal/runtime/process');
test(
+20 -6
View File
@@ -82,10 +82,15 @@ async function fixture(t) {
data: { data: [{ id: 12, name: 'example' }], total: 1 },
});
else if (
['/panel/open/envs', '/panel/open/configs/files', '/panel/open/scripts',
'/panel/open/subscriptions', '/panel/open/dependencies',
'/panel/open/logs', '/panel/open/dashboard/overview']
.includes(url.pathname)
[
'/panel/open/envs',
'/panel/open/configs/files',
'/panel/open/scripts',
'/panel/open/subscriptions',
'/panel/open/dependencies',
'/panel/open/logs',
'/panel/open/dashboard/overview',
].includes(url.pathname)
)
json({ code: 200, data: [] });
else if (
@@ -172,7 +177,13 @@ test('compiled entry: login aliases, private storage, status, refresh and local
['logs:read', '/panel/open/logs'],
['dashboard:read', '/panel/open/dashboard/overview'],
]) {
const checked = await f.invoke(['auth', 'status', '--scope', scope, '--json']);
const checked = await f.invoke([
'auth',
'status',
'--scope',
scope,
'--json',
]);
assert.equal(checked.code, 0, checked.err);
assert.equal(JSON.parse(checked.out).data.scopeChecked, scope);
assert.equal(f.requests.at(-1).url.pathname, pathname);
@@ -338,7 +349,10 @@ test('config content and symlinks are checked independently of permission bits',
fs.symlinkSync(target, f.file);
const linked = await f.invoke(['task', 'list', '--json'], { QL_LANG: 'en' });
failure(linked, 1);
assert.match(JSON.parse(linked.err).message, /regular file, not a symbolic link/);
assert.match(
JSON.parse(linked.err).message,
/regular file, not a symbolic link/,
);
await f.login();
assert.equal(fs.lstatSync(f.file).isSymbolicLink(), false);
assert.equal(JSON.parse(fs.readFileSync(target)).clientId, 123);
+28 -7
View File
@@ -4,26 +4,47 @@ const { task } = require('../../dist/remote/commands/task');
const { subscription } = require('../../dist/remote/commands/subscription');
test('task and subscription logs preserve server truncation as well as local tail limits', async (t) => {
const previous = { url: process.env.QL_URL, token: process.env.QL_ACCESS_TOKEN };
const previous = {
url: process.env.QL_URL,
token: process.env.QL_ACCESS_TOKEN,
};
process.env.QL_URL = 'http://127.0.0.1';
process.env.QL_ACCESS_TOKEN = 'fixture';
t.after(() => {
for (const [key, value] of [['QL_URL', previous.url], ['QL_ACCESS_TOKEN', previous.token]]) {
for (const [key, value] of [
['QL_URL', previous.url],
['QL_ACCESS_TOKEN', previous.token],
]) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
let response;
t.mock.method(global, 'fetch', async () => new Response(JSON.stringify(response), {
headers: { 'content-type': 'application/json' },
}));
t.mock.method(
global,
'fetch',
async () =>
new Response(JSON.stringify(response), {
headers: { 'content-type': 'application/json' },
}),
);
const run = async (tail) => [
await task({ kind: 'logs', id: 1, tail }),
await subscription({ name: 'subscription logs', positionals: ['1'], values: { tail: String(tail) } }),
await subscription({
name: 'subscription logs',
positionals: ['1'],
values: { tail: String(tail) },
}),
];
// A byte-limited backend response can contain fewer lines than --tail.
response = { code: 200, data: 'partial long line\nlast line\n', offset: 262144, total: 524288, truncated: true };
response = {
code: 200,
data: 'partial long line\nlast line\n',
offset: 262144,
total: 524288,
truncated: true,
};
for (const result of await run(200)) {
assert.equal(result.data, 'partial long line\nlast line');
assert.equal(result.truncated, true);
+408 -104
View File
@@ -15,41 +15,99 @@ async function fixture(t) {
const server = http.createServer(async (req, res) => {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const record = { method: req.method, url: req.url, headers: req.headers, body: Buffer.concat(chunks).toString() };
const record = {
method: req.method,
url: req.url,
headers: req.headers,
body: Buffer.concat(chunks).toString(),
};
requests.push(record);
if (reply) return reply(req, res);
if (/\/(download|data\/export|command-run)$/.test(req.url)) {
res.writeHead(200, { 'content-type': 'application/json', 'content-disposition': 'attachment; filename="fixture.json"' });
res.writeHead(200, {
'content-type': 'application/json',
'content-disposition': 'attachment; filename="fixture.json"',
});
res.end('{"fixture":true}');
} else if (req.url === '/panel/open/system/log') {
res.writeHead(200, { 'content-type': 'text/plain' }); res.end('log content');
res.writeHead(200, { 'content-type': 'text/plain' });
res.end('log content');
} else {
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ code: 200, data: { id: 7, name: 'fixture', client_secret: 'SECRET-MARKER', tokens: [{ value: 'TOKEN-MARKER' }] } }));
res.end(
JSON.stringify({
code: 200,
data: {
id: 7,
name: 'fixture',
client_secret: 'SECRET-MARKER',
tokens: [{ value: 'TOKEN-MARKER' }],
},
}),
);
}
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); await fs.rm(root, { recursive: true, force: true }); });
const url = `http://127.0.0.1:${server.address().port}/panel`;
const run = (args, stdin = '', extra = {}) => new Promise((resolve, reject) => {
const child = spawn(process.execPath, [entry, ...args, '--json'], {
env: { PATH: process.env.PATH, QL_URL: url, QL_ACCESS_TOKEN: 'fixture-token', QL_LANG: 'en', ...extra },
stdio: ['pipe', 'pipe', 'pipe'],
});
let out = '', err = '';
const timer = setTimeout(() => { child.kill(); reject(new Error('CLI timeout')); }, 12000);
child.stdout.on('data', data => { out += data; }); child.stderr.on('data', data => { err += data; });
child.on('error', reject); child.on('close', code => { clearTimeout(timer); resolve({ code, out, err }); });
child.stdin.end(stdin);
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
t.after(async () => {
server.closeAllConnections();
await new Promise((resolve) => server.close(resolve));
await fs.rm(root, { recursive: true, force: true });
});
return { root, requests, run, reply: value => { reply = value; } };
const url = `http://127.0.0.1:${server.address().port}/panel`;
const run = (args, stdin = '', extra = {}) =>
new Promise((resolve, reject) => {
const child = spawn(process.execPath, [entry, ...args, '--json'], {
env: {
PATH: process.env.PATH,
QL_URL: url,
QL_ACCESS_TOKEN: 'fixture-token',
QL_LANG: 'en',
...extra,
},
stdio: ['pipe', 'pipe', 'pipe'],
});
let out = '',
err = '';
const timer = setTimeout(() => {
child.kill();
reject(new Error('CLI timeout'));
}, 12000);
child.stdout.on('data', (data) => {
out += data;
});
child.stderr.on('data', (data) => {
err += data;
});
child.on('error', reject);
child.on('close', (code) => {
clearTimeout(timer);
resolve({ code, out, err });
});
child.stdin.end(stdin);
});
return {
root,
requests,
run,
reply: (value) => {
reply = value;
},
};
}
function success(result) {
assert.equal(result.code, 0, result.err);
return JSON.parse(result.out);
}
function success(result) { assert.equal(result.code, 0, result.err); return JSON.parse(result.out); }
test('dashboard record sends execution statistics and rejects a missing body before HTTP', async t => {
test('dashboard record sends execution statistics and rejects a missing body before HTTP', async (t) => {
const f = await fixture(t);
const payload = { ref_id: 7, code: 0, elapsed: 1.5 };
success(await f.run(['dashboard', 'record', '--data', '-'], JSON.stringify(payload)));
success(
await f.run(
['dashboard', 'record', '--data', '-'],
JSON.stringify(payload),
),
);
assert.equal(f.requests.length, 1);
assert.equal(f.requests[0].method, 'POST');
assert.equal(f.requests[0].url, '/panel/open/dashboard/record');
@@ -58,7 +116,7 @@ test('dashboard record sends execution statistics and rejects a missing body bef
assert.equal(f.requests.length, 1);
});
test('schedule anomaly commands preserve sources, pagination and expired responses', async t => {
test('schedule anomaly commands preserve sources, pagination and expired responses', async (t) => {
const f = await fixture(t);
const response = { code: 200, data: { status: 'expired' } };
f.reply((_req, res) => {
@@ -67,19 +125,38 @@ test('schedule anomaly commands preserve sources, pagination and expired respons
});
for (const source of ['panel', 'system']) {
for (const kind of ['missing', 'skipped', 'unconfirmed']) {
const query = { source, kind, at: 1795046400000, page: 3, revision: 'a'.repeat(64), live: true };
const query = {
source,
kind,
at: 1795046400000,
page: 3,
revision: 'a'.repeat(64),
live: true,
};
for (const command of [
['dashboard', 'schedule-anomalies'],
['api', 'request', 'GET', '/open/dashboard/schedule-anomalies'],
]) {
const before = f.requests.length;
assert.deepEqual(success(await f.run([...command, '--query', JSON.stringify(query)])), response);
assert.equal(f.requests.length, before + 1, 'expired responses must not be retried');
const req = f.requests.at(-1), url = new URL(req.url, 'http://localhost');
assert.deepEqual(
success(await f.run([...command, '--query', JSON.stringify(query)])),
response,
);
assert.equal(
f.requests.length,
before + 1,
'expired responses must not be retried',
);
const req = f.requests.at(-1),
url = new URL(req.url, 'http://localhost');
assert.equal(req.method, 'GET');
assert.equal(url.pathname, '/panel/open/dashboard/schedule-anomalies');
assert.deepEqual(Object.fromEntries(url.searchParams),
Object.fromEntries(Object.entries(query).map(([key, value]) => [key, String(value)])));
assert.deepEqual(
Object.fromEntries(url.searchParams),
Object.fromEntries(
Object.entries(query).map(([key, value]) => [key, String(value)]),
),
);
assert.equal(req.body, '');
assert.equal(req.headers.authorization, 'Bearer fixture-token');
}
@@ -87,7 +164,7 @@ test('schedule anomaly commands preserve sources, pagination and expired respons
}
});
test('script history commands send exact query parameters and restore payloads', async t => {
test('script history commands send exact query parameters and restore payloads', async (t) => {
const f = await fixture(t);
const identity = { filename: '中文 script.js', path: 'nested folder' };
const version = { ...identity, id: '32ec8b22-2c48-4bcf-85d4-b394198417ba' };
@@ -96,25 +173,38 @@ test('script history commands send exact query parameters and restore payloads',
['history-detail', 'scripts/history/detail', version],
]) {
success(await f.run(['script', command, '--query', JSON.stringify(query)]));
const req = f.requests.at(-1), url = new URL(req.url, 'http://localhost');
const req = f.requests.at(-1),
url = new URL(req.url, 'http://localhost');
assert.equal(req.method, 'GET');
assert.equal(url.pathname, '/panel/open/' + endpoint);
for (const [key, value] of Object.entries(query)) assert.equal(url.searchParams.get(key), value);
for (const [key, value] of Object.entries(query))
assert.equal(url.searchParams.get(key), value);
assert.equal(req.body, '');
}
const payload = { ...version, expectedHash: 'a'.repeat(64) };
success(await f.run(['script', 'history-restore', '--data', '-'], JSON.stringify(payload)));
success(
await f.run(
['script', 'history-restore', '--data', '-'],
JSON.stringify(payload),
),
);
assert.equal(f.requests.at(-1).method, 'PUT');
assert.equal(f.requests.at(-1).url, '/panel/open/scripts/history/restore');
assert.deepEqual(JSON.parse(f.requests.at(-1).body), payload);
const count = f.requests.length;
assert.equal((await f.run(['script', 'history-restore'])).code, 2);
assert.equal(f.requests.length, count, 'missing restore payload must not issue a request');
assert.equal(
f.requests.length,
count,
'missing restore payload must not issue a request',
);
});
test('dependency refresh commands send the dependency type and address background jobs', async t => {
test('dependency refresh commands send the dependency type and address background jobs', async (t) => {
const f = await fixture(t);
success(await f.run(['dependency', 'refresh', '--data', '{"type":"python3"}']));
success(
await f.run(['dependency', 'refresh', '--data', '{"type":"python3"}']),
);
assert.equal(f.requests[0].method, 'POST');
assert.equal(f.requests[0].url, '/panel/open/dependencies/refresh');
assert.deepEqual(JSON.parse(f.requests[0].body), { type: 'python3' });
@@ -125,164 +215,378 @@ test('dependency refresh commands send the dependency type and address backgroun
success(await f.run(['dependency', 'refresh-active']));
assert.equal(f.requests[2].method, 'GET');
assert.equal(f.requests[2].url, '/panel/open/dependencies/refresh/active');
success(await f.run(['api', 'request', 'GET', `/open/dependencies/refresh/${id}`]));
success(
await f.run(['api', 'request', 'GET', `/open/dependencies/refresh/${id}`]),
);
assert.equal(f.requests[3].url, `/panel/open/dependencies/refresh/${id}`);
assert.equal((await f.run(['dependency', 'refresh-status', '7'])).code, 2);
assert.equal((await f.run(['api', 'request', 'GET', '/open/dependencies/refresh/7'])).code, 2);
assert.equal(
(await f.run(['api', 'request', 'GET', '/open/dependencies/refresh/7']))
.code,
2,
);
assert.equal((await f.run(['dependency', 'refresh'])).code, 2);
assert.equal(f.requests.length, 4, 'invalid arguments must not issue a request');
assert.equal(
f.requests.length,
4,
'invalid arguments must not issue a request',
);
});
test('OpenAPI catalogue covers every active registered backend route; retired 410 routes are explicit', async () => {
const root = path.resolve(__dirname, '../../../back/api');
const expected = [];
const retired = new Set(['GET configs/:file', 'GET scripts/:file', 'GET logs/:file']);
const retired = new Set([
'GET configs/:file',
'GET scripts/:file',
'GET logs/:file',
]);
const index = await fs.readFile(path.join(root, 'index.ts'), 'utf8');
for (const filename of await fs.readdir(root)) {
if (!filename.endsWith('.ts') || filename === 'index.ts') continue;
const source = await fs.readFile(path.join(root, filename), 'utf8');
assert.ok(index.includes(`'./${filename.slice(0, -3)}'`), `Unregistered API module ${filename}`);
assert.ok(
index.includes(`'./${filename.slice(0, -3)}'`),
`Unregistered API module ${filename}`,
);
const mount = /app\.use\(['"]([^'"]+)['"]/.exec(source);
assert.ok(mount, filename);
for (const m of source.matchAll(/route\.(get|post|put|delete|patch)\(\s*['"]([^'"]+)['"]/g)) {
const endpoint = [mount[1], m[2]].join('/').split('/').filter(Boolean).join('/');
for (const m of source.matchAll(
/route\.(get|post|put|delete|patch)\(\s*['"]([^'"]+)['"]/g,
)) {
const endpoint = [mount[1], m[2]]
.join('/')
.split('/')
.filter(Boolean)
.join('/');
const key = `${m[1].toUpperCase()} ${endpoint}`;
if (!retired.has(key)) expected.push(key);
else assert.match(source.slice(m.index, m.index + 200), /code: 410/);
}
}
const actual = openOperations.map(op => `${op.method} ${op.path}`);
const actual = openOperations.map((op) => `${op.method} ${op.path}`);
assert.equal(new Set(actual).size, actual.length);
assert.equal(new Set(openOperations.map(op => op.name)).size, openOperations.length);
assert.equal(
new Set(openOperations.map((op) => op.name)).size,
openOperations.length,
);
assert.deepEqual(actual.sort(), expected.sort());
});
test('task, subscription and app CRUD produce exact 2.x requests and protect app credentials', async t => {
test('task, subscription and app CRUD produce exact 2.x requests and protect app credentials', async (t) => {
const f = await fixture(t);
success(await f.run(['task', 'create', '--name', 'demo', '--command', 'task demo.js', '--schedule', '0 0 * * *']));
assert.deepEqual(JSON.parse(f.requests.at(-1).body), { name: 'demo', command: 'task demo.js', schedule: '0 0 * * *' });
assert.equal(f.requests.at(-1).method, 'POST'); assert.equal(f.requests.at(-1).url, '/panel/open/crons');
success(await f.run(['task', 'update', '7', '--data', '-', '--name', 'updated'], '{"command":"task demo.js","schedule":"0 1 * * *"}'));
assert.deepEqual(JSON.parse(f.requests.at(-1).body), { id: 7, name: 'updated', command: 'task demo.js', schedule: '0 1 * * *' });
success(await f.run(['task', 'delete', '7', '8'])); assert.deepEqual(JSON.parse(f.requests.at(-1).body), [7, 8]);
success(
await f.run([
'task',
'create',
'--name',
'demo',
'--command',
'task demo.js',
'--schedule',
'0 0 * * *',
]),
);
assert.deepEqual(JSON.parse(f.requests.at(-1).body), {
name: 'demo',
command: 'task demo.js',
schedule: '0 0 * * *',
});
assert.equal(f.requests.at(-1).method, 'POST');
assert.equal(f.requests.at(-1).url, '/panel/open/crons');
success(
await f.run(
['task', 'update', '7', '--data', '-', '--name', 'updated'],
'{"command":"task demo.js","schedule":"0 1 * * *"}',
),
);
assert.deepEqual(JSON.parse(f.requests.at(-1).body), {
id: 7,
name: 'updated',
command: 'task demo.js',
schedule: '0 1 * * *',
});
success(await f.run(['task', 'delete', '7', '8']));
assert.deepEqual(JSON.parse(f.requests.at(-1).body), [7, 8]);
assert.equal(f.requests.at(-1).method, 'DELETE');
success(await f.run(['subscription', 'create', '--type', 'public-repo', '--url', 'https://example.com/repo.git', '--alias', 'demo', '--schedule-type', 'crontab', '--schedule', '0 0 * * *']));
success(
await f.run([
'subscription',
'create',
'--type',
'public-repo',
'--url',
'https://example.com/repo.git',
'--alias',
'demo',
'--schedule-type',
'crontab',
'--schedule',
'0 0 * * *',
]),
);
assert.equal(f.requests.at(-1).url, '/panel/open/subscriptions');
assert.equal(JSON.parse(f.requests.at(-1).body).schedule_type, 'crontab');
const app = success(await f.run(['app', 'create', '--name', 'worker', '--scopes', 'crons,subscriptions']));
assert.deepEqual(JSON.parse(f.requests.at(-1).body), { name: 'worker', scopes: ['crons', 'subscriptions'] });
assert.equal(app.data.client_secret, undefined); assert.equal(app.data.tokens, undefined);
assert.equal(success(await f.run(['app', 'reset-secret', '7', '--show-secrets'])).data.client_secret, 'SECRET-MARKER');
const app = success(
await f.run([
'app',
'create',
'--name',
'worker',
'--scopes',
'crons,subscriptions',
]),
);
assert.deepEqual(JSON.parse(f.requests.at(-1).body), {
name: 'worker',
scopes: ['crons', 'subscriptions'],
});
assert.equal(app.data.client_secret, undefined);
assert.equal(app.data.tokens, undefined);
assert.equal(
success(await f.run(['app', 'reset-secret', '7', '--show-secrets'])).data
.client_secret,
'SECRET-MARKER',
);
assert.equal(f.requests.at(-1).url, '/panel/open/apps/7/reset-secret');
for (const req of f.requests) assert.equal(req.headers.authorization, 'Bearer fixture-token');
for (const req of f.requests)
assert.equal(req.headers.authorization, 'Bearer fixture-token');
});
test('all added named operations reach their registered method/path, including upload/download and anonymous routes', async t => {
test('all added named operations reach their registered method/path, including upload/download and anonymous routes', async (t) => {
const f = await fixture(t);
const file = path.join(f.root, 'fixture.json'); await fs.writeFile(file, '{}');
for (const op of openOperations.filter(op => !op.existing)) {
const file = path.join(f.root, 'fixture.json');
await fs.writeFile(file, '{}');
for (const op of openOperations.filter((op) => !op.existing)) {
const args = op.name.split(' ');
const parameter = name => op.uuidParams?.includes(name) ? '32ec8b22-2c48-4bcf-85d4-b394198417ba' : '7';
const parameter = (name) =>
op.uuidParams?.includes(name)
? '32ec8b22-2c48-4bcf-85d4-b394198417ba'
: '7';
for (const name of op.params ?? []) args.push(parameter(name));
if (op.body === 'ids') args.push('7', '8');
else if (op.body) {
const data = op.name.startsWith('task ') ? { command: 'echo fixture', schedule: '0 0 * * *' }
: op.name.startsWith('subscription ') ? { type: 'file', url: 'https://example.com/job.js', alias: 'job', schedule_type: 'crontab' } : {};
const data = op.name.startsWith('task ')
? { command: 'echo fixture', schedule: '0 0 * * *' }
: op.name.startsWith('subscription ')
? {
type: 'file',
url: 'https://example.com/job.js',
alias: 'job',
schedule_type: 'crontab',
}
: {};
args.push('--data', JSON.stringify(data));
}
if (op.upload) args.push('--file', file);
if (op.download) args.push('--output', path.join(f.root, op.name.replace(' ', '-') + '.out'));
if (op.download)
args.push(
'--output',
path.join(f.root, op.name.replace(' ', '-') + '.out'),
);
success(await f.run(args));
const last = f.requests.at(-1);
assert.equal(last.method, op.method, op.name);
assert.equal(last.url, '/panel/open/' + op.path.replace(/:([A-Za-z]+)/g, (_match, name) => parameter(name)), op.name);
assert.equal(last.headers.authorization, op.anonymous ? undefined : 'Bearer fixture-token', op.name);
if (op.upload) assert.ok(last.body.includes(`name="${op.upload}"; filename="fixture.json"`), op.name);
assert.equal(
last.url,
'/panel/open/' +
op.path.replace(/:([A-Za-z]+)/g, (_match, name) => parameter(name)),
op.name,
);
assert.equal(
last.headers.authorization,
op.anonymous ? undefined : 'Bearer fixture-token',
op.name,
);
if (op.upload)
assert.ok(
last.body.includes(`name="${op.upload}"; filename="fixture.json"`),
op.name,
);
}
});
test('raw route access retains query/body capabilities and rejects unsupported paths before authentication', async t => {
test('raw route access retains query/body capabilities and rejects unsupported paths before authentication', async (t) => {
const f = await fixture(t);
success(await f.run(['api', 'request', 'GET', '/open/crons', '--query', '{"searchValue":"a & b","page":2}']));
assert.equal(f.requests.at(-1).url, '/panel/open/crons?searchValue=a+%26+b&page=2');
const bodyFile = path.join(f.root, 'env.json'); await fs.writeFile(bodyFile, '[{"name":"A","value":"B"}]');
success(
await f.run([
'api',
'request',
'GET',
'/open/crons',
'--query',
'{"searchValue":"a & b","page":2}',
]),
);
assert.equal(
f.requests.at(-1).url,
'/panel/open/crons?searchValue=a+%26+b&page=2',
);
const bodyFile = path.join(f.root, 'env.json');
await fs.writeFile(bodyFile, '[{"name":"A","value":"B"}]');
success(await f.run(['env', 'create', '--data', '@' + bodyFile]));
assert.equal(f.requests.at(-1).body, '[{"name":"A","value":"B"}]');
const count = f.requests.length;
for (const args of [
['api', 'request', 'GET', 'https://example.com'], ['api', 'request', 'DELETE', 'auth/token'],
['api', 'request', 'GET', '../api/user'], ['api', 'request', 'GET', 'crons/0'], ['api', 'request', 'GET', 'crons/9007199254740993'],
['task', 'create', '--data', '{'], ['task', 'create', '--command', 'echo fixture'],
['task', 'update', '7', '--data', '{"id":8}'], ['task', 'delete', '-1'],
['api', 'request', 'GET', 'https://example.com'],
['api', 'request', 'DELETE', 'auth/token'],
['api', 'request', 'GET', '../api/user'],
['api', 'request', 'GET', 'crons/0'],
['api', 'request', 'GET', 'crons/9007199254740993'],
['task', 'create', '--data', '{'],
['task', 'create', '--command', 'echo fixture'],
['task', 'update', '7', '--data', '{"id":8}'],
['task', 'delete', '-1'],
['env', 'list', '--query', '{"secret":{"value":1}}'],
['app', 'create', '--data', '{"name":"A"}', '--name', 'B'],
['log', 'download', '--data', '{}', '--output', bodyFile],
]) { const result = await f.run(args); assert.equal(result.code, 2, JSON.stringify(args) + result.err); assert.equal(result.out, ''); }
]) {
const result = await f.run(args);
assert.equal(result.code, 2, JSON.stringify(args) + result.err);
assert.equal(result.out, '');
}
assert.equal(f.requests.length, count);
const output = path.join(f.root, 'download.json');
success(await f.run(['log', 'download', '--data', '{"filename":"fixture.json"}', '--output', output]));
success(
await f.run([
'log',
'download',
'--data',
'{"filename":"fixture.json"}',
'--output',
output,
]),
);
assert.equal(await fs.readFile(output, 'utf8'), '{"fixture":true}');
assert.equal((await fs.stat(output)).mode & 0o777, 0o600);
});
test('POST/DELETE uncertainty and permission failures never retry or print server secrets', async t => {
test('POST/DELETE uncertainty and permission failures never retry or print server secrets', async (t) => {
const f = await fixture(t);
f.reply((_req, res) => { res.writeHead(503); res.end('SERVER-SECRET'); });
for (const args of [['task', 'create', '--command', 'echo fixture', '--schedule', '0 0 * * *'], ['task', 'delete', '7']]) {
const count = f.requests.length; const result = await f.run(args);
assert.equal(result.code, 1); assert.match(result.err, /unknown|retry/i);
assert.doesNotMatch(result.err, /SERVER-SECRET/); assert.equal(f.requests.length, count + 1);
f.reply((_req, res) => {
res.writeHead(503);
res.end('SERVER-SECRET');
});
for (const args of [
['task', 'create', '--command', 'echo fixture', '--schedule', '0 0 * * *'],
['task', 'delete', '7'],
]) {
const count = f.requests.length;
const result = await f.run(args);
assert.equal(result.code, 1);
assert.match(result.err, /unknown|retry/i);
assert.doesNotMatch(result.err, /SERVER-SECRET/);
assert.equal(f.requests.length, count + 1);
}
f.reply((_req, res) => { res.writeHead(403); res.end('SERVER-SECRET'); });
const result = await f.run(['app', 'list']); assert.equal(result.code, 3); assert.match(result.err, /apps/);
f.reply((_req, res) => {
res.writeHead(403);
res.end('SERVER-SECRET');
});
const result = await f.run(['app', 'list']);
assert.equal(result.code, 3);
assert.match(result.err, /apps/);
assert.doesNotMatch(result.err, /SERVER-SECRET/);
});
test('failed downloads leave no partial files and timed-out mutations are not replayed', async t => {
test('failed downloads leave no partial files and timed-out mutations are not replayed', async (t) => {
const f = await fixture(t);
const output = path.join(f.root, 'partial.log');
f.reply((_req, res) => {
res.writeHead(200, { 'content-type': 'application/octet-stream' }); res.write('partial');
res.writeHead(200, { 'content-type': 'application/octet-stream' });
res.write('partial');
setTimeout(() => res.destroy(), 50);
});
const failed = await f.run(['log', 'download', '--data', '{"filename":"fixture.log"}', '--output', output]);
assert.equal(failed.code, 1); assert.equal(failed.out, '');
const failed = await f.run([
'log',
'download',
'--data',
'{"filename":"fixture.log"}',
'--output',
output,
]);
assert.equal(failed.code, 1);
assert.equal(failed.out, '');
await assert.rejects(fs.stat(output), { code: 'ENOENT' });
f.reply(() => {});
const count = f.requests.length;
const timeout = await f.run(['app', 'create', '--name', 'fixture', '--scopes', 'crons', '--timeout', '1']);
assert.equal(timeout.code, 1); assert.match(timeout.err, /unknown/);
const timeout = await f.run([
'app',
'create',
'--name',
'fixture',
'--scopes',
'crons',
'--timeout',
'1',
]);
assert.equal(timeout.code, 1);
assert.match(timeout.err, /unknown/);
assert.equal(f.requests.length, count + 1);
});
test('owner two-factor challenge remains actionable without exposing server messages', async t => {
test('owner two-factor challenge remains actionable without exposing server messages', async (t) => {
const f = await fixture(t);
f.reply((_req, res) => { res.setHeader('content-type', 'application/json'); res.end('{"code":420,"message":"SERVER-SECRET"}'); });
const result = await f.run(['user', 'login', '--data', '{"username":"fixture","password":"fixture"}']);
assert.equal(result.code, 3); assert.match(result.err, /two-factor-login/); assert.doesNotMatch(result.err, /SERVER-SECRET/);
assert.equal(f.requests.length, 1); assert.equal(f.requests[0].headers.authorization, undefined);
f.reply((_req, res) => {
res.setHeader('content-type', 'application/json');
res.end('{"code":420,"message":"SERVER-SECRET"}');
});
const result = await f.run([
'user',
'login',
'--data',
'{"username":"fixture","password":"fixture"}',
]);
assert.equal(result.code, 3);
assert.match(result.err, /two-factor-login/);
assert.doesNotMatch(result.err, /SERVER-SECRET/);
assert.equal(f.requests.length, 1);
assert.equal(f.requests[0].headers.authorization, undefined);
});
test('node mirror configuration accepts the real empty response for named and raw API commands', async t => {
test('node mirror configuration accepts the real empty response for named and raw API commands', async (t) => {
const f = await fixture(t);
f.reply((_req, res) => { res.writeHead(200, { 'content-type': 'application/octet-stream' }); res.end(); });
f.reply((_req, res) => {
res.writeHead(200, { 'content-type': 'application/octet-stream' });
res.end();
});
for (const args of [
['system', 'config-node-mirror'],
['api', 'request', 'PUT', '/open/system/config/node-mirror'],
]) {
const reply = success(await f.run([...args, '--data', '{"nodeMirror":"https://registry.npmmirror.com"}']));
const reply = success(
await f.run([
...args,
'--data',
'{"nodeMirror":"https://registry.npmmirror.com"}',
]),
);
assert.equal(reply.code, 200);
assert.equal(f.requests.at(-1).method, 'PUT');
assert.equal(f.requests.at(-1).url, '/panel/open/system/config/node-mirror');
assert.equal(
f.requests.at(-1).url,
'/panel/open/system/config/node-mirror',
);
}
assert.equal(f.requests.length, 2, 'configuration writes must not be retried');
assert.equal(
f.requests.length,
2,
'configuration writes must not be retried',
);
});
test('empty node mirror responses still reject authentication and server failures without retries', async t => {
test('empty node mirror responses still reject authentication and server failures without retries', async (t) => {
const f = await fixture(t);
for (const status of [401, 403, 500]) {
f.reply((_req, res) => { res.writeHead(status, { 'content-type': 'application/octet-stream' }); res.end(); });
const result = await f.run(['system', 'config-node-mirror', '--data', '{}']);
f.reply((_req, res) => {
res.writeHead(status, { 'content-type': 'application/octet-stream' });
res.end();
});
const result = await f.run([
'system',
'config-node-mirror',
'--data',
'{}',
]);
assert.notEqual(result.code, 0);
assert.equal(result.out, '');
}
+21 -18
View File
@@ -17,13 +17,15 @@ test('saved login works on the host filesystem', async (t) => {
if (url.pathname === '/panel/open/auth/token') {
assert.equal(url.searchParams.get('client_id'), 'smoke-id');
assert.equal(url.searchParams.get('client_secret'), 'smoke-secret');
res.end(JSON.stringify({
code: 200,
data: {
token: 'smoke-token',
expiration: Math.floor(Date.now() / 1000) + 3600,
},
}));
res.end(
JSON.stringify({
code: 200,
data: {
token: 'smoke-token',
expiration: Math.floor(Date.now() / 1000) + 3600,
},
}),
);
return;
}
assert.equal(req.headers.authorization, 'Bearer smoke-token');
@@ -48,18 +50,19 @@ test('saved login works on the host filesystem', async (t) => {
QL_URL: '',
QL_ACCESS_TOKEN: '',
};
const invoke = (args) => new Promise((resolve, reject) => {
const child = spawn(process.execPath, [entry, ...args], {
env,
stdio: ['ignore', 'pipe', 'pipe'],
const invoke = (args) =>
new Promise((resolve, reject) => {
const child = spawn(process.execPath, [entry, ...args], {
env,
stdio: ['ignore', 'pipe', 'pipe'],
});
let out = '';
let err = '';
child.stdout.on('data', (data) => (out += data));
child.stderr.on('data', (data) => (err += data));
child.once('error', reject);
child.once('close', (code) => resolve({ code, out, err }));
});
let out = '';
let err = '';
child.stdout.on('data', (data) => (out += data));
child.stderr.on('data', (data) => (err += data));
child.once('error', reject);
child.once('close', (code) => resolve({ code, out, err }));
});
const url = `http://127.0.0.1:${server.address().port}/panel`;
const login = await invoke(['login', '--url', url, '--json']);
assert.equal(login.code, 0, login.err);
+3 -1
View File
@@ -6,7 +6,9 @@ const os = require('node:os');
const http = require('node:http');
const { randomUUID } = require('node:crypto');
const { createContext } = require('../../dist/internal/runtime/context');
const { syncRaw } = require('../../dist/internal/subscription/subscriptionRunner');
const {
syncRaw,
} = require('../../dist/internal/subscription/subscriptionRunner');
const { runProcess } = require('../../dist/internal/runtime/process');
test('raw subscriptions retain legacy netrc authentication and preserve files on denied access', async (t) => {
+31 -11
View File
@@ -8,22 +8,42 @@ const { openOperations } = require('../../dist/remote/api/openOperations');
test('body-consuming backend routes expose a CLI request body or upload', () => {
const root = path.resolve(__dirname, '../../../back/api');
let checked = 0;
for (const filename of fs.readdirSync(root).filter(name => name.endsWith('.ts'))) {
for (const filename of fs
.readdirSync(root)
.filter((name) => name.endsWith('.ts'))) {
const text = fs.readFileSync(path.join(root, filename), 'utf8');
const mount = text.match(/app\.use\(['"]([^'"]+)/)?.[1];
if (!mount) continue;
const source = ts.createSourceFile(filename, text, ts.ScriptTarget.Latest, true);
const visit = node => {
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)
&& node.expression.expression.getText(source) === 'route'
&& ['post', 'put', 'delete'].includes(node.expression.name.text)
&& node.arguments[0] && ts.isStringLiteral(node.arguments[0])
&& /\breq\.body\b/.test(node.getText(source))) {
const endpoint = [mount, node.arguments[0].text].join('/').split('/').filter(Boolean).join('/');
const source = ts.createSourceFile(
filename,
text,
ts.ScriptTarget.Latest,
true,
);
const visit = (node) => {
if (
ts.isCallExpression(node) &&
ts.isPropertyAccessExpression(node.expression) &&
node.expression.expression.getText(source) === 'route' &&
['post', 'put', 'delete'].includes(node.expression.name.text) &&
node.arguments[0] &&
ts.isStringLiteral(node.arguments[0]) &&
/\breq\.body\b/.test(node.getText(source))
) {
const endpoint = [mount, node.arguments[0].text]
.join('/')
.split('/')
.filter(Boolean)
.join('/');
const method = node.expression.name.text.toUpperCase();
const operation = openOperations.find(item => item.method === method && item.path === endpoint);
const operation = openOperations.find(
(item) => item.method === method && item.path === endpoint,
);
assert.ok(operation, `${method} ${endpoint} is missing`);
assert.ok(operation.body || operation.upload, `${operation.name} cannot provide req.body`);
assert.ok(
operation.body || operation.upload,
`${operation.name} cannot provide req.body`,
);
checked++;
}
ts.forEachChild(node, visit);
+43 -9
View File
@@ -11,18 +11,47 @@ test('public task entries retain no-argument script discovery and help stays rea
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ql-public-inventory-'));
t.after(() => fs.rm(root, { recursive: true, force: true }));
await fs.mkdir(path.join(root, 'data/scripts'), { recursive: true });
await fs.writeFile(path.join(root, 'data/scripts/job.js'), 'throw Error("do not execute"); const $ = new Env("Job");');
for (const [entry, args] of [['task', []], ['ql', ['task']]]) {
const run = (...extra) => spawnSync(process.execPath, [path.resolve(__dirname, `../../dist/${entry}.js`), ...args, ...extra, '--json'], { env: { PATH: process.env.PATH, QL_DIR: root }, encoding: 'utf8' });
await fs.writeFile(
path.join(root, 'data/scripts/job.js'),
'throw Error("do not execute"); const $ = new Env("Job");',
);
for (const [entry, args] of [
['task', []],
['ql', ['task']],
]) {
const run = (...extra) =>
spawnSync(
process.execPath,
[
path.resolve(__dirname, `../../dist/${entry}.js`),
...args,
...extra,
'--json',
],
{ env: { PATH: process.env.PATH, QL_DIR: root }, encoding: 'utf8' },
);
const listing = run();
assert.equal(listing.status, 0, listing.stderr);
assert.deepEqual(JSON.parse(listing.stdout).data.scripts, [{ file: 'job.js', name: 'Job' }]);
assert.deepEqual(JSON.parse(listing.stdout).data.scripts, [
{ file: 'job.js', name: 'Job' },
]);
assert.equal(JSON.parse(run('--help').stdout).data.scripts, undefined);
}
});
test('removed development publication is rejected before doing any work', () => {
const result = spawnSync(process.execPath, [path.resolve(__dirname, '../../dist/ql.js'), 'dev', 'release', '--root', '/absent', '--json'], { encoding: 'utf8' });
const result = spawnSync(
process.execPath,
[
path.resolve(__dirname, '../../dist/ql.js'),
'dev',
'release',
'--root',
'/absent',
'--json',
],
{ encoding: 'utf8' },
);
assert.equal(result.status, 2);
assert.equal(result.stdout, '');
assert.equal(JSON.parse(result.stderr).code, 2);
@@ -39,13 +68,18 @@ test('health probes use the base path and reject failed or malformed scheduler h
} else if (req.url === '/ql/') res.end('<div id="root"></div>');
else res.end('{"code":200,"data":{"version":"2.21.0"}}');
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
t.after(() => new Promise(resolve => server.close(resolve)));
const context = { env: { QlPort: String(server.address().port), QlBaseUrl: '/ql/' } };
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
t.after(() => new Promise((resolve) => server.close(resolve)));
const context = {
env: { QlPort: String(server.address().port), QlBaseUrl: '/ql/' },
};
assert.equal((await inspectPanel(context)).backend.healthy, false);
health = { status: 200, body: { code: 200, data: {} } };
assert.equal((await inspectPanel(context)).backend.healthy, false);
health = { status: 200, body: { code: 200, data: { status: 'ok' } } };
assert.equal((await inspectPanel(context)).backend.healthy, true);
assert.equal(seen.some(route => route.includes('/api/system')), false);
assert.equal(
seen.some((route) => route.includes('/api/system')),
false,
);
});
+3 -4
View File
@@ -18,10 +18,9 @@ test('public CLI excludes local maintenance while the admin entry retains compat
parse(['--help'], 'local').help,
/subscription list|auth login/,
);
assert.throws(
() => parse(['auth', 'status', '--scope', 'all']),
{ exitCode: 2 },
);
assert.throws(() => parse(['auth', 'status', '--scope', 'all']), {
exitCode: 2,
});
});
test('subscription management uses panel API, projects credentials out and never invokes local repo/raw', async (t) => {
+320
View File
@@ -0,0 +1,320 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const http = require('node:http');
const path = require('node:path');
const { spawn } = require('node:child_process');
const entry = path.resolve(__dirname, '../../dist/npm/ql.js');
const triggerId = '6ecf88e9-b7dc-42c9-b2a6-47a0d707aceb-12';
async function fixture(t) {
const requests = [];
const state = {
run: [{ taskId: 12, triggerId, state: 'queued', reason: null }],
rows: [
{
id: triggerId,
cron_id: 12,
state: 'finished',
reason: null,
exit_code: 0,
},
],
log: {
code: 200,
triggerId,
data: 'this run\nlast line\n',
logStatus: 'completed',
},
polls: 0,
};
const server = http.createServer(async (req, res) => {
let body = '';
for await (const chunk of req) body += chunk;
const url = new URL(req.url, 'http://localhost');
requests.push({
path: url.pathname,
query: url.searchParams,
method: req.method,
body,
});
assert.equal(req.headers.authorization, 'Bearer fixture');
res.setHeader('content-type', 'application/json');
if (url.pathname === '/panel/open/crons/run') {
assert.equal(req.method, 'PUT');
assert.equal(body, '[12]');
return res.end(JSON.stringify({ code: 200, data: state.run }));
}
if (url.pathname === '/panel/open/crons/12/triggers') {
assert.equal(url.searchParams.get('ids'), triggerId);
state.polls++;
if (state.hang) return;
if (state.denied) {
res.statusCode = 403;
return res.end('{}');
}
if (state.disconnect) return req.socket.destroy();
const data =
state.polls <= (state.pending || 0)
? [
{
id: triggerId,
cron_id: 12,
state: 'running',
reason: null,
exit_code: null,
},
]
: state.rows;
return res.end(JSON.stringify({ code: 200, data }));
}
if (url.pathname === '/panel/open/crons/12/log')
return res.end(JSON.stringify(state.log));
res.statusCode = 404;
res.end('{}');
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
t.after(() => {
server.closeAllConnections();
server.close();
});
const invoke = (args, language = 'en') =>
new Promise((resolve, reject) => {
const child = spawn(process.execPath, [entry, ...args, '--json'], {
env: {
PATH: process.env.PATH,
QL_URL: `http://127.0.0.1:${server.address().port}/panel`,
QL_ACCESS_TOKEN: 'fixture',
QL_LANG: language,
},
stdio: ['ignore', 'pipe', 'pipe'],
});
let out = '',
err = '';
child.stdout.on('data', (chunk) => (out += chunk));
child.stderr.on('data', (chunk) => (err += chunk));
child.on('error', reject);
child.on('close', (code) => resolve({ code, out, err }));
});
return { state, requests, invoke };
}
function failure(result, code = 1) {
assert.equal(result.code, code, result.err);
assert.equal(result.out, '');
const error = JSON.parse(result.err);
assert.equal(error.code, code);
return error;
}
test('immediate run exposes its receipt and remains compatible with older panels', async (t) => {
const f = await fixture(t);
let result = await f.invoke(['task', 'run', '12']);
assert.equal(result.code, 0, result.err);
assert.deepEqual(JSON.parse(result.out).data, {
taskId: 12,
action: 'run',
accepted: true,
triggerId,
state: 'queued',
reason: null,
});
assert.equal(f.state.polls, 0);
for (const data of [undefined, null]) {
f.state.run = data;
result = await f.invoke(['task', 'run', '12']);
assert.deepEqual(JSON.parse(result.out).data, {
taskId: 12,
action: 'run',
accepted: true,
});
const error = failure(await f.invoke(['task', 'run', '12', '--wait']));
assert.match(
error.message,
/submitted.*no triggerId.*do not blindly retry/,
);
}
assert.equal(f.state.polls, 0);
assert.equal(f.requests.length, 5); // Exactly one mutation per invocation, never replayed.
});
test('wait polls only the returned trigger and logs read exactly that run', async (t) => {
const f = await fixture(t);
f.state.pending = 1;
const result = await f.invoke([
'task',
'run',
'12',
'--wait',
'--timeout',
'5',
]);
assert.equal(result.code, 0, result.err);
assert.deepEqual(JSON.parse(result.out).data, {
taskId: 12,
action: 'run',
accepted: true,
triggerId,
state: 'finished',
reason: null,
exitCode: 0,
});
assert.equal(f.state.polls, 2);
assert.equal(f.requests.filter((r) => r.method === 'PUT').length, 1);
const log = await f.invoke([
'task',
'logs',
'12',
'--trigger-id',
triggerId,
'--tail',
'1',
]);
assert.equal(log.code, 0, log.err);
assert.deepEqual(JSON.parse(log.out), {
code: 200,
data: 'last line',
triggerId,
logStatus: 'completed',
truncated: true,
});
assert.equal(f.requests.at(-1).query.get('triggerId'), triggerId);
});
test('each non-success terminal state returns structured outcome and never reruns', async (t) => {
const f = await fixture(t);
for (const [state, reason, exit_code] of [
['failed', 'exit', 17],
['skipped', 'overlap', null],
['stopped', 'manual', null],
['unknown', 'restart', null],
['finished', 'exit_pending', null],
]) {
f.state.rows = [{ id: triggerId, cron_id: 12, state, reason, exit_code }];
const error = failure(
await f.invoke(['task', 'wait', '12', '--trigger-id', triggerId]),
);
assert.deepEqual(error.data, {
taskId: 12,
action: 'wait',
triggerId,
state,
reason,
exitCode: exit_code,
});
}
assert.ok(f.requests.every((r) => r.method === 'GET'));
});
test('timeouts bound polling and in-flight reads, retain the trigger and never stop it', async (t) => {
for (const hang of [false, true]) {
const f = await fixture(t);
f.state.pending = Infinity;
f.state.hang = hang;
const start = Date.now();
const error = failure(
await f.invoke(['task', 'run', '12', '--wait', '--timeout', '1']),
);
assert.equal(error.data.triggerId, triggerId);
assert.equal(error.data.waitStatus, 'timeout');
assert.ok(Date.now() - start < 5000);
assert.equal(f.requests.filter((r) => r.method === 'PUT').length, 1);
f.state.pending = 0;
f.state.hang = false;
const resumed = await f.invoke([
'task',
'wait',
'12',
'--trigger-id',
triggerId,
]);
assert.equal(resumed.code, 0, resumed.err);
assert.equal(JSON.parse(resumed.out).data.action, 'wait');
assert.equal(f.requests.filter((r) => r.method === 'PUT').length, 1);
}
});
test('missing, mismatched or malformed receipts never fall back to the latest run', async (t) => {
const f = await fixture(t);
for (const rows of [
[],
[{ id: 'sibling', cron_id: 12 }],
[{ id: triggerId, cron_id: 13 }],
[{ ...f.state.rows[0], state: 'invalid' }],
[{ ...f.state.rows[0], state: ['finished'] }],
[{ ...f.state.rows[0], exit_code: '0' }],
{ data: [] },
[f.state.rows[0], f.state.rows[0]],
]) {
f.state.rows = rows;
const error = failure(
await f.invoke(['task', 'wait', '12', '--trigger-id', triggerId]),
);
assert.equal(error.data.triggerId, triggerId);
assert.ok(['invalidResponse', 'notFound'].includes(error.data.waitStatus));
}
for (const data of [
[],
{},
[{ taskId: 13, triggerId }],
[{ taskId: 12, triggerId: 'bad id', state: 'queued', reason: null }],
]) {
f.state.run = data;
failure(await f.invoke(['task', 'run', '12', '--wait']));
}
});
test('legacy or mismatched log responses are rejected only when selecting a trigger', async (t) => {
const f = await fixture(t);
for (const id of [undefined, 'another-trigger']) {
f.state.log.triggerId = id;
const result = await f.invoke([
'task',
'logs',
'12',
'--trigger-id',
triggerId,
]);
assert.match(failure(result).message, /did not confirm the log trigger ID/);
const latest = await f.invoke(['task', 'logs', '12']);
assert.equal(latest.code, 0, latest.err);
assert.equal(JSON.parse(latest.out).triggerId, undefined);
assert.equal(f.requests.at(-1).query.has('triggerId'), false);
}
});
test('auth and network failures retain the trigger without replaying mutations', async (t) => {
for (const mode of ['denied', 'disconnect']) {
const f = await fixture(t);
f.state[mode] = true;
const error = failure(
await f.invoke(['task', 'run', '12', '--wait']),
mode === 'denied' ? 3 : 1,
);
assert.equal(error.data.triggerId, triggerId);
assert.equal(error.data.waitStatus, 'interrupted');
assert.equal(f.requests.length, 2);
assert.doesNotMatch(JSON.stringify(error), /Bearer fixture/);
}
});
test('new option validation happens before any network access and errors are bilingual', async (t) => {
const f = await fixture(t);
for (const args of [
['task', 'run', '12', '--timeout', '10'],
['task', 'run', '12', '--wait', '--timeout', '0'],
['task', 'run', '12', '--wait', '--timeout', '86401'],
['task', 'wait', '12'],
['task', 'wait', '12', '--trigger-id', 'bad id'],
['task', 'logs', '12', '--trigger-id', 'a'.repeat(257)],
])
failure(await f.invoke(args), 2);
assert.equal(f.requests.length, 0);
f.state.rows = [];
const error = failure(
await f.invoke(['task', 'wait', '12', '--trigger-id', triggerId], 'zh'),
);
assert.match(error.message, /不存在、已清理或不属于该任务/);
});
+68 -19
View File
@@ -6,38 +6,87 @@ const fs = require('node:fs');
const path = require('node:path');
test('Commander adapter preserves literal values, option polarity, duplicate errors and IDs', () => {
assert.equal(parse(['task','list','--search','00123']).values.search, '00123');
assert.equal(parse(['local','start','--no-startup'], 'local').values['no-startup'], true);
assert.equal(parse(['local','start'], 'local').values['no-startup'], undefined);
assert.equal(parse(['auth','login','--url=--json']).values.url, '--json');
assert.deepEqual(parse(['local','resetpwd','--','-literal'], 'local').positionals, ['-literal']);
assert.equal(
parse(['task', 'list', '--search', '00123']).values.search,
'00123',
);
assert.equal(
parse(['local', 'start', '--no-startup'], 'local').values['no-startup'],
true,
);
assert.equal(
parse(['local', 'start'], 'local').values['no-startup'],
undefined,
);
assert.equal(parse(['auth', 'login', '--url=--json']).values.url, '--json');
assert.deepEqual(
parse(['local', 'resetpwd', '--', '-literal'], 'local').positionals,
['-literal'],
);
for (const args of [
['task','list','--search','--json'], ['auth','login','--url','--json'],
['task','list','-p','2','--page','3'], ['task','list','--json','--json'],
['--json','task','list','--json'], ['task','list','unexpected'],
['task','run','0'], ['task','run','script.js'], ['task','list','--size','201'],
['task','list','--json=false'],
]) assert.throws(() => parse(args), { exitCode:2 }, JSON.stringify(args));
assert.ok(parse(['auth','login','--help']).help);
['task', 'list', '--search', '--json'],
['auth', 'login', '--url', '--json'],
['task', 'list', '-p', '2', '--page', '3'],
['task', 'list', '--json', '--json'],
['--json', 'task', 'list', '--json'],
['task', 'list', 'unexpected'],
['task', 'run', '0'],
['task', 'run', 'script.js'],
['task', 'list', '--size', '201'],
['task', 'list', '--json=false'],
])
assert.throws(() => parse(args), { exitCode: 2 }, JSON.stringify(args));
assert.ok(parse(['auth', 'login', '--help']).help);
assert.ok(parse(['--help']).help);
});
test('Commander task parsing stops at the script and preserves the execution separator', () => {
const args = ['--root','/isolated','--json','script.sh','now','--','--json','--root','-literal'];
const args = [
'--root',
'/isolated',
'--json',
'script.sh',
'now',
'--',
'--json',
'--root',
'-literal',
];
const parsed = parseExecution(args);
assert.equal(parsed.values.root, '/isolated');
assert.equal(parsed.values.json, true);
assert.deepEqual(parsed.execution.scriptArgs, ['--json','--root','-literal']);
assert.deepEqual(parseExecution(['script.sh','--json']).execution.argv, ['script.sh','--json']);
assert.deepEqual(parseExecution(['--','-script','--','-x']).execution.scriptArgs, ['-x']);
assert.throws(() => parseExecution(['--root','--json','script.sh']), { exitCode:2 });
assert.deepEqual(parsed.execution.scriptArgs, [
'--json',
'--root',
'-literal',
]);
assert.deepEqual(parseExecution(['script.sh', '--json']).execution.argv, [
'script.sh',
'--json',
]);
assert.deepEqual(
parseExecution(['--', '-script', '--', '-x']).execution.scriptArgs,
['-x'],
);
assert.throws(() => parseExecution(['--root', '--json', 'script.sh']), {
exitCode: 2,
});
});
test('Commander is bundled once with its license and has no external runtime resolution', () => {
const manifest = require('../../package.json');
assert.equal(manifest.devDependencies.commander, '15.0.0');
assert.equal(Object.keys(manifest.dependencies || {}).length, 0);
const bundled = fs.readFileSync(path.join(__dirname,'../../dist/shared/cli/commander.js'), 'utf8');
const bundled = fs.readFileSync(
path.join(__dirname, '../../dist/shared/cli/commander.js'),
'utf8',
);
assert.doesNotMatch(bundled, /require\(["']commander["']\)/);
assert.match(fs.readFileSync(path.join(__dirname,'../../dist/licenses/commander-LICENSE'), 'utf8'), /MIT/);
assert.match(
fs.readFileSync(
path.join(__dirname, '../../dist/licenses/commander-LICENSE'),
'utf8',
),
/MIT/,
);
});
+4 -6
View File
@@ -82,11 +82,7 @@ test('maintenance log banners honor Chinese fallback and English selection', asy
});
test('standalone entry help supports both languages without panel or repository setup', () => {
for (const entry of [
'runner',
'compat',
'subscription-worker',
]) {
for (const entry of ['runner', 'compat', 'subscription-worker']) {
for (const language of ['en', 'zh']) {
const result = spawnSync(
process.execPath,
@@ -113,7 +109,9 @@ test('standalone entry help supports both languages without panel or repository
test('task, maintenance and subscription failure warnings honor locale without failing completed work', async (t) => {
const { LocalApi } = require('../../dist/internal/runtime/api');
const { executeTask } = require('../../dist/internal/execution/taskRunner');
const { syncRepository } = require('../../dist/internal/subscription/subscriptionRunner');
const {
syncRepository,
} = require('../../dist/internal/subscription/subscriptionRunner');
const { withOperationOutput } = require('../../dist/internal/runtime/output');
const { execFileSync } = require('node:child_process');
const git = process.platform === 'darwin' ? '/usr/bin/git' : 'git';