import type { ReactNode } from "react"; import { useCallback, useEffect, useState } from "react"; import { Alert, Button, Card, Descriptions, Form, InputNumber, Popconfirm, Space, Switch, Table, Tag, Typography, } from "antd"; import type { ColumnsType } from "antd/es/table"; import { ReloadOutlined, ThunderboltOutlined } from "@ant-design/icons"; import { message } from "../utils/antdMessage"; import { getErrorMessage } from "../utils/error"; import { automationApi, type AutomationJobItem, type AutomationManualGroup, type AutomationManualSample, type AutomationRunItem, } from "../api/modules"; import { usePermissions } from "../hooks/usePermissions"; import { formatTime } from "../utils/time"; const STATUS_TAG: Record = { success: { color: "green", text: "成功" }, failed: { color: "red", text: "失败" }, running: { color: "blue", text: "执行中" }, skipped: { color: "default", text: "已跳过" }, }; /** * 下次运行时间:两个作业串行跑在同一个调度线程里,前一个作业耗时长时, * 后一个会排队等待 —— 于是 next_run_at 会停在「已经过了」的时刻。 * 直接显示一个过去时间看起来像故障,这里标明「排队中」。 */ function nextRunLabel(job: AutomationJobItem): ReactNode { if (!job.next_run_at) { return 未启用; } const next = new Date(job.next_run_at).getTime(); if (!Number.isFinite(next)) return formatTime(job.next_run_at); if (next > Date.now()) return formatTime(job.next_run_at); return ( 排队中{" "} ({formatTime(job.next_run_at)} 到期,等待前序作业让出线程) ); } function secondsToHours(seconds: number): number { return Math.round((seconds / 3600) * 10) / 10; } export default function AutomationPage() { const [jobs, setJobs] = useState([]); const [schedulerEnabled, setSchedulerEnabled] = useState(true); const [schedulerRunning, setSchedulerRunning] = useState(false); const [runs, setRuns] = useState([]); const [manualGroups, setManualGroups] = useState([]); const [manualTotal, setManualTotal] = useState(0); const [pendingRelogin, setPendingRelogin] = useState(0); const [loading, setLoading] = useState(false); const [savingKey, setSavingKey] = useState(null); const [runningKey, setRunningKey] = useState(null); const [forms] = Form.useForm(); const { can } = usePermissions(); const canManage = can("automation:manage"); const load = useCallback(async () => { setLoading(true); try { const data = await automationApi.jobs(); setJobs(data.jobs); setPendingRelogin(data.pending_relogin ?? 0); setSchedulerEnabled(data.scheduler.enabled); setSchedulerRunning(data.scheduler.running); const history = await automationApi.runs({ limit: 50 }); setRuns(history.items); const manual = await automationApi.manualQueue(); setManualGroups(manual.groups); setManualTotal(manual.total); // 统一回填表单:initialValue 只在首次渲染生效,刷新后不会跟着变。 forms.setFieldsValue( Object.fromEntries( data.jobs.map((job) => [ job.key, { enabled: job.enabled, interval_hours: secondsToHours(job.interval_seconds), batch_size: job.batch_size, concurrency: job.concurrency, }, ]), ), ); } catch (e: unknown) { message.error(getErrorMessage(e)); } finally { setLoading(false); } }, [forms]); useEffect(() => { load(); }, [load]); const saveJob = async (job: AutomationJobItem) => { const values = forms.getFieldValue(job.key) || {}; setSavingKey(job.key); try { await automationApi.updateJob(job.key, { enabled: values.enabled, interval_seconds: Math.max( Math.round((values.interval_hours ?? 6) * 3600), 300, ), batch_size: values.batch_size, concurrency: values.concurrency, }); message.success(`${job.title} 配置已保存`); await load(); } catch (e: unknown) { message.error(getErrorMessage(e)); } finally { setSavingKey(null); } }; const runOnce = async (job: AutomationJobItem) => { setRunningKey(job.key); try { const outcome = await automationApi.runJob(job.key); message.success( `跑完一轮:扫描 ${outcome.scanned} 条,有效 ${outcome.valid},失效 ${outcome.invalid}`, ); await load(); } catch (e: unknown) { message.error(getErrorMessage(e)); } finally { setRunningKey(null); } }; const manualColumns: ColumnsType = [ { title: "记录", dataIndex: "task_id", width: 80 }, { title: "账号", dataIndex: "account_username", width: 160, ellipsis: true, }, { title: "已重试", dataIndex: "relogin_attempts", width: 80 }, { title: "失败原因", dataIndex: "last_error", ellipsis: true, render: (value: string) => value || "-", }, { title: "最近尝试", dataIndex: "attempt_at", width: 160, render: (value: string | null) => formatTime(value), }, ]; const runColumns: ColumnsType = [ { title: "开始时间", dataIndex: "started_at", width: 180, render: (value: string | null) => formatTime(value), }, { title: "作业", dataIndex: "job_key", width: 120, }, { title: "结果", dataIndex: "status", width: 90, render: (value: string) => { const tag = STATUS_TAG[value] ?? { color: "default", text: value || "-", }; return {tag.text}; }, }, { title: "扫描", dataIndex: "scanned", width: 80 }, { title: "有效", dataIndex: "valid", width: 80 }, { title: "失效", dataIndex: "invalid", width: 80, render: (value: number) => value > 0 ? ( {value} ) : ( 0 ), }, { title: "耗时", width: 90, render: (_, row) => // 没实际扫描过的轮次没有真实耗时:被中断的记录 finished_at 是重启后 // 补上的(见 cleanup_orphan_runs),差值里混入了停机时间,是个假数字; // 一轮就报错的(如 SQL 语法错误)同理。 row.scanned > 0 && row.finished_at ? formatDuration(row.started_at, row.finished_at) : "-", }, { title: "说明", dataIndex: "message", ellipsis: true }, ]; return ( } onClick={load} loading={loading}> 刷新 } > {!schedulerEnabled && ( )} {schedulerEnabled && !schedulerRunning && ( )} {jobs.map((job) => ( 上游:巡检标记为失效且有 CK 的账号,当前待重登{" "} {pendingRelogin} 个 ) : job.key === "ck_health" ? ( 下游:CK 自动重登(发现失效后自动接手) ) : null } style={{ marginBottom: 16 }} > {formatTime(job.last_run_at)} {nextRunLabel(job)} {job.last_status ? ( {STATUS_TAG[job.last_status]?.text ?? job.last_status} ) : ( "-" )} {job.last_message || "-"}
saveJob(job)}> runOnce(job)} disabled={!canManage} >
{!canManage && ( 当前账号只能查看,修改配置需要 automation:manage 权限。 )}
))}
自动重登救不了的类型(共 {manualTotal} 个) } > {manualGroups.length === 0 ? ( 暂无 —— 能自动重试的都会自己重试,需要人工的才出现在这里。 ) : ( manualGroups.map((group) => ( )) )}
); } function formatDuration(start: string | null, end: string | null): string { if (!start || !end) return "-"; const ms = new Date(end).getTime() - new Date(start).getTime(); if (!Number.isFinite(ms) || ms < 0) return "-"; if (ms < 1000) return `${ms}ms`; return `${(ms / 1000).toFixed(1)}s`; }