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

+10 -8
View File
@@ -24,14 +24,16 @@ export default defineConfig({
},
},
chainWebpack: ((config: any) => {
config.plugin('compression-webpack-plugin').use(
new CompressionPlugin({
algorithm: 'gzip',
test: new RegExp('\\.(js|css)$'),
threshold: 10240,
minRatio: 0.6,
}),
);
if (process.env.NODE_ENV === 'production') {
config.plugin('compression-webpack-plugin').use(
new CompressionPlugin({
algorithm: 'gzip',
test: new RegExp('\\.(js|css)$'),
threshold: 10240,
minRatio: 0.6,
}),
);
}
}) as any,
headScripts: [`./api/env.js`],
copy: [
+3 -1
View File
@@ -115,7 +115,9 @@ pnpm install
pnpm start
```
Open your browser and visit <http://127.0.0.1:5700>
Open your browser and visit <http://127.0.0.1:8000>. The development server proxies API requests to the backend on port 5700.
The backend starts with `ts-node/register/transpile-only`, skipping type checking during development, and restarts automatically after source changes. Run `pnpm build:back` for full type checking. `[boot:timing]` logs report startup stages. Development builds skip gzip generation; production builds retain gzip compression. Keep frontend caches and the `data` directory during normal development to avoid rebuilding dependencies, initializing the database and generating certificates on each start.
## Links
+3 -1
View File
@@ -117,7 +117,9 @@ pnpm install
pnpm start
```
打开你的浏览器,访问 <http://127.0.0.1:5700>
打开你的浏览器,访问 <http://127.0.0.1:8000>,开发服务器会将 API 请求代理到后端的 5700 端口。
后端通过 `ts-node/register/transpile-only` 启动,开发时跳过类型检查;修改源码后自动重启。完整类型检查使用 `pnpm build:back`。`[boot:timing]` 日志记录各启动阶段耗时。开发环境不生成 gzip 文件,生产构建保留 gzip 压缩。日常开发保留前端缓存和 `data` 目录,可避免重复编译依赖、初始化数据库和生成证书。
## 链接
+64 -3
View File
@@ -1,10 +1,17 @@
import config from '../config';
import { stat } from 'fs/promises';
import { resolveFileAccess } from '../shared/fileAccess';
import { AnomalyPage, AnomalyKind } from '../shared/scheduleAnomalies';
import { auditSchedule } from '../shared/scheduleAudit';
import { systemScheduleAudit } from '../shared/systemScheduleAudit';
import { celebrate, Joi } from 'celebrate';
import { executionIdPattern, executionTriggerId, receiptFinishTime } from '../shared/executionIdentity';
import { oldestQueued } from '../shared/queueDiagnostics';
import { containerResources } from '../shared/containerResources';
import { TriggerHistory } from '../shared/triggerHistory';
import { Router, Request, Response, NextFunction } from 'express';
import { Container } from 'typedi';
import { fn, col, where, Op } from 'sequelize';
import { fn, col, where, Op, QueryTypes } from 'sequelize';
import { CrontabModel } from '../data/cron';
import { CrontabStatModel } from '../data/cronStats';
import {
@@ -56,7 +63,9 @@ export default (app: Router) => {
'/overview',
async (req: Request, res: Response, next: NextFunction) => {
try {
const today = dayjs().format('YYYY-MM-DD');
const serverNow = Date.now();
const day = dayjs(serverNow).startOf('day');
const today = day.format('YYYY-MM-DD');
const [total, enabled, disabled, stats, triggers] = await Promise.all([
CrontabModel.count(),
@@ -73,7 +82,7 @@ export default (app: Router) => {
where: { date: today },
raw: true,
}),
new TriggerHistory(CrontabStatModel.sequelize!).metrics(dayjs().startOf('day').valueOf()),
new TriggerHistory(CrontabStatModel.sequelize!).metrics(day.valueOf()),
]);
const row = stats as any;
@@ -85,6 +94,8 @@ export default (app: Router) => {
res.send({
code: 200,
data: {
serverNow,
expiresAt: day.add(1, 'day').valueOf(),
total,
enabled,
disabled,
@@ -103,6 +114,56 @@ export default (app: Router) => {
},
);
route.get('/schedule-anomalies', celebrate({ query: Joi.object({
source: Joi.string().valid('panel', 'system').required(),
kind: Joi.string().valid('missing', 'skipped', 'unconfirmed').required(),
at: Joi.number().integer().positive().required(),
page: Joi.number().integer().min(1).default(1),
revision: Joi.string().hex().length(64),
live: Joi.boolean().default(false),
}).unknown(true) }), async (req, res, next) => {
try {
const { source, kind, page, at, revision, live } = req.query;
const until = Number(at);
const serverNow = Date.now();
const expiresAt = dayjs(until).startOf('day').add(1, 'day').valueOf();
if (live && serverNow >= expiresAt)
return res.send({ code: 200, data: { status: 'expired' } });
if (until > Date.now() || until < dayjs().subtract(1, 'day').startOf('day').valueOf())
return res.status(400).send({ code: 400 });
const [snapshotRetention] = live ? await CrontabStatModel.sequelize!.query<{ cutoff: number }>(
'SELECT cutoff FROM CronHistoryRetention WHERE id=1', { type: QueryTypes.SELECT },
) : [];
const details = new AnomalyPage(kind as AnomalyKind, Number(page), revision as string | undefined);
const audit = source === 'panel' ? auditSchedule : systemScheduleAudit;
const summary = await audit(CrontabStatModel.sequelize!, dayjs(until).startOf('day').valueOf(), until, details);
if (live && (!summary || summary.since > summary.through))
return res.send({ code: 200, data: { status: 'unavailable' } });
if (!summary) return res.status(409).send({ code: 409 });
const result = details.result();
const ids = [...new Set(result.rows.filter(row => !row.name).map(row => row.task))];
const tasks = ids.length ? await CrontabModel.findAll({ where: { id: ids }, attributes: ['id','name','command'], raw: true }) : [];
const names = new Map(tasks.map(task => [task.id, task.name || task.command]));
const rows = await Promise.all(result.rows.map(async ({ logPath, ...row }) => {
const path = logPath && resolveFileAccess(config.logPath, [logPath]);
const hasLog = path ? await stat(path).then(file => file.isFile(), () => false) : false;
return { ...row, name: row.name || names.get(row.task), hasLog };
}));
// Log checks can yield after the audit transaction. Do not publish that
// snapshot if history cleanup has since removed part of its plan window.
if (live) {
const [retention] = await CrontabStatModel.sequelize!.query<{ cutoff: number }>(
'SELECT cutoff FROM CronHistoryRetention WHERE id=1', { type: QueryTypes.SELECT },
);
if (retention && retention.cutoff > (snapshotRetention?.cutoff ?? 0))
return res.send({ code: 200, data: { status: 'unavailable' } });
}
if (live && Date.now() >= expiresAt)
return res.send({ code: 200, data: { status: 'expired' } });
return res.send({ code: 200, data: { ...result, rows, serverNow, expiresAt, summary: source === 'panel' ? { audit: summary } : { systemAudit: summary }, zone: Intl.DateTimeFormat().resolvedOptions().timeZone } });
} catch (error) { next(error); }
});
for (const isSuccess of [false, true]) {
route.get(
isSuccess ? '/successes' : '/failures',
+12 -11
View File
@@ -6,6 +6,7 @@ import config from './config';
import Logger from './loaders/logger';
import { errStack } from './shared/errors';
import { initializeLanguageSync } from './shared/languageSync';
import { startupStage } from './shared/startupTiming';
import { type GrpcServerService } from './services/grpc';
import { type HttpServerService } from './services/http';
@@ -26,9 +27,9 @@ class Application {
async start() {
try {
if (cluster.isPrimary) {
await this.initializeDatabase();
await startupStage('database', () => this.initializeDatabase());
}
await initializeLanguageSync();
await startupStage('language', () => initializeLanguageSync());
if (cluster.isPrimary) {
this.startMasterProcess();
} else {
@@ -229,9 +230,9 @@ class Application {
Logger.info(`[boot] ${serviceType} worker started (PID: ${process.pid})`);
try {
const { triggerHistory } = await import('./shared/triggerHistory');
const { triggerHistory } = await startupStage('history.import', () => import('./shared/triggerHistory'));
const history = triggerHistory();
await history.interrupt(serviceType);
await startupStage('history.recover', () => history.interrupt(serviceType));
if (serviceType === 'http') {
await this.startHttpService();
const retryExits = async () => {
@@ -257,16 +258,16 @@ class Application {
private async startHttpService() {
// 在导入任何 gRPC 客户端模块之前初始化 mTLS 证书
const { initGrpcCerts } = await import('./config/grpcCerts');
await initGrpcCerts();
const { initGrpcCerts } = await startupStage('certificates.import', () => import('./config/grpcCerts'));
await startupStage('certificates.initialize', () => initGrpcCerts());
const app = await this.setupMiddlewares();
const app = await startupStage('http.middleware', () => this.setupMiddlewares());
const { HttpServerService } = await import('./services/http');
this.httpServerService = Container.get(HttpServerService);
const appLoader = await import('./loaders/app');
await appLoader.default({ app });
const appLoader = await startupStage('http.import', () => import('./loaders/app'));
await startupStage('http.initialize', () => appLoader.default({ app }));
const server = await this.httpServerService.initialize(
app,
@@ -279,10 +280,10 @@ class Application {
}
private async startGrpcService() {
const { GrpcServerService } = await import('./services/grpc');
const { GrpcServerService } = await startupStage('grpc.import', () => import('./services/grpc'));
this.grpcServerService = Container.get(GrpcServerService);
await this.grpcServerService.initialize();
await startupStage('grpc.initialize', () => this.grpcServerService!.initialize());
this.setupWorkerShutdown('grpc');
}
+42
View File
@@ -0,0 +1,42 @@
import { createHash } from 'crypto';
export type AnomalyKind = 'missing' | 'skipped' | 'unconfirmed';
export interface ScheduleAnomaly {
task: number;
name?: string;
rule: string | null;
time: number | null;
source: 'node' | 'recovery' | 'system';
trigger: string | null;
observed: number | null;
reason: string | null;
logPath: string | null;
ruleIndex?: number;
}
// Keep only the requested page and the first page. If late evidence changes
// the result between requests, return the new first page instead of mixing scans.
export class AnomalyPage {
private hash = createHash('sha256');
private total = 0;
private first: ScheduleAnomaly[] = [];
private selected: ScheduleAnomaly[] = [];
static readonly size = 25;
constructor(readonly kind: AnomalyKind, private page: number, private previous?: string) {}
add(row: ScheduleAnomaly) {
this.hash.update(JSON.stringify(row)).update('\n');
const page = Math.floor(this.total++ / AnomalyPage.size) + 1;
if (page === 1) this.first.push(row);
if (page === this.page) this.selected.push(row);
}
result() {
const revision = this.hash.digest('hex');
const changed = !!this.previous && revision !== this.previous;
const reset = changed || (this.page > 1 && !this.selected.length);
return { rows: reset ? this.first : this.selected, total: this.total,
page: reset ? 1 : this.page, pageSize: AnomalyPage.size, revision, changed };
}
}
+27 -5
View File
@@ -1,3 +1,4 @@
import { AnomalyPage } from './scheduleAnomalies';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { AddCronRequest, DeleteCronRequest } from '../protos/cron';
import { upcomingSlots } from './cronScheduler';
@@ -19,6 +20,9 @@ type Receipt = {
scheduled_at: number;
observed_at: number;
state: string;
reason: string | null;
log_path: string | null;
source: 'node' | 'recovery';
command_started_at: number | null;
verified_exit: number;
script_started_at: number | null;
@@ -158,6 +162,7 @@ export async function auditSchedule(
db: Sequelize,
dayStart: number,
now = Date.now(),
details?: AnomalyPage,
) {
// All counts use the same settled plan window and the same committed snapshot.
const nextDay = new Date(dayStart);
@@ -180,14 +185,14 @@ export async function auditSchedule(
CASE WHEN c.token IS NULL THEN COALESCE(r.until,$through) ELSE COALESCE(c.last_at,$through) END AS close_latest
FROM CronPlanRules r LEFT JOIN CronPlanSwitches o ON o.token=r.opened_by
LEFT JOIN CronPlanSwitches c ON c.token=r.closed_by
WHERE r.since < $through AND close_latest >= $since`,
WHERE r.since < $through AND close_latest >= $since ORDER BY r.cron_id,r.rule_index,r.since,r.rowid`,
{ transaction, bind, type: QueryTypes.SELECT },
);
const receipts = await db.query<Receipt>(
`SELECT id,cron_id,scheduled_at,observed_at,state,
`SELECT id,cron_id,scheduled_at,observed_at,state,${details ? 'source,reason,log_path,' : ''}
command_started_at,script_started_at,queued_at,COALESCE(dequeued_at,started_at) AS started_at,
EXISTS(SELECT 1 FROM CronLegacyExitBookings b WHERE b.trigger_id=CronTriggers.id AND b.bound=1) AS verified_exit FROM CronTriggers
WHERE scheduled_at BETWEEN $since AND $through AND source IN ('node','recovery')`,
WHERE scheduled_at BETWEEN $since AND $through AND source IN ('node','recovery') ${details ? 'ORDER BY cron_id,scheduled_at,id' : ''}`,
{ transaction, bind, type: QueryTypes.SELECT },
);
return { since: coverage.since, rules, receipts };
@@ -235,6 +240,7 @@ export async function auditSchedule(
);
if (certain < possible) partial = true;
expected += certain;
const received = details?.kind === 'missing' && certain ? new Set<number>() : null;
for (const row of byTaskBlock.get(rule.cron_id + '/' + block) ?? []) {
const time = row.scheduled_at;
if (
@@ -244,6 +250,7 @@ export async function auditSchedule(
row.id !== slotId(rule.cron_id, rule.rule_index, rule.schedule, time)
)
continue;
received?.add(time);
const deviation = Math.abs(row.observed_at - time);
deviations.push(deviation);
if (deviation <= 5000) onTime++;
@@ -255,13 +262,28 @@ export async function auditSchedule(
dispatched++;
if (row.command_started_at != null && row.command_started_at >= time)
starts.push(row.command_started_at - time);
} else if (row.state === 'skipped') skipped++;
else if (row.state === 'queued') queued++;
} else if (row.state === 'queued') {
queued++;
} else {
const kind = row.state === 'skipped' ? 'skipped' : 'unconfirmed';
if (kind === 'skipped') skipped++;
if (details?.kind === kind) details.add({
task: row.cron_id, rule: rule.schedule, ruleIndex: rule.rule_index, time, source: row.source,
trigger: row.id, observed: row.observed_at, reason: row.reason, logPath: row.log_path,
});
}
if (row.script_started_at != null && row.script_started_at >= time)
entries.push(row.script_started_at - time);
if (row.started_at != null && row.queued_at != null && row.started_at >= row.queued_at)
waits.push(row.started_at - row.queued_at);
}
if (details && received && received.size < certain) {
for (let i = lowerBound(times, certainFirst); i < times.length && times[i] <= certainLast; i++) {
if (!received.has(times[i])) details.add({ task: Number(rule.cron_id), rule: rule.schedule,
ruleIndex: rule.rule_index, time: times[i], source: 'node', trigger: null,
observed: null, reason: null, logPath: null });
}
}
}
}
const observed = deviations.length;
+13
View File
@@ -0,0 +1,13 @@
import Logger from '../loaders/logger';
import { performance } from 'perf_hooks';
export async function startupStage<T>(name: string, operation: () => Promise<T>): Promise<T> {
if (process.env.QL_STARTUP_TIMING !== '1') return operation();
const started = performance.now();
try {
return await operation();
} finally {
const role = process.env.SERVICE_TYPE || 'primary';
Logger.info(`[boot:timing] ${role}:${name} ${Math.round(performance.now() - started)}ms (PID: ${process.pid})`);
}
}
+24 -4
View File
@@ -1,3 +1,4 @@
import { AnomalyPage } from './scheduleAnomalies';
import { QueryTypes, Sequelize, Transaction } from 'sequelize';
import { blockSize, blockSlots } from './scheduleAudit';
@@ -15,6 +16,8 @@ type Receipt = {
system_rule: string | null;
observed_at: number;
system_dispatch_at: number | null;
reason: string | null;
log_path: string | null;
launched: number;
state: string;
};
@@ -83,6 +86,7 @@ export async function systemScheduleAudit(
db: Sequelize,
dayStart: number,
now = Date.now(),
details?: AnomalyPage,
) {
const next = new Date(dayStart);
next.setHours(24, 0, 0, 0);
@@ -101,7 +105,7 @@ export async function systemScheduleAudit(
{ transaction, bind: { since, now }, type: QueryTypes.SELECT },
);
const receipts = await db.query<Receipt>(
`SELECT id,cron_id,system_rule,system_dispatch_at,observed_at,state,
`SELECT id,cron_id,system_rule,system_dispatch_at,observed_at,state,${details ? 'reason,log_path,' : ''}
(command_started_at IS NOT NULL OR script_started_at IS NOT NULL OR
(started_at IS NOT NULL AND EXISTS (SELECT 1 FROM CronLegacyExitBookings b
WHERE b.trigger_id=CronTriggers.id AND b.bound=1 AND b.disputed=0))) AS launched
@@ -133,6 +137,7 @@ export async function systemScheduleAudit(
(JSON.parse(plan.rules) as SystemRule[]).map((rule) => [rule.id, rule]),
),
}));
const matched = details && details.kind !== 'missing' ? new Map<string, { time: number; name?: string }>() : null;
const groups = new Map<string, Receipt[]>();
const dispatchedTasks = new Set<string>();
const legacyThrough = new Map<string, number>();
@@ -247,10 +252,11 @@ export async function systemScheduleAudit(
);
let status: string;
const launched = group.find((row) => row.launched === 1);
const skip = group.find((row) => row.state === 'skipped');
const skip = group.find((row) => !row.launched && row.state === 'skipped');
if (group.length) {
++expected;
++observed;
if (matched) for (const row of group) matched.set(row.id, { time, name });
matchedReceipts += group.length;
duplicates += group.length - 1;
if (launched) ++dispatched;
@@ -277,6 +283,8 @@ export async function systemScheduleAudit(
status = 'awaiting';
} else {
++missing;
if (details?.kind === 'missing') details.add({ task, name, rule: schedule, time, source: 'system',
trigger: null, observed: null, reason: null, logPath: null });
status = 'missing';
}
}
@@ -287,7 +295,7 @@ export async function systemScheduleAudit(
status,
triggerCount: group.length,
startCount: group.filter((row) => row.launched === 1).length,
skipCount: group.filter((row) => row.state === 'skipped').length,
skipCount: group.filter((row) => !row.launched && row.state === 'skipped').length,
unknownExitCount: group.filter((row) => row.launched === 1 && row.state === 'unknown').length,
id: (launched || skip || group[0])?.id,
});
@@ -296,6 +304,18 @@ export async function systemScheduleAudit(
recent.unshift(...entries.sort((a, b) => a.task - b.task).slice(0, 25));
recent.splice(25);
}
let actualSkips = 0, actualUnconfirmed = 0;
for (const row of receipts) {
if (row.launched === 1) continue;
const kind = row.state === 'skipped' ? 'skipped' : 'unconfirmed';
if (kind === 'skipped') actualSkips++;
else actualUnconfirmed++;
if (details?.kind === kind) {
const slot = matched?.get(row.id);
details.add({ task: row.cron_id, name: slot?.name, rule: row.system_rule, time: slot?.time ?? null,
source: 'system', trigger: row.id, observed: row.observed_at, reason: row.reason, logPath: row.log_path });
}
}
return {
since: Math.max(since, plans[0]?.staged ?? since),
through,
@@ -312,7 +332,7 @@ export async function systemScheduleAudit(
uncertain,
awaiting,
switchSlots,
actualSkips: receipts.filter((row) => row.state === 'skipped').length,
actualSkips, actualUnconfirmed,
actualStarts: receipts.filter((row) => row.launched === 1).length,
unmatched: receipts.length - matchedReceipts,
recent,
@@ -8,6 +8,10 @@ The catalogue covers the active routes in the current backend. `ql api routes --
Log and script pages return `versions`. Pass the visited directories’ versions to the matching `entries-check --data` command in groups of 1 to 128. Restart pagination when it returns `current: false`.
`ql dashboard schedule-anomalies --query '{"source":"panel","kind":"missing","at":1795046400000}'` 查询异常明细。`source` 为 `panel` 或 `system`,`kind` 为 `missing`、`skipped` 或 `unconfirmed`;`at` 必须替换为查询窗口的服务端毫秒时间戳。分页传 `page` 和上一响应的 `revision`,记录变化时按返回的 `page` 重新展示。`live:true` 用于今日实时明细:返回 `status: expired` 或 `unavailable` 时重新读取 overview,不能把该响应当作空页继续拼接。
`ql dashboard schedule-anomalies` accepts required `source` (`panel` or `system`), `kind` (`missing`, `skipped` or `unconfirmed`) and `at` (server epoch milliseconds for the query window) through `--query`. Pass `page` and the previous `revision` for pagination and honor the returned page if records change. With `live:true`, refresh the overview when `status` is `expired` or `unavailable`; do not append these responses as empty pages.
`ql task instances <id>` 默认返回该任务的完整运行历史,按启动时间倒序。显式传 `--query '{"paged":true,"limit":25}'` 后按实例 ID 倒序分页(默认 25,最多 100),将返回的 `next` 作为下一页的 `before`,直到 `next` 为 `null`。刷新指定实例可传 `{"paged":true,"ids":"12,13"}`。触发记录使用独立的 `task triggers` 接口,日志和脚本目录分页使用 `log entries` 和 `script entries`。
`ql task instances <id>` returns the full history ordered by start time by default. Opt in with `--query '{"paged":true,"limit":25}'` to page by descending instance ID (default 25, maximum 100). Pass `next` as `before` until `next` is `null`. Use `{"paged":true,"ids":"12,13"}` to refresh specific rows. Trigger history and directory pagination use separate endpoints.
@@ -214,6 +218,7 @@ System/user operations below execute remotely through the panel API. They do not
| `ql system config-dependence-clean ` | PUT | `system/config/dependence-clean` | --data, --query |
| `ql dashboard record ` | POST | `dashboard/record` | --data, --query |
| `ql dashboard overview ` | GET | `dashboard/overview` | --query |
| `ql dashboard schedule-anomalies ` | GET | `dashboard/schedule-anomalies` | --query |
| `ql dashboard trend ` | GET | `dashboard/trend` | --query |
| `ql dashboard top-time ` | GET | `dashboard/top-time` | --query |
| `ql dashboard top-count ` | GET | `dashboard/top-count` | --query |
+5
View File
@@ -523,6 +523,11 @@ export const openOperations: readonly OpenOperation[] = [
body: 'json',
},
{ name: 'dashboard overview', method: 'GET', path: 'dashboard/overview' },
{
name: 'dashboard schedule-anomalies',
method: 'GET',
path: 'dashboard/schedule-anomalies',
},
{ name: 'dashboard trend', method: 'GET', path: 'dashboard/trend' },
{ name: 'dashboard top-time', method: 'GET', path: 'dashboard/top-time' },
{ name: 'dashboard top-count', method: 'GET', path: 'dashboard/top-count' },
+29
View File
@@ -58,6 +58,35 @@ test('dashboard record sends execution statistics and rejects a missing body bef
assert.equal(f.requests.length, 1);
});
test('schedule anomaly commands preserve sources, pagination and expired responses', async t => {
const f = await fixture(t);
const response = { code: 200, data: { status: 'expired' } };
f.reply((_req, res) => {
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify(response));
});
for (const source of ['panel', 'system']) {
for (const kind of ['missing', 'skipped', 'unconfirmed']) {
const query = { source, kind, at: 1795046400000, page: 3, revision: 'a'.repeat(64), live: true };
for (const command of [
['dashboard', 'schedule-anomalies'],
['api', 'request', 'GET', '/open/dashboard/schedule-anomalies'],
]) {
const before = f.requests.length;
assert.deepEqual(success(await f.run([...command, '--query', JSON.stringify(query)])), response);
assert.equal(f.requests.length, before + 1, 'expired responses must not be retried');
const req = f.requests.at(-1), url = new URL(req.url, 'http://localhost');
assert.equal(req.method, 'GET');
assert.equal(url.pathname, '/panel/open/dashboard/schedule-anomalies');
assert.deepEqual(Object.fromEntries(url.searchParams),
Object.fromEntries(Object.entries(query).map(([key, value]) => [key, String(value)])));
assert.equal(req.body, '');
assert.equal(req.headers.authorization, 'Bearer fixture-token');
}
}
}
});
test('script history commands send exact query parameters and restore payloads', async t => {
const f = await fixture(t);
const identity = { filename: '中文 script.js', path: 'nested folder' };
+5 -4
View File
@@ -3,13 +3,14 @@
"back",
".env"
],
"ext": "js,ts,json",
"ext": "js,cjs,ts,json",
"env": {
"NODE_ENV": "development",
"TS_NODE_PROJECT": "./back/tsconfig.json"
"TS_NODE_PROJECT": "./back/tsconfig.json",
"QL_STARTUP_TIMING": "1"
},
"verbose": true,
"execMap": {
"ts": "node --require ts-node/register"
"ts": "node --require ts-node/register/transpile-only"
}
}
}
+14
View File
@@ -1,4 +1,18 @@
{
"日期已变化,已关闭旧明细并刷新今日调度。": "The date changed. Previous details were closed and today’s schedule was refreshed.",
"这次明细已不可用,已关闭并刷新调度统计。": "These details are no longer available. The dialog was closed and scheduling statistics were refreshed.",
"截至 {time} 的计划,明细随回报更新。": "Plans through {time}. Details update as reports arrive.",
"记录已更新,已返回第一页,当前共 {count} 条。": "Records changed. Returned to page 1 with {count} records.",
"{title},查看 {count} 条明细": "{title}, view {count} details",
"规则已生效,计划过了一分钟仍无匹配的系统触发记录。": "The rule was active. No matching crond trigger was recorded within the minute or by the time of this check.",
"规则已生效,统计时未找到本轮计划的触发记录。": "The rule was active. No trigger matched this scheduled occurrence at the time of this check.",
"已记录跳过,未提供具体原因。": "The trigger was recorded as skipped without a specific reason.",
"已收到触发,缺少可核实命令已启动的记录。": "The trigger was recorded, but command startup could not be verified.",
"触发记录已有更新,当前共 {count} 条。": "Trigger records have changed. The current total is {count}.",
"计划时间无法确定": "Scheduled time unknown",
"收到于 {time}": "Received at {time}",
"调度来源": "Scheduler",
"判断原因": "Reason",
"查看最新记录": "View latest records",
"查看新的运行记录": "View new runs",
"加载更多": "Load more",
+14
View File
@@ -1,4 +1,18 @@
{
"日期已变化,已关闭旧明细并刷新今日调度。": "日期已变化,已关闭旧明细并刷新今日调度。",
"这次明细已不可用,已关闭并刷新调度统计。": "这次明细已不可用,已关闭并刷新调度统计。",
"截至 {time} 的计划,明细随回报更新。": "截至 {time} 的计划,明细随回报更新。",
"记录已更新,已返回第一页,当前共 {count} 条。": "记录已更新,已返回第一页,当前共 {count} 条。",
"{title},查看 {count} 条明细": "{title},查看 {count} 条明细",
"规则已生效,计划过了一分钟仍无匹配的系统触发记录。": "规则已生效,计划过了一分钟仍无匹配的系统触发记录。",
"规则已生效,统计时未找到本轮计划的触发记录。": "规则已生效,统计时未找到本轮计划的触发记录。",
"已记录跳过,未提供具体原因。": "已记录跳过,未提供具体原因。",
"已收到触发,缺少可核实命令已启动的记录。": "已收到触发,缺少可核实命令已启动的记录。",
"触发记录已有更新,当前共 {count} 条。": "触发记录已有更新,当前共 {count} 条。",
"计划时间无法确定": "计划时间无法确定",
"收到于 {time}": "收到于 {time}",
"调度来源": "调度来源",
"判断原因": "判断原因",
"查看最新记录": "查看最新记录",
"查看新的运行记录": "查看新的运行记录",
"加载更多": "加载更多",
+12
View File
@@ -1,3 +1,5 @@
@import '~antd/es/style/themes/default.less';
.schedule-overview {
margin-top: 16px;
container-type: inline-size;
@@ -121,3 +123,13 @@
> :first-child { margin-top: 0; }
.timing-samples { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px 16px; }
}
.anomaly-count {
padding: 0;
border: 0;
background: transparent;
color: var(--ant-primary-color, @primary-color);
font: inherit;
cursor: pointer;
&:hover, &:focus-visible { text-decoration: underline; }
}
+67 -15
View File
@@ -1,5 +1,5 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { Button, Card, Col, Popover, Row, Statistic, Table, Tabs, Tag, Spin, Empty } from 'antd';
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { message, Button, Card, Col, Popover, Row, Statistic, Table, Tabs, Tag, Spin, Empty } from 'antd';
import {
CheckCircleOutlined,
CloseCircleOutlined,
@@ -19,10 +19,14 @@ import config from '@/utils/config';
import CronLogModal from '../crontab/logModal';
import { QueueReason } from '../crontab/triggerTiming';
import TimingStatistic from './timingStatistic';
import ScheduleAnomalies, { AnomalyMetric, AnomalySelection } from './scheduleAnomalies';
import TaskResultModal from './taskResultModal';
import './index.less';
interface Overview {
export interface Overview {
serverNow?: number;
expiresAt?: number;
anomalyDeadline?: number;
total: number;
enabled: number;
disabled: number;
@@ -33,7 +37,7 @@ interface Overview {
triggerDeviationP95: number | null; waitP95: number | null; commandStartP95: number | null;
scriptStartP95: number | null; scriptSamples: number;
} | null; systemAudit?: {
since: number; confirmedAt: number | null; pending: boolean; partial: boolean; expected: number; observed: number;
since: number; through: number; actualUnconfirmed?: number; confirmedAt: number | null; pending: boolean; partial: boolean; expected: number; observed: number;
dispatched: number; skipped: number; missing: number; unmatched: number; duplicates: number; actualStarts: number; actualSkips?: number; uncertain: number; awaiting: number; switchSlots: number;
recent: { time: number; task: number; name?: string; status: string; id?: string; triggerCount?: number; startCount?: number; skipCount?: number; unknownExitCount?: number }[];
} | null };
@@ -137,6 +141,29 @@ const Dashboard = () => {
const [result, setResult] = useState<'success' | 'failure' | null>(null);
const [selectedSource, setSelectedSource] = useState<string>();
const [anomaly, setAnomaly] = useState<AnomalySelection>();
const anomalySession = useRef<AnomalySelection>();
const anomalyVersion = useRef(0);
const closeAnomaly = useCallback(() => {
anomalySession.current = undefined;
setAnomaly(undefined);
}, []);
const updateAnomalySummary = useCallback((selection: AnomalySelection, summary: NonNullable<Overview['triggers']>) => {
if (anomalySession.current !== selection) return;
setOverview(previous => anomalySession.current === selection && previous
? { ...previous, triggers: { ...previous.triggers, ...summary } } : previous);
}, []);
const invalidateAnomaly = useCallback((selection: AnomalySelection, reason: 'expired' | 'unavailable') => {
if (anomalySession.current !== selection) return;
const version = anomalyVersion.current;
closeAnomaly();
setOverview(previous => anomalyVersion.current === version && previous
? { ...previous, triggers: undefined } : previous);
setLogCron(previous => previous?.anomalySession === selection.session ? null : previous);
message.info(intl.get(reason === 'expired'
? '日期已变化,已关闭旧明细并刷新今日调度。'
: '这次明细已不可用,已关闭并刷新调度统计。'));
}, [closeAnomaly]);
const [helpOpen, setHelpOpen] = useState(false);
const helpButton = useRef<HTMLButtonElement>(null);
const helpPopover = useRef<{ forcePopupAlign(): void }>(null);
@@ -207,11 +234,22 @@ const Dashboard = () => {
if (pending.has(section)) return;
pending.add(section);
try {
const requestedAt = performance.now();
const response = await request.get<{ code: number; data: T }>(
`${config.apiPrefix}dashboard/${section}`, { signal, retryInPlace: true },
);
if (signal.aborted) return;
if (response.code === 200) apply(response.data);
if (response.code === 200) {
let data = response.data;
if (section === 'overview' && data) {
const clock = data as Overview;
if (typeof clock.expiresAt === 'number' && typeof clock.serverNow === 'number') {
const deadline = requestedAt + clock.expiresAt - clock.serverNow;
if (Number.isFinite(deadline)) data = { ...data, anomalyDeadline: deadline };
}
}
apply(data);
}
if (section === 'overview') setOverviewFailed(response.code !== 200);
} catch {
if (!signal.aborted && section === 'overview') setOverviewFailed(true);
@@ -222,7 +260,7 @@ const Dashboard = () => {
}
function poll() {
void refresh<Overview>('overview', setOverview);
if (!anomaly) void refresh<Overview>('overview', setOverview);
void refresh<TrendItem[]>('trend', setTrend);
void refresh<TopItem[]>('top-time', setTopTime);
void refresh<TopItem[]>('top-count', setTopCount);
@@ -237,7 +275,7 @@ const Dashboard = () => {
clearInterval(timer);
controller.abort();
};
}, []);
}, [anomaly]);
const trendConfig = {
data: trend.flatMap((d) => [
@@ -270,6 +308,13 @@ const Dashboard = () => {
if (loading) return <Spin size="large" style={{ display: 'block', marginTop: 100 }} />;
const anomalyMetric = (source: AnomalySelection['source'], kind: AnomalySelection['kind'], count: number | undefined, through: number) =>
<AnomalyMetric kind={kind} count={count} open={() => {
const selection = { kind, source, count: count!, at: through + 5000, session: ++anomalyVersion.current,
deadline: overview?.anomalyDeadline };
anomalySession.current = selection;
setAnomaly(selection);
}} />;
const sources = [];
if (audit) {
const timings = [
@@ -298,13 +343,13 @@ const Dashboard = () => {
children: <>
<div className="schedule-metrics">
<Statistic title={intl.get('计划触发次数')} value={audit.expected} />
<Statistic title={intl.get('未收到触发记录')} value={audit.missing} />
{anomalyMetric('panel', 'missing', audit.missing, audit.through)}
<Statistic title={intl.get('有触发记录的计划')} value={audit.observed} />
<ScheduleRate title={intl.get('准时触发率')} count={audit.partial ? undefined : audit.onTime} total={audit.expected} />
<Statistic title={intl.get('命令已启动')} value={audit.dispatched} />
<Statistic title={intl.get('触发后跳过')} value={audit.skipped} />
{anomalyMetric('panel', 'skipped', audit.skipped, audit.through)}
<Statistic title={intl.get('仍在排队')} value={audit.queued} />
<Statistic title={intl.get('启动未确认')} value={audit.unconfirmed} />
{anomalyMetric('panel', 'unconfirmed', audit.unconfirmed, audit.through)}
</div>
<details className="schedule-details">
<summary>{intl.get('查看启动耗时')}</summary>
@@ -332,14 +377,15 @@ const Dashboard = () => {
<div className="schedule-metrics">
<Statistic title={intl.get('计划触发次数')} value={systemAudit.expected} />
<Statistic title={intl.get('有触发记录的计划')} value={systemAudit.observed} />
<Statistic title={intl.get('未收到触发记录')} value={systemAudit.missing} />
{anomalyMetric('system', 'missing', systemAudit.missing, systemAudit.through)}
</div>
<h4 className="schedule-group-title">{intl.get('按触发记录统计(共 {count} 条)', {
count: systemAudit.observed + systemAudit.duplicates + systemAudit.unmatched,
})}</h4>
<div className="schedule-metrics">
<Statistic title={intl.get('命令启动次数')} value={systemAudit.actualStarts} />
<Statistic title={intl.get('跳过次数')} value={systemAudit.actualSkips ?? '—'} />
{anomalyMetric('system', 'skipped', systemAudit.actualSkips, systemAudit.through)}
{anomalyMetric('system', 'unconfirmed', systemAudit.actualUnconfirmed, systemAudit.through)}
<Statistic title={intl.get('重复触发次数')} value={systemAudit.duplicates} />
<Statistic title={intl.get('找不到对应计划的触发记录')} value={systemAudit.unmatched} />
</div>
@@ -447,7 +493,7 @@ const Dashboard = () => {
</>}>
{sources.length === 2 ? (
<Tabs items={sources.map(({ key, label, children }) => ({ key, label, children }))}
activeKey={activeSource?.key} onChange={setSelectedSource} />
activeKey={activeSource?.key} onChange={source => { setSelectedSource(source); closeAnomaly(); }} />
) : sources.length === 1 ? (
sources[0].children
) : (
@@ -616,11 +662,17 @@ const Dashboard = () => {
</Col>
</Row>
{result && <TaskResultModal key={result} result={result} onCancel={() => setResult(null)} />}
{anomaly && <ScheduleAnomalies key={anomaly.session}
selection={anomaly} onUpdate={updateAnomalySummary} onInvalidate={invalidateAnomaly} close={closeAnomaly}
openLog={(id, trigger, name) => {
if (anomalySession.current === anomaly)
setLogCron({ id, trigger, name, anomalySession: anomaly.session });
}} />}
{logCron && (
<CronLogModal
key={logCron.instanceId}
key={logCron.trigger ?? logCron.instanceId}
cron={logCron}
logUrl={`${config.apiPrefix}crons/${logCron.id}/log?instanceId=${logCron.instanceId}`}
logUrl={`${config.apiPrefix}crons/${logCron.id}/log?${logCron.trigger ? 'triggerId=' + encodeURIComponent(logCron.trigger) : 'instanceId=' + logCron.instanceId}`}
handleCancel={() => setLogCron(null)}
/>
)}
+140
View File
@@ -0,0 +1,140 @@
import { useEffect, useRef, useState } from 'react';
import { Alert, Button, Modal, Table } from 'antd';
import intl from 'react-intl-universal';
import { request } from '@/utils/http';
import config from '@/utils/config';
import type { Overview } from './index';
const titles = { missing: '未收到触发记录', skipped: '触发后跳过', unconfirmed: '启动未确认' };
export interface AnomalySelection {
kind: keyof typeof titles;
source: 'panel' | 'system';
at: number;
count: number;
session?: number;
deadline?: number;
}
interface Row {
task: number; name?: string; time: number | null; observed: number | null; source: string;
rule: string | null; ruleIndex?: number; trigger: string | null; reason: string | null; hasLog: boolean;
}
interface Result { summary: NonNullable<Overview['triggers']>; rows: Row[]; page: number; total: number; pageSize: number; revision: string; changed: boolean; zone: string }
export function AnomalyMetric({ kind, count, open }: {
kind: AnomalySelection['kind']; count?: number; open: () => void;
}) {
return <div className="ant-statistic">
<div className="ant-statistic-title">{intl.get(titles[kind])}</div>
<div className="ant-statistic-content">
{count != null && count > 0 ? <button className="anomaly-count" onClick={open}
aria-label={intl.get('{title},查看 {count} 条明细', { title: intl.get(titles[kind]), count })}>{count.toLocaleString()}</button> : count ?? '—'}
</div>
</div>;
}
const reasons: Record<string, string> = {
pending: '上一次定时触发仍在排队或运行', overlap: '上一次执行仍在运行', changed: '任务已变更或取消',
queue_timeout: '超过排队时限', capacity: '该任务的待执行次数已达上限', restart: '服务重启',
spawn: '启动或执行失败', cancelled: '已取消',
};
function explanation(kind: AnomalySelection['kind'], row: Row) {
if (kind === 'missing') return intl.get(row.source === 'system'
? '规则已生效,计划过了一分钟仍无匹配的系统触发记录。' : '规则已生效,统计时未找到本轮计划的触发记录。');
const reason = row.reason && (reasons[row.reason] ? intl.get(reasons[row.reason]) : row.reason);
if (kind === 'skipped') return reason || intl.get('已记录跳过,未提供具体原因。');
return [intl.get('已收到触发,缺少可核实命令已启动的记录。'), reason].filter(Boolean).join(' ');
}
export default function ScheduleAnomalies({ selection, close, openLog, onUpdate, onInvalidate }: {
onUpdate: (selection: AnomalySelection, summary: NonNullable<Overview['triggers']>) => void;
onInvalidate: (selection: AnomalySelection, reason: 'expired' | 'unavailable') => void;
selection: AnomalySelection; close: () => void; openLog: (id: number, trigger: string, name?: string) => void;
}) {
const [query, setQuery] = useState<{ page: number; revision?: string }>({ page: 1 });
const [response, setResponse] = useState<{ query: typeof query; result: Result }>();
const data = response?.query === query ? response.result : undefined;
const [failed, setFailed] = useState(false);
const [loading, setLoading] = useState(true);
const expiresAt = useRef<number>();
useEffect(() => {
const ctrl = new AbortController();
let timer: ReturnType<typeof setTimeout>;
let deadline: ReturnType<typeof setTimeout>;
const invalidate = (reason: 'expired' | 'unavailable') => {
ctrl.abort();
clearTimeout(timer);
clearTimeout(deadline);
onInvalidate(selection, reason);
};
const deadlineAt = expiresAt.current ?? selection.deadline;
if (deadlineAt != null) {
const remaining = deadlineAt - performance.now();
if (remaining <= 0) {
invalidate('expired');
return () => ctrl.abort();
}
deadline = setTimeout(() => invalidate('expired'), remaining);
}
let cursor = { ...query };
setFailed(false);
setLoading(true);
async function refresh() {
try {
const requestedAt = performance.now();
const { code, data } = await request.get(config.apiPrefix + 'dashboard/schedule-anomalies', {
params: { kind: selection.kind, source: selection.source, at: selection.at, live: true, ...cursor },
signal: ctrl.signal, retryInPlace: true,
});
if (ctrl.signal.aborted) return;
if (code !== 200) throw new Error();
if (data.status === 'expired' || data.status === 'unavailable') {
invalidate(data.status);
return;
}
const remaining = data.expiresAt - data.serverNow - (performance.now() - requestedAt);
if (Number.isFinite(remaining)) {
if (remaining <= 0) {
invalidate('expired');
return;
}
clearTimeout(deadline);
expiresAt.current = performance.now() + remaining;
deadline = setTimeout(() => invalidate('expired'), remaining);
}
cursor = { page: data.page, revision: data.revision };
setResponse({ query, result: data });
onUpdate(selection, data.summary);
timer = setTimeout(refresh, 5000);
} catch {
if (!ctrl.signal.aborted) setFailed(true);
} finally {
if (!ctrl.signal.aborted) setLoading(false);
}
}
void refresh();
return () => { ctrl.abort(); clearTimeout(timer); clearTimeout(deadline); };
}, [selection, query, onUpdate, onInvalidate]);
const format = (ms: number) => new Date(ms).toLocaleString(undefined, { timeZone: data?.zone, hour12: false });
return <Modal open width={860} title={<>{intl.get(titles[selection.kind])} · {intl.get(selection.source === 'panel' ? '由青龙触发' : '由系统触发(crond)')}</>} onCancel={close} footer={null}>
<p>{intl.get('截至 {time} 的计划,明细随回报更新。', { time: format(selection.at - 5000) })}</p>
{failed ? <Alert type="error" message={<>{intl.get('加载失败')} <Button type="link"
onClick={() => setQuery({ ...query })}>{intl.get('重试')}</Button></>} /> : <>
{data && (data.changed || data.total !== selection.count) && <Alert type="info" showIcon
message={intl.get(data.changed ? '记录已更新,已返回第一页,当前共 {count} 条。' : '触发记录已有更新,当前共 {count} 条。', { count: data.total })} />}
<Table<Row> size="small" loading={loading} dataSource={data?.rows ?? []} scroll={{ x: 660 }}
rowKey={row => row.trigger ?? [row.task, row.time, row.ruleIndex, row.rule].join('/')}
pagination={data && { current: data.page, pageSize: data.pageSize, total: data.total, showSizeChanger: false,
showTotal: total => intl.get('总条数', { total }), onChange: page => setQuery({ page, revision: data.revision }) }}
columns={[
{ title: intl.get('任务'), render: (_, r) => <>{r.name || '#' + r.task}<br/><small>{r.rule}</small></> },
{ title: intl.get('计划时间'), render: (_, r) => r.time != null ? format(r.time) : <>
{intl.get('计划时间无法确定')}<br/><small>{r.observed != null && intl.get('收到于 {time}', {time: format(r.observed)})}</small></> },
{ title: intl.get('调度来源'), render: (_, r) => intl.get(r.source === 'system' ? '由系统触发(crond)' : r.source === 'recovery' ? '重启补跑' : '由青龙触发') },
{ title: intl.get('判断原因'), render: (_, r) => explanation(selection.kind, r) },
{ title: intl.get('日志'), render: (_, r) => r.hasLog && r.trigger ? <Button type="link" size="small"
onClick={() => openLog(r.task, r.trigger!, r.name)}>{intl.get('查看日志')}</Button> : '—' },
]} />
</>}
</Modal>;
}
+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);
});