feat: add scheduling anomaly drill-down and improve dev startup

This commit is contained in:
whyour committed 2026-11-19 23:11:20 +08:00
1 parent d9e9e083ab
commit 2070931c82
21 files changed
+1185 -54

No files matched your search

+309
View File
@@ -6075,3 +6075,312 @@ test('a late skipped timer affects trigger deviation but only valid queue endpoi
assert.equal(metrics.samples, 3);
assert.equal(metrics.waitP95, 136);
});
test('overview clock pins the original server day when its data query crosses midnight', async t => {
const { root, models, stats } = await fixture(t);
const day = require('dayjs')().startOf('day');
const midnight = day.add(1, 'day').valueOf();
let clock = midnight - 100;
t.mock.method(Date, 'now', () => clock);
const router = express.Router();
load('back/api/dashboard.ts', {
'../config': { logPath: root }, '../data/cron': models, '../data/cronStats': stats,
'../shared/triggerHistory': { TriggerHistory: class {
async metrics(since) {
assert.equal(since, day.valueOf());
clock = midnight + 100;
return { audit: { through: midnight - 5100 } };
}
} },
}).default(router);
const handler = router.stack[0].handle.stack.find(x => x.route?.path === '/overview').route.stack.at(-1).handle;
let result;
await handler({}, { send(value) { result = value; } }, error => { throw error; });
assert.equal(result.code, 200);
assert.equal(result.data.serverNow, midnight - 100);
assert.equal(result.data.expiresAt, midnight);
assert.equal(result.data.todayRuns, 0);
});
test('panel anomaly pages match scheduled counts, isolate overlapping rules and restart paging on late evidence', async t => {
const { db, history } = await fixture(t);
const { AnomalyPage } = require('../../back/shared/scheduleAnomalies');
const { saveSchedulePlan, auditSchedule } = require('../../back/shared/scheduleAudit');
const start = new Date(2026, 1, 1, 9).getTime(), rule = '* * * * * *';
await saveSchedulePlan(db, { replace: true, crons: [{ id:'9', schedule:rule, extra_schedules:[{schedule:rule}] }] }, start);
const read = async (kind, page = 1, revision) => {
const rows = new AnomalyPage(kind, page, revision);
const audit = await auditSchedule(db,start,start+35000,rows);
const result = rows.result();
assert.equal(result.total, audit[kind]);
return result;
};
const put = (i,n,source='node') => {
const at=start+n*1000;
return history.enqueue(slotId('9',i,rule,at),9,source,at,at);
};
const first=await read('missing'), second=await read('missing',2,first.revision);
assert.equal(first.total,60); assert.equal(second.page,2);
assert.equal(new Set([...first.rows,...second.rows].map(r=>r.ruleIndex+'/'+r.time)).size,50);
await put(0,1,'recovery'); await put(1,1); await put(0,2); await put(1,2);
const id=(i,n)=>slotId('9',i,rule,start+n*1000);
await history.finish(id(0,1),'skipped','overlap',null);
await history.start(id(1,1),start+1100,true);
await history.finish(id(1,1),'failed','spawn',127);
await db.query("UPDATE CronTriggers SET log_path='one.log' WHERE id=$id",{bind:{id:id(1,1)}});
await history.recordCommandStart(id(0,2),start+2100);
const late=await read('missing',2,first.revision);
assert.deepEqual([late.changed,late.page,late.total],[true,1,56]);
assert.ok(late.rows.every(r=>r.trigger===null && !r.logPath));
assert.deepEqual((await read('skipped')).rows.map(r=>[r.trigger,r.reason,r.source]),[[id(0,1),'overlap','recovery']]);
assert.deepEqual((await read('unconfirmed')).rows.map(r=>[r.trigger,!!r.logPath]),[[id(1,1),true]]);
});
test('crond anomaly details count individual duplicate and unmatched receipts without inventing their schedule', async t => {
const { db } = await fixture(t);
const { AnomalyPage } = require('../../back/shared/scheduleAnomalies');
const { stageSystemPlan, confirmSystemPlan, systemScheduleAudit } = require('../../back/shared/systemScheduleAudit');
const m=60000, start=new Date(2026,1,1,9).getTime(), schedule='* * * * *';
const plan=await stageSystemPlan(db,[{id:1,name:'minute',schedule}],start-2*m);
await confirmSystemPlan(db,plan,start-2*m+1);
for (const [id,state,launch,rule,dispatch,observed,log] of [
['ran','finished',start+1,schedule,start,start,null], ['skip','skipped',null,schedule,start,start+m+7,null],
['unknown','unknown',null,schedule,start,start+2,null], ['old','skipped',null,null,null,start+3,'/dev/null'],
['unmatched','unknown',null,'0 0 * * *',start+m,start+m+4,'task/x.log'],
]) await db.query('INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,system_rule,system_dispatch_at,command_started_at,log_path) VALUES($id,1,\'system\',$state,$observed,$rule,$dispatch,$launch,$log)',{bind:{id,state,launch,rule,dispatch,observed,log}});
for (const [kind,field,count] of [['missing','missing',2],['skipped','actualSkips',2],['unconfirmed','actualUnconfirmed',2]]) {
const page=new AnomalyPage(kind,1);
const audit=await systemScheduleAudit(db,start,start+4*m+6000,page), report=page.result();
assert.equal(report.total,count);assert.equal(audit[field],count);
assert.equal(audit.actualStarts+audit.actualSkips+audit.actualUnconfirmed,5);
if (kind==='missing') assert.deepEqual(report.rows.map(r=>r.time),[start+2*m,start+3*m]);
if (kind==='skipped') assert.deepEqual(report.rows.map(r=>[r.trigger,r.time,r.logPath]),[['old',null,'/dev/null'],['skip',start,null]]);
if (kind==='unconfirmed') assert.deepEqual(report.rows.map(r=>[r.trigger,r.time,r.logPath]),[['unknown',start,null],['unmatched',null,'task/x.log']]);
}
});
test('anomaly endpoint resolves task names and offers only the retained log for the exact trigger', async t => {
const { root, db, models, stats } = await fixture(t);
const at = require('dayjs')().subtract(1, 'day').hour(12).valueOf();
await models.CrontabModel.create({ id: 4, name: 'Report', command: 'echo report' });
const logs = path.join(root, 'logs');
await fs.mkdir(logs);
await fs.writeFile(path.join(logs, 'one.log'), 'only for run one');
await fs.symlink(path.join(root, 'panel.sqlite'), path.join(logs, 'outside'));
for (const [id, file] of [['one', 'one.log'], ['two', 'missing.log'], ['three', 'outside'], ['four', '/dev/null']]) {
await db.query(`INSERT INTO CronTriggers(id,cron_id,source,state,observed_at,log_path)
VALUES($id,4,'system','unknown',$at,$file)`, { bind: { id, at: at - 10000, file } });
}
const router = express.Router();
load('back/api/dashboard.ts', {
'../config': { logPath: logs }, '../data/cron': models, '../data/cronStats': stats,
}).default(router);
const handle = router.stack[0].handle.stack.find(layer => layer.route?.path === '/schedule-anomalies').route.stack.at(-1).handle;
const read = async () => {
let result;
await handle({ query: { source: 'system', kind: 'unconfirmed', page: 1, at } },
{ send(value) { result = value.data; } }, error => { throw error; });
assert.equal(result.total, 4);
assert.ok(result.rows.every(row => row.name === 'Report' && row.time === null && !('logPath' in row)));
return result.rows.filter(row => row.hasLog).map(row => row.trigger);
};
assert.deepEqual(await read(), ['one']);
await fs.unlink(path.join(logs, 'one.log'));
assert.deepEqual(await read(), []);
});
for (const source of ['node', 'system']) test(source + ' anomaly pages reset after late reports and expose the same summary as starts are confirmed', async t => {
const { root, db, models, stats, history } = await fixture(t);
const { saveSchedulePlan } = require('../../back/shared/scheduleAudit');
const { stageSystemPlan, confirmSystemPlan } = require('../../back/shared/systemScheduleAudit');
const day = require('dayjs')().subtract(1, 'day').startOf('day').valueOf();
const start = day + 9 * 3600000;
const period = source === 'node' ? 1000 : 60000;
const rule = source === 'node' ? '* * * * * *' : '* * * * *';
const at = start + 61 * period + 5000;
await models.CrontabModel.create({ id: 7, name: 'Late', command: 'echo late' });
if (source === 'node') await saveSchedulePlan(db, { replace: true, crons: [{ id: '7', schedule: rule }] }, start);
else {
const plan = await stageSystemPlan(db, [{ id: 7, name: 'Late', schedule: rule }], start);
await confirmSystemPlan(db, plan, start + 1);
}
const router = express.Router();
load('back/api/dashboard.ts', { '../config': { logPath: root }, '../data/cron': models, '../data/cronStats': stats }).default(router);
const handler = router.stack[0].handle.stack.find(x => x.route?.path === '/schedule-anomalies').route.stack.at(-1).handle;
const read = async (kind, page = 1, revision) => {
let result;
await handler({ query: { source: source === 'node' ? 'panel' : 'system', kind, at, page, revision } },
{ send(value) { result = value.data; } }, error => { throw error; });
const summary = result.summary[source === 'node' ? 'audit' : 'systemAudit'];
const field = source === 'node' || kind === 'missing' ? kind : kind === 'skipped' ? 'actualSkips' : 'actualUnconfirmed';
assert.equal(result.total, summary[field]);
return result;
};
const first = await read('missing');
assert.ok(first.total > 50);
const second = await read('missing', 2, first.revision);
const third = await read('missing', 3, first.revision);
assert.equal(new Set([...first.rows, ...second.rows, ...third.rows].map(r => r.time)).size, first.total);
const slot = first.rows[0];
const id = source === 'node' ? slotId('7', 0, rule, slot.time) : 'system-late';
await history.enqueue(id, 7, source, slot.time, at);
await history.start(id, at, true);
if (source === 'system') await db.query('UPDATE CronTriggers SET system_rule=$rule,system_dispatch_at=$time WHERE id=$id',
{ bind: { rule, time: slot.time, id } });
await history.finish(id, 'failed', 'spawn', 127);
const filled = await read('missing', 3, first.revision);
assert.equal(filled.page, 1);
assert.equal(filled.changed, true);
assert.equal(filled.total, first.total - 1);
assert.ok(filled.rows.every(row => row.time !== slot.time));
const unknown = await read('unconfirmed');
assert.deepEqual(unknown.rows.map(r => r.trigger), [id]);
await history.recordCommandStart(id, at);
const started = await read('unconfirmed', 1, unknown.revision);
assert.equal(started.changed, true);
assert.equal(started.total, 0);
assert.deepEqual(started.rows, []);
const summary = started.summary[source === 'node' ? 'audit' : 'systemAudit'];
assert.equal(summary[source === 'node' ? 'dispatched' : 'actualStarts'], 1);
// Same count with a different member must also invalidate page offsets.
await db.query('DELETE FROM CronTriggers WHERE id=$id', { bind: { id } });
const nextSlot = second.rows[0];
const nextId = source === 'node' ? slotId('7', 0, rule, nextSlot.time) : 'system-other';
await history.enqueue(nextId, 7, source, nextSlot.time, at);
if (source === 'system') await db.query('UPDATE CronTriggers SET system_rule=$rule,system_dispatch_at=$time WHERE id=$id',
{ bind: { rule, time: nextSlot.time, id: nextId } });
const replaced = await read('missing', 2, filled.revision);
assert.equal(replaced.total, filled.total);
assert.equal(replaced.changed, true);
assert.equal(replaced.page, 1);
const retried = await read('missing', 2, replaced.revision);
assert.equal(retried.page, 2);
assert.equal(retried.changed, false);
assert.equal(new Set([...replaced.rows, ...retried.rows].map(r => r.time)).size, 50);
});
for (const source of ['node', 'system']) test(source + ' partial history cleanup fences in-flight anomaly pages and preserves retained pagination', async t => {
const { root, db, models, stats, history } = await fixture(t);
const dayjs = require('dayjs');
const at = dayjs().startOf('day').hour(12).valueOf(), start = at - 70 * 60000, rule = '* * * * *';
t.mock.method(Date, 'now', () => at + 1000);
await models.CrontabModel.create({ id: 12, name: 'Partial cleanup', command: 'echo retained' });
if (source === 'node') await require('../../back/shared/scheduleAudit').saveSchedulePlan(db,
{ replace: true, crons: [{ id: '12', schedule: rule }] }, start);
else {
const { stageSystemPlan, confirmSystemPlan } = require('../../back/shared/systemScheduleAudit');
const plan = await stageSystemPlan(db, [{ id: 12, schedule: rule }], start - 60000);
await confirmSystemPlan(db, plan, start - 60000 + 1);
}
const ids = [];
for (let n = 1; n <= 60; n++) {
const time = start + n * 60000;
const id = source === 'node' ? slotId('12', 0, rule, time) : 'partial-system-' + n;
ids.push(id);
await history.enqueue(id, 12, source, time, time + 10);
await history.start(id, time + 20, true);
await history.finish(id, 'failed', 'spawn', 127);
await db.query("UPDATE CronTriggers SET finished_at=$end,log_path='retained.log',system_rule=$rule,system_dispatch_at=$time WHERE id=$id",
{ bind: { id, time, rule, end: time + 1000 } });
}
await fs.writeFile(path.join(root, 'retained.log'), 'retained log');
// After an upgrade the earliest known installation can be newer than
// retained unmatched receipts. Plan coverage is not the retention boundary.
if (source === 'system') await db.query('UPDATE CronSystemPlans SET staged=$time,confirmed=$confirmed',
{ bind: { time: start + 40 * 60000, confirmed: start + 40 * 60000 + 1 } });
let cleanOnStat = false;
const cutoff = start + 20 * 60000 + 2000;
const router = express.Router();
load('back/api/dashboard.ts', {
'../config': { logPath: root }, '../data/cron': models, '../data/cronStats': stats,
'fs/promises': { stat: async file => {
if (cleanOnStat) {
cleanOnStat = false;
await db.transaction(transaction => history.deleteExpired(cutoff, transaction));
}
return fs.stat(file);
} },
}).default(router);
const handler = router.stack[0].handle.stack.find(x => x.route?.path === '/schedule-anomalies').route.stack.at(-1).handle;
const read = async (page = 1, revision, kind = 'unconfirmed') => {
let result;
await handler({ query: { source: source === 'node' ? 'panel' : 'system', kind, at, page, revision, live: true } },
{ send(value) { result = value.data; } }, error => { throw error; });
return result;
};
const first = await read();
assert.equal(first.total, 60);
assert.equal((await read(3, first.revision)).rows.length, 10);
cleanOnStat = true;
assert.deepEqual(await read(2, first.revision), { status: 'unavailable' });
const retained = await read(3, first.revision);
assert.equal(retained.total, 40);
assert.equal(retained.page, 1);
assert.equal(retained.changed, true);
const second = await read(2, retained.revision);
const rows = [...retained.rows, ...second.rows];
assert.equal(new Set(rows.map(r => r.trigger)).size, 40);
assert.deepEqual(rows.map(r => r.trigger).sort(), ids.slice(20).sort());
assert.ok(rows.every(r => r.hasLog));
for (const kind of ['missing', 'skipped', 'unconfirmed']) {
const result = await read(1, undefined, kind);
const summary = result.summary[source === 'node' ? 'audit' : 'systemAudit'];
const field = source === 'node' || kind === 'missing' ? kind : kind === 'skipped' ? 'actualSkips' : 'actualUnconfirmed';
assert.equal(result.total, summary[field]);
assert.ok(result.rows.every(r => r.time == null || r.time >= cutoff));
}
assert.deepEqual(await history.visibleTriggers(12, ids.slice(0, 20)), []);
});
for (const source of ['node', 'system']) test(source + ' live anomaly sessions expire across midnight and after retained history is cleared', async t => {
const { root, db, models, stats, history } = await fixture(t);
const dayjs = require('dayjs');
const { saveSchedulePlan } = require('../../back/shared/scheduleAudit');
const { stageSystemPlan, confirmSystemPlan } = require('../../back/shared/systemScheduleAudit');
const at = dayjs().startOf('day').hour(12).valueOf(), start = at - 180000, rule = '* * * * *';
const expiresAt = dayjs(at).startOf('day').add(1, 'day').valueOf();
let clock = at + 10000, crossOnStat = false;
t.mock.method(Date, 'now', () => clock);
await models.CrontabModel.create({ id: 11, name: 'Midnight', command: 'echo midnight' });
if (source === 'node') await saveSchedulePlan(db, { replace: true, crons: [{ id: '11', schedule: rule }] }, start);
else {
const plan = await stageSystemPlan(db, [{ id: 11, schedule: rule }], start - 60000);
await confirmSystemPlan(db, plan, start - 60000 + 1);
}
const time = Math.ceil((start + 60000) / 60000) * 60000;
const id = source === 'node' ? slotId('11', 0, rule, time) : 'system-midnight';
await history.enqueue(id, 11, source, time, time + 10);
await history.start(id, time + 20, true);
await history.finish(id, 'failed', 'spawn', 127);
await fs.writeFile(path.join(root, 'midnight.log'), id);
await db.query("UPDATE CronTriggers SET finished_at=$end,log_path='midnight.log',system_rule=$rule,system_dispatch_at=$time WHERE id=$id",
{ bind: { end: time + 1000, id, rule, time } });
const router = express.Router();
load('back/api/dashboard.ts', {
'../config': { logPath: root }, '../data/cron': models, '../data/cronStats': stats,
'fs/promises': { stat: async file => { if (crossOnStat) clock = expiresAt; return fs.stat(file); } },
}).default(router);
const handler = router.stack[0].handle.stack.find(x => x.route?.path === '/schedule-anomalies').route.stack.at(-1).handle;
const read = async kind => {
let result;
const res = { status() { return this; }, send(value) { result = value; } };
await handler({ query: { source: source === 'node' ? 'panel' : 'system', kind, at, page: 1, live: true } }, res, error => { throw error; });
assert.equal(result.code, 200);
return result.data;
};
const first = await read('unconfirmed');
assert.deepEqual(first.rows.map(row => row.trigger), [id]);
assert.equal(first.expiresAt, expiresAt);
crossOnStat = true;
assert.deepEqual(await read('unconfirmed'), { status: 'expired' });
crossOnStat = false;
assert.deepEqual(await read('missing'), { status: 'expired' });
clock = at + 10000;
await db.transaction(transaction => history.deleteExpired(at + 1000, transaction));
assert.deepEqual(await history.visibleTriggers(11, [id]), []);
for (const kind of ['missing', 'skipped', 'unconfirmed'])
assert.deepEqual(await read(kind), { status: 'unavailable' });
// Repeated reads do not reconstitute the missing plan or the old log entry.
assert.deepEqual(await read('unconfirmed'), { status: 'unavailable' });
assert.deepEqual(await history.visibleTriggers(11, [id]), []);
});
+101
View File
@@ -0,0 +1,101 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');
const { spawnSync } = require('node:child_process');
const ts = require('typescript');
test('development launcher preserves cluster loading, decorator metadata and source locations', (t) => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ql-dev-start-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.mkdirSync(path.join(root, 'back'));
fs.symlinkSync(path.resolve('node_modules'), path.join(root, 'node_modules'), 'dir');
fs.copyFileSync('back/tsconfig.json', path.join(root, 'back/tsconfig.json'));
fs.writeFileSync(path.join(root, 'back/app.ts'), `
import 'reflect-metadata';
import cluster from 'node:cluster';
class Dependency {}
function decorated(target: Function) {}
@decorated class Consumer { constructor(dependency: Dependency) {} }
// Deliberate type error: development startup must skip type checking.
const value: string = 42;
if (cluster.isPrimary) {
cluster.fork();
cluster.on('exit', (_worker, code) => { process.exitCode = code; });
} else {
console.log('FIXTURE_RESULT=' + JSON.stringify({ value,
metadata: Reflect.getMetadata('design:paramtypes', Consumer)[0] === Dependency,
stack: new Error('source location').stack }));
process.disconnect!();
}
`);
const config = JSON.parse(fs.readFileSync('nodemon.json', 'utf8'));
const [command, ...args] = config.execMap.ts.split(' ');
assert.equal(command, 'node');
const env = { ...process.env, ...config.env };
delete env.NODE_OPTIONS;
const result = spawnSync(process.execPath, [...args, 'back/app.ts'], {
cwd: root, env, encoding: 'utf8', timeout: 20000,
});
assert.ifError(result.error);
assert.equal(result.status, 0, result.stdout + result.stderr);
const output = JSON.parse(result.stdout.split('FIXTURE_RESULT=')[1].split('\n')[0]);
assert.equal(output.value, 42);
assert.equal(output.metadata, true);
assert.match(output.stack, /back[/\\]app\.ts:\d+:\d+/);
});
test('startup timing preserves results and failures with timing enabled or disabled', async (t) => {
const loadModule = require('../helpers/load-security-module.cjs');
const logs = [];
const { startupStage } = loadModule('back/shared/startupTiming.ts', {
'../loaders/logger': { info: (message) => logs.push(message) },
});
const original = process.env.QL_STARTUP_TIMING;
const role = process.env.SERVICE_TYPE;
t.after(() => {
if (original === undefined) delete process.env.QL_STARTUP_TIMING;
else process.env.QL_STARTUP_TIMING = original;
if (role === undefined) delete process.env.SERVICE_TYPE;
else process.env.SERVICE_TYPE = role;
});
process.env.SERVICE_TYPE = 'grpc';
for (const enabled of ['0', '1']) {
process.env.QL_STARTUP_TIMING = enabled;
logs.length = 0;
const value = {};
const failure = new Error('startup failed');
let calls = 0;
assert.equal(await startupStage('success', async () => { calls++; return value; }), value);
await assert.rejects(startupStage('failure', async () => { calls++; throw failure; }),
(error) => error === failure);
await assert.rejects(startupStage('sync-failure', () => { calls++; throw failure; }),
(error) => error === failure);
assert.equal(calls, 3);
assert.equal(logs.length, enabled === '1' ? 3 : 0);
if (enabled === '1') {
for (const [index, stage] of ['success', 'failure', 'sync-failure'].entries()) {
assert.match(logs[index], new RegExp('^\\[boot:timing\\] grpc:' + stage + ' \\d+ms \\(PID: \\d+\\)$'));
}
}
}
});
test('frontend gzip assets are enabled for production only', () => {
const source = ts.transpileModule(fs.readFileSync('.umirc.ts', 'utf8'), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
}).outputText;
for (const mode of ['development', 'production']) {
const module = { exports: {} };
class Compression { constructor(options) { this.options = options; } }
new Function('require', 'module', 'exports', 'process', source)(
(name) => name === '@umijs/max' ? { defineConfig: (config) => config } : Compression,
module, module.exports, { env: { NODE_ENV: mode } },
);
const plugins = [];
module.exports.default.chainWebpack({ plugin: (name) => ({ use: (plugin) => plugins.push({ name, plugin }) }) });
assert.equal(plugins.length, mode === 'production' ? 1 : 0);
if (mode === 'production') assert.equal(plugins[0].plugin.options.algorithm, 'gzip');
}
});
+286 -2
View File
@@ -3,7 +3,7 @@ const assert = require('node:assert/strict');
const fs = require('node:fs');
const ts = require('typescript');
function dashboard() {
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);
let effect;
@@ -17,7 +17,8 @@ function dashboard() {
const requests = [], results = [], failures = [], timers = new Set();
const noop = () => {};
const bindings = {
config: { apiPrefix: '/api/' }, REFRESH_INTERVAL: 30000,
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); },
@@ -34,6 +35,50 @@ function dashboard() {
}
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 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: {} } });
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 close = v.start(selection, { page: 1 });
v.requests[0].reject(new Error('offline'));
await flush();
v.advance(7000);
close();
const cancel = v.start(selection, { page: 1 });
v.tick(3000);
assert.equal(v.requests[1].signal.aborted, true);
assert.deepEqual(v.invalidated, [{ selection, reason: 'expired' }]);
cancel();
});
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 };
v.advance(1001);
const close = v.start(selection, { page: 1 });
assert.equal(v.requests.length, 0);
assert.deepEqual(v.invalidated, [{ selection, reason: 'expired' }]);
close();
});
test('overview deadlines use server time and request start, independent of the browser wall clock', async () => {
const v = dashboard(), close = v.start();
const serverNow = 1795017590000;
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();
view.tick();
@@ -119,3 +164,242 @@ test('dashboard timing preserves millisecond precision, rounds long waits and di
await intl.init({ currentLocale: 'en-US', locales });
assert.equal(component.formatTiming(1703994), '28 min 24 s');
});
function anomalies() {
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);
let effect;
function visit(node) {
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();
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() {},
onUpdate: (selection, summary) => summaries.push(summary),
onInvalidate: (selection, reason) => invalidated.push({ selection, reason }),
performance: { now: () => now },
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(); } },
};
}
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 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 } } };
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();
assert.equal(v.requests.length, 2);
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 });
v.requests[1].resolve({ code: 200, data: { ...updated, total: 99 } });
v.requests[2].reject(new Error('timeout'));
await flush();
assert.equal(v.failed.at(-1), true);
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 } } };
v.requests[3].resolve({ code: 200, data: empty });
await flush();
assert.equal(v.failed.at(-1), false);
assert.deepEqual(v.summaries, [updated.summary, empty.summary]);
finish();
v.tick();
assert.equal(v.requests.length, 4);
});
test('opening anomaly details cancels older overview responses and keeps its counts owned by the detail snapshot', async () => {
const v = dashboard(), close = v.start();
close();
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();
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);
});
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 leave = v.start(selection, { page: 1 });
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();
assert.equal(v.requests.length, 2);
v.tick(10000);
assert.equal(v.requests[1].signal.aborted, true);
assert.deepEqual(v.invalidated, [{ selection, reason: 'expired' }]);
v.requests[1].resolve({ code: 200, data });
await flush();
assert.deepEqual(v.summaries, [data.summary]);
assert.equal(v.timers.size, 0);
leave();
});
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 leave = v.start(selection, { page: 1 });
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);
leave();
const cancelPage = v.start(selection, { page: 2, revision: 'old' });
assert.ok([...v.timers.values()].includes(7000));
v.requests[1].reject(new Error('timeout'));
await flush();
v.advance(2000);
cancelPage();
const cancelRetry = v.start(selection, { page: 2, revision: 'old' });
v.tick(5000);
assert.equal(v.requests[2].signal.aborted, true);
assert.deepEqual(v.invalidated, [{ selection, reason: 'expired' }]);
v.requests[2].resolve({ code: 200, data });
await flush();
assert.deepEqual(v.received, [data]);
assert.equal(v.timers.size, 0);
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();
});
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 close = v.start(selection, { page: 1 });
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, []);
assert.deepEqual(v.summaries, []);
close();
});
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);
let callback;
function visit(node) {
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));
update(old, { audit: { missing: 8 } });
anomalySession.current = next;
update(old, { audit: { missing: 9 } });
assert.equal(queued.length, 1);
const fresh = { triggers: { audit: { missing: 0 } } };
assert.strictEqual(queued[0](fresh), fresh);
});
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);
let callback;
function visit(node) {
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 = [];
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 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);
invalidate(current, 'expired');
assert.equal(closes, 1);
assert.equal(logs[0]({ anomalySession: 2 }), null);
const next = { session: 3 };
anomalySession.current = next;
anomalyVersion.current = 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);
});