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

+104 -26
View File
@@ -6,38 +6,91 @@ const ts = require('typescript');
// Exercise the real list effect while explicitly releasing each HTTP response.
function listEffect() {
const source = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/index.tsx'), 'utf8');
const ast = ts.createSourceFile('index.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const source = fs.readFileSync(
path.join(__dirname, '../../src/pages/crontab/index.tsx'),
'utf8',
);
const ast = ts.createSourceFile(
'index.tsx',
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
const effects = [];
function visit(node) {
if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect' &&
node.arguments[1]?.getText(ast).includes('searchText')) effects.push(node.arguments[0]);
if (
ts.isCallExpression(node) &&
node.expression.getText(ast) === 'useEffect' &&
node.arguments[1]?.getText(ast).includes('searchText')
)
effects.push(node.arguments[0]);
ts.forEachChild(node, visit);
}
visit(ast);
assert.equal(effects.length, 1);
const js = ts.transpile('const effect = ' + effects[0].getText(ast), {target: ts.ScriptTarget.ES2022});
const requests = [], timers = new Set(), rows = [], totals = [], failures = [];
const js = ts.transpile('const effect = ' + effects[0].getText(ast), {
target: ts.ScriptTarget.ES2022,
});
const requests = [],
timers = new Set(),
rows = [],
totals = [],
failures = [];
const bindings = {
pageConf: { page: 1, size: 20 }, viewConf: null, config: {apiPrefix: '/api/'},
request: { get(url, options) {
return new Promise((resolve, reject) => requests.push({url, options, resolve, reject}));
} }, setValue: value => rows.push(value), setTotal: value => totals.push(value),
setLoading() {}, setListFailed(failed) { failures.push(failed); },
setTimeout(fn) { timers.add(fn); return fn; }, clearTimeout(fn) { timers.delete(fn); },
pageConf: { page: 1, size: 20 },
viewConf: null,
config: { apiPrefix: '/api/' },
request: {
get(url, options) {
return new Promise((resolve, reject) =>
requests.push({ url, options, resolve, reject }),
);
},
},
setValue: (value) => rows.push(value),
setTotal: (value) => totals.push(value),
setLoading() {},
setListFailed(failed) {
failures.push(failed);
},
setTimeout(fn) {
timers.add(fn);
return fn;
},
clearTimeout(fn) {
timers.delete(fn);
},
};
return {
requests,
timers,
rows,
totals,
failures,
start(searchText) {
return Function(
'searchText',
...Object.keys(bindings),
js + '\nreturn effect();',
)(searchText, ...Object.values(bindings));
},
};
return { requests, timers, rows, totals, failures, start(searchText) {
return Function('searchText', ...Object.keys(bindings), js + '\nreturn effect();')(searchText, ...Object.values(bindings));
} };
}
const flush = () => new Promise(resolve => setImmediate(resolve));
const page = (id, sub_id) => ({code: 200, data: {data: [{id, sub_id}], total: 1}});
const flush = () => new Promise((resolve) => setImmediate(resolve));
const page = (id, sub_id) => ({
code: 200,
data: { data: [{ id, sub_id }], total: 1 },
});
test('switching searches discards stale list and subscription responses and cancels old polling', async () => {
for (const delaySubscription of [false, true]) {
const view = listEffect();
const closeA = view.start('A');
if (delaySubscription) { view.requests[0].resolve(page(1, 7)); await flush(); }
if (delaySubscription) {
view.requests[0].resolve(page(1, 7));
await flush();
}
const stale = view.requests.at(-1);
closeA();
assert.ok(stale.options.signal.aborted);
@@ -46,9 +99,14 @@ test('switching searches discards stale list and subscription responses and canc
assert.equal(fresh.options.params.searchValue, 'B&+');
fresh.resolve(page(2));
await flush();
stale.resolve(delaySubscription ? {code: 200, data: [{id: 7}]} : page(1, 7));
stale.resolve(
delaySubscription ? { code: 200, data: [{ id: 7 }] } : page(1, 7),
);
await flush();
assert.deepEqual(view.rows.map(rows => rows.map(r => r.id)), [[2]]);
assert.deepEqual(
view.rows.map((rows) => rows.map((r) => r.id)),
[[2]],
);
assert.deepEqual(view.totals, [1]);
assert.equal(view.requests.length, delaySubscription ? 3 : 2);
assert.equal(view.timers.size, 1);
@@ -75,18 +133,35 @@ test('list polling recovers on the next tick after a network failure', async ()
});
test('the next search can be submitted while the table request is in flight', () => {
const source = fs.readFileSync(path.join(__dirname, '../../src/pages/crontab/index.tsx'), 'utf8');
const ast = ts.createSourceFile('index.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const source = fs.readFileSync(
path.join(__dirname, '../../src/pages/crontab/index.tsx'),
'utf8',
);
const ast = ts.createSourceFile(
'index.tsx',
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
const controls = [];
function visit(node) {
if (ts.isJsxSelfClosingElement(node) && node.tagName.getText(ast) === 'Search') controls.push(node);
if (
ts.isJsxSelfClosingElement(node) &&
node.tagName.getText(ast) === 'Search'
)
controls.push(node);
ts.forEachChild(node, visit);
}
visit(ast);
assert.equal(controls.length, 1);
const attributes = controls[0].attributes.properties.map(p => p.name?.getText(ast));
const attributes = controls[0].attributes.properties.map((p) =>
p.name?.getText(ast),
);
assert.ok(attributes.includes('onSearch'));
assert.ok(!attributes.includes('loading') && !attributes.includes('disabled'));
assert.ok(
!attributes.includes('loading') && !attributes.includes('disabled'),
);
});
test('a failed subscription lookup still displays the current task list', async () => {
@@ -96,7 +171,10 @@ test('a failed subscription lookup still displays the current task list', async
await flush();
view.requests[1].reject(Error('offline'));
await flush();
assert.deepEqual(view.rows[0].map(row => row.id), [42]);
assert.deepEqual(
view.rows[0].map((row) => row.id),
[42],
);
assert.deepEqual(view.totals, [1]);
stop();
});
+129 -48
View File
@@ -40,7 +40,12 @@ function fixture(get) {
config: { apiPrefix: '/api/' },
cron: { id: 1 },
session: { current: new AbortController() },
pinnedTrigger: {}, reading: {current: false}, drained: {}, lastPath: {}, lastCursor: {}, scrollTimer: {},
pinnedTrigger: {},
reading: { current: false },
drained: {},
lastPath: {},
lastCursor: {},
scrollTimer: {},
LOG_CHUNK_BYTES: 256 * 1024,
MAX_LOG_VIEW_CHARS: 1024 * 1024,
logOffsetRef: { current: undefined },
@@ -54,8 +59,12 @@ function fixture(get) {
},
},
intl: { get: (value) => value },
setLoading(value) { values.loading = value; },
setReadFailed(value) { values.failed = value; },
setLoading(value) {
values.loading = value;
},
setReadFailed(value) {
values.failed = value;
},
autoScroll() {},
handleCancel() {},
setValue(value) {
@@ -87,7 +96,9 @@ function fixture(get) {
return {
values,
timers,
retry() { context.getCronLog(context.logOffsetRef.current === undefined); },
retry() {
context.getCronLog(context.logOffsetRef.current === undefined);
},
start() {
context.getCronLog(true);
},
@@ -228,12 +239,17 @@ test('first log read failure is recoverable on retry', async () => {
test('independent log readers can receive responses in reverse order across close and reopen', async () => {
let resolveOld;
const old = fixture(() => new Promise(resolve => { resolveOld = resolve; }));
const old = fixture(
() =>
new Promise((resolve) => {
resolveOld = resolve;
}),
);
old.start();
old.close();
const current = fixture(async () => ({code: 200, data: 'new log'}));
const current = fixture(async () => ({ code: 200, data: 'new log' }));
await current.read();
resolveOld({code: 200, data: 'old log', logStatus: 'running'});
resolveOld({ code: 200, data: 'old log', logStatus: 'running' });
await old.settle();
assert.equal(current.values.content, 'new log');
assert.equal(old.values.content, '');
@@ -242,7 +258,10 @@ test('independent log readers can receive responses in reverse order across clos
test('repeated retries share one in-flight read and closing aborts its transport', async () => {
const pending = [];
const view = fixture((url, { signal }) => new Promise(resolve => pending.push({ signal, resolve })));
const view = fixture(
(url, { signal }) =>
new Promise((resolve) => pending.push({ signal, resolve })),
);
view.start();
view.retry();
assert.equal(pending.length, 1);
@@ -257,25 +276,43 @@ test('repeated retries share one in-flight read and closing aborts its transport
test('polling a missing log displays its status once and retries from the last confirmed byte', async () => {
const calls = [];
const responses = [
{data: 'waiting', total: 0, nextOffset: 0}, {data: 'waiting', total: 0, nextOffset: 0},
{data: 'abc', total: 3, nextOffset: 3, logPath: 'a'}, null,
{data: 'd', total: 4, nextOffset: 4, logPath: 'a'},
{data: 'new!', total: 4, nextOffset: 4, logPath: 'b', logStatus: 'completed'},
{ data: 'waiting', total: 0, nextOffset: 0 },
{ data: 'waiting', total: 0, nextOffset: 0 },
{ data: 'abc', total: 3, nextOffset: 3, logPath: 'a' },
null,
{ data: 'd', total: 4, nextOffset: 4, logPath: 'a' },
{
data: 'new!',
total: 4,
nextOffset: 4,
logPath: 'b',
logStatus: 'completed',
},
];
const view = fixture(async url => {
const view = fixture(async (url) => {
calls.push(new URL(url, 'http://localhost').searchParams);
const r = responses.shift();
if (!r) throw Error('offline');
return {code: 200, logStatus: 'running', ...r};
return { code: 200, logStatus: 'running', ...r };
});
await view.read(); await view.tick();
await view.read();
await view.tick();
assert.equal(view.values.content, 'waiting');
await view.tick(); await view.tick();
await view.tick();
await view.tick();
assert.equal(view.values.failed, true);
assert.equal(view.values.content, 'abc');
view.retry(); view.retry(); await view.settle();
view.retry();
view.retry();
await view.settle();
assert.equal(view.values.content, 'abcd');
assert.deepEqual(calls.slice(3).map(p => [p.get('offset'), p.get('previousPath')]), [['3','a'],['3','a']]);
assert.deepEqual(
calls.slice(3).map((p) => [p.get('offset'), p.get('previousPath')]),
[
['3', 'a'],
['3', 'a'],
],
);
await view.tick();
assert.equal(view.values.content, 'new!');
assert.equal(view.timers.size, 0);
@@ -283,21 +320,28 @@ test('polling a missing log displays its status once and retries from the last c
test('a shortened file during a retry is reread from its new tail', async () => {
const responses = [
{data: 'previous log', nextOffset: 12, total: 12}, {data: '', nextOffset: 3, total: 3},
{data: 'new', nextOffset: 3, total: 3},
{ data: 'previous log', nextOffset: 12, total: 12 },
{ data: '', nextOffset: 3, total: 3 },
{ data: 'new', nextOffset: 3, total: 3 },
];
const calls = [];
const view = fixture(async url => {
const view = fixture(async (url) => {
calls.push(url);
return {code: 200, logStatus: responses.length === 3 ? 'running' : 'completed', ...responses.shift()};
return {
code: 200,
logStatus: responses.length === 3 ? 'running' : 'completed',
...responses.shift(),
};
});
await view.read(); await view.tick(); await view.tick();
await view.read();
await view.tick();
await view.tick();
assert.match(calls[2], /tail=true/);
assert.equal(view.values.content, 'new');
assert.equal(view.timers.size, 0);
});
test('retry after a truncate and regrow replaces displayed bytes and drains all pages exactly once', async t => {
test('retry after a truncate and regrow replaces displayed bytes and drains all pages exactly once', async (t) => {
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), 'ql-log-regrow-'));
t.after(() => fsp.rm(dir, { recursive: true, force: true }));
const file = path.join(dir, 'run.log');
@@ -305,23 +349,34 @@ test('retry after a truncate and regrow replaces displayed bytes and drains all
let running = true;
let fail = false;
const offsets = [];
const view = fixture(async url => {
const view = fixture(async (url) => {
const p = new URL(url, 'http://localhost').searchParams;
const offset = p.has('offset') ? Number(p.get('offset')) : undefined;
offsets.push(offset);
if (fail) throw Error('timeout');
const chunk = await readLogChunk(file, {
offset, follow: p.get('follow') === 'true', cursor: p.get('cursor'),
tail: p.get('tail') === 'true', limit: Number(p.get('limit')),
offset,
follow: p.get('follow') === 'true',
cursor: p.get('cursor'),
tail: p.get('tail') === 'true',
limit: Number(p.get('limit')),
});
return { ...chunk, code: 200, data: chunk.content, logPath: 'run.log',
logStatus: running ? 'running' : 'completed' };
return {
...chunk,
code: 200,
data: chunk.content,
logPath: 'run.log',
logStatus: running ? 'running' : 'completed',
};
});
await view.read();
fail = true;
await view.tick();
assert.equal(view.values.failed, true);
const current = Array.from({ length: 16000 }, (_, i) => `${i} · 中文日志🚀\n`).join('');
const current = Array.from(
{ length: 16000 },
(_, i) => `${i} · 中文日志🚀\n`,
).join('');
await fsp.writeFile(file, current);
fail = running = false;
view.retry();
@@ -338,42 +393,68 @@ test('retry after a truncate and regrow replaces displayed bytes and drains all
test('a fresh list snapshot wakes a drained live viewer only for a new path or active task', () => {
const effects = [];
function visitEffect(node) {
if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect' &&
node.arguments[1]?.getText(ast) === '[cron]') effects.push(node.arguments[0]);
if (
ts.isCallExpression(node) &&
node.expression.getText(ast) === 'useEffect' &&
node.arguments[1]?.getText(ast) === '[cron]'
)
effects.push(node.arguments[0]);
ts.forEachChild(node, visitEffect);
}
visitEffect(ast);
assert.equal(effects.length, 1);
const wake = ts.transpile('var wake = ' + effects[0].getText(ast), {target: ts.ScriptTarget.ES2020});
const wake = ts.transpile('var wake = ' + effects[0].getText(ast), {
target: ts.ScriptTarget.ES2020,
});
let calls = 0;
const context = { cron: { log_path: 'old', status: 1 }, lastPath: {current: 'old'},
drained: {current: true}, pinnedTrigger: {}, logUrl: undefined,
CrontabStatus: {running: 0, queued: 3}, getCronLog: () => calls++ };
const context = {
cron: { log_path: 'old', status: 1 },
lastPath: { current: 'old' },
drained: { current: true },
pinnedTrigger: {},
logUrl: undefined,
CrontabStatus: { running: 0, queued: 3 },
getCronLog: () => calls++,
};
const update = () => vm.runInNewContext(wake + '\nwake()', context);
update(); assert.equal(calls, 0);
context.cron = {log_path: 'new', status: 1};
update(); assert.equal(calls, 1);
context.cron = {log_path: 'old', status: 3};
update(); assert.equal(calls, 2);
update();
assert.equal(calls, 0);
context.cron = { log_path: 'new', status: 1 };
update();
assert.equal(calls, 1);
context.cron = { log_path: 'old', status: 3 };
update();
assert.equal(calls, 2);
context.drained.current = false;
update(); assert.equal(calls, 2);
update();
assert.equal(calls, 2);
context.drained.current = true;
context.logUrl = '/api/logs/detail?file=old';
update(); assert.equal(calls, 2);
update();
assert.equal(calls, 2);
});
test('concurrent live log polling and retries stay scoped to the initially selected trigger', async () => {
const calls = [];
const view = fixture(async url => {
const view = fixture(async (url) => {
const p = new URL(url, 'http://localhost').searchParams;
calls.push(p.get('triggerId'));
if (calls.length === 2) throw Error('timeout');
const selected = p.get('triggerId') || (calls.length === 1 ? 'a' : 'b');
return { code: 200, triggerId: selected, logPath: selected + '.log', total: calls.length === 1 ? 1 : 2,
nextOffset: calls.length === 1 ? 1 : 2, logStatus: calls.length < 3 ? 'running' : 'completed',
data: calls.length === 1 ? 'A' : selected === 'a' ? '!' : 'B!' };
return {
code: 200,
triggerId: selected,
logPath: selected + '.log',
total: calls.length === 1 ? 1 : 2,
nextOffset: calls.length === 1 ? 1 : 2,
logStatus: calls.length < 3 ? 'running' : 'completed',
data: calls.length === 1 ? 'A' : selected === 'a' ? '!' : 'B!',
};
});
await view.read(); await view.tick(); view.retry(); await view.settle();
await view.read();
await view.tick();
view.retry();
await view.settle();
assert.deepEqual(calls, [null, 'a', 'a']);
assert.equal(view.values.content, 'A!');
assert.equal(view.timers.size, 0);
+478 -141
View File
@@ -4,51 +4,107 @@ const fs = require('node:fs');
const ts = require('typescript');
function dashboard(anomaly) {
const source = fs.readFileSync(require.resolve('../../src/pages/dashboard/index.tsx'), 'utf8');
const ast = ts.createSourceFile('dashboard.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const source = fs.readFileSync(
require.resolve('../../src/pages/dashboard/index.tsx'),
'utf8',
);
const ast = ts.createSourceFile(
'dashboard.tsx',
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
let effect;
function visit(node) {
if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect' &&
node.arguments[0].getText(ast).includes('setOverview')) effect = node.arguments[0].getText(ast);
if (
ts.isCallExpression(node) &&
node.expression.getText(ast) === 'useEffect' &&
node.arguments[0].getText(ast).includes('setOverview')
)
effect = node.arguments[0].getText(ast);
ts.forEachChild(node, visit);
}
visit(ast);
assert.ok(effect);
const requests = [], results = [], failures = [], timers = new Set();
const requests = [],
results = [],
failures = [],
timers = new Set();
const noop = () => {};
const bindings = {
performance: { now: () => 1000 },
anomaly, config: { apiPrefix: '/api/' }, REFRESH_INTERVAL: 30000,
setOverview: value => results.push(value), setOverviewFailed: value => failures.push(value),
setLoading: noop, setTrend: noop, setSystem: noop, setTopTime: noop, setTopCount: noop, setLabels: noop, setRuntime: noop,
setInterval(fn) { timers.add(fn); return fn; }, clearInterval(fn) { timers.delete(fn); },
request: { get(url, options) {
return new Promise((resolve, reject) => requests.push({ url, options, resolve, reject }));
} },
anomaly,
config: { apiPrefix: '/api/' },
REFRESH_INTERVAL: 30000,
setOverview: (value) => results.push(value),
setOverviewFailed: (value) => failures.push(value),
setLoading: noop,
setTrend: noop,
setSystem: noop,
setTopTime: noop,
setTopCount: noop,
setLabels: noop,
setRuntime: noop,
setInterval(fn) {
timers.add(fn);
return fn;
},
clearInterval(fn) {
timers.delete(fn);
},
request: {
get(url, options) {
return new Promise((resolve, reject) =>
requests.push({ url, options, resolve, reject }),
);
},
},
};
const js = ts.transpile('const start = ' + effect, { target: ts.ScriptTarget.ES2022 });
const js = ts.transpile('const start = ' + effect, {
target: ts.ScriptTarget.ES2022,
});
return {
start: Function(...Object.keys(bindings), js + '\nreturn start;')(...Object.values(bindings)),
tick() { for (const fn of timers) fn(); }, timers, results, failures,
requests: section => requests.filter(r => r.url === '/api/dashboard/' + section),
start: Function(
...Object.keys(bindings),
js + '\nreturn start;',
)(...Object.values(bindings)),
tick() {
for (const fn of timers) fn();
},
timers,
results,
failures,
requests: (section) =>
requests.filter((r) => r.url === '/api/dashboard/' + section),
};
}
const flush = () => new Promise(resolve => setImmediate(resolve));
const flush = () => new Promise((resolve) => setImmediate(resolve));
test('a first anomaly request that never succeeds still expires using the overview deadline', async () => {
const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100, deadline: 10000 };
const v = anomalies(),
selection = { source: 'panel', kind: 'missing', at: 100, deadline: 10000 };
const close = v.start(selection, { page: 1 });
v.tick(10000);
assert.deepEqual(v.invalidated, [{ selection, reason: 'expired' }]);
assert.equal(v.requests[0].signal.aborted, true);
v.requests[0].resolve({ code: 200, data: { rows: ['yesterday'], summary: {} } });
v.requests[0].resolve({
code: 200,
data: { rows: ['yesterday'], summary: {} },
});
await flush();
assert.deepEqual(v.received, []);
close();
});
test('a first failure and manual retry cannot reset the overview deadline', async () => {
const v = anomalies(), selection = { source: 'system', kind: 'unconfirmed', at: 100, deadline: 10000 };
const v = anomalies(),
selection = {
source: 'system',
kind: 'unconfirmed',
at: 100,
deadline: 10000,
};
const close = v.start(selection, { page: 1 });
v.requests[0].reject(new Error('offline'));
await flush();
@@ -62,7 +118,8 @@ test('a first failure and manual retry cannot reset the overview deadline', asyn
});
test('opening an already expired overview does not send an obsolete detail request', () => {
const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100, deadline: 1000 };
const v = anomalies(),
selection = { source: 'panel', kind: 'missing', at: 100, deadline: 1000 };
v.advance(1001);
const close = v.start(selection, { page: 1 });
assert.equal(v.requests.length, 0);
@@ -71,16 +128,21 @@ test('opening an already expired overview does not send an obsolete detail reque
});
test('overview deadlines use server time and request start, independent of the browser wall clock', async () => {
const v = dashboard(), close = v.start();
const v = dashboard(),
close = v.start();
const serverNow = 1795017590000;
v.requests('overview')[0].resolve({ code: 200, data: { serverNow, expiresAt: serverNow + 10000 } });
v.requests('overview')[0].resolve({
code: 200,
data: { serverNow, expiresAt: serverNow + 10000 },
});
await flush();
assert.equal(v.results[0].anomalyDeadline, 11000);
close();
});
test('slow dashboard cards do not block crond counts, overlap a pending refresh or restart polling after unmount', async () => {
const view = dashboard(), leave = view.start();
const view = dashboard(),
leave = view.start();
view.tick();
assert.equal(view.requests('overview').length, 1);
view.requests('overview')[0].resolve({ code: 200, data: { actualSkips: 0 } });
@@ -107,7 +169,11 @@ test('slow dashboard cards do not block crond counts, overlap a pending refresh
await flush();
stale.resolve({ code: 200, data: { actualSkips: 0 } });
await flush();
assert.deepEqual(view.results, [{ actualSkips: 0 }, { actualSkips: 1 }, { actualSkips: 2 }]);
assert.deepEqual(view.results, [
{ actualSkips: 0 },
{ actualSkips: 1 },
{ actualSkips: 2 },
]);
assert.deepEqual(view.failures, [false, true, false, false]);
assert.equal(view.timers.size, 1);
closeAgain();
@@ -117,47 +183,114 @@ test('system crond results distinguish missing records, unknown exits and record
const intl = require('react-intl-universal');
const messages = require('../../src/locales/zh-CN.json');
await intl.init({ currentLocale: 'zh-CN', locales: { 'zh-CN': messages } });
const source = fs.readFileSync(require.resolve('../../src/pages/dashboard/index.tsx'), 'utf8');
const ast = ts.createSourceFile('dashboard.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const source = fs.readFileSync(
require.resolve('../../src/pages/dashboard/index.tsx'),
'utf8',
);
const ast = ts.createSourceFile(
'dashboard.tsx',
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
let renderer;
function visit(node) {
if (ts.isObjectLiteralExpression(node) && node.properties.some(p =>
ts.isPropertyAssignment(p) && p.name.getText(ast) === 'title' &&
p.initializer.getText(ast) === "intl.get('执行情况')")) {
renderer = node.properties.find(p => p.name.getText(ast) === 'render').initializer;
if (
ts.isObjectLiteralExpression(node) &&
node.properties.some(
(p) =>
ts.isPropertyAssignment(p) &&
p.name.getText(ast) === 'title' &&
p.initializer.getText(ast) === "intl.get('执行情况')",
)
) {
renderer = node.properties.find(
(p) => p.name.getText(ast) === 'render',
).initializer;
}
ts.forEachChild(node, visit);
}
visit(ast);
assert.ok(renderer);
const js = ts.transpileModule('const render = ' + renderer.getText(ast), {
fileName: 'cell.tsx', compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 },
fileName: 'cell.tsx',
compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 },
}).outputText;
const cell = Function('React', 'intl', js + '\nreturn render;')(require('react'), intl);
const html = row => require('react-dom/server').renderToStaticMarkup(cell(null, row));
const cell = Function(
'React',
'intl',
js + '\nreturn render;',
)(require('react'), intl);
const html = (row) =>
require('react-dom/server').renderToStaticMarkup(cell(null, row));
assert.equal(html({ status: 'missing', triggerCount: 0 }), '未收到触发记录');
assert.equal(html({ status: 'skipped', triggerCount: 1, skipCount: 1 }), '已跳过');
assert.equal(
html({ status: 'skipped', triggerCount: 1, skipCount: 1 }),
'已跳过',
);
assert.equal(html({ status: 'started' }), '命令已启动');
assert.equal(html({ status: 'started', triggerCount: 1, startCount: 1, unknownExitCount: 1 }),
'命令已启动 · 结果未知');
assert.equal(html({ status: 'started', triggerCount: 2, startCount: 1, skipCount: 1, unknownExitCount: 1 }),
'启动 1 次 · 跳过 1 次 · 其中 1 次执行结果未知');
assert.equal(
html({
status: 'started',
triggerCount: 1,
startCount: 1,
unknownExitCount: 1,
}),
'命令已启动 · 结果未知',
);
assert.equal(
html({
status: 'started',
triggerCount: 2,
startCount: 1,
skipCount: 1,
unknownExitCount: 1,
}),
'启动 1 次 · 跳过 1 次 · 其中 1 次执行结果未知',
);
});
test('dashboard timing preserves millisecond precision, rounds long waits and distinguishes zero from no samples', async () => {
const intl = require('react-intl-universal');
const locales = { 'zh-CN': require('../../src/locales/zh-CN.json'), 'en-US': require('../../src/locales/en-US.json') };
const source = fs.readFileSync(require.resolve('../../src/pages/dashboard/timingStatistic.tsx'), 'utf8');
const { outputText } = ts.transpileModule(source, { compilerOptions: {
jsx: ts.JsxEmit.ReactJSX, module: ts.ModuleKind.CommonJS, esModuleInterop: true,
} });
const locales = {
'zh-CN': require('../../src/locales/zh-CN.json'),
'en-US': require('../../src/locales/en-US.json'),
};
const source = fs.readFileSync(
require.resolve('../../src/pages/dashboard/timingStatistic.tsx'),
'utf8',
);
const { outputText } = ts.transpileModule(source, {
compilerOptions: {
jsx: ts.JsxEmit.ReactJSX,
module: ts.ModuleKind.CommonJS,
esModuleInterop: true,
},
});
const component = {};
Function('require', 'exports', outputText)(require, component);
await intl.init({ currentLocale: 'zh-CN', locales });
assert.deepEqual([null, 0, 136, 1000, 5989, 59999, 60000, 119999, 1703994].map(component.formatTiming),
['—', '0 ms', '136 ms', '1 秒', '5.989 秒', '59.999 秒', '1 分 0 秒', '2 分 0 秒', '28 分 24 秒']);
const render = ms => require('react-dom/server').renderToStaticMarkup(
require('react').createElement(component.default, { title: 'P95', ms }));
assert.deepEqual(
[null, 0, 136, 1000, 5989, 59999, 60000, 119999, 1703994].map(
component.formatTiming,
),
[
'—',
'0 ms',
'136 ms',
'1 秒',
'5.989 秒',
'59.999 秒',
'1 分 0 秒',
'2 分 0 秒',
'28 分 24 秒',
],
);
const render = (ms) =>
require('react-dom/server').renderToStaticMarkup(
require('react').createElement(component.default, { title: 'P95', ms }),
);
assert.match(render(1703994), /title="1703994 ms">28 分 24 秒/);
assert.match(render(null), /—/);
assert.doesNotMatch(render(136), /个样本/);
@@ -166,56 +299,127 @@ test('dashboard timing preserves millisecond precision, rounds long waits and di
});
function anomalies() {
const filename = require.resolve('../../src/pages/dashboard/scheduleAnomalies.tsx');
const filename = require.resolve(
'../../src/pages/dashboard/scheduleAnomalies.tsx',
);
const source = fs.readFileSync(filename, 'utf8');
const ast = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const ast = ts.createSourceFile(
filename,
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
let effect;
function visit(node) {
if (ts.isCallExpression(node) && node.expression.getText(ast) === 'useEffect')
if (
ts.isCallExpression(node) &&
node.expression.getText(ast) === 'useEffect'
)
effect = node.arguments[0].getText(ast);
ts.forEachChild(node, visit);
}
visit(ast);
const js = ts.transpile('const start = ' + effect, { target: ts.ScriptTarget.ES2022 });
const requests = [], received = [], failed = [], summaries = [], invalidated = [], timers = new Map();
const js = ts.transpile('const start = ' + effect, {
target: ts.ScriptTarget.ES2022,
});
const requests = [],
received = [],
failed = [],
summaries = [],
invalidated = [],
timers = new Map();
let now = 0;
const bindings = {
expiresAt: { current: undefined },
config: { apiPrefix: '/api/' },
request: { get(url, options) {
assert.equal(url, '/api/dashboard/schedule-anomalies');
return new Promise((resolve, reject) => requests.push({ ...options, resolve, reject }));
} },
setResponse: data => received.push(data.result), setFailed: flag => failed.push(flag), setLoading() {},
request: {
get(url, options) {
assert.equal(url, '/api/dashboard/schedule-anomalies');
return new Promise((resolve, reject) =>
requests.push({ ...options, resolve, reject }),
);
},
},
setResponse: (data) => received.push(data.result),
setFailed: (flag) => failed.push(flag),
setLoading() {},
onUpdate: (selection, summary) => summaries.push(summary),
onInvalidate: (selection, reason) => invalidated.push({ selection, reason }),
onInvalidate: (selection, reason) =>
invalidated.push({ selection, reason }),
performance: { now: () => now },
setTimeout(fn, ms) { timers.set(fn, ms); return fn; }, clearTimeout(fn) { timers.delete(fn); },
setTimeout(fn, ms) {
timers.set(fn, ms);
return fn;
},
clearTimeout(fn) {
timers.delete(fn);
},
};
return {
start: (selection, query) => Function(...Object.keys(bindings), 'selection', 'query',
js + '\nreturn start();')(...Object.values(bindings), selection, query),
requests, received, failed, summaries, invalidated, timers,
advance(ms) { now += ms; },
tick(delay = 5000) { for (const [fn, ms] of [...timers]) if (ms === delay) { timers.delete(fn); fn(); } },
start: (selection, query) =>
Function(
...Object.keys(bindings),
'selection',
'query',
js + '\nreturn start();',
)(...Object.values(bindings), selection, query),
requests,
received,
failed,
summaries,
invalidated,
timers,
advance(ms) {
now += ms;
},
tick(delay = 5000) {
for (const [fn, ms] of [...timers])
if (ms === delay) {
timers.delete(fn);
fn();
}
},
};
}
test('anomaly pagination pins its plan window, advances revisions after resets and stops old polling across source changes', async () => {
const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100 };
const v = anomalies(),
selection = { source: 'panel', kind: 'missing', at: 100 };
const close = v.start(selection, { page: 2, revision: 'old' });
assert.deepEqual(v.requests[0].params, { ...selection, live: true, page: 2, revision: 'old' });
const updated = { rows: ['remaining'], page: 1, revision: 'new', total: 26, changed: true, summary: { audit: { missing: 26 } } };
assert.deepEqual(v.requests[0].params, {
...selection,
live: true,
page: 2,
revision: 'old',
});
const updated = {
rows: ['remaining'],
page: 1,
revision: 'new',
total: 26,
changed: true,
summary: { audit: { missing: 26 } },
};
v.requests[0].resolve({ code: 200, data: updated });
await flush();
assert.deepEqual(v.received, [updated]);
assert.deepEqual(v.summaries, [updated.summary]);
v.tick(); v.tick();
v.tick();
v.tick();
assert.equal(v.requests.length, 2);
assert.deepEqual(v.requests[1].params, { ...selection, live: true, page: 1, revision: 'new' });
assert.deepEqual(v.requests[1].params, {
...selection,
live: true,
page: 1,
revision: 'new',
});
close();
assert.equal(v.requests[1].signal.aborted, true);
const leave = v.start({ source: 'system', kind: 'unconfirmed', at: 200 }, { page: 1 });
const leave = v.start(
{ source: 'system', kind: 'unconfirmed', at: 200 },
{ page: 1 },
);
v.requests[1].resolve({ code: 200, data: { ...updated, total: 99 } });
v.requests[2].reject(new Error('timeout'));
await flush();
@@ -223,8 +427,17 @@ test('anomaly pagination pins its plan window, advances revisions after resets a
assert.equal(v.received.length, 1);
assert.equal(v.timers.size, 0);
leave();
const finish = v.start({ source: 'system', kind: 'unconfirmed', at: 200 }, { page: 1 });
const empty = { rows: [], page: 1, revision: 'empty', total: 0, summary: { systemAudit: { actualUnconfirmed: 0 } } };
const finish = v.start(
{ source: 'system', kind: 'unconfirmed', at: 200 },
{ page: 1 },
);
const empty = {
rows: [],
page: 1,
revision: 'empty',
total: 0,
summary: { systemAudit: { actualUnconfirmed: 0 } },
};
v.requests[3].resolve({ code: 200, data: empty });
await flush();
assert.equal(v.failed.at(-1), false);
@@ -235,48 +448,90 @@ test('anomaly pagination pins its plan window, advances revisions after resets a
});
test('opening anomaly details cancels older overview responses and keeps its counts owned by the detail snapshot', async () => {
const v = dashboard(), close = v.start();
const v = dashboard(),
close = v.start();
close();
v.requests('overview')[0].resolve({ code: 200, data: { triggers: { audit: { missing: 55 } } } });
v.requests('overview')[0].resolve({
code: 200,
data: { triggers: { audit: { missing: 55 } } },
});
await flush();
assert.deepEqual(v.results, []);
const opened = dashboard({ source: 'panel' }), leave = opened.start();
const opened = dashboard({ source: 'panel' }),
leave = opened.start();
opened.tick();
assert.equal(opened.requests('overview').length, 0);
assert.equal(opened.requests('runtime').length, 1);
leave();
});
for (const source of ['panel', 'system']) test(source + ' partial cleanup resets pagination and abandoned page replies cannot restore deleted rows after switching source', async () => {
const v = anomalies(), selection = { source, kind: 'unconfirmed', at: 100, session: 1 };
const stop = v.start(selection, { page: 3, revision: 'before-cleanup' });
const retained = { page: 1, total: 40, revision: 'after-cleanup', changed: true,
rows: [{ trigger: 'retained', hasLog: true }], summary: source === 'panel'
? { audit: { unconfirmed: 40 } } : { systemAudit: { actualUnconfirmed: 40 } } };
v.requests[0].resolve({ code: 200, data: retained });
await flush();
v.tick();
assert.equal(v.requests[1].params.page, 1);
assert.equal(v.requests[1].params.revision, 'after-cleanup');
stop();
const next = { ...selection, source: source === 'panel' ? 'system' : 'panel', session: 2 };
const close = v.start(next, { page: 1 });
const fresh = { ...retained, rows: [{ trigger: 'other-source', hasLog: true }], total: 1, revision: 'fresh',
summary: next.source === 'panel' ? { audit: { unconfirmed: 1 } } : { systemAudit: { actualUnconfirmed: 1 } } };
v.requests[2].resolve({ code: 200, data: fresh });
await flush();
v.requests[1].resolve({ code: 200, data: { ...retained, total: 60, rows: [{ trigger: 'deleted' }] } });
await flush();
assert.deepEqual(v.received, [retained, fresh]);
assert.deepEqual(v.summaries, [retained.summary, fresh.summary]);
close();
assert.equal(v.timers.size, 0);
});
for (const source of ['panel', 'system'])
test(
source +
' partial cleanup resets pagination and abandoned page replies cannot restore deleted rows after switching source',
async () => {
const v = anomalies(),
selection = { source, kind: 'unconfirmed', at: 100, session: 1 };
const stop = v.start(selection, { page: 3, revision: 'before-cleanup' });
const retained = {
page: 1,
total: 40,
revision: 'after-cleanup',
changed: true,
rows: [{ trigger: 'retained', hasLog: true }],
summary:
source === 'panel'
? { audit: { unconfirmed: 40 } }
: { systemAudit: { actualUnconfirmed: 40 } },
};
v.requests[0].resolve({ code: 200, data: retained });
await flush();
v.tick();
assert.equal(v.requests[1].params.page, 1);
assert.equal(v.requests[1].params.revision, 'after-cleanup');
stop();
const next = {
...selection,
source: source === 'panel' ? 'system' : 'panel',
session: 2,
};
const close = v.start(next, { page: 1 });
const fresh = {
...retained,
rows: [{ trigger: 'other-source', hasLog: true }],
total: 1,
revision: 'fresh',
summary:
next.source === 'panel'
? { audit: { unconfirmed: 1 } }
: { systemAudit: { actualUnconfirmed: 1 } },
};
v.requests[2].resolve({ code: 200, data: fresh });
await flush();
v.requests[1].resolve({
code: 200,
data: { ...retained, total: 60, rows: [{ trigger: 'deleted' }] },
});
await flush();
assert.deepEqual(v.received, [retained, fresh]);
assert.deepEqual(v.summaries, [retained.summary, fresh.summary]);
close();
assert.equal(v.timers.size, 0);
},
);
test('midnight cancels a hung anomaly refresh and a late reply cannot publish yesterday counts', async () => {
const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100, session: 1 };
const v = anomalies(),
selection = { source: 'panel', kind: 'missing', at: 100, session: 1 };
const leave = v.start(selection, { page: 1 });
const data = { page: 1, revision: 'before-midnight', rows: ['old'], summary: { audit: { missing: 1 } }, serverNow: 1000, expiresAt: 11000 };
const data = {
page: 1,
revision: 'before-midnight',
rows: ['old'],
summary: { audit: { missing: 1 } },
serverNow: 1000,
expiresAt: 11000,
};
v.requests[0].resolve({ code: 200, data });
await flush();
v.tick();
@@ -292,9 +547,17 @@ test('midnight cancels a hung anomaly refresh and a late reply cannot publish ye
});
test('pagination and retry preserve the midnight deadline while their requests remain hung', async () => {
const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100, session: 1 };
const v = anomalies(),
selection = { source: 'panel', kind: 'missing', at: 100, session: 1 };
const leave = v.start(selection, { page: 1 });
const data = { page: 1, revision: 'old', rows: ['old'], summary: { audit: { missing: 30 } }, serverNow: 1000, expiresAt: 11000 };
const data = {
page: 1,
revision: 'old',
rows: ['old'],
summary: { audit: { missing: 30 } },
serverNow: 1000,
expiresAt: 11000,
};
v.requests[0].resolve({ code: 200, data });
await flush();
v.advance(3000);
@@ -316,28 +579,56 @@ test('pagination and retry preserve the midnight deadline while their requests r
cancelRetry();
});
for (const status of ['expired', 'unavailable']) test('anomaly ' + status + ' closes the old session without republishing old rows or retrying', async () => {
const v = anomalies(), selection = { source: 'system', kind: 'unconfirmed', at: 100, session: 1 };
const leave = v.start(selection, { page: 2, revision: 'old' });
v.requests[0].resolve({ code: 200, data: { status } });
await flush();
assert.deepEqual(v.invalidated, [{ selection, reason: status }]);
assert.deepEqual(v.received, []);
assert.deepEqual(v.summaries, []);
assert.equal(v.timers.size, 0);
leave();
const next = { ...selection, session: 2 }, close = v.start(next, { page: 1 });
const data = { page: 1, revision: 'new', rows: [], total: 0, summary: { systemAudit: { actualUnconfirmed: 0 } } };
v.requests[1].resolve({ code: 200, data });
await flush();
assert.deepEqual(v.received, [data]);
close();
});
for (const status of ['expired', 'unavailable'])
test(
'anomaly ' +
status +
' closes the old session without republishing old rows or retrying',
async () => {
const v = anomalies(),
selection = {
source: 'system',
kind: 'unconfirmed',
at: 100,
session: 1,
};
const leave = v.start(selection, { page: 2, revision: 'old' });
v.requests[0].resolve({ code: 200, data: { status } });
await flush();
assert.deepEqual(v.invalidated, [{ selection, reason: status }]);
assert.deepEqual(v.received, []);
assert.deepEqual(v.summaries, []);
assert.equal(v.timers.size, 0);
leave();
const next = { ...selection, session: 2 },
close = v.start(next, { page: 1 });
const data = {
page: 1,
revision: 'new',
rows: [],
total: 0,
summary: { systemAudit: { actualUnconfirmed: 0 } },
};
v.requests[1].resolve({ code: 200, data });
await flush();
assert.deepEqual(v.received, [data]);
close();
},
);
test('an expired response that arrived across midnight cannot be rendered for even one poll', async () => {
const v = anomalies(), selection = { source: 'panel', kind: 'missing', at: 100 };
const v = anomalies(),
selection = { source: 'panel', kind: 'missing', at: 100 };
const close = v.start(selection, { page: 1 });
v.requests[0].resolve({ code: 200, data: { serverNow: 1000, expiresAt: 999, summary: { audit: { missing: 7 } }, rows: ['old'] } });
v.requests[0].resolve({
code: 200,
data: {
serverNow: 1000,
expiresAt: 999,
summary: { audit: { missing: 7 } },
rows: ['old'],
},
});
await flush();
assert.equal(v.invalidated[0].reason, 'expired');
assert.deepEqual(v.received, []);
@@ -347,18 +638,37 @@ test('an expired response that arrived across midnight cannot be rendered for ev
test('a queued summary update is fenced even when closing and reopening happens before effect cleanup', () => {
const file = require.resolve('../../src/pages/dashboard/index.tsx');
const source = fs.readFileSync(file, 'utf8'), ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const source = fs.readFileSync(file, 'utf8'),
ast = ts.createSourceFile(
file,
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
let callback;
function visit(node) {
if (ts.isVariableDeclaration(node) && node.name.getText(ast) === 'updateAnomalySummary')
if (
ts.isVariableDeclaration(node) &&
node.name.getText(ast) === 'updateAnomalySummary'
)
callback = node.initializer.arguments[0].getText(ast);
ts.forEachChild(node, visit);
}
visit(ast);
assert.ok(callback);
const old = { session: 1 }, next = { session: 2 }, anomalySession = { current: old }, queued = [];
const js = ts.transpile('const update = ' + callback, { target: ts.ScriptTarget.ES2022 });
const update = Function('anomalySession', 'setOverview', js + '\nreturn update;')(anomalySession, updater => queued.push(updater));
const old = { session: 1 },
next = { session: 2 },
anomalySession = { current: old },
queued = [];
const js = ts.transpile('const update = ' + callback, {
target: ts.ScriptTarget.ES2022,
});
const update = Function(
'anomalySession',
'setOverview',
js + '\nreturn update;',
)(anomalySession, (updater) => queued.push(updater));
update(old, { audit: { missing: 8 } });
anomalySession.current = next;
update(old, { audit: { missing: 9 } });
@@ -369,26 +679,52 @@ test('a queued summary update is fenced even when closing and reopening happens
test('an old invalidation cannot close a reopened session or clear its freshly queued summary', () => {
const file = require.resolve('../../src/pages/dashboard/index.tsx');
const source = fs.readFileSync(file, 'utf8'), ast = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
const source = fs.readFileSync(file, 'utf8'),
ast = ts.createSourceFile(
file,
source,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TSX,
);
let callback;
function visit(node) {
if (ts.isVariableDeclaration(node) && node.name.getText(ast) === 'invalidateAnomaly')
if (
ts.isVariableDeclaration(node) &&
node.name.getText(ast) === 'invalidateAnomaly'
)
callback = node.initializer.arguments[0].getText(ast);
ts.forEachChild(node, visit);
}
visit(ast);
assert.ok(callback);
const old = { session: 1 }, current = { session: 2 };
const anomalySession = { current }, anomalyVersion = { current: 2 };
const summaries = [], logs = [], messages = [];
const old = { session: 1 },
current = { session: 2 };
const anomalySession = { current },
anomalyVersion = { current: 2 };
const summaries = [],
logs = [],
messages = [];
let closes = 0;
const bindings = { anomalySession, anomalyVersion,
closeAnomaly() { closes++; anomalySession.current = undefined; },
setOverview: update => summaries.push(update), setLogCron: update => logs.push(update),
message: { info: text => messages.push(text) }, intl: { get: text => text },
const bindings = {
anomalySession,
anomalyVersion,
closeAnomaly() {
closes++;
anomalySession.current = undefined;
},
setOverview: (update) => summaries.push(update),
setLogCron: (update) => logs.push(update),
message: { info: (text) => messages.push(text) },
intl: { get: (text) => text },
};
const js = ts.transpile('const invalidate = ' + callback, { target: ts.ScriptTarget.ES2022 });
const invalidate = Function(...Object.keys(bindings), js + '\nreturn invalidate;')(...Object.values(bindings));
const js = ts.transpile('const invalidate = ' + callback, {
target: ts.ScriptTarget.ES2022,
});
const invalidate = Function(
...Object.keys(bindings),
js + '\nreturn invalidate;',
)(...Object.values(bindings));
invalidate(old, 'unavailable');
assert.equal(closes, 0);
assert.equal(summaries.length, 0);
@@ -398,7 +734,8 @@ test('an old invalidation cannot close a reopened session or clear its freshly q
const next = { session: 3 };
anomalySession.current = next;
anomalyVersion.current = 3;
const fresh = { triggers: { audit: { missing: 0 } } }, freshLog = { anomalySession: 3 };
const fresh = { triggers: { audit: { missing: 0 } } },
freshLog = { anomalySession: 3 };
assert.strictEqual(summaries[0](fresh), fresh);
assert.strictEqual(logs[0](freshLog), freshLog);
assert.equal(messages.length, 1);
+268 -65
View File
@@ -46,29 +46,64 @@ const flush = () => new Promise((resolve) => setImmediate(resolve));
const pastCursor = action('components/fileBrowser/index.tsx', 'pastCursor', {});
test('a retry at the top restores the next visible file when the first file was deleted', () => {
const row = (title, top) => ({ title, getBoundingClientRect: () => ({ top, bottom: top + 24 }) });
const row = (title, top) => ({
title,
getBoundingClientRect: () => ({ top, bottom: top + 24 }),
});
const element = {
scrollTop: 0, clientHeight: 48, getBoundingClientRect: () => ({ top: 100 }),
querySelectorAll: () => [row('gone', 100), row('survivor', 124), row('below', 148)],
querySelector: selector => selector === 'button[title="survivor"]' ? row('survivor', 364) : null,
scrollTop: 0,
clientHeight: 48,
getBoundingClientRect: () => ({ top: 100 }),
querySelectorAll: () => [
row('gone', 100),
row('survivor', 124),
row('below', 148),
],
querySelector: (selector) =>
selector === 'button[title="survivor"]' ? row('survivor', 364) : null,
};
const viewport = { current: element }, position = {};
action('components/fileBrowser/index.tsx', 'rememberPosition', { viewport, position })();
assert.deepEqual([...position.current.offsets], [['gone', 0], ['survivor', 24]]);
const viewport = { current: element },
position = {};
action('components/fileBrowser/index.tsx', 'rememberPosition', {
viewport,
position,
})();
assert.deepEqual(
[...position.current.offsets],
[
['gone', 0],
['survivor', 24],
],
);
const emptyListing = { rows: [], next: '', versions: new Map() };
action('components/fileBrowser/index.tsx', 'Entries', {
React: require('react'), emptyListing, Spin: 'i', CSS: { escape: key => key },
useRef: value => value === null ? viewport : value === undefined ? position : { current: value },
useState: value => [value, () => {}], useEffect() {}, useLayoutEffect: effect => effect(),
React: require('react'),
emptyListing,
Spin: 'i',
CSS: { escape: (key) => key },
useRef: (value) =>
value === null
? viewport
: value === undefined
? position
: { current: value },
useState: (value) => [value, () => {}],
useEffect() {},
useLayoutEffect: (effect) => effect(),
})({ source: 'logs', path: '', search: '' });
assert.equal(element.scrollTop, 240);
assert.equal(position.current, undefined);
});
test('a new execution has its own title before its log path arrives', () => {
const readableLogName = action('components/fileBrowser/name.ts', 'readableLogName', {});
const readableLogName = action(
'components/fileBrowser/name.ts',
'readableLogName',
{},
);
const title = action('pages/crontab/detail.tsx', 'instanceTitle', {
readableLogName, intl: { get: (key, { id }) => key.replace('{id}', id) },
readableLogName,
intl: { get: (key, { id }) => key.replace('{id}', id) },
});
const next = { id: 34834, status: 0, log_path: null };
const stopped = { id: 34814, status: 2, log_path: 'task/old.log' };
@@ -79,17 +114,34 @@ test('a new execution has its own title before its log path arrives', () => {
test('file rows preserve meaningful suffixes, separate the search directory and expose the full path', () => {
const React = require('react');
const names = ['async_components___init__', 'async_components_register.js', '中文任务_同步明细.log'];
const rows = names.map(title => ({ title, parent: 'workers', key: 'workers/' + title, type: 'file' }));
const names = [
'async_components___init__',
'async_components_register.js',
'中文任务_同步明细.log',
];
const rows = names.map((title) => ({
title,
parent: 'workers',
key: 'workers/' + title,
type: 'file',
}));
const emptyListing = { rows, next: '', versions: new Map() };
const entries = action('components/fileBrowser/index.tsx', 'Entries', {
React, useRef: current => ({ current }), useState: value => [value, () => {}], useEffect() {}, useLayoutEffect() {},
emptyListing, FileOutlined: 'i', Spin: 'i', Typography: { Text: 'span' }, readableLogName: value => value,
React,
useRef: (current) => ({ current }),
useState: (value) => [value, () => {}],
useEffect() {},
useLayoutEffect() {},
emptyListing,
FileOutlined: 'i',
Spin: 'i',
Typography: { Text: 'span' },
readableLogName: (value) => value,
})({ source: 'logs', path: '', search: 'work' }).props.children[0];
const tails = ['___init__', '_register.js', '_同步明细.log'];
for (const [i, button] of entries.entries()) {
const [name, parent] = button.props.children[1].props.children;
const parts = name.props.children.map(span => span.props.children);
const parts = name.props.children.map((span) => span.props.children);
assert.equal(parts.join(''), names[i]);
assert.equal(parts[1], tails[i]);
assert.equal(parent.props.children, 'workers');
@@ -101,24 +153,53 @@ test('file rows preserve meaningful suffixes, separate the search directory and
for (const remaining of [0, 2, 8]) {
test(`manual retry retains the requested depth through churn and a network error with ${remaining} files left`, async () => {
const emptyListing = { rows: [], next: '', versions: new Map() };
const listing = { current: { rows: [0, 1, 2, 3], next: '4', versions: new Map([['a', '1']]) } };
const states = [], failures = [];
let checks = 0, reads = 0, phase = 'churn';
const listing = {
current: {
rows: [0, 1, 2, 3],
next: '4',
versions: new Map([['a', '1']]),
},
};
const states = [],
failures = [];
let checks = 0,
reads = 0,
phase = 'churn';
const read = action('components/fileBrowser/index.tsx', 'read', {
pastCursor, rememberPosition() {},
listing, emptyListing, pending: {}, path: 'a', source: 'scripts', search: '', folders: false,
config: { apiPrefix: '/api/' }, setLoading() {}, setFailed: v => failures.push(v),
setListing: page => states.push(page.rows),
pastCursor,
rememberPosition() {},
listing,
emptyListing,
pending: {},
path: 'a',
source: 'scripts',
search: '',
folders: false,
config: { apiPrefix: '/api/' },
setLoading() {},
setFailed: (v) => failures.push(v),
setListing: (page) => states.push(page.rows),
request: {
async get(_url, { params }) {
reads++;
if (phase === 'offline') throw new Error('network unavailable');
const count = phase === 'churn' ? 8 : remaining;
const offset = Number(params.after);
const data = Array.from({ length: Math.min(2, count - offset) }, (_, i) => offset + i);
return { code: 200, data, next: offset + 2 < count ? String(offset + 2) : null, versions: [['a', '1']] };
const data = Array.from(
{ length: Math.min(2, count - offset) },
(_, i) => offset + i,
);
return {
code: 200,
data,
next: offset + 2 < count ? String(offset + 2) : null,
versions: [['a', '1']],
};
},
async post() {
checks++;
return { code: 200, current: phase === 'stable' };
},
async post() { checks++; return { code: 200, current: phase === 'stable' }; },
},
});
await read(listing.current);
@@ -135,7 +216,10 @@ for (const remaining of [0, 2, 8]) {
phase = 'stable';
await Promise.all([read(retry), read(retry)]);
const count = Math.min(6, remaining);
assert.deepEqual(listing.current.rows, Array.from({ length: count }, (_, i) => i));
assert.deepEqual(
listing.current.rows,
Array.from({ length: count }, (_, i) => i),
);
assert.equal(listing.current.next, remaining > count ? String(count) : '');
const completedReads = reads;
await read(retry);
@@ -149,21 +233,44 @@ for (const [source, search, boundary, cursors] of [
// DFS enters directory "a" before visiting sibling "a-".
['logs', 'needle', 'a-', ['a/1', 'a/2', 'a/3', 'a/x', 'a.', 'z']],
]) {
test(`retry traverses the old boundary after earlier inserts and deletion of the cursor (${source}, ${search || 'directory'})`, async () => {
test(`retry traverses the old boundary after earlier inserts and deletion of the cursor (${source}, ${
search || 'directory'
})`, async () => {
const emptyListing = { rows: [], next: '', versions: new Map() };
const listing = { current: { rows: ['old1', 'old2'], next: boundary, versions: new Map() } };
const listing = {
current: { rows: ['old1', 'old2'], next: boundary, versions: new Map() },
};
const failures = [];
let stable = false;
const read = action('components/fileBrowser/index.tsx', 'read', {
pastCursor, rememberPosition() {}, listing, emptyListing, pending: {}, source, path: '', search, folders: false,
config: { apiPrefix: '/api/' }, setLoading() {}, setFailed: v => failures.push(v), setListing() {},
pastCursor,
rememberPosition() {},
listing,
emptyListing,
pending: {},
source,
path: '',
search,
folders: false,
config: { apiPrefix: '/api/' },
setLoading() {},
setFailed: (v) => failures.push(v),
setListing() {},
request: {
async get(_url, { params }) {
const index = params.after === boundary ? 4 : cursors.indexOf(params.after) + 1;
const index =
params.after === boundary ? 4 : cursors.indexOf(params.after) + 1;
assert.ok(index < cursors.length);
return { code: 200, next: cursors[index], data: search && index === 3 ? [] : [cursors[index]], versions: [['', '1']] };
return {
code: 200,
next: cursors[index],
data: search && index === 3 ? [] : [cursors[index]],
versions: [['', '1']],
};
},
async post() {
return { code: 200, current: stable };
},
async post() { return { code: 200, current: stable }; },
},
});
await read(listing.current);
@@ -173,53 +280,119 @@ for (const [source, search, boundary, cursors] of [
await read(listing.current);
assert.equal(failures.at(-1), false);
assert.equal(listing.current.next, cursors[4]);
assert.deepEqual(listing.current.rows, cursors.slice(0, 5).filter((_, i) => !search || i !== 3));
assert.deepEqual(
listing.current.rows,
cursors.slice(0, 5).filter((_, i) => !search || i !== 3),
);
});
}
test('loading more rebuilds the original depth if a delayed last page missed a move into a previous directory', async () => {
const pages = [
{ data: ['c/old'], next: null, versions: [['c', '1']] },
{ data: ['a/moved', 'b/kept'], next: 'b/kept', versions: [['a', '2'], ['b', '1']] },
{
data: ['a/moved', 'b/kept'],
next: 'b/kept',
versions: [
['a', '2'],
['b', '1'],
],
},
{ data: ['c/new'], next: null, versions: [['c', '2']] },
];
const cursors = [], checks = [], commits = [], emptyListing = { rows: [], next: '', versions: new Map() };
const listing = { current: { rows: ['a/deleted', 'b/kept'], next: 'b/kept', versions: new Map([['a', '1'], ['b', '1']]) } };
const cursors = [],
checks = [],
commits = [],
emptyListing = { rows: [], next: '', versions: new Map() };
const listing = {
current: {
rows: ['a/deleted', 'b/kept'],
next: 'b/kept',
versions: new Map([
['a', '1'],
['b', '1'],
]),
},
};
const read = action('components/fileBrowser/index.tsx', 'read', {
pastCursor, rememberPosition() {},
pending: {}, listing, emptyListing, source: 'logs', path: '', search: 'match',
folders: false, config: { apiPrefix: '/api/' }, setListing: value => commits.push(value.rows),
setLoading() {}, setFailed(value) { assert.equal(value, false); },
pastCursor,
rememberPosition() {},
pending: {},
listing,
emptyListing,
source: 'logs',
path: '',
search: 'match',
folders: false,
config: { apiPrefix: '/api/' },
setListing: (value) => commits.push(value.rows),
setLoading() {},
setFailed(value) {
assert.equal(value, false);
},
request: {
async get(_url, { params }) { cursors.push(params.after); return { code: 200, ...pages.shift() }; },
async post(_url, stamps) { checks.push(Object.fromEntries(stamps)); return { code: 200, current: checks.length > 1 }; },
async get(_url, { params }) {
cursors.push(params.after);
return { code: 200, ...pages.shift() };
},
async post(_url, stamps) {
checks.push(Object.fromEntries(stamps));
return { code: 200, current: checks.length > 1 };
},
},
});
const previous = listing.current;
await read(previous);
await read(previous); // A late second click from the previous render.
assert.deepEqual(cursors, ['b/kept', '', 'b/kept']);
assert.deepEqual(checks, [{ a: '1', b: '1', c: '1' }, { a: '2', b: '1', c: '2' }]);
assert.deepEqual(checks, [
{ a: '1', b: '1', c: '1' },
{ a: '2', b: '1', c: '2' },
]);
assert.deepEqual(commits, [[], ['a/moved', 'b/kept', 'c/new']]);
});
for (const retrying of [false, true]) {
test(`abandoning a search discards its delayed validation during ${retrying ? 'manual retry' : 'initial load'}`, async () => {
const pending = {}, commits = [];
test(`abandoning a search discards its delayed validation during ${
retrying ? 'manual retry' : 'initial load'
}`, async () => {
const pending = {},
commits = [];
const emptyListing = { rows: [], next: '', versions: new Map() };
const previous = retrying ? { ...emptyListing, retryMinimum: 2 } : emptyListing;
let finish, reads = 0;
const previous = retrying
? { ...emptyListing, retryMinimum: 2 }
: emptyListing;
let finish,
reads = 0;
const read = action('components/fileBrowser/index.tsx', 'read', {
pastCursor, rememberPosition() {},
pending, listing: { current: previous }, emptyListing, source: 'scripts', path: '', search: 'old',
folders: false, config: { apiPrefix: '/api/' }, setListing: value => commits.push(value),
setLoading() {}, setFailed() {},
pastCursor,
rememberPosition() {},
pending,
listing: { current: previous },
emptyListing,
source: 'scripts',
path: '',
search: 'old',
folders: false,
config: { apiPrefix: '/api/' },
setListing: (value) => commits.push(value),
setLoading() {},
setFailed() {},
request: {
async get() {
reads++;
return { code: 200, data: [`old-${reads}.js`], next: reads === 1 ? 'more' : null, versions: [['', '1']] };
return {
code: 200,
data: [`old-${reads}.js`],
next: reads === 1 ? 'more' : null,
versions: [['', '1']],
};
},
post() {
return new Promise((resolve) => {
finish = resolve;
});
},
post() { return new Promise(resolve => { finish = resolve; }); },
},
});
const loading = read(previous);
@@ -237,11 +410,27 @@ test('directory navigation shows the current path separately and returns exactly
for (const source of ['scripts', 'logs']) {
let directory = 'parent/child';
const render = (input = '') => {
const states = [[directory, next => { directory = next; }], [input, () => {}], [input, () => {}]];
const states = [
[
directory,
(next) => {
directory = next;
},
],
[input, () => {}],
[input, () => {}],
];
return action('components/fileBrowser/index.tsx', 'FileBrowser', {
React, Entries: 'div', Spin: 'span', ArrowUpOutlined: 'i', Button: 'button',
Input: { Search: 'input' }, Typography: { Text: 'span' }, intl: { get: key => key },
useEffect() {}, useState: () => states.shift(),
React,
Entries: 'div',
Spin: 'span',
ArrowUpOutlined: 'i',
Button: 'button',
Input: { Search: 'input' },
Typography: { Text: 'span' },
intl: { get: (key) => key },
useEffect() {},
useState: () => states.shift(),
})({ source }).props.children[1];
};
assert.ok(!render('query'));
@@ -336,7 +525,7 @@ test('expanded history retains its cursor and original head during inserts and r
pending,
paging,
visibleIds,
list: { current: { scrollTo: position => scrolls.push(position) } },
list: { current: { scrollTo: (position) => scrolls.push(position) } },
pageSize: 2,
config: { apiPrefix: '/api/' },
id: 1,
@@ -356,13 +545,20 @@ test('expanded history retains its cursor and original head during inserts and r
await reading;
reading = load('older');
await load('older');
assert.deepEqual(request.calls.at(-1).config.params, { paged: true, limit: 2, before: 3 });
assert.deepEqual(request.calls.at(-1).config.params, {
paged: true,
limit: 2,
before: 3,
});
assert.equal(request.calls.length, 2);
request.calls.at(-1).reject(new Error('older request interrupted'));
await reading;
assert.equal(failure, 'older');
reading = load('refresh');
assert.deepEqual(request.calls.at(-1).config.params, { paged: true, limit: 1 });
assert.deepEqual(request.calls.at(-1).config.params, {
paged: true,
limit: 1,
});
answer([5], null);
await flush();
answer([3], null);
@@ -370,13 +566,20 @@ test('expanded history retains its cursor and original head during inserts and r
assert.equal(state.current.hasNew, true);
assert.equal(failure, 'older');
reading = load(failure);
assert.deepEqual(request.calls.at(-1).config.params, { paged: true, limit: 2, before: 3 });
assert.deepEqual(request.calls.at(-1).config.params, {
paged: true,
limit: 2,
before: 3,
});
answer([2, 1], null);
await reading;
reading = load('refresh');
answer([6], null);
await flush();
assert.deepEqual(request.calls.at(-1).config.params, { paged: true, ids: '3' });
assert.deepEqual(request.calls.at(-1).config.params, {
paged: true,
ids: '3',
});
answer([3], null);
await reading;
assert.deepEqual(
+21 -6
View File
@@ -152,12 +152,27 @@ test('healthy bootstrap continues loading system information', async () => {
});
test('retryable panel reads retain their route on gateway failures and still enforce login expiry', async () => {
for (const [status, retryInPlace, expected] of [[502, true, []], [504, true, []],
[502, false, ['/error']], [401, true, ['/login']]]) {
const {request, pushes} = fixture('/crontab');
await assert.rejects(request.get('/api/crons/1/triggers', {retryInPlace, adapter: async config => {
throw new axios.AxiosError('failed', 'ERR_BAD_RESPONSE', config, null, {status, config, data: {}});
}}));
for (const [status, retryInPlace, expected] of [
[502, true, []],
[504, true, []],
[502, false, ['/error']],
[401, true, ['/login']],
]) {
const { request, pushes } = fixture('/crontab');
await assert.rejects(
request.get('/api/crons/1/triggers', {
retryInPlace,
adapter: async (config) => {
throw new axios.AxiosError(
'failed',
'ERR_BAD_RESPONSE',
config,
null,
{ status, config, data: {} },
);
},
}),
);
assert.deepEqual(pushes, expected);
}
});
+32 -7
View File
@@ -6,19 +6,44 @@ const load = require('../helpers/load-security-module.cjs');
test('debugger keeps the selected script when an older read completes after it', async () => {
const ts = require('typescript');
const file = path.resolve(__dirname, '../../src/pages/script/editModal.tsx');
const source = ts.createSourceFile(file, require('fs').readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
const source = ts.createSourceFile(
file,
require('fs').readFileSync(file, 'utf8'),
ts.ScriptTarget.Latest,
true,
);
let read;
function visit(node) {
if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'getDetail')
if (
ts.isVariableDeclaration(node) &&
node.name.getText(source) === 'getDetail'
)
read = node.initializer.getText(source);
ts.forEachChild(node, visit);
}
visit(source);
const js = ts.transpile('const read = ' + read, { target: ts.ScriptTarget.ES2022 });
const responses = [], ready = [], contents = [];
const get = Function('request', 'pendingFile', 'setFileReady', 'setValue', 'config', js + '\nreturn read;')(
{ get: (_url, { signal }) => new Promise(resolve => responses.push({ resolve, signal })) },
{ current: undefined }, state => ready.push(state), text => contents.push(text), { apiPrefix: '/api/' },
const js = ts.transpile('const read = ' + read, {
target: ts.ScriptTarget.ES2022,
});
const responses = [],
ready = [],
contents = [];
const get = Function(
'request',
'pendingFile',
'setFileReady',
'setValue',
'config',
js + '\nreturn read;',
)(
{
get: (_url, { signal }) =>
new Promise((resolve) => responses.push({ resolve, signal })),
},
{ current: undefined },
(state) => ready.push(state),
(text) => contents.push(text),
{ apiPrefix: '/api/' },
);
get({ title: 'slow.js' });
get({ title: 'current.js' });
File diff suppressed because it is too large. Load diff
+175 -58
View File
@@ -9,20 +9,37 @@ const zh = require('../../src/locales/zh-CN.json');
const en = require('../../src/locales/en-US.json');
// Render the actual TSX, including disclosure markup and translated field names.
const source = fs.readFileSync(require.resolve('../../src/pages/crontab/triggerTiming.tsx'), 'utf8');
const { outputText } = ts.transpileModule(source, { compilerOptions: {
jsx: ts.JsxEmit.ReactJSX, module: ts.ModuleKind.CommonJS, esModuleInterop: true,
target: ts.ScriptTarget.ES2022,
}});
const source = fs.readFileSync(
require.resolve('../../src/pages/crontab/triggerTiming.tsx'),
'utf8',
);
const { outputText } = ts.transpileModule(source, {
compilerOptions: {
jsx: ts.JsxEmit.ReactJSX,
module: ts.ModuleKind.CommonJS,
esModuleInterop: true,
target: ts.ScriptTarget.ES2022,
},
});
const output = {};
Function('require', 'exports', outputText)(require, output);
const base = new Date(2026, 10, 16, 14, 55).getTime();
before(() => intl.init({currentLocale: 'zh-CN', locales: {'zh-CN': zh, 'en-US': en}}));
before(() =>
intl.init({ currentLocale: 'zh-CN', locales: { 'zh-CN': zh, 'en-US': en } }),
);
function render(fields) {
const html = renderToStaticMarkup(React.createElement(output.default, { row: {
observed_at: base, state: 'running', source: 'node', exit_code: null, ...fields,
}}));
const html = renderToStaticMarkup(
React.createElement(output.default, {
row: {
observed_at: base,
state: 'running',
source: 'node',
exit_code: null,
...fields,
},
}),
);
const [summary, details] = html.split(/<details[^>]*>/);
assert.doesNotMatch(html, /<details[^>]* open/);
assert.match(details, /<summary>时间明细<\/summary>/);
@@ -31,8 +48,12 @@ function render(fields) {
}
test('summary separates 57 ms in queue from 158 ms to command start and optional script entry', () => {
const fields = { scheduled_at: base, queued_at: base + 10, started_at: base + 67,
command_started_at: base + 158 };
const fields = {
scheduled_at: base,
queued_at: base + 10,
started_at: base + 67,
command_started_at: base + 158,
};
for (const script_started_at of [null, base + 201]) {
const { summary, details } = render({ ...fields, script_started_at });
assert.match(summary, /排队等待 <b>57 ms/);
@@ -46,59 +67,103 @@ test('summary separates 57 ms in queue from 158 ms to command start and optional
assert.match(details, /计划到脚本开始 <b>201 ms/);
}
}
const {summary} = render({...fields, state:'finished', finished_at:base+3158});
const { summary } = render({
...fields,
state: 'finished',
finished_at: base + 3158,
});
assert.match(summary, /计划到命令启动 <b>158 ms/);
assert.match(summary, /结束时间 <b>14:55:03/);
});
test('only a currently queued run accumulates wait; skip or stop freezes the wait', (t) => {
t.mock.method(Date, 'now', () => base + 7000);
const fields = { queued_at:base, scheduled_at:base, started_at:null };
assert.match(render({...fields, state:'queued'}).summary, /已排队 <b>7 s/);
const { summary, details } = render({...fields, state:'skipped', finished_at:base+12});
const fields = { queued_at: base, scheduled_at: base, started_at: null };
assert.match(render({ ...fields, state: 'queued' }).summary, /已排队 <b>7 s/);
const { summary, details } = render({
...fields,
state: 'skipped',
finished_at: base + 12,
});
assert.doesNotMatch(summary, /已排队|计划到命令启动|排队等待/);
assert.match(details, /跳过前等待 <b>12 ms/);
const stopped = render({...fields,state:'stopped',finished_at:base+2100});
assert.match(stopped.summary,/排队等待 <b>2.1 s/);
const unknown = render({...fields,state:'unknown',finished_at:base+6000});
assert.doesNotMatch(unknown.summary,/排队等待|结束时间|已排队/);
assert.match(unknown.details,/状态记录时间/);
const stopped = render({
...fields,
state: 'stopped',
finished_at: base + 2100,
});
assert.match(stopped.summary, /排队等待 <b>2.1 s/);
const unknown = render({
...fields,
state: 'unknown',
finished_at: base + 6000,
});
assert.doesNotMatch(unknown.summary, /排队等待|结束时间|已排队/);
assert.match(unknown.details, /状态记录时间/);
});
test('manual and legacy rows never synthesize a schedule, queue time, command start or sample', () => {
const manual=render({source:'manual',queued_at:base, started_at:base+30,command_started_at:base+51});
assert.match(manual.summary,/进入队列/);
assert.match(manual.summary,/命令启动 <b>14:55:00/);
assert.doesNotMatch(manual.summary,/计划到命令启动/);
for (const source of ['system','legacy','client']) {
const {summary,details}=render({source,started_at:base, state:'failed',exit_code:17});
assert.match(summary,/记录启动/);
assert.match(summary,/退出码 <b>17/);
assert.doesNotMatch(summary,/计划运行|排队等待|计划到命令启动/);
assert.match(details,/记录启动<\/dt><dd>14:55:00.000/);
assert.match(details,/命令启动<\/dt><dd>未记录/);
const manual = render({
source: 'manual',
queued_at: base,
started_at: base + 30,
command_started_at: base + 51,
});
assert.match(manual.summary, /进入队列/);
assert.match(manual.summary, /命令启动 <b>14:55:00/);
assert.doesNotMatch(manual.summary, /计划到命令启动/);
for (const source of ['system', 'legacy', 'client']) {
const { summary, details } = render({
source,
started_at: base,
state: 'failed',
exit_code: 17,
});
assert.match(summary, /记录启动/);
assert.match(summary, /退出码 <b>17/);
assert.doesNotMatch(summary, /计划运行|排队等待|计划到命令启动/);
assert.match(details, /记录启动<\/dt><dd>14:55:00.000/);
assert.match(details, /命令启动<\/dt><dd>未记录/);
}
});
test('retain precision and dates across midnight, accept zero latency, omit reversed timestamps', () => {
const scheduled = new Date(2026, 11, 31, 23, 59, 59, 900).getTime();
const {summary,details}=render({state:'finished',scheduled_at:scheduled,queued_at:scheduled,
started_at:scheduled,command_started_at:scheduled+150,finished_at:scheduled+3100});
assert.match(summary,/2026-12-31 23:59:59/);
assert.match(summary,/排队等待 <b>0 ms/);
assert.match(summary,/结束时间 <b>2027-01-01 00:00:03/);
assert.match(details,/命令启动<\/dt><dd>2027-01-01 00:00:00.050/);
assert.doesNotMatch(render({scheduled_at:base, command_started_at:base-1}).summary,/计划到命令启动/);
const { summary, details } = render({
state: 'finished',
scheduled_at: scheduled,
queued_at: scheduled,
started_at: scheduled,
command_started_at: scheduled + 150,
finished_at: scheduled + 3100,
});
assert.match(summary, /2026-12-31 23:59:59/);
assert.match(summary, /排队等待 <b>0 ms/);
assert.match(summary, /结束时间 <b>2027-01-01 00:00:03/);
assert.match(details, /命令启动<\/dt><dd>2027-01-01 00:00:00.050/);
assert.doesNotMatch(
render({ scheduled_at: base, command_started_at: base - 1 }).summary,
/计划到命令启动/,
);
});
test('an entry sample with no schedule names the measured starting point and keeps millisecond precision', () => {
const script_started_at = base + 1635;
const manual = render({source:'manual', queued_at:base, started_at:base+10, script_started_at});
assert.match(manual.details,/入队到脚本开始 <b>1.635 s/);
const client = render({source:'client', started_at:base, script_started_at});
assert.match(client.details,/启动记录到脚本开始 <b>1.635 s/);
for (const {summary,details} of [manual,client]) {
assert.doesNotMatch(summary + details,/计划到脚本开始|计划到命令启动/);
const manual = render({
source: 'manual',
queued_at: base,
started_at: base + 10,
script_started_at,
});
assert.match(manual.details, /入队到脚本开始 <b>1.635 s/);
const client = render({
source: 'client',
started_at: base,
script_started_at,
});
assert.match(client.details, /启动记录到脚本开始 <b>1.635 s/);
for (const { summary, details } of [manual, client]) {
assert.doesNotMatch(summary + details, /计划到脚本开始|计划到命令启动/);
}
});
@@ -106,23 +171,75 @@ test('an expanded queued row uses its server snapshot even when the browser cloc
t.mock.method(Date, 'now', () => base + 600000);
const queued = { queued_at: base, queue_wait_ms: 375, state: 'queued' };
assert.match(render(queued).summary, /已排队 <b>375 ms/);
assert.match(render({...queued, queue_wait_ms:0}).summary, /已排队 <b>0 ms/);
assert.match(render({...queued, state:'running', started_at:base+812}).summary, /排队等待 <b>812 ms/);
assert.match(
render({ ...queued, queue_wait_ms: 0 }).summary,
/已排队 <b>0 ms/,
);
assert.match(
render({ ...queued, state: 'running', started_at: base + 812 }).summary,
/排队等待 <b>812 ms/,
);
});
test('expanded wait reasons retain the actual slot holders after the timer freezes', () => {
const queue_context=JSON.stringify({queue:'manual',limit:2,occupied:2,holders:[{id:'instance-101',name:'长任务 A'},{id:'instance-102',name:'长任务 B'}]});
const {summary,details}=render({state:'finished',queued_at:base,started_at:base+3712,finished_at:base+5000,queue_context});
assert.match(summary,/排队等待 <b>3.712 s/);
assert.match(details,/手动执行队列/);assert.match(details,/入队时已达并发上限(运行 2,上限 2)/);
assert.match(details,/长任务 A/);assert.match(details,/长任务 B/);
assert.match(render({state:'queued',queued_at:base}).details,/尚无同时运行的任务记录/);
const queue_context = JSON.stringify({
queue: 'manual',
limit: 2,
occupied: 2,
holders: [
{ id: 'instance-101', name: '长任务 A' },
{ id: 'instance-102', name: '长任务 B' },
],
});
const { summary, details } = render({
state: 'finished',
queued_at: base,
started_at: base + 3712,
finished_at: base + 5000,
queue_context,
});
assert.match(summary, /排队等待 <b>3.712 s/);
assert.match(details, /手动执行队列/);
assert.match(details, /入队时已达并发上限(运行 2,上限 2)/);
assert.match(details, /长任务 A/);
assert.match(details, /长任务 B/);
assert.match(
render({ state: 'queued', queued_at: base }).details,
/尚无同时运行的任务记录/,
);
});
test('a live queue shows the resampled holders and preserves the measured dequeue time after preparation',()=>{
const admission=JSON.stringify({queue:'manual',occupied:2,limit:2,holders:[{id:'a',name:'holder-A'},{id:'b',name:'holder-B'}]});
const live=JSON.stringify({queue:'manual',occupied:1,limit:1,holders:[{id:'b',name:'holder-B'}]});
const row={state:'queued',queued_at:base,queue_context:admission,queue_live_context:live};
assert.match(render(row).details,/最近一次检查(运行 1,上限 1)/);assert.doesNotMatch(render(row).details,/holder-A/);
assert.match(render({...row,state:'finished',dequeued_at:base+210,started_at:base+810}).summary,/排队等待 <b>210 ms/);
test('a live queue shows the resampled holders and preserves the measured dequeue time after preparation', () => {
const admission = JSON.stringify({
queue: 'manual',
occupied: 2,
limit: 2,
holders: [
{ id: 'a', name: 'holder-A' },
{ id: 'b', name: 'holder-B' },
],
});
const live = JSON.stringify({
queue: 'manual',
occupied: 1,
limit: 1,
holders: [{ id: 'b', name: 'holder-B' }],
});
const row = {
state: 'queued',
queued_at: base,
queue_context: admission,
queue_live_context: live,
};
assert.match(render(row).details, /最近一次检查(运行 1,上限 1)/);
assert.doesNotMatch(render(row).details, /holder-A/);
assert.match(
render({
...row,
state: 'finished',
dequeued_at: base + 210,
started_at: base + 810,
}).summary,
/排队等待 <b>210 ms/,
);
});
+4 -1
View File
@@ -456,7 +456,10 @@ test('sidebar and dialog use the same authoritative status even when old phase f
);
f.store.setJob({ status: 'ready', phase: 'downloading', percent: 62 });
notice.render();
assert.equal(notice.nodes('button')[0].props['aria-label'], '下载完成,等待重启');
assert.equal(
notice.nodes('button')[0].props['aria-label'],
'下载完成,等待重启',
);
f.store.setJob({ status: 'completed', phase: 'ready' });
assert.equal(notice.render(), null);
panel.render();