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

+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,