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

+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>;
}