mirror of
https://github.com/whyour/qinglong.git
synced 2026-12-01 09:45:36 +08:00
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:
1 parent
77ece406ac
commit
c5458596c8
346 files changed
+32133
-11556
No files matched your search
@@ -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);
|
||||
|
||||
@@ -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
@@ -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, '');
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
});
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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, /不存在、已清理或不属于该任务/);
|
||||
});
|
||||
Reference in new issue
Block a user