feat: harden cron execution recovery and expose scheduling diagnostics

Reconcile scheduled and system cron triggers, isolate concurrent executions and retain verifiable exit statistics across restarts. Add paged task history, log and script browsing, dashboard timing details and regression coverage.
This commit is contained in:
whyour committed 2026-11-17 01:01:57 +08:00
1 parent 3b6a873520
commit 8a9e70e90b
166 files changed
+18942 -1800

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
.file-browser { height: 100%; display: flex; flex-direction: column; gap: 6px; min-height: 0; }
.file-browser-location { display: flex; align-items: center; gap: 8px; min-width: 0; padding-bottom: 4px; border-bottom: 1px solid rgba(127,127,127,.24); }
.file-browser-location > button { flex: none; min-height: 28px; }
.file-browser-path { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 0.9em; padding-inline-start: 8px; border-inline-start: 1px solid rgba(127,127,127,.3); }
.file-picker-label { max-width: 100%; overflow: hidden; text-overflow: ellipsis; text-align: left; }
.file-browser-entries { min-height: 0; overflow: auto; flex: 1; }
.file-browser-pagination { display: flex; justify-content: center; align-items: center; min-height: 32px; }
.file-browser-entries > button:not(.ant-btn) {
background: transparent; border: 0; color: inherit; cursor: pointer; display: flex;
align-items: flex-start; gap: 6px; padding: 4px; text-align: left; width: 100%; line-height: 1.5;
}
.file-browser-entries > button > .anticon { flex: none; margin-top: .25em; }
.file-browser-label { display: block; min-width: 0; }
.file-browser-name { display: flex; white-space: nowrap; }
.file-browser-name > span:first-child,
.file-browser-parent { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.file-browser-name > span:last-child { display: flex; justify-content: flex-end; flex: none; max-width: 100%; overflow: hidden; }
.file-browser-name > span:first-child:not(:empty) + span { max-width: 70%; }
.file-browser-parent { font-size: .85em; }
.file-browser-entries > button:hover, .file-browser-entries > button[aria-pressed=true] { background: rgba(127,127,127,.14); }
.file-picker { width: min(320px, 74vw); height: 320px; display: flex; flex-direction: column; }
.file-picker-label { max-width: min(300px, 60vw); }
+196
View File
@@ -0,0 +1,196 @@
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { Button, Empty, Input, Popover, Spin, Typography } from 'antd';
import { FileOutlined, FolderOutlined, ArrowUpOutlined, ReloadOutlined } from '@ant-design/icons';
import intl from 'react-intl-universal';
import config from '@/utils/config';
import { request } from '@/utils/http';
import { readableLogName } from './name';
import './index.less';
type Entry = { key: string; title: string; parent: string; type: 'file' | 'directory'; size?: number };
type Listing = { rows: Entry[]; next: string; versions: Map<string, string | null>; retryMinimum?: number; retryAfter?: string };
type ReadingPosition = { scrollTop: number; offsets: Map<string, number> };
const emptyListing: Listing = { rows: [], next: '', versions: new Map() };
type Props = {
source: 'logs' | 'scripts'; value?: string; initialDirectory?: string; revision?: number; folders?: boolean;
onSelect: (entry: Entry) => void; onDoubleClick?: (entry: Entry) => void;
};
// Match readDirectoryPage's depth-first search and directory-first listing order.
function pastCursor(cursor: string, boundary: string, source: Props['source'], search: string) {
if (search) {
// A directory's children precede its next sibling. NUL cannot occur in a filename.
return cursor.replace(/\//g, '\0') > boundary.replace(/\//g, '\0');
}
if (source === 'logs' && cursor.startsWith('1') && boundary.startsWith('1')) return cursor < boundary;
return cursor > boundary;
}
function Entries({ source, path, search, folders, value, open, onDoubleClick }: Props & {
path: string; search: string; open: (entry: Entry) => void;
}) {
const listing = useRef(emptyListing);
const [visible, setListing] = useState(listing.current);
const { rows, next } = visible;
const [loading, setLoading] = useState(true);
const [failed, setFailed] = useState(false);
const pending = useRef<AbortController>();
const viewport = useRef<HTMLDivElement>(null);
const position = useRef<ReadingPosition>();
function rememberPosition() {
const element = viewport.current;
if (!element || position.current) return;
const top = element.getBoundingClientRect().top;
const offsets = new Map<string, number>();
for (const row of Array.from(element.querySelectorAll<HTMLButtonElement>('button[title]'))) {
const rect = row.getBoundingClientRect();
if (rect.top >= top + element.clientHeight) break;
if (rect.bottom > top) offsets.set(row.title, rect.top - top);
}
if (offsets.size) position.current = { scrollTop: element.scrollTop, offsets };
}
useLayoutEffect(() => {
const element = viewport.current;
const saved = position.current;
if (!element || !saved || visible.retryMinimum !== undefined) return;
position.current = undefined;
const top = element.getBoundingClientRect().top;
for (const [key, offset] of saved.offsets) {
const row = element.querySelector<HTMLButtonElement>(`button[title="${CSS.escape(key)}"]`);
if (row) {
element.scrollTop += row.getBoundingClientRect().top - top - offset;
return;
}
}
element.scrollTop = saved.scrollTop;
}, [visible]);
async function read(previous: Listing) {
if (pending.current || listing.current !== previous) return;
const after = previous.next;
const controller = new AbortController();
pending.current = controller;
setLoading(true);
setFailed(false);
try {
const url = config.apiPrefix + source + '/entries';
const options = { signal: controller.signal, retryInPlace: true };
const minimum = previous.retryMinimum ?? (previous.rows.length + 1);
const boundary = previous.retryAfter ?? after;
// Rebuild the visible prefix if an external change crossed the cursor.
// Bound automatic restarts so a busy directory still offers a manual retry.
for (let attempt = 0; attempt < 3; attempt++) {
const append = attempt === 0 && Boolean(after);
const batch = append ? [...previous.rows] : [];
const seen = new Map(append ? previous.versions : emptyListing.versions);
let current = true;
let cursor = append ? after : '';
do {
const result = await request.get<{code: number; data: Entry[]; next: string | null; versions?: [string, string | null][]}>(url, {
...options, params: { path, after: cursor, search, folders },
});
if (controller.signal.aborted) return;
if (result.code !== 200 || !Array.isArray(result.data)) throw new Error();
for (const [dir, version] of result.versions || []) {
if (seen.has(dir) && seen.get(dir) !== version) current = false;
seen.set(dir, version);
}
batch.push(...result.data);
cursor = result.next || '';
} while (current && cursor && (batch.length < minimum ||
(!append && boundary && !pastCursor(cursor, boundary, source, search))));
// Recheck even a terminal page: the response itself may have been delayed.
const stamps = [...seen];
for (let i = 0; current && i < stamps.length; i += 128) {
const check = await request.post<{code: number; current: boolean}>(url + '/check', stamps.slice(i, i + 128), options);
if (controller.signal.aborted) return;
if (check.code !== 200) throw new Error();
current = check.current;
}
if (current) {
listing.current = { rows: batch, next: cursor, versions: seen };
setListing(listing.current);
return;
}
// The old rows and cursor are stale, but a manual retry must reach the
// same depth even if this read exhausts its retries or loses the network.
rememberPosition();
listing.current = { ...emptyListing, retryMinimum: minimum, retryAfter: boundary };
setListing(listing.current);
}
setFailed(true);
} catch {
if (!controller.signal.aborted) setFailed(true);
} finally {
if (!controller.signal.aborted) { pending.current = undefined; setLoading(false); }
}
}
useEffect(() => {
void read(listing.current);
return () => { pending.current?.abort(); pending.current = undefined; };
}, []);
return <div className="file-browser-entries" ref={viewport}>
{rows.map(item => {
const name = source === 'logs' ? readableLogName(item.title) : item.title;
// Prefer a complete suffix such as "_register.js" or "___init__".
const tail = name.match(/[_ .-].{4,14}$/su)?.[0] ?? Array.from(name).slice(-10).join('');
return <button type="button" key={item.key} title={item.key} aria-label={item.key} aria-pressed={value === item.key}
onClick={() => open(item)} onDoubleClick={() => onDoubleClick?.(item)}>
{item.type === 'directory' ? <FolderOutlined /> : <FileOutlined />}
<span className="file-browser-label">
<span className="file-browser-name">
<span>{name.slice(0, name.length - tail.length)}</span><span>{tail}</span>
</span>
{search && item.parent && <Typography.Text type="secondary" className="file-browser-parent">{item.parent}</Typography.Text>}
</span>
</button>;
})}
{loading || failed || next ? <div className="file-browser-pagination">
{loading ? <Spin size="small" /> : <Button type="link"
icon={failed ? <ReloadOutlined aria-hidden /> : undefined} onClick={() => read(visible)}>
{intl.get(failed ? '重试' : '加载更多')}</Button>}
</div> : !rows.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
</div>;
}
export function FileBrowser(props: Props) {
const [path, setPath] = useState(props.initialDirectory || '');
const [input, setInput] = useState('');
const [search, setSearch] = useState('');
useEffect(() => { setPath(props.initialDirectory || ''); }, [props.initialDirectory]);
useEffect(() => {
const timer = setTimeout(() => setSearch(input.trim()), 220);
return () => clearTimeout(timer);
}, [input]);
const open = (entry: Entry) => {
if (entry.type === 'directory') { setPath(entry.key); setInput(''); setSearch(''); }
props.onSelect(entry);
};
return <div className="file-browser">
<Input.Search allowClear value={input} onChange={e => setInput(e.target.value)}
placeholder={intl.get(props.source === 'logs' ? '搜索日志名称' : '搜索脚本名称')} />
{!input.trim() && path && <div className="file-browser-location">
<Button size="small" type="text" icon={<ArrowUpOutlined aria-hidden="true" />}
onClick={() => setPath(path.split('/').slice(0, -1).join('/'))}>{intl.get('上一级')}</Button>
<Typography.Text type="secondary" className="file-browser-path" dir="auto" title={path}>{path}</Typography.Text>
</div>}
{input.trim() === search
? <Entries key={JSON.stringify([props.source, path, search, props.revision, props.folders])} {...props} path={path} search={search} open={open} />
: <Spin size="small" />}
</div>;
}
export function FilePicker({ onChange, ...props }: Omit<Props,'onSelect'> & { onSelect?: Props['onSelect']; onChange?: (key: string) => void }) {
const [visible, setVisible] = useState(false);
return <Popover trigger="click" open={visible} onOpenChange={setVisible} content={<div className="file-picker">
{visible && <FileBrowser {...props} onSelect={entry => {
if (props.folders || entry.type === 'file') {
onChange?.(entry.key); props.onSelect?.(entry);
if (!props.folders) setVisible(false);
}
}} />}
{props.folders && <Button onClick={() => { onChange?.(''); setVisible(false); }}>{intl.get('根目录')}</Button>}
</div>}>
<Button className="file-picker-label" title={props.value}>{props.value || intl.get(props.folders ? '请选择父目录' : props.source === 'logs' ? '请选择日志' : '请选择脚本')}</Button>
</Popover>;
}
+7
View File
@@ -0,0 +1,7 @@
// Keep the on-disk identity for API operations; shorten only generated names.
export function readableLogName(name: string) {
const match = /^(\d{4}-\d\d-\d\d)-(\d\d)-(\d\d)-(\d\d)-(\d{3})(?:-([a-z0-9-]{8,120}))?\.log$/.exec(name);
if (!match) return name;
const [, date, h, m, s, ms, id] = match;
return `${date} ${h}:${m}:${s}.${ms}${id ? ' · ' + id.slice(-6) : ''}`;
}
+133 -2
View File
@@ -1,4 +1,55 @@
{
"查看最新记录": "View latest records",
"查看新的运行记录": "View new runs",
"加载更多": "Load more",
"根目录": "Root directory",
"触发后跳过": "Skipped after trigger",
"仍在排队": "Still queued",
"启动未确认": "Start unconfirmed",
"查看启动耗时": "Show startup timings",
"日统计": "Daily totals",
"日期": "Date",
"客户端执行": "Client execution",
"旧版客户端": "Legacy client",
"停止请求未确认,可重试本次操作": "Stop request unconfirmed. Retry this operation.",
"触发时间偏差 P95": "Trigger timing error P95",
"可用内存上限": "Effective memory limit",
"将删除触发记录": "Trigger records to delete",
"无法获取调度预览,请重试": "Unable to load the schedule preview. Please retry.",
"上一次定时触发仍在排队或运行": "Previous scheduled trigger is queued or running",
"已跳过": "Skipped",
"排队等待 P95": "Queue wait P95",
"定时触发": "Scheduled",
"系统定时": "System cron",
"重启补跑": "Recovery run",
"结果未知": "Outcome unknown",
"上一次执行仍在运行": "Previous execution is still running",
"任务已变更或取消": "Task changed or cancelled",
"超过排队时限": "Queue deadline exceeded",
"服务重启": "Service restarted",
"启动或执行失败": "Launch or execution failed",
"计划运行": "Scheduled for",
"进入队列": "Queued at",
"记录启动": "Recorded start",
"记录时间": "Recorded at",
"跳过时间": "Skipped at",
"状态记录时间": "Status recorded at",
"排队结束": "Left queue",
"命令启动": "Command started",
"脚本开始执行(采样)": "Script entry (sampled)",
"已排队": "Waiting in queue",
"计划到命令启动": "Scheduled to command start",
"时间明细": "Timing details",
"未记录": "Not recorded",
"跳过前等待": "Wait before skip",
"计划时间": "Scheduled",
"排队等待": "Queue wait",
"查看新的触发记录": "View new triggers",
"任务列表刷新失败": "Unable to refresh the task list",
"任务状态刷新失败": "Unable to refresh task status",
"触发状态刷新失败": "Unable to refresh trigger status",
"触发记录": "Trigger history",
"规则待同步": "Schedule sync pending",
"选中条数": "Selected {count} items",
"重新检查依赖": "Recheck dependencies",
"依赖检查失败": "Dependency check failed",
@@ -180,7 +231,7 @@
"加载中...": "Loading...",
"包含": "Include",
"单实例": "Single Instance",
"单实例模式:定时启动新任务前会自动停止旧任务;多实例模式:允许同时运行多个任务实例": "Single instance mode: automatically stop old task before starting new scheduled task; Multi-instance mode: allow multiple task instances to run simultaneously",
"单实例模式下,已有实例运行时会跳过新触发。多实例模式允许同时运行多个实例。": "Single instance skips a trigger while an instance is running. Multiple instances can run at the same time.",
"单文件": "Single File",
"去登录": "Go to Login",
"发送模板": "send template, can use type: 'html,txt,json,markdown,cloudMonitor,jenkins,route,pay'",
@@ -258,6 +309,7 @@
"已启用": "Enabled",
"已安装": "Installed",
"已禁用": "Disabled",
"实例已结束": "Instance already ended",
"实例已停止": "Instance stopped",
"已经是最新版了!": "It is already the latest version!",
"已运行": "Elapsed",
@@ -418,6 +470,7 @@
"激活成功": "Activation successful",
"点击或者拖拽文件到此区域上传": "Click or drag files here to upload",
"父目录": "Parent Directory",
"上一级": "Up one level",
"版本": "Version",
"状态": "Status",
"环境变量": "Environment variable",
@@ -598,6 +651,7 @@
"运行任务前执行的命令,比如 cp/mv/python3 xxx.py/node xxx.js": "Run commands before executing the task, e.g., cp/mv/python3 xxx.py/node xxx.js",
"运行任务后执行的命令,比如 cp/mv/python3 xxx.py/node xxx.js": "Run commands after executing the task, e.g., cp/mv/python3 xxx.py/node xxx.js",
"运行实例": "Running Instances",
"执行实例 #{id}": "Execution #{id}",
"运行订阅前执行的命令,比如 cp/mv/python3 xxx.py/node xxx.js": "Run commands before executing the subscription, e.g., cp/mv/python3 xxx.py/node xxx.js",
"运行订阅后执行的命令,比如 cp/mv/python3 xxx.py/node xxx.js": "Run commands after executing the subscription, e.g., cp/mv/python3 xxx.py/node xxx.js",
"运行设置": "Run Settings",
@@ -697,6 +751,7 @@
"成功次数": "Success count",
"失败次数": "Failure count",
"最新日志": "Latest log",
"加载更早记录": "Load older records",
"加载失败": "Failed to load",
"重试": "Retry",
"WPUSH的API Key,在 https://wpush.cn/settings 获取,参考 https://wpush.cn/docs": "WPUSH API Key from https://wpush.cn/settings, see https://wpush.cn/docs",
@@ -775,5 +830,81 @@
"启动版本与更新包不一致": "The running build does not match the update package.",
"下载完成,等待重启": "Download complete, restart to update",
"升级成功": "Update successful",
"已重新启动并运行新版本,无需再次重启。": "Restarted and running the new version. No further restart is needed."
"已重新启动并运行新版本,无需再次重启。": "Restarted and running the new version. No further restart is needed.",
"手动执行队列": "Manual queue",
"定时执行队列": "Scheduled queue",
"执行 ID": "Execution ID",
"查看排队原因": "Inspect queue waits",
"仅显示等待最久的 25 个实例": "Showing the 25 oldest waits",
"计划触发次数": "Scheduled triggers",
"未收到触发记录": "No trigger recorded",
"有触发记录的计划": "Schedules with a trigger",
"准时触发率": "On-time trigger rate",
"命令已启动": "Command started",
"命令启动次数": "Command starts",
"重复触发次数": "Extra triggers",
"找不到对应计划的触发记录": "Triggers without a matching schedule",
"上次成功安装规则": "Rules last installed",
"等待触发记录 {waiting} 次,无法确定触发分钟 {uncertain} 次,无法确定生效规则 {switches} 次。": "Waiting for a trigger record: {waiting}. Trigger minute unknown: {uncertain}. Active rule unknown: {switches}.",
"生效规则不确定": "Active rule unknown",
"触发分钟不确定": "Trigger minute unknown",
"等待触发记录": "Awaiting trigger record",
"部分时段的计划还无法确定,只统计能确认的计划。": "Only confirmed schedules are counted. Some periods are still unverified.",
"查看最近 25 次计划触发": "View the 25 most recent scheduled triggers",
"暂时无法显示调度数据。": "Scheduling data is unavailable.",
"当前面板服务未提供系统定时任务统计。": "This panel server does not provide system scheduling statistics.",
"规则切换期间有些计划无法确认。这里只统计能确认的计划,暂不显示准时率。": "Some schedules could not be confirmed during a rule change. Only confirmed schedules are counted. The on-time rate is unavailable.",
"从 {time} 起统计,最近 5 秒暂不计入。触发时间与计划相差不超过 5 秒算准时。准时率 = 准时触发次数 ÷ 计划触发次数。": "Counts schedules from {time}, excluding the latest 5 seconds. The on-time rate is the share of scheduled triggers received within 5 seconds of their planned time.",
"暂时无法确认应触发的计划,未收到触发的次数和准时率未知。": "The expected schedule could not be determined. Missing trigger counts and the on-time rate are unavailable.",
"计划到命令启动 P95": "Scheduled time to command start (P95)",
"计划到脚本开始 P95": "Scheduled time to script start (P95)",
"调度统计说明": "Scheduling statistics help",
"样本与计算方式": "Samples and calculation",
"{count} 个样本": "{count} samples",
"{value} 秒": "{value} s",
"{minutes} 分 {seconds} 秒": "{minutes} min {seconds} s",
"P95 取各项样本从小到大排列的第 95 百分位。触发偏差比较计划时间与收到触发的时间,包含迟到后跳过的记录。排队等待只统计从入队到取得执行资格的耗时,旧记录用开始派发时间估算。直接执行命令时可能没有脚本开始样本。": "P95 is the 95th percentile of each metric’s samples. Trigger deviation compares scheduled and observed times, including late triggers that were skipped. Queue wait measures time from enqueue to acquiring a slot. Older records use dispatch start as an estimate. Direct commands may have no script start sample.",
"按执行明细统计": "From execution records",
"每日汇总": "Daily totals",
"其中升级时补记": "Added during upgrade",
"近 7 天按面板日期显示。执行明细按任务结束日期统计仍可核实的结果。每日汇总包含升级时补记的次数。清理明细或旧版客户端跨日报告时,两组次数可能不同。": "Dates use the panel time zone and cover the last 7 days. Execution records count verifiable outcomes by finish date. Daily totals include runs added during upgrade. The counts can differ after records are cleared or an older client reports on a later day.",
"刷新失败,仍显示上次的数据": "Refresh failed. Showing the previous results.",
"入队时已达并发上限(运行 {used},上限 {limit})": "At the limit when queued ({used} running, limit {limit})",
"最近一次检查(运行 {used},上限 {limit})": "At last check ({used} running, limit {limit})",
"仅列出最早开始运行的 8 个实例": "Showing the 8 earliest runs",
"正在排队,尚无同时运行的任务记录": "Queued. No information yet about other running tasks.",
"排队结束,正在准备命令": "Queue wait ended. Preparing the command.",
"该任务的待执行次数已达上限": "Too many runs are waiting for this task",
"收到的结束记录不一致": "Conflicting completion records",
"等待确认执行结果": "Awaiting confirmation of the outcome",
"如果上一次定时执行仍在排队或运行,跳过本次": "Skip this run if the previous scheduled run is still queued or running",
"最长排队时间(秒)": "Maximum queue wait (seconds)",
"超时后跳过本次执行。填 0 表示不限时。": "Skip this run when the wait expires. Enter 0 for no limit.",
"重启后往前查找的时长(秒)": "How far back to check after restart (seconds)",
"每条规则只补跑这段时间内最近一次错过的执行。填 0 关闭补跑。": "Run only the most recent missed occurrence per rule within this period. Enter 0 to disable catch-up.",
"自动设置": "Automatic",
"定时和手动任务各有一条队列,每条最多同时运行 {slots} 个实例。当前可用 CPU 核数为 {cpus}。": "Scheduled and manual tasks have separate queues. Each can run up to {slots} instances at once. Available CPU cores: {cpus}.",
"宿主机资源": "Host resources",
"计划到脚本开始": "Scheduled time to script start",
"入队到脚本开始": "Queue entry to script start",
"启动记录到脚本开始": "Recorded start to script start",
"未采集到开始时间": "Start time not sampled",
"搜索日志名称": "Search log names",
"搜索脚本名称": "Search script names",
"排队中 {runs} 次,涉及 {tasks} 个任务": "Queued runs: {runs} across {tasks} tasks",
"今日定时调度": "Today's scheduled triggers",
"由青龙触发": "Triggered by Qinglong",
"由系统触发(crond)": "Triggered by system cron",
"按计划统计": "Scheduled occurrences",
"按触发记录统计(共 {count} 条)": "Trigger records ({count} total)",
"跳过次数": "Skipped runs",
"按任务、规则和系统发出命令的分钟匹配。超过计划时间一分钟仍无记录,显示“未收到触发记录”。": "Triggers are matched by task, rule and dispatch minute. A trigger is marked missing after one minute without a record.",
"匹配的触发记录": "Matched records",
"执行情况": "Outcome",
"启动 {count} 次": "Started × {count}",
"跳过 {count} 次": "Skipped × {count}",
"启动未确认 {count} 次": "Start unconfirmed × {count}",
"执行 ID(示例)": "Example execution ID",
"同一计划多出的记录计为重复。只有明确记录的跳过才计入跳过次数。记录写入前中断的派发无法核实。": "Extra records for the same scheduled occurrence count as duplicates. Only recorded skips count. Dispatches interrupted before a record is saved cannot be verified.",
"其中 {count} 次执行结果未知": "Unknown outcome for {count} of these runs"
}
+133 -2
View File
@@ -1,4 +1,55 @@
{
"查看最新记录": "查看最新记录",
"查看新的运行记录": "查看新的运行记录",
"加载更多": "加载更多",
"根目录": "根目录",
"触发后跳过": "触发后跳过",
"仍在排队": "仍在排队",
"启动未确认": "启动未确认",
"查看启动耗时": "查看启动耗时",
"日统计": "日统计",
"日期": "日期",
"客户端执行": "客户端执行",
"旧版客户端": "旧版客户端",
"停止请求未确认,可重试本次操作": "停止请求未确认,可重试本次操作",
"触发时间偏差 P95": "触发时间偏差 P95",
"可用内存上限": "可用内存上限",
"将删除触发记录": "将删除触发记录",
"无法获取调度预览,请重试": "无法获取调度预览,请重试",
"上一次定时触发仍在排队或运行": "上一次定时触发仍在排队或运行",
"已跳过": "已跳过",
"排队等待 P95": "排队等待 P95",
"定时触发": "定时触发",
"系统定时": "系统定时",
"重启补跑": "重启补跑",
"结果未知": "结果未知",
"上一次执行仍在运行": "上一次执行仍在运行",
"任务已变更或取消": "任务已变更或取消",
"超过排队时限": "超过排队时限",
"服务重启": "服务重启",
"启动或执行失败": "启动或执行失败",
"计划运行": "计划运行",
"进入队列": "进入队列",
"记录启动": "记录启动",
"记录时间": "记录时间",
"跳过时间": "跳过时间",
"状态记录时间": "状态记录时间",
"排队结束": "排队结束",
"命令启动": "命令启动",
"脚本开始执行(采样)": "脚本开始执行(采样)",
"已排队": "已排队",
"计划到命令启动": "计划到命令启动",
"时间明细": "时间明细",
"未记录": "未记录",
"跳过前等待": "跳过前等待",
"计划时间": "计划时间",
"排队等待": "排队等待",
"查看新的触发记录": "查看新的触发记录",
"任务列表刷新失败": "任务列表刷新失败",
"任务状态刷新失败": "任务状态刷新失败",
"触发状态刷新失败": "触发状态刷新失败",
"触发记录": "触发记录",
"规则待同步": "规则待同步",
"选中条数": "已选择 {count} 项",
"重新检查依赖": "重新检查依赖",
"依赖检查失败": "依赖检查失败",
@@ -179,7 +230,7 @@
"加载中...": "加载中...",
"包含": "包含",
"单实例": "单实例",
"单实例模式:定时启动新任务前会自动停止旧任务;多实例模式:允许同时运行多个任务实例": "单实例模式:定时启动新任务前会自动停止旧任务;多实例模式:允许同时运行多个任务实例",
"单实例模式下,已有实例运行时会跳过新触发。多实例模式允许同时运行多个实例。": "单实例模式下,已有实例运行时会跳过新触发。多实例模式允许同时运行多个实例。",
"单文件": "单文件",
"去登录": "去登录",
"发送模板": "发送模板,支持html,txt,json,markdown,cloudMonitor,jenkins,route,pay",
@@ -257,6 +308,7 @@
"已启用": "已启用",
"已安装": "已安装",
"已禁用": "已禁用",
"实例已结束": "实例已结束",
"实例已停止": "实例已停止",
"已经是最新版了!": "已经是最新版了!",
"已运行": "已运行",
@@ -418,6 +470,7 @@
"激活成功": "激活成功",
"点击或者拖拽文件到此区域上传": "点击或者拖拽文件到此区域上传",
"父目录": "父目录",
"上一级": "上一级",
"版本": "版本",
"状态": "状态",
"环境变量": "环境变量",
@@ -598,6 +651,7 @@
"运行任务前执行的命令,比如 cp/mv/python3 xxx.py/node xxx.js": "运行任务前执行的命令,比如 cp/mv/python3 xxx.py/node xxx.js",
"运行任务后执行的命令,比如 cp/mv/python3 xxx.py/node xxx.js": "运行任务后执行的命令,比如 cp/mv/python3 xxx.py/node xxx.js",
"运行实例": "运行实例",
"执行实例 #{id}": "执行实例 #{id}",
"运行订阅前执行的命令,比如 cp/mv/python3 xxx.py/node xxx.js": "运行订阅前执行的命令,比如 cp/mv/python3 xxx.py/node xxx.js",
"运行订阅后执行的命令,比如 cp/mv/python3 xxx.py/node xxx.js": "运行订阅后执行的命令,比如 cp/mv/python3 xxx.py/node xxx.js",
"运行设置": "运行设置",
@@ -697,6 +751,7 @@
"成功次数": "成功次数",
"失败次数": "失败次数",
"最新日志": "最新日志",
"加载更早记录": "加载更早记录",
"加载失败": "加载失败",
"重试": "重试",
"WPUSH的API Key,在 https://wpush.cn/settings 获取,参考 https://wpush.cn/docs": "WPUSH的API Key,在 https://wpush.cn/settings 获取,参考 https://wpush.cn/docs",
@@ -775,5 +830,81 @@
"启动版本与更新包不一致": "启动版本与更新包不一致",
"下载完成,等待重启": "下载完成,等待重启",
"升级成功": "升级成功",
"已重新启动并运行新版本,无需再次重启。": "已重新启动并运行新版本,无需再次重启。"
"已重新启动并运行新版本,无需再次重启。": "已重新启动并运行新版本,无需再次重启。",
"手动执行队列": "手动执行队列",
"定时执行队列": "定时执行队列",
"执行 ID": "执行 ID",
"查看排队原因": "查看排队原因",
"仅显示等待最久的 25 个实例": "仅显示等待最久的 25 个实例",
"计划触发次数": "计划触发次数",
"未收到触发记录": "未收到触发记录",
"有触发记录的计划": "有触发记录的计划",
"准时触发率": "准时触发率",
"命令已启动": "命令已启动",
"命令启动次数": "命令启动次数",
"重复触发次数": "重复触发次数",
"找不到对应计划的触发记录": "找不到对应计划的触发记录",
"上次成功安装规则": "上次成功安装规则",
"等待触发记录 {waiting} 次,无法确定触发分钟 {uncertain} 次,无法确定生效规则 {switches} 次。": "等待触发记录 {waiting} 次,无法确定触发分钟 {uncertain} 次,无法确定生效规则 {switches} 次。",
"生效规则不确定": "生效规则不确定",
"触发分钟不确定": "触发分钟不确定",
"等待触发记录": "等待触发记录",
"部分时段的计划还无法确定,只统计能确认的计划。": "部分时段的计划还无法确定,只统计能确认的计划。",
"查看最近 25 次计划触发": "查看最近 25 次计划触发",
"暂时无法显示调度数据。": "暂时无法显示调度数据。",
"当前面板服务未提供系统定时任务统计。": "当前面板服务未提供系统定时任务统计。",
"规则切换期间有些计划无法确认。这里只统计能确认的计划,暂不显示准时率。": "规则切换期间有些计划无法确认。这里只统计能确认的计划,暂不显示准时率。",
"从 {time} 起统计,最近 5 秒暂不计入。触发时间与计划相差不超过 5 秒算准时。准时率 = 准时触发次数 ÷ 计划触发次数。": "从 {time} 起统计,最近 5 秒暂不计入。触发时间与计划相差不超过 5 秒算准时。准时率 = 准时触发次数 ÷ 计划触发次数。",
"暂时无法确认应触发的计划,未收到触发的次数和准时率未知。": "暂时无法确认应触发的计划,未收到触发的次数和准时率未知。",
"计划到命令启动 P95": "计划到命令启动 P95",
"计划到脚本开始 P95": "计划到脚本开始 P95",
"调度统计说明": "调度统计说明",
"样本与计算方式": "样本与计算方式",
"{count} 个样本": "{count} 个样本",
"{value} 秒": "{value} 秒",
"{minutes} 分 {seconds} 秒": "{minutes} 分 {seconds} 秒",
"P95 取各项样本从小到大排列的第 95 百分位。触发偏差比较计划时间与收到触发的时间,包含迟到后跳过的记录。排队等待只统计从入队到取得执行资格的耗时,旧记录用开始派发时间估算。直接执行命令时可能没有脚本开始样本。": "P95 取各项样本从小到大排列的第 95 百分位。触发偏差比较计划时间与收到触发的时间,包含迟到后跳过的记录。排队等待只统计从入队到取得执行资格的耗时,旧记录用开始派发时间估算。直接执行命令时可能没有脚本开始样本。",
"按执行明细统计": "按执行明细统计",
"每日汇总": "每日汇总",
"其中升级时补记": "其中升级时补记",
"近 7 天按面板日期显示。执行明细按任务结束日期统计仍可核实的结果。每日汇总包含升级时补记的次数。清理明细或旧版客户端跨日报告时,两组次数可能不同。": "近 7 天按面板日期显示。执行明细按任务结束日期统计仍可核实的结果。每日汇总包含升级时补记的次数。清理明细或旧版客户端跨日报告时,两组次数可能不同。",
"刷新失败,仍显示上次的数据": "刷新失败,仍显示上次的数据",
"入队时已达并发上限(运行 {used},上限 {limit})": "入队时已达并发上限(运行 {used},上限 {limit})",
"最近一次检查(运行 {used},上限 {limit})": "最近一次检查(运行 {used},上限 {limit})",
"仅列出最早开始运行的 8 个实例": "仅列出最早开始运行的 8 个实例",
"正在排队,尚无同时运行的任务记录": "正在排队,尚无同时运行的任务记录",
"排队结束,正在准备命令": "排队结束,正在准备命令",
"该任务的待执行次数已达上限": "该任务的待执行次数已达上限",
"收到的结束记录不一致": "收到的结束记录不一致",
"等待确认执行结果": "等待确认执行结果",
"如果上一次定时执行仍在排队或运行,跳过本次": "如果上一次定时执行仍在排队或运行,跳过本次",
"最长排队时间(秒)": "最长排队时间(秒)",
"超时后跳过本次执行。填 0 表示不限时。": "超时后跳过本次执行。填 0 表示不限时。",
"重启后往前查找的时长(秒)": "重启后往前查找的时长(秒)",
"每条规则只补跑这段时间内最近一次错过的执行。填 0 关闭补跑。": "每条规则只补跑这段时间内最近一次错过的执行。填 0 关闭补跑。",
"自动设置": "自动设置",
"定时和手动任务各有一条队列,每条最多同时运行 {slots} 个实例。当前可用 CPU 核数为 {cpus}。": "定时和手动任务各有一条队列,每条最多同时运行 {slots} 个实例。当前可用 CPU 核数为 {cpus}。",
"宿主机资源": "宿主机资源",
"计划到脚本开始": "计划到脚本开始",
"入队到脚本开始": "入队到脚本开始",
"启动记录到脚本开始": "启动记录到脚本开始",
"未采集到开始时间": "未采集到开始时间",
"搜索日志名称": "搜索日志名称",
"搜索脚本名称": "搜索脚本名称",
"排队中 {runs} 次,涉及 {tasks} 个任务": "排队中 {runs} 次,涉及 {tasks} 个任务",
"今日定时调度": "今日定时调度",
"由青龙触发": "由青龙触发",
"由系统触发(crond)": "由系统触发(crond)",
"按计划统计": "按计划统计",
"按触发记录统计(共 {count} 条)": "按触发记录统计(共 {count} 条)",
"跳过次数": "跳过次数",
"按任务、规则和系统发出命令的分钟匹配。超过计划时间一分钟仍无记录,显示“未收到触发记录”。": "按任务、规则和系统发出命令的分钟匹配。超过计划时间一分钟仍无记录,显示“未收到触发记录”。",
"匹配的触发记录": "匹配的触发记录",
"执行情况": "执行情况",
"启动 {count} 次": "启动 {count} 次",
"跳过 {count} 次": "跳过 {count} 次",
"启动未确认 {count} 次": "启动未确认 {count} 次",
"执行 ID(示例)": "执行 ID(示例)",
"同一计划多出的记录计为重复。只有明确记录的跳过才计入跳过次数。记录写入前中断的派发无法核实。": "同一计划多出的记录计为重复。只有明确记录的跳过才计入跳过次数。记录写入前中断的派发无法核实。",
"其中 {count} 次执行结果未知": "其中 {count} 次执行结果未知"
}
+62
View File
@@ -0,0 +1,62 @@
import { useEffect, useState } from 'react';
import { Button, Table, Typography } from 'antd';
import intl from 'react-intl-universal';
import { request } from '@/utils/http';
import config from '@/utils/config';
type DailyResult = {
day: string;
exitSuccess: number;
exitFail: number;
bookedSuccess: number;
bookedFail: number;
supplement: number;
};
export default function DailyResults({ id }: { id: number }) {
const [rows, setRows] = useState<DailyResult[]>([]);
const [loading, setLoading] = useState(true);
const [failed, setFailed] = useState(false);
const [attempt, setAttempt] = useState(0);
useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
let timer: ReturnType<typeof setTimeout>;
async function load() {
try {
const { code, data } = await request.get(`${config.apiPrefix}crons/${id}/daily-results`, { signal, retryInPlace: true });
if (code !== 200) throw new Error();
if (signal.aborted) return;
setRows(data);
setFailed(false);
timer = setTimeout(load, 10000);
} catch {
if (!signal.aborted) setFailed(true);
} finally {
if (!signal.aborted) setLoading(false);
}
}
void load();
return () => { controller.abort(); clearTimeout(timer); };
}, [id, attempt]);
return <section>
<Typography.Paragraph type="secondary">{intl.get('近 7 天按面板日期显示。执行明细按任务结束日期统计仍可核实的结果。每日汇总包含升级时补记的次数。清理明细或旧版客户端跨日报告时,两组次数可能不同。')}</Typography.Paragraph>
{failed && <div role="status">{intl.get(rows.length ? '刷新失败,仍显示上次的数据' : '加载失败')}
<Button type="link" onClick={() => { setFailed(false); setLoading(true); setAttempt(a => a + 1); }}>{intl.get('重试')}</Button>
</div>}
<Table<DailyResult> size="small" rowKey="day" dataSource={rows} pagination={false}
loading={loading} scroll={{ x: 520 }} columns={[
{ title: intl.get('日期'), dataIndex: 'day' },
{ title: intl.get('按执行明细统计'), children: [
{ title: intl.get('成功'), dataIndex: 'exitSuccess', align: 'right' },
{ title: intl.get('失败'), dataIndex: 'exitFail', align: 'right' },
] },
{ title: intl.get('每日汇总'), children: [
{ title: intl.get('成功'), dataIndex: 'bookedSuccess', align: 'right' },
{ title: intl.get('失败'), dataIndex: 'bookedFail', align: 'right' },
{ title: intl.get('其中升级时补记'), dataIndex: 'supplement', align: 'right' },
] },
]} />
</section>;
}
+112 -86
View File
@@ -1,3 +1,6 @@
import { createStopRequest } from './stopRequest';
import DailyResults from './dailyResults';
import TriggerList from './triggerList';
import intl from 'react-intl-universal';
import React, { useEffect, useRef, useState } from 'react';
import {
@@ -30,17 +33,21 @@ import CronLogModal from './logModal';
import Editor from '@monaco-editor/react';
import IconFont from '@/components/iconfont';
import { getCommandScript, getEditorMode } from '@/utils';
import VirtualList from 'rc-virtual-list';
import useScrollHeight from '@/hooks/useScrollHeight';
import InstanceHistory from './instanceHistory';
import { readableLogName } from '@/components/fileBrowser/name';
import dayjs from 'dayjs';
const { Text } = Typography;
function instanceTitle(item: { id: number; log_path?: string | null }) {
const filename = item.log_path?.split('/').pop();
return filename ? readableLogName(filename) : intl.get('执行实例 #{id}', { id: String(item.id) });
}
const tabList = [
{
key: 'runningHistory',
tab: intl.get('运行历史'),
},
{ key: 'runningHistory', tab: intl.get('运行历史') },
{ key: 'triggers', tab: intl.get('触发记录') },
{ key: 'daily', tab: intl.get('日统计') },
{
key: 'script',
tab: intl.get('脚本'),
@@ -60,48 +67,65 @@ const CronDetailModal = ({
}) => {
const [activeTabKey, setActiveTabKey] = useState('runningHistory');
const [value, setValue] = useState('');
const [scriptState, setScriptState] = useState<'loading' | 'ready' | 'failed'>('loading');
const editorRef = useRef<any>(null);
const [scriptInfo, setScriptInfo] = useState<any>({});
const [validTabs, setValidTabs] = useState(tabList);
const [currentCron, setCurrentCron] = useState<any>({});
const listRef = useRef<HTMLDivElement>(null);
const tableScrollHeight = useScrollHeight(listRef);
const [runningInstances, setRunningInstances] = useState<any[]>([]);
const [historyRevision, setHistoryRevision] = useState(0);
const needRefreshRef = useRef(false);
const [isLogModalVisible, setIsLogModalVisible] = useState(false);
const [logData, setLogData] = useState('');
const [logUrl, setLogUrl] = useState('');
const fetchRunningInstances = async () => {
if (!cron.id) return Promise.resolve();
return request
.get(`${config.apiPrefix}crons/${cron.id}/instances`)
.then(({ code, data }) => {
if (code === 200 && data) {
setRunningInstances(data);
}
})
.catch(() => { });
const refreshVersion = useRef(0);
const session = useRef<AbortController>();
const [refreshFailed, setRefreshFailed] = useState(false);
const refreshDetails = async () => {
const signal = session.current?.signal;
if (!cron.id || !signal || signal.aborted) return;
const options = { signal, retryInPlace: true };
const version = ++refreshVersion.current;
const base = `${config.apiPrefix}crons/${cron.id}`;
try {
const { code, data } = await request.get(base, options);
if (code !== 200) throw new Error();
if (!signal.aborted && version === refreshVersion.current) {
setCurrentCron(data);
setRefreshFailed(false);
}
} catch {
if (!signal.aborted && version === refreshVersion.current) setRefreshFailed(true);
}
};
const refreshAfterChange = () => {
needRefreshRef.current = true;
setHistoryRevision(n => n + 1);
return refreshDetails();
};
useEffect(() => {
fetchRunningInstances();
if (!cron.id) return;
let timer: ReturnType<typeof setTimeout>;
let cancelled = false;
const controller = new AbortController();
session.current = controller;
const poll = async () => {
await fetchRunningInstances();
if (cancelled) return;
timer = setTimeout(poll, 10000);
await refreshDetails();
if (!controller.signal.aborted) timer = setTimeout(poll, 10000);
};
poll();
void poll();
return () => {
cancelled = true;
controller.abort();
++refreshVersion.current;
clearTimeout(timer);
};
}, [cron.id]);
const contentList: any = {
script: scriptInfo.filename && (
daily: <DailyResults key={cron.id} id={cron.id} />,
triggers: activeTabKey === 'triggers' && <TriggerList key={cron.id} id={cron.id} onViewLog={(row) => viewInstanceLog(row, row.id)} />,
script: scriptState === 'failed' ? (
<span role="status">{intl.get('加载失败')} <Button type="link" onClick={() => getScript()}>{intl.get('重试')}</Button></span>
) : scriptState === 'loading' ? intl.get('加载中...') : scriptInfo.filename && (
<Editor
language={getEditorMode(scriptInfo.filename)}
theme={theme}
@@ -118,15 +142,8 @@ const CronDetailModal = ({
}}
/>
),
runningHistory: (
<div ref={listRef}>
<List>
<VirtualList
data={runningInstances}
height={tableScrollHeight}
itemHeight={47}
itemKey="id"
>
runningHistory: activeTabKey === 'runningHistory' && (
<InstanceHistory key={cron.id} id={cron.id} revision={historyRevision}>
{(item) => (
<List.Item
className="log-item"
@@ -165,11 +182,9 @@ const CronDetailModal = ({
<List.Item.Meta
title={
<span>
{item.log_path && (
<span style={{ marginRight: 8 }}>
{item.log_path.split('/').pop()}
</span>
)}
<span style={{ marginRight: 8 }} title={item.log_path || undefined}>
{instanceTitle(item)}
</span>
{item.status === 0 && (
<Tag icon={<Loading3QuartersOutlined spin />} color="processing">
{intl.get('运行中')}
@@ -181,6 +196,9 @@ const CronDetailModal = ({
{item.status === 2 && (
<Tag color="default">{intl.get('已停止')}</Tag>
)}
{item.status === 4 && (
<Tag>{intl.get('结果未知')}</Tag>
)}
{item.status === 3 && (
<Tag color="error">{intl.get('错误')}</Tag>
)}
@@ -199,7 +217,7 @@ const CronDetailModal = ({
{' | '}{intl.get('结束')}: {dayjs.unix(item.finished_at).format('YYYY-MM-DD HH:mm:ss')}
</span>
)}
{item.exit_code !== undefined && item.exit_code !== null && (
{item.exit_code != null && item.exit_code !== 0 && (
<span>
{' | '}{intl.get('退出码')}: {item.exit_code}
</span>
@@ -209,14 +227,16 @@ const CronDetailModal = ({
/>
</List.Item>
)}
</VirtualList>
</List>
</div>
</InstanceHistory>
),
};
const stopDialogs = useRef(new Set<number>());
const stopRunningInstance = (instance: any) => {
if (stopDialogs.current.has(instance.id)) return;
stopDialogs.current.add(instance.id);
Modal.confirm({
afterClose: () => stopDialogs.current.delete(instance.id),
title: intl.get('确认停止实例'),
content: (
<>
@@ -225,53 +245,59 @@ const CronDetailModal = ({
</>
),
onOk() {
request
return request
.post(`${config.apiPrefix}crons/${cron.id}/instances/${instance.id}/stop`)
.then(({ code }) => {
.then(({ code, data }) => {
if (code === 200) {
message.success(intl.get('实例已停止'));
needRefreshRef.current = true;
fetchRunningInstances();
if (data?.outcome === 'ended') message.info(intl.get('实例已结束'));
else message.success(intl.get('实例已停止'));
return refreshAfterChange();
}
});
},
});
};
const viewInstanceLog = (instance: any) => {
const viewInstanceLog = (instance: any, triggerId?: string) => {
if (!instance.log_path) return;
const parts = instance.log_path.split('/');
const filename = parts.pop() || '';
const directory = parts.join('/');
const url = `${config.apiPrefix}logs/detail?file=${filename}&path=${directory}`;
localStorage.setItem('logCron', url);
const base = `${config.apiPrefix}crons/${cron.id}/log`;
let url: string;
if (triggerId) url = `${base}?${new URLSearchParams({ triggerId })}`;
else if (instance.id) url = `${base}?${new URLSearchParams({ instanceId: String(instance.id) })}`;
else {
const parts = instance.log_path.split('/');
const file = parts.pop()!;
url = `${config.apiPrefix}logs/detail?${new URLSearchParams({ file, path: parts.join('/') })}`;
}
setLogUrl(url);
request.get(url).then(({ code, data }) => {
if (code === 200) {
setLogData(data);
setIsLogModalVisible(true);
}
});
setIsLogModalVisible(true);
};
const onTabChange = (key: string) => {
setActiveTabKey(key);
void refreshDetails();
};
const getScript = () => {
const signal = session.current?.signal;
const result = getCommandScript(cron.command);
if (Array.isArray(result)) {
setValidTabs(tabList);
const [s, p] = result;
setScriptInfo({ parent: p, filename: s });
setScriptState('loading');
request
.get(`${config.apiPrefix}scripts/detail?file=${s}&path=${p || ''}`)
.get(`${config.apiPrefix}scripts/detail`, { params: { file: s, path: p || '' }, signal, retryInPlace: true })
.then(({ code, data }) => {
if (code === 200) {
setValue(data);
}
if (signal?.aborted) return;
if (code !== 200) throw new Error('Script read failed');
setValue(data);
setScriptState('ready');
}).catch(() => {
if (!signal?.aborted) setScriptState('failed');
});
} else {
setValidTabs([{ key: 'runningHistory', tab: intl.get('运行历史') }]);
setValidTabs(tabList.filter((tab) => tab.key !== 'script'));
setActiveTabKey('runningHistory');
}
};
@@ -330,8 +356,7 @@ const CronDetailModal = ({
.put(`${config.apiPrefix}crons/run`, [currentCron.id])
.then(({ code, data }) => {
if (code === 200) {
setCurrentCron({ ...currentCron, status: CrontabStatus.running });
fetchRunningInstances();
return refreshAfterChange();
}
});
},
@@ -339,6 +364,7 @@ const CronDetailModal = ({
};
const stopCron = () => {
const stop = createStopRequest([currentCron.id]);
Modal.confirm({
title: intl.get('确认停止'),
content: (
@@ -351,11 +377,10 @@ const CronDetailModal = ({
</>
),
onOk() {
request
.put(`${config.apiPrefix}crons/stop`, [currentCron.id])
return stop()
.then(({ code, data }) => {
if (code === 200) {
setCurrentCron({ ...currentCron, status: CrontabStatus.idle });
return refreshAfterChange();
}
});
},
@@ -381,12 +406,9 @@ const CronDetailModal = ({
}`,
[currentCron.id],
)
.then(({ code, data }) => {
.then(async ({ code }) => {
if (code === 200) {
setCurrentCron({
...currentCron,
isDisabled: currentCron.isDisabled === 1 ? 0 : 1,
});
return refreshAfterChange();
}
});
},
@@ -414,10 +436,7 @@ const CronDetailModal = ({
)
.then(({ code, data }) => {
if (code === 200) {
setCurrentCron({
...currentCron,
isPinned: currentCron.isPinned === 1 ? 0 : 1,
});
return refreshAfterChange();
}
});
},
@@ -553,6 +572,13 @@ const CronDetailModal = ({
<div className="cron-detail-info-item">
<div className="cron-detail-info-title">{intl.get('状态')}</div>
<div className="cron-detail-info-value">
{refreshFailed && <span role="status">
{intl.get('任务状态刷新失败')}
<Button type="link" size="small" onClick={() => {
setRefreshFailed(false);
void refreshDetails();
}}>{intl.get('重试')}</Button>
</span>}
{(!currentCron.isDisabled ||
currentCron.status !== CrontabStatus.idle) && (
<>
@@ -610,7 +636,7 @@ const CronDetailModal = ({
{intl.get('最后运行时长')}
</div>
<div className="cron-detail-info-value">
{currentCron.last_running_time
{currentCron.last_execution_time && currentCron.last_running_time != null
? diffTime(currentCron.last_running_time)
: '-'}
</div>
@@ -633,7 +659,7 @@ const CronDetailModal = ({
onTabChange(key);
}}
tabBarExtraContent={
activeTabKey === 'script' && (
activeTabKey === 'script' && scriptState === 'ready' && (
<>
<Button
type="primary"
@@ -658,10 +684,10 @@ const CronDetailModal = ({
<CronLogModal
handleCancel={() => {
setIsLogModalVisible(false);
fetchRunningInstances();
void refreshDetails();
}}
cron={cron}
data={logData}
key={logUrl}
logUrl={logUrl}
/>
)}
+92
View File
@@ -1,3 +1,5 @@
@import '~antd/es/style/themes/default.less';
.ant-table-pagination.ant-pagination {
margin-bottom: 0 !important;
}
@@ -200,3 +202,93 @@ body[data-mode='desktop'] {
.cron.pinned-cron > td {
background: #f2f2f2;
}
.trigger-history {
container-type: inline-size;
font-variant-numeric: tabular-nums;
.trigger-history-entry {
width: 100%;
min-width: 0;
}
.trigger-history-header,
.trigger-history-summary {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 4px 20px;
}
.trigger-history-header {
justify-content: space-between;
.ant-tag {
margin-right: 0;
}
}
.trigger-history-summary {
margin: 4px 0;
}
.trigger-history-timing {
summary {
width: fit-content;
color: @primary-color;
cursor: pointer;
padding: 3px 0;
}
}
.trigger-timestamps {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
gap: 4px 12px;
margin: 10px 0;
dt {
opacity: 0.65;
}
dd {
margin: 0;
white-space: nowrap;
}
}
.trigger-history-summary b {
font-weight: 500;
}
}
.instance-history-pagination,
.trigger-history-pagination {
display: flex;
justify-content: center;
align-items: center;
padding-top: 8px;
}
.instance-history-pagination .ant-space { justify-content: center; }
@container (max-width: 800px) {
.trigger-history .trigger-timestamps {
grid-template-columns: repeat(2, minmax(0, 1fr));
row-gap: 8px;
}
}
@container (max-width: 420px) {
.trigger-history .trigger-timestamps {
grid-template-columns: minmax(0, 1fr);
row-gap: 4px;
> div {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
}
}
}
+99 -184
View File
@@ -1,6 +1,7 @@
import { createStopRequest } from './stopRequest';
import useTableScrollHeight from '@/hooks/useTableScrollHeight';
import { SharedContext } from '@/layouts';
import { getCommandScript, getCrontabsNextDate } from '@/utils';
import { getCommandScript } from '@/utils';
import config from '@/utils/config';
import { diffTime } from '@/utils/date';
import { request } from '@/utils/http';
@@ -41,11 +42,10 @@ import {
import { ColumnProps } from 'antd/lib/table';
import { FilterValue, SorterResult } from 'antd/lib/table/interface';
import dayjs from 'dayjs';
import { noop, omit } from 'lodash';
import { omit } from 'lodash';
import React, { useEffect, useRef, useState } from 'react';
import intl from 'react-intl-universal';
import { useVT } from 'virtualizedtableforantd4';
import { getScheduleType } from './const';
import CronDetailModal from './detail';
import './index.less';
import CronLogModal from './logModal';
@@ -55,7 +55,6 @@ import {
ICrontab,
OperationName,
OperationPath,
ScheduleType,
} from './type';
import ViewCreateModal from './viewCreateModal';
import ViewManageModal from './viewManageModal';
@@ -170,7 +169,8 @@ const Crontab = () => {
)}
</>
)}
{record.isDisabled === 1 && record.status === CrontabStatus.idle && (
{record.saved === false && <Tag color="warning">{intl.get('规则待同步')}</Tag>}
{record.saved !== false && record.isDisabled === 1 && record.status === CrontabStatus.idle && (
<Tag icon={<CloseCircleOutlined />} color="error">
{intl.get('已禁用')}
</Tag>
@@ -224,7 +224,7 @@ const Crontab = () => {
},
},
render: (text, record) => {
return record.last_running_time
return record.last_execution_time && record.last_running_time != null
? diffTime(record.last_running_time)
: '-';
},
@@ -260,7 +260,7 @@ const Crontab = () => {
width: 144,
sorter: {
compare: (a: any, b: any) => {
return a.nextRunTime - b.nextRunTime;
return (a.nextRunTime ?? Infinity) - (b.nextRunTime ?? Infinity);
},
},
render: (text, record) => {
@@ -312,7 +312,7 @@ const Crontab = () => {
<a
onClick={(e) => {
e.stopPropagation();
setLogCron({ ...record, timestamp: Date.now() });
setLogCron(record);
}}
>
{intl.get('日志')}
@@ -330,7 +330,6 @@ const Crontab = () => {
const [isLabelModalVisible, setIsLabelModalVisible] = useState(false);
const [editedCron, setEditedCron] = useState();
const [searchText, setSearchText] = useState('');
const [isLogModalVisible, setIsLogModalVisible] = useState(false);
const [logCron, setLogCron] = useState<any>();
const [selectedRowIds, setSelectedRowIds] = useState<string[]>([]);
const [pageConf, setPageConf] = useState<{
@@ -365,77 +364,57 @@ const Crontab = () => {
}
};
const getCrons = async (silent?: boolean) => {
if (!silent) setLoading(true);
const { page = 1, size = 20, sorter, filters = {} } = pageConf;
let url = `${config.apiPrefix
}crons?searchValue=${searchText}&page=${page}&size=${size}&filters=${JSON.stringify(
filters,
)}`;
if (sorter && sorter.column && sorter.order) {
url += `&sorter=${JSON.stringify({
field: sorter.column.key,
type: sorter.order === 'ascend' ? 'ASC' : 'DESC',
})}`;
}
if (viewConf) {
url += `&queryString=${JSON.stringify({
filters: viewConf.filters,
sorts: viewConf.sorts,
filterRelation: viewConf.filterRelation || 'and',
})}`;
}
return request
.get(url)
.then(async ({ code, data: _data }) => {
if (code === 200) {
const { data, total } = _data;
const subscriptions = await request.get(
`${config.apiPrefix}subscriptions?ids=${JSON.stringify([
...new Set(data.map((x) => x.sub_id).filter(Boolean)),
])}`,
{
onError: noop,
},
);
const subscriptionMap = Object.fromEntries(
subscriptions?.data?.map((x) => [x.id, x]),
);
setValue(
data.map((x) => {
const scheduleType = getScheduleType(x.schedule);
const nextRunTime =
scheduleType === ScheduleType.Normal
? getCrontabsNextDate(x.schedule, x.extra_schedules)
: null;
return {
...x,
nextRunTime,
subscription: subscriptionMap?.[x.sub_id],
};
}),
);
setTotal(total);
}
})
.finally(() => !silent && setLoading(false));
};
const [reload, setReload] = useState(0);
const [listFailed, setListFailed] = useState(false);
const getCrons = () => setReload(n => n + 1);
useEffect(() => {
let timer: ReturnType<typeof setTimeout>;
let cancelled = false;
const poll = async () => {
await getCrons(true);
if (cancelled) return;
timer = setTimeout(poll, 10000);
if (!pageConf.size) return;
const controller = new AbortController();
const { signal } = controller;
const { page, size, sorter, filters = {} } = pageConf;
const params = {
searchValue: searchText, page, size, filters: JSON.stringify(filters),
...(sorter?.column && sorter.order && { sorter: JSON.stringify({
field: sorter.column.key, type: sorter.order === 'ascend' ? 'ASC' : 'DESC',
}) }),
...(viewConf && { queryString: JSON.stringify({
filters: viewConf.filters, sorts: viewConf.sorts,
filterRelation: viewConf.filterRelation || 'and',
}) }),
};
poll();
let timer: ReturnType<typeof setTimeout>;
async function poll() {
try {
const { code, data } = await request.get(`${config.apiPrefix}crons`, { params, signal, retryInPlace: true });
if (signal.aborted) return;
if (code !== 200) throw new Error('Task list read failed');
const { data: rows, total } = data;
const ids = [...new Set(rows.map(row => row.sub_id).filter(Boolean))];
const subscriptions = ids.length ? await request.get(`${config.apiPrefix}subscriptions`, {
params: { ids: JSON.stringify(ids) }, signal, retryInPlace: true,
}).catch(() => undefined) : undefined;
if (signal.aborted) return;
const byId = new Map(subscriptions?.data?.map(row => [row.id, row]));
setValue(rows.map(row => ({ ...row, subscription: byId.get(row.sub_id) })));
setTotal(total);
setListFailed(false);
} catch {
if (!signal.aborted) setListFailed(true);
} finally {
if (!signal.aborted) {
setLoading(false);
timer = setTimeout(poll, 10000);
}
}
}
setLoading(true);
void poll();
return () => {
cancelled = true;
controller.abort();
clearTimeout(timer);
};
}, [pageConf, viewConf, searchText]);
}, [pageConf, viewConf, searchText, reload]);
const addCron = () => {
setEditedCron(null as any);
@@ -465,12 +444,7 @@ const Crontab = () => {
.then(({ code, data }) => {
if (code === 200) {
message.success(intl.get('删除成功'));
const result = [...value];
const i = result.findIndex((x) => x.id === record.id);
if (i !== -1) {
result.splice(i, 1);
setValue(result);
}
getCrons();
}
});
},
@@ -494,15 +468,7 @@ const Crontab = () => {
.put(`${config.apiPrefix}crons/run`, [record.id])
.then(({ code, data }) => {
if (code === 200) {
const result = [...value];
const i = result.findIndex((x) => x.id === record.id);
if (i !== -1) {
result.splice(i, 1, {
...record,
status: CrontabStatus.running,
});
setValue(result);
}
getCrons();
}
});
},
@@ -510,6 +476,7 @@ const Crontab = () => {
};
const stopCron = (record: any, index: number) => {
const stop = createStopRequest([record.id]);
Modal.confirm({
title: intl.get('确认停止'),
content: (
@@ -522,20 +489,10 @@ const Crontab = () => {
</>
),
onOk() {
request
.put(`${config.apiPrefix}crons/stop`, [record.id])
return stop()
.then(({ code, data }) => {
if (code === 200) {
const result = [...value];
const i = result.findIndex((x) => x.id === record.id);
if (i !== -1) {
result.splice(i, 1, {
...record,
pid: null,
status: CrontabStatus.idle,
});
setValue(result);
}
getCrons();
}
});
},
@@ -566,16 +523,7 @@ const Crontab = () => {
)
.then(({ code, data }) => {
if (code === 200) {
const newStatus = record.isDisabled === 1 ? 0 : 1;
const result = [...value];
const i = result.findIndex((x) => x.id === record.id);
if (i !== -1) {
result.splice(i, 1, {
...record,
isDisabled: newStatus,
});
setValue(result);
}
getCrons();
}
});
},
@@ -606,16 +554,7 @@ const Crontab = () => {
)
.then(({ code, data }) => {
if (code === 200) {
const newStatus = record.isPinned === 1 ? 0 : 1;
const result = [...value];
const i = result.findIndex((x) => x.id === record.id);
if (i !== -1) {
result.splice(i, 1, {
...record,
isPinned: newStatus,
});
setValue(result);
}
getCrons();
}
});
},
@@ -690,30 +629,11 @@ const Crontab = () => {
};
const onSearch = (value: string) => {
setSearchText(value.trim());
};
const getCronDetail = (cron: any) => {
request
.get(`${config.apiPrefix}crons/${cron.id}`)
.then(({ code, data }) => {
if (code === 200) {
const index = value.findIndex((x) => x.id === cron.id);
const result = [...value];
data.nextRunTime = getCrontabsNextDate(
data.schedule,
data.extra_schedules,
);
if (index !== -1) {
result.splice(index, 1, {
...cron,
...data,
});
setValue(result);
}
}
})
.finally(() => setLoading(false));
const text = value.trim();
if (text !== searchText) {
setPageConf(previous => ({ ...previous, page: 1 }));
setSearchText(text);
}
};
const onSelectChange = (selectedIds: any[]) => {
@@ -744,6 +664,7 @@ const Crontab = () => {
};
const operateCrons = (operationStatus: number) => {
const stop = operationStatus === OperationPath.stop ? createStopRequest(selectedRowIds) : undefined;
Modal.confirm({
title: intl.get('确认操作', {
operation: intl.get(OperationName[operationStatus]),
@@ -754,6 +675,7 @@ const Crontab = () => {
</>
),
onOk() {
if (stop) return stop().then(() => getCrons());
request
.put(
`${config.apiPrefix}crons/${OperationPath[operationStatus]}`,
@@ -788,24 +710,10 @@ const Crontab = () => {
};
useEffect(() => {
if (logCron) {
localStorage.setItem('logCron', logCron.id);
setIsLogModalVisible(true);
}
}, [logCron]);
useEffect(() => {
setPageConf({ ...pageConf, page: 1 });
}, [searchText]);
useEffect(() => {
if (pageConf.page && pageConf.size) {
getCrons();
}
if (viewConf && viewConf.id) {
setActiveKey(viewConf.id);
}
}, [pageConf, viewConf]);
}, [viewConf]);
useEffect(() => {
if (viewConf && enabledCronViews && enabledCronViews.length > 0) {
@@ -890,27 +798,29 @@ const Crontab = () => {
request
.get(`${config.apiPrefix}crons/views`)
.then(({ code, data }) => {
if (code === 200) {
setCronViews(data);
const firstEnableView = data
.filter((x) => !x.isDisabled)
.map((x) => ({
...x,
name: x.name === '全部任务' ? intl.get('全部任务') : x.name,
}));
setEnabledCronViews(firstEnableView);
setPageConf({
page: 1,
size: parseInt(localStorage.getItem('pageSize') || '20'),
sorter: {},
filters: {},
});
setViewConf({
...firstEnableView[0],
});
if (code !== 200) {
setLoading(false);
return;
}
setCronViews(data);
const firstEnableView = data
.filter((x) => !x.isDisabled)
.map((x) => ({
...x,
name: x.name === '全部任务' ? intl.get('全部任务') : x.name,
}));
setEnabledCronViews(firstEnableView);
setPageConf({
page: 1,
size: parseInt(localStorage.getItem('pageSize') || '20'),
sorter: {},
filters: {},
});
setViewConf({
...firstEnableView[0],
});
})
.finally(() => {
.catch(() => {
setLoading(false);
});
};
@@ -937,7 +847,6 @@ const Crontab = () => {
style={{ width: 'auto' }}
enterButton
allowClear
loading={loading}
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
onSearch={onSearch}
@@ -1039,6 +948,10 @@ const Crontab = () => {
</span>
</div>
)}
{listFailed && <div role="status">
{intl.get('任务列表刷新失败')}
<Button type="link" loading={loading} onClick={getCrons}>{intl.get('重试')}</Button>
</div>}
<Table
columns={columns}
sortDirections={['descend', 'ascend']}
@@ -1065,13 +978,14 @@ const Crontab = () => {
components={isPhone || pageConf.size < 50 ? undefined : vt}
/>
</div>
{isLogModalVisible && (
{logCron && (
<CronLogModal
handleCancel={() => {
getCronDetail(logCron);
setIsLogModalVisible(false);
setLogCron(null);
getCrons();
}}
cron={logCron}
key={logCron.id}
cron={value.find(row => row.id === logCron.id) ?? logCron}
/>
)}
{isModalVisible && (
@@ -1096,6 +1010,7 @@ const Crontab = () => {
getCrons();
}
}}
key={detailCron.id}
cron={detailCron}
theme={theme}
isPhone={isPhone}
+108
View File
@@ -0,0 +1,108 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Button, List, Space } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import useScrollHeight from '@/hooks/useScrollHeight';
import intl from 'react-intl-universal';
import VirtualList from 'rc-virtual-list';
import type { ListRef } from 'rc-virtual-list';
import config from '@/utils/config';
import { request } from '@/utils/http';
import { pageSize } from './triggerUpdates';
const paginationRow = { id: 'pagination' };
export default function InstanceHistory({ id, revision, children }: {
id: number; revision: number; children: (row: any) => React.ReactElement;
}) {
const state = useRef({ rows: [] as any[], next: null as number | null, expanded: false, head: 0, hasNew: false });
const visibleIds = useRef(new Set<number>());
const [view, setView] = useState(state.current);
const [busy, setBusy] = useState(true);
const [failed, setFailed] = useState<'' | 'older' | 'refresh' | 'latest'>('');
const pending = useRef<AbortController>();
const paging = useRef(false);
const viewport = useRef<HTMLDivElement>(null);
const list = useRef<ListRef>(null);
const listHeight = useScrollHeight(viewport);
const showPagination = Boolean(failed || view.next || view.expanded);
const items = useMemo(() => showPagination ? [...view.rows, paginationRow] : view.rows,
[view.rows, showPagination]);
async function load(action: 'older' | 'refresh' | 'latest') {
if (action === 'older' && !state.current.next) return;
if (pending.current && (action === 'refresh' || paging.current)) return;
pending.current?.abort();
const controller = new AbortController();
pending.current = controller;
paging.current = action !== 'refresh';
setBusy(true);
// A failed first page request must retry from the snapshot the user opened.
if (action === 'older' && !state.current.expanded) {
state.current = { ...state.current, expanded: true };
setView(state.current);
}
const previous = state.current;
const read = async (params: any) => {
const result = await request.get<{code: number; data: any[]; next?: number | null}>(`${config.apiPrefix}crons/${id}/instances`, {
params: { paged: true, ...params }, signal: controller.signal, retryInPlace: true,
});
if (result.code !== 200 || !Array.isArray(result.data)) throw new Error();
return result;
};
try {
let result = previous;
if (action === 'refresh' && previous.expanded) {
const latest = await read({ limit: 1 });
if (controller.signal.aborted) return;
const active = previous.rows.filter(row => row.status === 0 || row.status === 4 || visibleIds.current.has(row.id));
const updates = new Map<number, any>();
for (let i = 0; i < active.length; i += pageSize) {
const ids = active.slice(i, i + pageSize).map(row => row.id);
const page = await read({ ids: ids.join(',') });
if (controller.signal.aborted) return;
ids.forEach(id => updates.set(id, undefined));
page.data.forEach((r: any) => updates.set(r.id, r));
}
result = { ...previous, hasNew: latest.data[0]?.id > previous.head,
rows: previous.rows.map(r => updates.has(r.id) ? updates.get(r.id) : r).filter(Boolean) };
} else {
const more = action === 'older';
const page = await read({ limit: pageSize, ...(more && { before: previous.next }) });
result = { rows: more ? [...previous.rows, ...page.data] : page.data, next: page.next ?? null, expanded: more,
head: more ? previous.head : (page.data[0]?.id ?? 0), hasNew: more && previous.hasNew };
}
if (!controller.signal.aborted) {
state.current = result; setView(result);
if (action === 'latest') list.current?.scrollTo(0);
setFailed(old => action === 'refresh' && old !== 'refresh' ? old : '');
}
} catch {
if (!controller.signal.aborted) setFailed(old => action === 'refresh' && old ? old : action);
} finally {
if (!controller.signal.aborted) { pending.current = undefined; paging.current = false; setBusy(false); }
}
}
useEffect(() => {
void load('refresh');
const timer = setInterval(() => void load('refresh'), 10000);
return () => { clearInterval(timer); pending.current?.abort(); pending.current = undefined; paging.current = false; };
}, [id, revision]);
const pagination = <div className="instance-history-pagination">
<Space wrap>
{failed && <Button type="link" icon={<ReloadOutlined aria-hidden />} onClick={() => load(failed)}>{intl.get('重试')}</Button>}
{!!view.next && failed !== 'older' && <Button type="link" disabled={busy && paging.current}
onClick={() => load('older')}>{intl.get('加载更早记录')}</Button>}
{view.expanded && failed !== 'latest' && <Button type="link" disabled={busy && paging.current} onClick={() => load('latest')}>
{intl.get(view.hasNew ? '查看新的运行记录' : '查看最新记录')}</Button>}
</Space>
</div>;
return <div className="instance-history" ref={viewport}>
<List loading={busy && !view.rows.length}>
{listHeight > 0 && <VirtualList ref={list} data={items} height={listHeight} itemHeight={52} itemKey="id"
onVisibleChange={rows => {
visibleIds.current = new Set(rows.filter(row => row !== paginationRow).map(row => row.id));
}}>
{row => row === paginationRow ? pagination : children(row)}
</VirtualList>}
</List>
</div>;
}
+84 -29
View File
@@ -37,52 +37,84 @@ const CronLogModal = ({
const [value, setValue] = useState<string>(intl.get("启动中..."));
const [loading, setLoading] = useState<any>(true);
const [executing, setExecuting] = useState<any>(true);
const [readFailed, setReadFailed] = useState(false);
const [isPhone, setIsPhone] = useState(false);
const scrollInfoRef = useRef({ value: 0, down: true });
const logOffsetRef = useRef<number>();
const valueRef = useRef(value);
const pollTimerRef = useRef<ReturnType<typeof setTimeout>>();
const uniqPath = logUrl ? logUrl : String(cron?.id);
const session = useRef<AbortController>();
const reading = useRef(false);
const pinnedTrigger = useRef<string>();
const lastPath = useRef<string>();
const drained = useRef(false);
const lastCursor = useRef<string>();
const scrollTimer = useRef<ReturnType<typeof setTimeout>>();
const logEndRef = useRef<HTMLDivElement>(null);
const getCronLog = (isFirst?: boolean) => {
const signal = session.current?.signal;
if (!signal || signal.aborted || reading.current) return;
reading.current = true;
drained.current = false;
if (isFirst) {
setLoading(true);
}
const baseUrl = logUrl ? logUrl : `${config.apiPrefix}crons/${cron.id}/log`;
const triggerParam = !logUrl && pinnedTrigger.current
? "&triggerId=" + encodeURIComponent(pinnedTrigger.current) : "";
const separator = baseUrl.includes("?") ? "&" : "?";
const offset = isFirst ? undefined : logOffsetRef.current;
const pagination = `${separator}limit=${LOG_CHUNK_BYTES}${
isFirst ? "&tail=true" : offset !== undefined ? `&offset=${offset}` : ""
}`;
const pathParam = offset !== undefined && lastPath.current
? "&previousPath=" + encodeURIComponent(lastPath.current) : "";
const cursorParam = offset !== undefined && lastCursor.current ? "&cursor=" + lastCursor.current : "";
request
.get(`${baseUrl}${pagination}`)
.then(({ code, data, logStatus, nextOffset, total }) => {
if (code !== 200 || localStorage.getItem("logCron") !== uniqPath) {
.get(`${baseUrl}${pagination}${pathParam}${cursorParam}${triggerParam}&follow=true`, { signal, retryInPlace: true })
.then(({ code, data, logStatus, logPath, triggerId, cursor, reset, nextOffset, total }) => {
if (signal.aborted) {
return;
}
if (code !== 200) throw new Error("Log read failed");
setReadFailed(false);
const isRunning = logStatus === "running";
// A completed process can still have multiple unread chunks. Drain
// them before stopping, without presenting it as a running task.
if (triggerId) pinnedTrigger.current = triggerId;
const changedFile = reset === true || lastPath.current !== logPath;
const hasUnread =
typeof nextOffset === "number" &&
typeof total === "number" &&
nextOffset > (offset ?? 0) &&
nextOffset > (changedFile ? 0 : offset ?? 0) &&
nextOffset < total;
const hasNext = isRunning || hasUnread;
const chunk = (data as string) || "";
let log = isFirst ? chunk : `${valueRef.current}${chunk}`;
lastPath.current = logPath;
lastCursor.current = cursor;
// A missing file can return a localized status message with zero bytes.
// Keep that message out of the buffer used for subsequent appends.
const noBytes = total === 0;
if (!isFirst && !changedFile && offset !== undefined && total > 0 && total < offset) {
logOffsetRef.current = undefined;
pollTimerRef.current = setTimeout(() => getCronLog(true), 0);
return;
}
let log = isFirst || changedFile || noBytes || offset === undefined ? chunk : valueRef.current + chunk;
if (!log && !hasNext) {
log = intl.get("暂无日志");
}
if (log.length > MAX_LOG_VIEW_CHARS) {
log = log.slice(-MAX_LOG_VIEW_CHARS);
}
valueRef.current = log;
valueRef.current = noBytes ? "" : log;
setValue(log);
if (typeof nextOffset === "number") {
logOffsetRef.current = nextOffset;
}
drained.current = !hasNext;
setExecuting(isRunning);
if (chunk || !hasNext) {
@@ -95,9 +127,13 @@ const CronLogModal = ({
);
}
})
.catch(() => {
if (!signal.aborted) setReadFailed(true);
})
.finally(() => {
if (isFirst) {
setLoading(false);
if (!signal.aborted) {
reading.current = false;
if (isFirst) setLoading(false);
}
});
};
@@ -107,18 +143,20 @@ const CronLogModal = ({
return;
}
setTimeout(() => {
document
.querySelector("#log-flag")
?.scrollIntoView({ behavior: "smooth" });
clearTimeout(scrollTimer.current);
scrollTimer.current = setTimeout(() => {
logEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, 600);
};
const stopReading = () => {
session.current?.abort();
clearTimeout(pollTimerRef.current);
clearTimeout(scrollTimer.current);
};
const cancel = () => {
if (pollTimerRef.current) {
clearTimeout(pollTimerRef.current);
}
localStorage.removeItem("logCron");
stopReading();
handleCancel();
};
@@ -135,25 +173,35 @@ const CronLogModal = ({
const titleElement = () => {
return (
<div style={{ display: "flex", alignItems: "center" }}>
{(executing || loading) && <Loading3QuartersOutlined spin />}
{!executing && !loading && <CheckCircleOutlined />}
{!readFailed && (executing || loading) && <Loading3QuartersOutlined spin />}
{!readFailed && !executing && !loading && <CheckCircleOutlined />}
<Typography.Text ellipsis={true} style={{ marginLeft: 5 }}>
{cron && cron.name}
{pinnedTrigger.current && lastPath.current && ` · ${lastPath.current.split("/").pop()}`}
</Typography.Text>
</div>
);
};
useEffect(() => {
if (cron && cron.id) {
logOffsetRef.current = undefined;
getCronLog(true);
session.current = new AbortController();
reading.current = false;
logOffsetRef.current = undefined;
pinnedTrigger.current = undefined;
lastPath.current = undefined;
lastCursor.current = undefined;
if (cron?.id) getCronLog(true);
return stopReading;
}, [cron?.id, logUrl]);
// The list already refreshes while the dialog is open. A later run can
// start (and finish) after this viewer drained the previous file.
useEffect(() => {
if (logUrl || pinnedTrigger.current || !cron || !drained.current) return;
if ((cron.log_path && cron.log_path !== lastPath.current) ||
cron.status === CrontabStatus.running || cron.status === CrontabStatus.queued) {
getCronLog();
}
return () => {
if (pollTimerRef.current) {
clearTimeout(pollTimerRef.current);
}
};
}, [cron]);
useEffect(() => {
@@ -183,6 +231,13 @@ const CronLogModal = ({
]}
>
<div onScroll={handleScroll} className="log-container">
{readFailed && <div role="status">
{intl.get("加载失败")}
<Button type="link" onClick={() => {
setReadFailed(false);
getCronLog(logOffsetRef.current === undefined);
}}>{intl.get("重试")}</Button>
</div>}
{loading ? (
<PageLoading />
) : (
@@ -196,10 +251,10 @@ const CronLogModal = ({
: {}
}
>
<Ansi>{value}</Ansi>
<Ansi>{readFailed && logOffsetRef.current === undefined ? "" : value}</Ansi>
</pre>
)}
<div id="log-flag"></div>
<div ref={logEndRef} />
</div>
</Modal>
);
+34 -20
View File
@@ -2,8 +2,7 @@ import EditableTagGroup from '@/components/tag';
import config from '@/utils/config';
import { request } from '@/utils/http';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Form, Input, Modal, Select, Space, message } from 'antd';
import CronExpressionParser from 'cron-parser';
import { Button, Checkbox, Form, Input, InputNumber, Modal, Select, Space, message } from 'antd';
import { useEffect, useState } from 'react';
import intl from 'react-intl-universal';
import { getScheduleType, scheduleTypeMap } from './const';
@@ -80,6 +79,23 @@ const CronModal = ({
</Select>
);
const [preview, setPreview] = useState('');
const previewRule = async (_: unknown, rule?: string) => {
if (!rule?.trim()) return;
let result;
let invalid = false;
try {
result = await request.get(`${config.apiPrefix}crons/preview`, {
params: { schedule: rule }, onError: (response) => { invalid = response?.status === 400; },
});
} catch { /* Transport errors have no validation result. */ }
if (!result?.data?.times) throw new Error(intl.get(invalid ? 'Cron表达式格式有误' : '无法获取调度预览,请重试'));
if (form.getFieldValue('schedule') === rule) {
const { times, timezone } = result.data;
setPreview(times.map((time: number) => new Date(time).toLocaleString(undefined, { timeZone: timezone })).join(' · ') + ' (' + timezone + ')');
}
};
const renderScheduleFields = () => {
if (scheduleType !== ScheduleType.Normal) return null;
@@ -88,23 +104,20 @@ const CronModal = ({
<Form.Item
name="schedule"
label={intl.get('定时规则')}
rules={[
{ required: true },
{
validator: (_, value) => {
try {
if (!value || CronExpressionParser.parse(value).hasNext()) {
return Promise.resolve();
}
return Promise.reject(intl.get('Cron表达式格式有误'));
} catch (e) {
return Promise.reject(intl.get('Cron表达式格式有误'));
}
},
},
]}
extra={preview || undefined}
validateTrigger="onBlur"
rules={[{ required: true }, { validator: previewRule }]}
>
<Input placeholder={intl.get('秒(可选) 分 时 天 月 周')} />
<Input onChange={() => setPreview('')} placeholder={intl.get('秒(可选) 分 时 天 月 周')} />
</Form.Item>
<Form.Item name="skip_if_pending" valuePropName="checked">
<Checkbox>{intl.get('如果上一次定时执行仍在排队或运行,跳过本次')}</Checkbox>
</Form.Item>
<Form.Item name="max_queue_wait" label={intl.get('最长排队时间(秒)')} extra={intl.get('超时后跳过本次执行。填 0 表示不限时。')}>
<InputNumber min={0} max={86400} precision={0} placeholder="0" />
</Form.Item>
<Form.Item name="catchup_seconds" label={intl.get('重启后往前查找的时长(秒)')} extra={intl.get('每条规则只补跑这段时间内最近一次错过的执行。填 0 关闭补跑。')}>
<InputNumber min={0} max={86400} precision={0} placeholder="0" />
</Form.Item>
<Form.List name="extra_schedules">
{(fields, { add, remove }, { errors }) => (
@@ -115,7 +128,8 @@ const CronModal = ({
<Form.Item
{...restField}
name={[name, 'schedule']}
rules={[{ required: true }]}
validateTrigger="onBlur"
rules={[{ required: true }, { validator: previewRule }]}
>
<Input
placeholder={intl.get('秒(可选) 分 时 天 月 周')}
@@ -189,7 +203,7 @@ const CronModal = ({
name="allow_multiple_instances"
label={intl.get('实例模式')}
tooltip={intl.get(
'单实例模式:定时启动新任务前会自动停止旧任务;多实例模式:允许同时运行多个任务实例',
'单实例模式下,已有实例运行时会跳过新触发。多实例模式允许同时运行多个实例。',
)}
>
<Select placeholder={intl.get('请选择实例模式')}>
+21
View File
@@ -0,0 +1,21 @@
import { v4 as uuid } from 'uuid';
import { message } from 'antd';
import intl from 'react-intl-universal';
import config from '@/utils/config';
import { request } from '@/utils/http';
// One confirmation owns one operation, including retries after a lost response.
export function createStopRequest(ids: readonly (string | number)[]) {
const targets = [...ids];
const headers = { 'Idempotency-Key': uuid() };
return async () => {
try {
const result = await request.put(`${config.apiPrefix}crons/stop`, targets, { headers, retryInPlace: true });
if (result.code !== 200) throw new Error(result.message);
return result;
} catch (error) {
message.error(intl.get('停止请求未确认,可重试本次操作'));
throw error;
}
};
}
+288
View File
@@ -0,0 +1,288 @@
import { useEffect, useRef, useState } from 'react';
import { Button, List, Space, Tag, Typography } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import intl from 'react-intl-universal';
import TriggerTiming from './triggerTiming';
import {
pageSize,
createTriggerPoll,
type TriggerEntry as Entry,
} from './triggerUpdates';
import config from '@/utils/config';
import { request } from '@/utils/http';
const names: Record<string, string> = {
client: '客户端执行',
legacy: '旧版客户端',
manual: '手动运行',
boot: '开机运行',
node: '定时触发',
system: '系统定时',
recovery: '重启补跑',
queued: '队列中',
running: '运行中',
finished: '已完成',
failed: '失败',
skipped: '已跳过',
pending: '上一次定时触发仍在排队或运行',
cancelled: '已取消',
unknown: '结果未知',
exit_pending: '等待确认执行结果',
exit_conflict: '收到的结束记录不一致',
stopped: '已停止',
overlap: '上一次执行仍在运行',
changed: '任务已变更或取消',
queue_timeout: '超过排队时限',
capacity: '该任务的待执行次数已达上限',
restart: '服务重启',
spawn: '启动或执行失败',
};
export default function TriggerList({
id,
onViewLog,
}: {
id: number;
onViewLog: (row: Entry) => void;
}) {
const [before, setBefore] = useState<Entry | null>(null);
const [rows, setRows] = useState<Entry[]>([]);
const [nextCursor, setNextCursor] = useState<Entry | null>(null);
const [loading, setLoading] = useState(true);
const [failed, setFailed] = useState(false);
const [attempt, setAttempt] = useState(0);
const [hasNew, setHasNew] = useState(false);
const [refreshFailed, setRefreshFailed] = useState(false);
const updateStatus = useRef<ReturnType<typeof createTriggerPoll>>();
const rowsRef = useRef(rows);
const headRef = useRef<Entry>();
const [openIds, setOpenIds] = useState<ReadonlySet<string>>(new Set());
const expanded = !!before;
// Pinning only the first page supports an immediate full refresh on reopen.
// Once paging, changes in selection share the existing workers and queue.
const firstPageSelection = expanded ? null : openIds;
const inspecting = rows.some((row) => openIds.has(row.id));
const paused = !before && inspecting;
const pinned = expanded || inspecting;
const pageRequest = useRef<AbortController>();
const statusRequest = useRef<AbortController>();
useEffect(() => {
rowsRef.current = rows;
}, [rows]);
useEffect(() => {
const controller = new AbortController();
pageRequest.current = controller;
if (paused) {
setLoading(false);
return () => controller.abort();
}
const { signal } = controller;
let timer: ReturnType<typeof setTimeout>;
async function refresh() {
try {
const { data } = await request.get(
`${config.apiPrefix}crons/${id}/triggers`,
{
signal,
retryInPlace: true,
params: {
limit: pageSize + 1,
withQueueWait: true,
...(before && {
beforeTime: before.observed_at,
beforeId: before.id,
}),
},
},
);
if (signal.aborted) return;
if (!Array.isArray(data)) throw new Error('Invalid trigger history');
const entries = data.slice(0, pageSize);
setRows((previous) => (before ? [...previous, ...entries] : entries));
setNextCursor(data.length > pageSize ? entries[pageSize - 1] : null);
setFailed(false);
} catch {
if (!signal.aborted) setFailed(true);
} finally {
if (!signal.aborted) {
setLoading(false);
if (!before) timer = setTimeout(refresh, 5000);
}
}
}
void refresh();
return () => {
controller.abort();
clearTimeout(timer);
};
}, [id, before, attempt, paused]);
useEffect(() => {
const head = headRef.current;
if (!pinned || !head) return;
const controller = new AbortController();
statusRequest.current = controller;
const { signal } = controller;
let timer: ReturnType<typeof setTimeout>;
const update = createTriggerPoll(
head,
async (params) => {
params.set('withQueueWait', 'true');
const { data } = await request.get(
`${config.apiPrefix}crons/${id}/triggers`,
// Give waiting batches a turn after two polling intervals.
{ params, signal, retryInPlace: true, timeout: 10000 },
);
if (!Array.isArray(data)) throw new Error('Invalid trigger history');
return data;
},
() => !signal.aborted,
setHasNew,
(ids, entries) => {
const requested = new Set(ids);
const updated = new Map(entries.map((entry) => [entry.id, entry]));
setRows((previous) =>
previous.flatMap((row) => {
if (!requested.has(row.id)) return [row];
const current = updated.get(row.id);
return current ? [current] : [];
}),
);
},
setRefreshFailed,
openIds,
);
updateStatus.current = update;
function poll() {
if (signal.aborted) return;
update(rowsRef.current);
timer = setTimeout(poll, 5000);
}
poll();
return () => {
updateStatus.current = undefined;
controller.abort();
clearTimeout(timer);
};
}, [id, pinned, firstPageSelection]);
useEffect(() => {
if (expanded) updateStatus.current?.(rowsRef.current, openIds);
}, [expanded, openIds]);
const label = (key: string) => (names[key] ? intl.get(names[key]) : key);
return (
<section aria-label={intl.get('触发记录')}>
{pinned && (hasNew || refreshFailed) && (
<Space wrap role="status">
{hasNew && (
<Button
type="link"
onClick={() => {
pageRequest.current?.abort();
pageRequest.current = undefined;
statusRequest.current?.abort();
setOpenIds(new Set());
setRows([]);
setNextCursor(null);
setHasNew(false);
setRefreshFailed(false);
setFailed(false);
setLoading(true);
setBefore(null);
}}
>
{intl.get('查看新的触发记录')}
</Button>
)}
{refreshFailed && (
<>
<Typography.Text type="secondary">
{intl.get('触发状态刷新失败')}
</Typography.Text>
<Button
type="link"
onClick={() => updateStatus.current?.(rowsRef.current, 'retry')}
>
{intl.get('重试')}
</Button>
</>
)}
</Space>
)}
<List
rowKey="id"
className="trigger-history"
loading={loading && !rows.length}
dataSource={rows}
renderItem={(row) => (
<List.Item key={row.id}>
<div className="trigger-history-entry" data-trigger-id={row.id}>
<div className="trigger-history-header">
<Space size={8} wrap>
<Tag>{label(row.state)}</Tag>
<span>{label(row.source)}</span>
{row.reason && (
<Typography.Text type="secondary">
{label(row.reason)}
</Typography.Text>
)}
</Space>
{row.log_path && row.log_path !== '/dev/null' && (
<Button
type="link"
size="small"
onClick={() => onViewLog(row)}
>
{intl.get('查看日志')}
</Button>
)}
</div>
<TriggerTiming row={row} open={openIds.has(row.id)} onToggle={() => {
if (!expanded) statusRequest.current?.abort();
if (!pinned) {
headRef.current = rows[0];
pageRequest.current?.abort();
// An open and close may be batched without ever committing a pinned page.
setAttempt((value) => value + 1);
setFailed(false);
setHasNew(false);
setRefreshFailed(false);
}
setOpenIds((previous) => {
const next = new Set(previous);
if (next.has(row.id)) next.delete(row.id);
else next.add(row.id);
return next;
});
}} />
</div>
</List.Item>
)}
/>
{(nextCursor || failed) && (
<div className="trigger-history-pagination">
{failed && <span role="status">{intl.get('加载失败')}</span>}
<Button
type="link"
loading={loading}
icon={failed ? <ReloadOutlined aria-hidden /> : undefined}
onClick={() => {
if (loading || !pageRequest.current) return;
pageRequest.current.abort();
// Reserve this transition until the effect installs its next controller.
pageRequest.current = undefined;
setLoading(true);
if (failed) setAttempt((value) => value + 1);
else {
if (!expanded) headRef.current = rows[0];
setBefore(nextCursor);
}
}}
>
{intl.get(failed ? '重试' : '加载更早记录')}
</Button>
</div>
)}
</section>
);
}
+91
View File
@@ -0,0 +1,91 @@
import dayjs from 'dayjs';
import intl from 'react-intl-universal';
import type { TriggerEntry } from './triggerUpdates';
function elapsed(start?: number, end?: number) {
if (start == null || end == null || end < start) return;
const ms = end - start;
if (ms < 1000) return ms + ' ms';
return (ms / 1000) + ' s';
}
export function QueueReason({ context, live = false }: { context: string; live?: boolean }) {
const admission: {queue: string; limit: number; occupied: number; holders: { id?: string; name: string }[]} = JSON.parse(context);
return <div className="queue-reason">
<strong>{intl.get(admission.queue === 'manual' ? '手动执行队列' : '定时执行队列')}</strong>
{' · '}{intl.get(live ? '最近一次检查(运行 {used},上限 {limit})' : '入队时已达并发上限(运行 {used},上限 {limit})', { used: admission.occupied, limit: admission.limit })}
<ul>{admission.holders.map((holder, i) => <li key={holder.id ?? i}>
{holder.name}{holder.id && <> · <code title={holder.id}>{holder.id.slice(-8)}</code></>}
</li>)}</ul>
{admission.occupied > admission.holders.length && intl.get('仅列出最早开始运行的 8 个实例')}
</div>;
}
export default function TriggerTiming({ row, open, onToggle }: { row: TriggerEntry; open: boolean; onToggle: () => void }) {
const queued = row.state === 'queued';
const skipped = row.state === 'skipped';
const unknown = row.state === 'unknown';
const terminal = !queued && row.state !== 'running';
const start = row.scheduled_at ?? row.queued_at ?? row.started_at ?? row.observed_at;
const startLabel = row.scheduled_at != null ? '计划运行' : row.queued_at != null
? '进入队列' : row.started_at != null ? '记录启动' : '记录时间';
const endLabel = skipped ? '跳过时间' : unknown ? '状态记录时间' : '结束时间';
const queueEnd = row.dequeued_at ?? row.started_at ?? (queued ? Date.now() : (skipped || row.state === 'stopped') ? row.finished_at : undefined);
const wait = queued && row.queue_wait_ms != null
? elapsed(0, row.queue_wait_ms) : elapsed(row.queued_at, queueEnd);
const launch = elapsed(row.scheduled_at, row.command_started_at);
const entryDelay = elapsed(row.scheduled_at ?? row.queued_at ?? row.started_at, row.script_started_at);
const entryLabel = row.scheduled_at != null ? '计划到脚本开始' : row.queued_at != null
? '入队到脚本开始' : '启动记录到脚本开始';
const time = (value: number, precise: boolean) => {
const date = dayjs(value);
const format = date.isSame(start, 'day') ? 'HH:mm:ss' : 'YYYY-MM-DD HH:mm:ss';
return date.format(precise ? format + '.SSS' : format);
};
const timestamps: [string, number | undefined][] = [
['计划运行', row.scheduled_at],
['进入队列', row.queued_at],
[row.queued_at != null ? '排队结束' : '记录启动', row.dequeued_at ?? row.started_at],
['命令启动', row.command_started_at],
['脚本开始执行(采样)', row.script_started_at],
[endLabel, row.finished_at],
];
return <>
<div className="trigger-history-summary">
<span>{intl.get(startLabel)} <b>{dayjs(start).format('YYYY-MM-DD HH:mm:ss')}</b></span>
{queued && wait != null && <span>{intl.get('已排队')} <b>{wait}</b></span>}
{!skipped && !queued && launch != null && <span>{intl.get('计划到命令启动')} <b>{launch}</b></span>}
{row.scheduled_at == null && row.command_started_at != null && (
<span>{intl.get('命令启动')} <b>{time(row.command_started_at, false)}</b></span>
)}
{!skipped && !queued && wait != null && <span>{intl.get('排队等待')} <b>{wait}</b></span>}
{terminal && row.finished_at != null && !unknown && !skipped && (
<span>{intl.get(endLabel)} <b>{time(row.finished_at, false)}</b></span>
)}
{row.exit_code != null && row.exit_code !== 0 && <span>{intl.get('退出码')} <b>{row.exit_code}</b></span>}
</div>
<details className="trigger-history-timing" open={open}>
<summary onClick={(event) => {
event.preventDefault();
onToggle();
}}>{intl.get('时间明细')}</summary>
{queued && row.dequeued_at != null ? <p>{intl.get('排队结束,正在准备命令')}</p>
: queued && row.queue_live_context ? <QueueReason live context={row.queue_live_context} />
: row.queue_context && <QueueReason context={row.queue_context} />}
{queued && row.dequeued_at == null && !row.queue_context && !row.queue_live_context && <p>{intl.get('正在排队,尚无同时运行的任务记录')}</p>}
<dl className="trigger-timestamps">
{timestamps.map(([key, value]) => <div key={key}>
<dt>{intl.get(key)}</dt>
<dd>{value != null ? time(value, true) : intl.get(
key === '脚本开始执行(采样)' ? '未采集到开始时间' : '未记录',
)}</dd>
</div>)}
</dl>
{(entryDelay != null || (skipped && wait != null)) && <div className="trigger-history-summary">
{skipped && wait != null && <span>{intl.get('跳过前等待')} <b>{wait}</b></span>}
{entryDelay != null && <span>{intl.get(entryLabel)} <b>{entryDelay}</b></span>}
</div>}
</details>
</>;
}
+126
View File
@@ -0,0 +1,126 @@
export type TriggerEntry = {
observed_at: number;
id: string;
source: string;
state: string;
reason?: string;
log_path?: string;
scheduled_at?: number;
queued_at?: number;
dequeued_at?: number;
queue_live_context?: string;
queue_wait_ms?: number;
queue_context?: string;
started_at?: number;
script_started_at?: number;
command_started_at?: number;
finished_at?: number;
exit_code: number | null;
legacy_exit_booking?: number;
};
export const pageSize = 25;
export function createTriggerPoll(
head: TriggerEntry,
read: (params: URLSearchParams) => Promise<TriggerEntry[]>,
active: () => boolean,
onHead: (newer: boolean) => void,
onBatch: (ids: string[], entries: TriggerEntry[]) => void,
onError: (failed: boolean) => void,
openIds: ReadonlySet<string>,
) {
const waiting = new Set<string>();
const inFlight = new Set<string>();
const failed = new Set<string>();
const recheck = new Set<string>();
let watched = new Set<string>();
let workers = 0;
let readingHead = false;
let headFailed = false;
function reportErrors() {
onError(headFailed || failed.size > 0);
}
async function checkHead() {
if (readingHead) return;
readingHead = true;
try {
const [latest] = await read(new URLSearchParams({ limit: '1' }));
if (!active()) return;
onHead(!!latest && (latest.observed_at > head.observed_at ||
(latest.observed_at === head.observed_at && latest.id > head.id)));
headFailed = false;
} catch {
headFailed = true;
} finally {
readingHead = false;
if (active()) reportErrors();
}
}
async function refreshBatches() {
workers++;
try {
while (active() && waiting.size) {
const batch: string[] = [];
const params = new URLSearchParams();
for (const id of waiting) {
waiting.delete(id);
if (!watched.has(id)) continue;
inFlight.add(id);
batch.push(id);
params.append('ids', id);
if (batch.length === pageSize) break;
}
if (!batch.length) continue;
try {
const entries = await read(params);
if (!active()) return;
onBatch(batch, entries);
for (const id of batch) failed.delete(id);
} catch {
for (const id of batch) if (watched.has(id)) failed.add(id);
} finally {
for (const id of batch) {
inFlight.delete(id);
if (recheck.delete(id) && watched.has(id)) waiting.add(id);
}
if (active()) reportErrors();
}
}
} finally {
workers--;
}
}
return function poll(rows: TriggerEntry[], action: 'poll' | 'retry' | ReadonlySet<string> = 'poll') {
if (!active()) return;
const previousOpen = openIds;
if (typeof action !== 'string') openIds = action;
watched = new Set(rows.filter(row =>
openIds.has(row.id) || row.state === 'running' || row.state === 'queued' ||
row.reason === 'exit_pending' || row.reason === 'exit_conflict' ||
row.legacy_exit_booking === 1 ||
(row.reason === 'restart' && (row.state === 'skipped' || row.state === 'unknown')),
).map(row => row.id));
const previousFailures = failed.size;
for (const id of failed) if (!watched.has(id)) failed.delete(id);
if (failed.size !== previousFailures) reportErrors();
// A close and reopen before dispatch must retain the original FIFO position.
// The worker checks current interest when it takes the ID off the queue.
for (const id of watched) {
if (action === 'retry' && !failed.has(id)) continue;
if (typeof action !== 'string') {
if (!openIds.has(id) || previousOpen.has(id)) continue;
if (inFlight.has(id)) recheck.add(id);
}
if (!inFlight.has(id)) waiting.add(id);
}
if (action === 'poll' || (action === 'retry' && headFailed)) void checkHead();
while (active() && waiting.size && workers < 2) void refreshBatches();
};
}
+3 -2
View File
@@ -32,9 +32,10 @@ export interface ICrontab {
isDisabled?: 1 | 0;
isPinned?: 1 | 0;
labels?: string[];
last_running_time?: number;
last_running_time?: number | null;
last_execution_time?: number;
nextRunTime: Date;
nextRunTime: number | null;
saved?: boolean;
sub_id: number;
extra_schedules?: Array<{ schedule: string }>;
allow_multiple_instances?: 1 | 0;
+123
View File
@@ -0,0 +1,123 @@
.schedule-overview {
margin-top: 16px;
container-type: inline-size;
}
.schedule-note {
margin: 12px 0 0;
color: var(--ant-color-text-secondary, inherit);
}
.schedule-details {
margin-top: 12px;
summary {
cursor: pointer;
width: fit-content;
}
&[open] > summary {
margin-bottom: 12px;
}
}
.schedule-metrics {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 16px 24px;
.ant-statistic {
display: flex;
flex-direction: column;
min-width: 0;
}
.ant-statistic-content {
font-variant-numeric: tabular-nums;
overflow-wrap: anywhere;
}
.ant-statistic-content-suffix {
font-size: 14px;
}
small {
opacity: 0.7;
font-size: 13px;
}
}
@container (max-width: 800px) {
.schedule-metrics {
grid-template-columns: repeat(2, minmax(0, 1fr));
column-gap: 16px;
}
}
@container (max-width: 280px) {
.schedule-metrics {
grid-template-columns: minmax(0, 1fr);
}
}
.dashboard-totals.ant-row {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
grid-auto-rows: 1fr;
gap: 12px;
margin: 0 !important;
> .ant-col { min-width: 0; max-width: none; padding: 0 !important; }
.ant-card { height: 100%; }
.ant-statistic-content { font-variant-numeric: tabular-nums; overflow-wrap: anywhere; line-height: 1.3; }
small { display: block; margin-top: 3px; }
}
.dashboard-wrapper { container-type: inline-size; }
@container (min-width: 640px) {
.dashboard-totals.ant-row { grid-template-columns: repeat(4, minmax(0, 1fr)); }
}
@container (min-width: 1280px) {
.dashboard-totals.ant-row { grid-template-columns: repeat(8, minmax(0, 1fr)); }
}
.queue-entry { padding: 8px 0; border-bottom: 1px solid var(--ant-border-color-split); }
.queue-reason ul { padding-inline-start: 22px; margin: 4px 0; }
.schedule-group-title { margin-top: 16px; }
.timing-samples {
margin: 0;
dd { margin: 0; }
}
.schedule-overview > .ant-card-head .ant-card-head-title {
display: flex;
align-items: center;
gap: 4px;
}
.schedule-help-button.ant-btn {
display: inline-flex;
align-items: center;
justify-content: center;
.anticon {
display: inline-flex;
font-size: 13px;
transform: translateY(0.25px);
}
}
.schedule-help {
width: 390px;
max-width: calc(100vw - 48px);
max-height: 65vh;
overflow-y: auto;
overscroll-behavior: contain;
overflow-wrap: anywhere;
h4 { margin: 12px 0 6px; }
p { margin: 8px 0 0; }
> :first-child { margin-top: 0; }
.timing-samples { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px 16px; }
}
+299 -52
View File
@@ -1,9 +1,10 @@
import { useEffect, useState, useCallback } from 'react';
import { Card, Col, Row, Statistic, Table, Tag, Spin, Empty } from 'antd';
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { Button, Card, Col, Popover, Row, Statistic, Table, Tabs, Tag, Spin, Empty } from 'antd';
import {
CheckCircleOutlined,
CloseCircleOutlined,
ClockCircleOutlined,
InfoCircleOutlined,
ThunderboltOutlined,
StopOutlined,
BarChartOutlined,
@@ -16,15 +17,30 @@ import { SharedContext } from '@/layouts';
import { request } from '@/utils/http';
import config from '@/utils/config';
import CronLogModal from '../crontab/logModal';
import { QueueReason } from '../crontab/triggerTiming';
import TimingStatistic from './timingStatistic';
import TaskResultModal from './taskResultModal';
import './index.less';
interface Overview {
total: number;
enabled: number;
disabled: number;
triggers?: { audit?: {
since: number; through: number; zone: string; partial?: boolean; expected: number; observed: number; missing: number;
onTime: number; dispatched: number; commandSamples: number; skipped: number; queued: number; unconfirmed: number;
waitSamples?: number;
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;
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 };
todayRuns: number;
todaySuccess: number;
todayFail: number;
todayStopped: number;
successRate: string;
avgTime: number;
}
@@ -48,6 +64,8 @@ interface TopItem {
interface Runtime {
runningCount: number;
queuedCount: number;
queuedTasks: number;
oldestQueued?: { id: string; name: string; queued_at: number; queue_context?: string; queue_live_context?: string }[];
running: Array<{ instanceId: number; id: number; name: string; pid: number; elapsed: number; logPath: string }>;
idleTasks: Array<{ id: number; name: string; lastRun: string }>;
}
@@ -62,6 +80,8 @@ interface SystemInfo {
heapTotal: number;
loadAvg: number[];
cpus: number;
hostCpus: number;
hostMemory: number;
}
const formatBytes = (bytes: number) => {
@@ -82,6 +102,25 @@ const formatSeconds = (s: number) => {
const REFRESH_INTERVAL = 30000;
function ScheduleRate({ title, count, total }: { title: string; count?: number; total: number }) {
const measured = count != null && total > 0;
const percent = measured ? (100 * count / total).toFixed(1) : null;
return (
<Statistic
title={title}
value={measured && percent === '100.0' && count < total ? '>99.9%' : measured ? `${percent}%` : '—'}
suffix={measured ? <small>({count}/{total})</small> : undefined}
/>
);
}
function formatCount(raw: number | string) {
const count = Number(raw);
const locale = document.documentElement.lang || navigator.language;
return <span title={count.toLocaleString(locale)}>{count.toLocaleString(locale,
count >= 100000 ? { notation: 'compact', maximumFractionDigits: 1 } : {})}</span>;
}
const Dashboard = () => {
const { headerStyle, theme } = useOutletContext<SharedContext>();
const isDark = theme === 'vs-dark';
@@ -94,52 +133,111 @@ const Dashboard = () => {
const [labels, setLabels] = useState<any[]>([]);
const [logCron, setLogCron] = useState<any>(null);
const [loading, setLoading] = useState(true);
const [overviewFailed, setOverviewFailed] = useState(false);
const [result, setResult] = useState<'success' | 'failure' | null>(null);
const fetchData = useCallback(async () => {
try {
const [overviewRes, trendRes, topTimeRes, topCountRes, runtimeRes, systemRes, labelsRes] =
await Promise.allSettled([
request.get(`${config.apiPrefix}dashboard/overview`),
request.get(`${config.apiPrefix}dashboard/trend`),
request.get(`${config.apiPrefix}dashboard/top-time`),
request.get(`${config.apiPrefix}dashboard/top-count`),
request.get(`${config.apiPrefix}dashboard/runtime`),
request.get(`${config.apiPrefix}dashboard/system`),
request.get(`${config.apiPrefix}dashboard/labels`),
]);
const [selectedSource, setSelectedSource] = useState<string>();
const [helpOpen, setHelpOpen] = useState(false);
const helpButton = useRef<HTMLButtonElement>(null);
const helpPopover = useRef<{ forcePopupAlign(): void }>(null);
const [helpContent, setHelpContent] = useState<HTMLDivElement | null>(null);
useLayoutEffect(() => {
const button = helpButton.current;
const popup = helpContent?.closest<HTMLElement>('.ant-popover');
const arrow = popup?.querySelector<HTMLElement>('.ant-popover-arrow');
if (!helpOpen || !button || !helpContent || !popup || !arrow) return;
if (overviewRes.status === 'fulfilled' && overviewRes.value.code === 200)
setOverview(overviewRes.value.data);
if (trendRes.status === 'fulfilled' && trendRes.value.code === 200)
setTrend(trendRes.value.data);
if (topTimeRes.status === 'fulfilled' && topTimeRes.value.code === 200)
setTopTime(topTimeRes.value.data);
if (topCountRes.status === 'fulfilled' && topCountRes.value.code === 200)
setTopCount(topCountRes.value.data);
if (runtimeRes.status === 'fulfilled' && runtimeRes.value.code === 200)
setRuntime(runtimeRes.value.data);
if (systemRes.status === 'fulfilled' && systemRes.value.code === 200)
setSystem(systemRes.value.data);
if (labelsRes.status === 'fulfilled' && labelsRes.value.code === 200)
setLabels(labelsRes.value.data);
} catch (e) {
console.error('[dashboard] fetch error', e);
} finally {
setLoading(false);
}
}, []);
// Ant moves the popup to fit the viewport. Center the arrow on the trigger
// after each alignment, even when the popup itself can no longer be centered.
const alignArrow = () => {
const trigger = button.getBoundingClientRect();
const box = popup.getBoundingClientRect();
if (box.width) arrow.style.left = `${(trigger.left + trigger.width / 2 - box.left) * popup.offsetWidth / box.width}px`;
};
const viewport = window.visualViewport;
const positionHelp = () => {
const trigger = button.getBoundingClientRect();
const top = viewport?.offsetTop ?? 0;
const height = viewport?.height ?? window.innerHeight;
const space = Math.max(trigger.top - top, top + height - trigger.bottom);
const chromeHeight = popup.offsetHeight - helpContent.offsetHeight;
// Leave room for the pointer, padding and viewport edge on the side that fits.
helpContent.style.maxHeight = `${Math.max(0, Math.min(height * 0.65, space - chromeHeight - 8))}px`;
helpPopover.current?.forcePopupAlign();
alignArrow();
};
const onScroll = (event: Event) => {
if (!(event.target instanceof Node && popup.contains(event.target))) positionHelp();
};
positionHelp();
const resize = new ResizeObserver(positionHelp);
resize.observe(button.closest('.schedule-overview')!);
resize.observe(helpContent);
const visibility = new IntersectionObserver(([entry]) => {
if (!entry.isIntersecting) setHelpOpen(false);
});
visibility.observe(button);
const observer = new MutationObserver(alignArrow);
observer.observe(popup, { attributes: true, attributeFilter: ['style', 'class'] });
popup.addEventListener('animationend', alignArrow);
window.addEventListener('resize', positionHelp);
window.addEventListener('scroll', onScroll, true);
viewport?.addEventListener('resize', positionHelp);
viewport?.addEventListener('scroll', positionHelp);
return () => {
observer.disconnect();
resize.disconnect();
visibility.disconnect();
popup.removeEventListener('animationend', alignArrow);
window.removeEventListener('resize', positionHelp);
window.removeEventListener('scroll', onScroll, true);
viewport?.removeEventListener('resize', positionHelp);
viewport?.removeEventListener('scroll', positionHelp);
};
}, [helpOpen, helpContent]);
const audit = overview?.triggers?.audit;
const systemAudit = overview?.triggers?.systemAudit;
useEffect(() => {
let timer: ReturnType<typeof setTimeout>;
const poll = async () => {
await fetchData();
timer = setTimeout(poll, REFRESH_INTERVAL);
const controller = new AbortController();
const { signal } = controller;
const pending = new Set<string>();
async function refresh<T>(section: string, apply: (data: T) => void) {
if (pending.has(section)) return;
pending.add(section);
try {
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 (section === 'overview') setOverviewFailed(response.code !== 200);
} catch {
if (!signal.aborted && section === 'overview') setOverviewFailed(true);
} finally {
pending.delete(section);
if (!signal.aborted && section === 'overview') setLoading(false);
}
}
function poll() {
void refresh<Overview>('overview', setOverview);
void refresh<TrendItem[]>('trend', setTrend);
void refresh<TopItem[]>('top-time', setTopTime);
void refresh<TopItem[]>('top-count', setTopCount);
void refresh<Runtime>('runtime', setRuntime);
void refresh<SystemInfo>('system', setSystem);
void refresh<any[]>('labels', setLabels);
}
poll();
const timer = setInterval(poll, REFRESH_INTERVAL);
return () => {
clearInterval(timer);
controller.abort();
};
fetchData();
timer = setTimeout(poll, REFRESH_INTERVAL);
return () => clearTimeout(timer);
}, [fetchData]);
}, []);
const trendConfig = {
data: trend.flatMap((d) => [
@@ -172,21 +270,128 @@ const Dashboard = () => {
if (loading) return <Spin size="large" style={{ display: 'block', marginTop: 100 }} />;
const sources = [];
if (audit) {
const timings = [
{ title: intl.get('触发时间偏差 P95'), ms: audit.triggerDeviationP95, samples: audit.observed },
{ title: intl.get('排队等待 P95'), ms: audit.waitP95, samples: audit.waitSamples },
{ title: intl.get('计划到命令启动 P95'), ms: audit.commandStartP95, samples: audit.commandSamples },
{ title: intl.get('计划到脚本开始 P95'), ms: audit.scriptStartP95, samples: audit.scriptSamples },
];
sources.push({
key: 'panel',
label: intl.get('由青龙触发'),
help: <>
{audit.partial && <p className="schedule-note">{intl.get('规则切换期间有些计划无法确认。这里只统计能确认的计划,暂不显示准时率。')}</p>}
<p className="schedule-note">{intl.get('从 {time} 起统计,最近 5 秒暂不计入。触发时间与计划相差不超过 5 秒算准时。准时率 = 准时触发次数 ÷ 计划触发次数。', {
time: new Date(audit.since).toLocaleTimeString(undefined, {timeZone: audit.zone, hour12: false}),
})}</p>
<h4>{intl.get('样本与计算方式')}</h4>
<dl className="schedule-metrics timing-samples">
{timings.map(({ title, samples }) => <div key={title}>
<dt>{title}</dt>
<dd>{samples == null ? '—' : intl.get('{count} 个样本', { count: samples })}</dd>
</div>)}
</dl>
<p className="schedule-note">{intl.get('P95 取各项样本从小到大排列的第 95 百分位。触发偏差比较计划时间与收到触发的时间,包含迟到后跳过的记录。排队等待只统计从入队到取得执行资格的耗时,旧记录用开始派发时间估算。直接执行命令时可能没有脚本开始样本。')}</p>
</>,
children: <>
<div className="schedule-metrics">
<Statistic title={intl.get('计划触发次数')} value={audit.expected} />
<Statistic title={intl.get('未收到触发记录')} value={audit.missing} />
<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} />
<Statistic title={intl.get('仍在排队')} value={audit.queued} />
<Statistic title={intl.get('启动未确认')} value={audit.unconfirmed} />
</div>
<details className="schedule-details">
<summary>{intl.get('查看启动耗时')}</summary>
<div className="schedule-metrics">
{timings.map(({ title, ms }) => <TimingStatistic key={title} title={title} ms={ms} />)}
</div>
</details>
</>,
});
}
if (systemAudit) {
sources.push({
key: 'system',
label: intl.get('由系统触发(crond)'),
help: <>
<p className="schedule-note">{intl.get('同一计划多出的记录计为重复。只有明确记录的跳过才计入跳过次数。记录写入前中断的派发无法核实。')}</p>
<p className="schedule-note">{intl.get('上次成功安装规则')} {systemAudit.confirmedAt ? new Date(systemAudit.confirmedAt).toLocaleString() : '—'}
{' · '}{intl.get('按任务、规则和系统发出命令的分钟匹配。超过计划时间一分钟仍无记录,显示“未收到触发记录”。')}</p>
{(systemAudit.uncertain>0 || systemAudit.awaiting>0 || systemAudit.switchSlots>0) &&
<p>{intl.get('等待触发记录 {waiting} 次,无法确定触发分钟 {uncertain} 次,无法确定生效规则 {switches} 次。', {waiting:systemAudit.awaiting,uncertain:systemAudit.uncertain,switches:systemAudit.switchSlots})}</p>}
{(systemAudit.partial || systemAudit.pending) && <p>{intl.get('部分时段的计划还无法确定,只统计能确认的计划。')}</p>}
</>,
children: <>
<h4>{intl.get('按计划统计')}</h4>
<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} />
</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 ?? '—'} />
<Statistic title={intl.get('重复触发次数')} value={systemAudit.duplicates} />
<Statistic title={intl.get('找不到对应计划的触发记录')} value={systemAudit.unmatched} />
</div>
<details className="schedule-details"><summary>{intl.get('查看最近 25 次计划触发')}</summary>
<Table size="small" pagination={false} dataSource={systemAudit.recent} rowKey={r => r.task + '/' + r.time} columns={[
{title:intl.get('计划时间'),render:(_,r) => new Date(r.time).toLocaleTimeString()},
{title:intl.get('任务'),render:(_,r) => r.name || '#' + r.task},
{title:intl.get('匹配的触发记录'),dataIndex:'triggerCount',render:count => count ?? '—'},
{title:intl.get('执行情况'),render:(_, row) => {
const { triggerCount = 0, startCount = 0, skipCount = 0, unknownExitCount = 0 } = row;
const unconfirmed = triggerCount - startCount - skipCount;
const status = triggerCount > 1 ? [
startCount > 0 && intl.get('启动 {count} 次', {count: startCount}),
skipCount > 0 && intl.get('跳过 {count} 次', {count: skipCount}),
unconfirmed > 0 && intl.get('启动未确认 {count} 次', {count: unconfirmed}),
].filter(Boolean).join(' · ') : intl.get(({
started:'命令已启动', skipped:'已跳过', unconfirmed:'启动未确认', missing:'未收到触发记录',
switch:'生效规则不确定', uncertain:'触发分钟不确定', awaiting:'等待触发记录',
} as Record<string,string>)[row.status]);
if (!unknownExitCount) return status;
return <>{status} · {triggerCount === 1 ? intl.get('结果未知') :
intl.get('其中 {count} 次执行结果未知', { count: unknownExitCount })}</>;
}},
{title:intl.get('执行 ID(示例)'),render:(_,r) => r.id ? <code title={r.id}>{r.id.slice(-8)}</code> : '—'},
]} />
</details>
</>,
});
}
const activeSource = sources.find(source => source.key === selectedSource)
?? sources.find(source => source.key === (audit?.expected || audit?.partial ? 'panel' : 'system'))
?? sources[0];
return (
<PageContainer
title={intl.get('仪表盘')}
header={{ style: headerStyle }}
className={'ql-container-wrapper dashboard-wrapper'}
>
<Row gutter={[16, 16]}>
<Row className="dashboard-totals" gutter={[16, 16]}>
<Col xs={12} sm={8} md={6} lg={3}>
<Card size="small"><Statistic title={intl.get('总任务')} value={overview?.total || 0} prefix={<BarChartOutlined />} /></Card>
<Card size="small"><Statistic title={intl.get('总任务')} value={overview?.total || 0} formatter={formatCount} prefix={<BarChartOutlined />} /></Card>
</Col>
<Col xs={12} sm={8} md={6} lg={3}>
<Card size="small"><Statistic title={intl.get('已启用')} value={overview?.enabled || 0} valueStyle={{ color: '#1677ff' }} prefix={<CheckCircleOutlined />} /></Card>
<Card size="small"><Statistic title={intl.get('已启用')} value={overview?.enabled || 0} formatter={formatCount} valueStyle={{ color: '#1677ff' }} prefix={<CheckCircleOutlined />} /></Card>
</Col>
<Col xs={12} sm={8} md={6} lg={3}>
<Card size="small"><Statistic title={intl.get('今日执行')} value={overview?.todayRuns || 0} valueStyle={{ color: '#1677ff' }} prefix={<ThunderboltOutlined />} /></Card>
<Card size="small"><Statistic title={intl.get('今日执行')} value={overview?.todayRuns || 0} formatter={formatCount}
valueStyle={{ color: '#1677ff' }} prefix={<ThunderboltOutlined />} />
{!!overview?.todayStopped && <small>{intl.get('已停止')} {overview.todayStopped}</small>}
</Card>
</Col>
<Col xs={12} sm={8} md={6} lg={3}>
<Card size="small"><Statistic title={intl.get('成功率')} value={`${overview?.successRate || '0'}%`} valueStyle={{ color: '#52c41a' }} /></Card>
@@ -201,7 +406,7 @@ const Dashboard = () => {
setResult('success');
}
}}
><Statistic title={intl.get('今日成功')} value={overview?.todaySuccess || 0} valueStyle={{ color: '#52c41a' }} prefix={<CheckCircleOutlined />} /></Card>
><Statistic title={intl.get('今日成功')} value={overview?.todaySuccess || 0} formatter={formatCount} valueStyle={{ color: '#52c41a' }} prefix={<CheckCircleOutlined />} /></Card>
</Col>
<Col xs={12} sm={8} md={6} lg={3}>
<Card size="small" hoverable role="button" tabIndex={0}
@@ -213,15 +418,45 @@ const Dashboard = () => {
setResult('failure');
}
}}
><Statistic title={intl.get('今日失败')} value={overview?.todayFail || 0} valueStyle={{ color: '#ff4d4f' }} prefix={<CloseCircleOutlined />} /></Card>
><Statistic title={intl.get('今日失败')} value={overview?.todayFail || 0} formatter={formatCount} valueStyle={{ color: '#ff4d4f' }} prefix={<CloseCircleOutlined />} /></Card>
</Col>
<Col xs={12} sm={8} md={6} lg={3}>
<Card size="small"><Statistic title={intl.get('平均耗时')} value={overview?.avgTime ? `${(overview.avgTime / 1000).toFixed(1)}s` : '-'} prefix={<ClockCircleOutlined />} /></Card>
</Col>
<Col xs={12} sm={8} md={6} lg={3}>
<Card size="small"><Statistic title={intl.get('已禁用')} value={overview?.disabled || 0} prefix={<StopOutlined />} /></Card>
<Card size="small"><Statistic title={intl.get('已禁用')} value={overview?.disabled || 0} formatter={formatCount} prefix={<StopOutlined />} /></Card>
</Col>
</Row>
{overviewFailed && overview && <p role="status">{intl.get('刷新失败,仍显示上次的数据')}</p>}
<Card size="small" className="schedule-overview" title={<>
{intl.get('今日定时调度')}
{activeSource && <Popover
ref={helpPopover}
trigger={['hover', 'focus', 'click']}
placement="bottom"
open={helpOpen}
onOpenChange={setHelpOpen}
content={<div ref={setHelpContent} className="schedule-help">{activeSource.help}</div>}
>
<Button ref={helpButton} className="schedule-help-button" type="text" size="small"
aria-label={intl.get('调度统计说明')} aria-expanded={helpOpen}
icon={<InfoCircleOutlined />} onKeyDown={event => {
if (event.key === 'Escape') setHelpOpen(false);
}} />
</Popover>}
</>}>
{sources.length === 2 ? (
<Tabs items={sources.map(({ key, label, children }) => ({ key, label, children }))}
activeKey={activeSource?.key} onChange={setSelectedSource} />
) : sources.length === 1 ? (
sources[0].children
) : (
<p>{intl.get(overview?.triggers ? '暂时无法确认应触发的计划,未收到触发的次数和准时率未知。' : '暂时无法显示调度数据。')}</p>
)}
{overview?.triggers && systemAudit === undefined && (
<p className="schedule-note">{intl.get('当前面板服务未提供系统定时任务统计。')}</p>
)}
</Card>
<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<Col span={24}>
@@ -297,10 +532,17 @@ const Dashboard = () => {
extra={
<>
<Tag color="processing">{intl.get('运行中')} {runtime?.runningCount || 0}</Tag>
<Tag color="warning">{intl.get('排队中')} {runtime?.queuedCount || 0}</Tag>
<Tag color="warning">{intl.get('排队中 {runs} 次,涉及 {tasks} 个任务', { runs: runtime?.queuedCount || 0, tasks: runtime?.queuedTasks || 0 })}</Tag>
</>
}
>
{!!runtime?.oldestQueued?.length && <details className="schedule-details"><summary>{intl.get('查看排队原因')}</summary>
{runtime.oldestQueued.map(row => <div className="queue-entry" key={row.id}>
<b>{row.name}</b>{' · '}{intl.get('已排队')} {formatSeconds(Math.max(0, Math.floor((Date.now()-row.queued_at)/1000)))}
{row.queue_live_context ? <QueueReason live context={row.queue_live_context} /> : row.queue_context ? <QueueReason context={row.queue_context} /> : <p>{intl.get('正在排队,尚无同时运行的任务记录')}</p>}
</div>)}
{runtime.queuedCount > runtime.oldestQueued.length && intl.get('仅显示等待最久的 25 个实例')}
</details>}
<Table
dataSource={runtime?.running || []}
rowKey="instanceId"
@@ -314,7 +556,7 @@ const Dashboard = () => {
} },
{ title: 'PID', dataIndex: 'pid', width: 80 },
{ title: intl.get('已运行'), dataIndex: 'elapsed', width: 100, render: (v: number) => v ? formatSeconds(v) : '-' },
{ title: intl.get('日志'), dataIndex: 'id', width: 60, render: (id, record) => <a onClick={() => { localStorage.setItem('logCron', String(id)); setLogCron({ id, name: record.name }); }}>{intl.get('查看')}</a> },
{ title: intl.get('日志'), dataIndex: 'id', width: 60, render: (id, record) => <a onClick={() => { setLogCron({ id, instanceId: record.instanceId, name: record.name }); }}>{intl.get('查看')}</a> },
]}
/>
{runtime?.idleTasks && runtime.idleTasks.length > 0 && (
@@ -362,7 +604,10 @@ const Dashboard = () => {
<Statistic title={intl.get('系统运行')} value={formatSeconds(system.uptime)} />
<Statistic title={intl.get('堆内存')} value={`${system.heapUsed} MB`} valueStyle={{ fontSize: 16 }} />
<div style={{ marginTop: 8, color: '#888', fontSize: 12 }}>
{intl.get('负载 1m')}: {system.loadAvg?.[0] || '-'} | CPU: {system.cpus} {intl.get('核心')} | {system.platform}
{intl.get('负载 1m')}: {system.loadAvg?.[0] ?? '-'} | CPU: {system.cpus} {intl.get('核心')} | {system.platform}
<br />{intl.get('可用内存上限')} {(system.memTotal / 1024 ** 3).toFixed(2)} GiB
{(system.hostCpus !== system.cpus || system.hostMemory !== system.memTotal) &&
<> · {intl.get('宿主机资源')} {system.hostCpus} CPU / {(system.hostMemory / 1024 ** 3).toFixed(2)} GiB</>}
</div>
</Col>
</Row>
@@ -373,7 +618,9 @@ const Dashboard = () => {
{result && <TaskResultModal key={result} result={result} onCancel={() => setResult(null)} />}
{logCron && (
<CronLogModal
key={logCron.instanceId}
cron={logCron}
logUrl={`${config.apiPrefix}crons/${logCron.id}/log?instanceId=${logCron.instanceId}`}
handleCancel={() => setLogCron(null)}
/>
)}
+1 -2
View File
@@ -107,7 +107,6 @@ export default function TaskResultModal({
size="small"
disabled={task.deleted}
onClick={() => {
localStorage.setItem('logCron', String(task.id));
setLogCron(task);
}}
>
@@ -120,7 +119,7 @@ export default function TaskResultModal({
)}
</Modal>
{logCron && (
<CronLogModal cron={logCron} handleCancel={() => setLogCron(null)} />
<CronLogModal key={logCron.id} cron={logCron} handleCancel={() => setLogCron(null)} />
)}
</>
);
+22
View File
@@ -0,0 +1,22 @@
import { Statistic } from 'antd';
import intl from 'react-intl-universal';
export function formatTiming(ms: number | null) {
if (ms == null) return '—';
if (ms < 1000) return `${ms} ms`;
if (ms < 60000) return intl.get('{value} 秒', { value: ms / 1000 });
const seconds = Math.round(ms / 1000);
return intl.get('{minutes} 分 {seconds} 秒', {
minutes: Math.floor(seconds / 60),
seconds: seconds % 60,
});
}
export default function TimingStatistic({ title, ms }: {
title: string;
ms: number | null;
}) {
return <Statistic title={title} value={ms ?? '—'} formatter={() => (
<span title={ms == null ? undefined : `${ms} ms`}>{formatTiming(ms)}</span>
)} />;
}
+28 -146
View File
@@ -1,6 +1,6 @@
import useFilterTreeData from '@/hooks/useFilterTreeData';
import { FileBrowser, FilePicker } from '@/components/fileBrowser';
import { readableLogName } from '@/components/fileBrowser/name';
import { SharedContext } from '@/layouts';
import { depthFirstSearch } from '@/utils';
import config from '@/utils/config';
import { request } from '@/utils/http';
import { CloudDownloadOutlined, DeleteOutlined } from '@ant-design/icons';
@@ -10,20 +10,14 @@ import CodeMirror from '@uiw/react-codemirror';
import { useOutletContext } from '@umijs/max';
import {
Button,
Empty,
Input,
message,
Modal,
Tooltip,
Tree,
TreeSelect,
Typography,
} from 'antd';
import { saveAs } from 'file-saver';
import debounce from 'lodash/debounce';
import uniq from 'lodash/uniq';
import prettyBytes from 'pretty-bytes';
import { Key, useCallback, useEffect, useRef, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import intl from 'react-intl-universal';
import SplitPane from 'react-split-pane';
import styles from './index.module.less';
@@ -34,38 +28,27 @@ const Log = () => {
const { headerStyle, isPhone, theme } = useOutletContext<SharedContext>();
const [value, setValue] = useState(intl.get('请选择日志文件'));
const [select, setSelect] = useState<string>(intl.get('请选择日志文件'));
const [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [height, setHeight] = useState<number>();
const treeDom = useRef<any>();
const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
const [revision, setRevision] = useState(0);
const selectedKey = useRef('');
const detailRequest = useRef<AbortController>();
const [readFailed, setReadFailed] = useState(false);
useEffect(() => () => detailRequest.current?.abort(), []);
const [currentNode, setCurrentNode] = useState<any>();
const [searchValue, setSearchValue] = useState('');
const getLogs = () => {
setLoading(true);
request
.get(`${config.apiPrefix}logs`)
.then(({ code, data }) => {
if (code === 200) {
setData(data);
}
})
.finally(() => setLoading(false));
};
const getLog = (node: any) => {
detailRequest.current?.abort();
const controller = new AbortController();
detailRequest.current = controller;
setReadFailed(false);
request
.get(
`${config.apiPrefix}logs/detail?file=${node.title}&path=${
node.parent || ''
}&tail=true&limit=${1024 * 1024}`,
`${config.apiPrefix}logs/detail`, { signal: controller.signal, retryInPlace: true, params: { file: node.title, path: node.parent || '', tail: true, limit: 1024 * 1024 } },
)
.then(({ code, data }) => {
if (code === 200) {
setValue(data);
}
});
if (controller.signal.aborted || selectedKey.current !== node.key) return;
if (code === 200) setValue(data);
else setReadFailed(true);
}).catch(() => { if (!controller.signal.aborted) setReadFailed(true); });
};
const downloadLog = () => {
@@ -88,6 +71,9 @@ const Log = () => {
return;
}
detailRequest.current?.abort();
setReadFailed(false);
selectedKey.current = node.key;
setCurrentNode(node);
setSelect(value);
@@ -100,35 +86,6 @@ const Log = () => {
getLog(node);
};
const onTreeSelect = useCallback((keys: Key[], e: any) => {
onSelect(keys[0], e.node);
}, []);
const onSearch = useCallback(
(e) => {
const keyword = e.target.value;
debounceSearch(keyword);
},
[data],
);
const debounceSearch = useCallback(
debounce((keyword) => {
setSearchValue(keyword);
}, 300),
[data],
);
const { treeData: filterData, keys: searchExpandedKeys } = useFilterTreeData(
data,
searchValue,
{ treeNodeFilterProp: 'title' },
);
useEffect(() => {
setExpandedKeys(uniq([...expandedKeys, ...searchExpandedKeys]));
}, [searchExpandedKeys]);
const deleteFile = () => {
Modal.confirm({
title: intl.get('确认删除'),
@@ -156,21 +113,7 @@ const Log = () => {
.then(({ code }) => {
if (code === 200) {
message.success(intl.get('删除成功'));
let newData = [...data];
if (currentNode.parent) {
newData = depthFirstSearch(
newData,
(c) => c.key === currentNode.key,
);
} else {
const index = newData.findIndex(
(x) => x.key === currentNode.key,
);
if (index !== -1) {
newData.splice(index, 1);
}
}
setData(newData);
setRevision(n => n + 1);
initState();
}
});
@@ -179,31 +122,20 @@ const Log = () => {
};
const initState = () => {
detailRequest.current?.abort();
selectedKey.current = '';
setSelect('');
setCurrentNode(null);
setValue(intl.get('请选择脚本文件'));
setValue(intl.get('请选择日志文件'));
};
const onExpand = (expKeys: any) => {
setExpandedKeys(expKeys);
};
useEffect(() => {
getLogs();
}, []);
useEffect(() => {
if (treeDom.current) {
setHeight(treeDom.current.clientHeight);
}
}, [treeDom.current, data]);
return (
<PageContainer
className="ql-container-wrapper log-wrapper"
title={
<>
{select}
{currentNode?.type === 'file' ? <span title={select}>{readableLogName(currentNode.title)}</span> : select}
{currentNode?.type === 'file' && readFailed && <Button type="link" onClick={() => getLog(currentNode)}>{intl.get('重试')}</Button>}
{currentNode?.type === 'file' && (
<span
style={{
@@ -219,23 +151,10 @@ const Log = () => {
)}
</>
}
loading={loading}
extra={
isPhone
? [
<TreeSelect
treeExpandAction="click"
className="log-select"
value={select}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
treeData={data}
placeholder={intl.get('请选择日志')}
fieldNames={{ value: 'key' }}
treeNodeFilterProp="title"
showSearch
allowClear
onSelect={onSelect}
/>,
<FilePicker source="logs" value={select} revision={revision} onSelect={node => onSelect(node.key, node)} />,
]
: [
<Tooltip title={intl.get('下载')}>
@@ -265,44 +184,7 @@ const Log = () => {
/*// @ts-ignore*/
<SplitPane split="vertical" size={200} maxSize={-100}>
<div className={styles['left-tree-container']}>
{data.length > 0 ? (
<>
<Input.Search
className={styles['left-tree-search']}
onChange={onSearch}
placeholder={intl.get('请输入日志名')}
allowClear
></Input.Search>
<div className={styles['left-tree-scroller']} ref={treeDom}>
<Tree
expandAction="click"
className={styles['left-tree']}
treeData={filterData}
showIcon={true}
height={height}
selectedKeys={[select]}
showLine={{ showLeafIcon: true }}
onSelect={onTreeSelect}
expandedKeys={expandedKeys}
onExpand={onExpand}
></Tree>
</div>
</>
) : (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100%',
}}
>
<Empty
description={intl.get('暂无日志')}
image={Empty.PRESENTED_IMAGE_SIMPLE}
/>
</div>
)}
<FileBrowser source="logs" value={select} revision={revision} onSelect={node => onSelect(node.key, node)} />
</div>
<Editor
language="shell"
+29 -23
View File
@@ -1,3 +1,4 @@
import { FilePicker } from '@/components/fileBrowser';
import intl from 'react-intl-universal';
import React, {
useEffect,
@@ -14,7 +15,6 @@ import {
Select,
Space,
Switch,
TreeSelect,
} from 'antd';
import { request } from '@/utils/http';
import config from '@/utils/config';
@@ -30,14 +30,12 @@ import Ansi from 'ansi-to-react';
const { Option } = Select;
const EditModal = ({
treeData,
currentNode,
content,
wordWrap,
onWordWrapChange,
handleCancel,
}: {
treeData?: any;
content?: string;
currentNode: any;
wordWrap: boolean;
@@ -54,6 +52,9 @@ const EditModal = ({
const [log, setLog] = useState('');
const { theme } = useTheme();
const editorRef = useRef<any>(null);
const pendingFile = useRef<AbortController>();
const pickedFile = useRef(false);
const [fileReady, setFileReady] = useState(false);
const [isRunning, setIsRunning] = useState(false);
const [currentPid, setCurrentPid] = useState(null);
const cancel = () => {
@@ -61,7 +62,7 @@ const EditModal = ({
};
const onSelect = (value: any, node: any) => {
if (node.key === selectedKey || !value) {
if ((node.key === selectedKey && (fileReady || pendingFile.current)) || !value) {
return;
}
@@ -70,6 +71,7 @@ const EditModal = ({
}
const newMode = getEditorMode(value);
pickedFile.current = true;
setCNode(node);
setLanguage(newMode);
getDetail(node);
@@ -77,17 +79,23 @@ const EditModal = ({
};
const getDetail = (node: any) => {
pendingFile.current?.abort();
const controller = new AbortController();
pendingFile.current = controller;
setFileReady(false);
setValue('');
request
.get(
`${config.apiPrefix}scripts/detail?file=${node.title}&path=${
node.parent || ''
}`,
`${config.apiPrefix}scripts/detail`, { params: { file: node.title, path: node.parent || '' }, signal: controller.signal },
)
.then(({ code, data }) => {
if (code === 200) {
if (code === 200 && !controller.signal.aborted) {
setValue(data);
setFileReady(true);
}
});
})
.catch(() => { /* The HTTP handler reports errors. Selecting the file again retries it. */ })
.finally(() => { if (pendingFile.current === controller) pendingFile.current = undefined; });
};
const run = () => {
@@ -140,15 +148,22 @@ const EditModal = ({
ws.subscribe('manuallyRunScript', handleMessage);
return () => {
pendingFile.current?.abort();
ws.unsubscribe('manuallyRunScript', handleMessage);
};
}, []);
useEffect(() => {
setLog('');
if (currentNode) {
if (currentNode?.type === 'file' && !pickedFile.current) {
pendingFile.current?.abort();
setCNode(currentNode);
setValue(content as string);
if (typeof content === 'string' && content !== intl.get('加载中...')) {
setFileReady(true);
setValue(content);
} else {
getDetail(currentNode);
}
setSelectedKey(currentNode.key);
const newMode = getEditorMode(currentNode.title);
setLanguage(newMode);
@@ -161,18 +176,7 @@ const EditModal = ({
closable={false}
title={
<>
<TreeSelect
treeExpandAction="click"
style={{ marginRight: 8, width: 300 }}
value={selectedKey}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
treeData={treeData}
placeholder={intl.get('请选择脚本文件')}
fieldNames={{ value: 'key', label: 'title' }}
showSearch
onSelect={onSelect}
treeLine={{ showLeafIcon: true }}
/>
<FilePicker source="scripts" value={selectedKey} onSelect={node => onSelect(node.key, node)} />
<Select
value={language}
style={{ width: 110, marginRight: 8 }}
@@ -189,6 +193,7 @@ const EditModal = ({
type="primary"
style={{ marginRight: 8 }}
onClick={isRunning ? stop : run}
disabled={!isRunning && !fileReady}
>
{isRunning ? intl.get('停止') : intl.get('运行')}
</Button>
@@ -216,6 +221,7 @@ const EditModal = ({
onClick={() => {
setSaveModalVisible(true);
}}
disabled={!fileReady}
>
{intl.get('保存')}
</Button>
+2 -31
View File
@@ -1,3 +1,4 @@
import { FilePicker } from '@/components/fileBrowser';
import intl from 'react-intl-universal';
import React, { useEffect, useState } from 'react';
import {
@@ -8,7 +9,6 @@ import {
Select,
Upload,
Radio,
TreeSelect,
} from 'antd';
import { request } from '@/utils/http';
import config from '@/utils/config';
@@ -18,9 +18,7 @@ const { Option } = Select;
const EditScriptNameModal = ({
handleCancel,
treeData,
}: {
treeData: any[];
handleCancel: (file?: {
filename: string;
path: string;
@@ -30,7 +28,6 @@ const EditScriptNameModal = ({
}) => {
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
const [dirs, setDirs] = useState<any[]>([]);
const [file, setFile] = useState<File>();
const [type, setType] = useState<'blank' | 'upload' | 'directory'>('blank');
@@ -73,26 +70,6 @@ const EditScriptNameModal = ({
setType(e.target.value);
};
const getDirs = (data) => {
for (const item of data) {
if (item.children && item.children.length > 0) {
item.children = item.children
.filter((x) => x.type === 'directory')
.map((x) => ({ ...x, disabled: false }));
getDirs(item.children);
}
}
return data;
};
useEffect(() => {
const originDirs = treeData
.filter((x) => x.type === 'directory')
.map((x) => ({ ...x, disabled: false }));
const dirs = getDirs(originDirs);
setDirs(dirs);
}, [treeData]);
return (
<Modal
title={intl.get('创建')}
@@ -153,13 +130,7 @@ const EditScriptNameModal = ({
</Form.Item>
)}
<Form.Item label={intl.get('父目录')} name="path">
<TreeSelect
allowClear
treeData={dirs}
fieldNames={{ value: 'key', label: 'title' }}
placeholder={intl.get('请选择父目录')}
treeDefaultExpandAll
/>
<FilePicker source="scripts" folders />
</Form.Item>
{type === 'upload' && (
<Form.Item label={intl.get('文件')} name="file">
+55 -201
View File
@@ -1,7 +1,7 @@
import IconFont from '@/components/iconfont';
import useFilterTreeData from '@/hooks/useFilterTreeData';
import { FileBrowser, FilePicker } from '@/components/fileBrowser';
import { SharedContext } from '@/layouts';
import { depthFirstSearch, findNode, getEditorMode } from '@/utils';
import { getEditorMode } from '@/utils';
import config from '@/utils/config';
import { request } from '@/utils/http';
import { getCodeMirrorExtensions } from '@/utils/codemirror/language';
@@ -22,21 +22,15 @@ import { history, useOutletContext } from '@umijs/max';
import {
Button,
Dropdown,
Empty,
Input,
MenuProps,
message,
Modal,
Space,
Switch,
Tooltip,
Tree,
TreeSelect,
Typography,
} from 'antd';
import { saveAs } from 'file-saver';
import debounce from 'lodash/debounce';
import uniq from 'lodash/uniq';
import prettyBytes from 'pretty-bytes';
import { parse } from 'query-string';
import { Key, useCallback, useEffect, useRef, useState } from 'react';
@@ -56,20 +50,16 @@ const Script = () => {
const { headerStyle, isPhone, theme } = useOutletContext<SharedContext>();
const [value, setValue] = useState(intl.get('请选择脚本文件'));
const [select, setSelect] = useState<string>(intl.get('请选择脚本文件'));
const [data, setData] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [revision, setRevision] = useState(0);
const [mode, setMode] = useState('');
const [height, setHeight] = useState<number>();
const treeDom = useRef<any>();
const [directory, setDirectory] = useState('');
const [isLogModalVisible, setIsLogModalVisible] = useState(false);
const [searchValue, setSearchValue] = useState('');
const [isEditing, setIsEditing] = useState(false);
const editorRef = useRef<any>(null);
const [isAddFileModalVisible, setIsAddFileModalVisible] = useState(false);
const [isRenameFileModalVisible, setIsRenameFileModalVisible] =
useState(false);
const [currentNode, setCurrentNode] = useState<any>();
const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
const [showMonaco, setShowMonaco] = useState(true);
const [historyVisible, setHistoryVisible] = useState(false);
const [saving, setSaving] = useState(false);
@@ -81,6 +71,9 @@ const Script = () => {
const savingRef = useRef(false);
const savedContentRef = useRef('');
const currentKeyRef = useRef(currentNode?.key);
const detailRequest = useRef<AbortController>();
const [readState, setReadState] = useState<'loading' | 'ready' | 'failed'>('loading');
useEffect(() => () => detailRequest.current?.abort(), []);
currentKeyRef.current = currentNode?.key;
useEffect(() => {
@@ -91,7 +84,7 @@ const Script = () => {
const content =
!isPhone && editorRef.current ? editorRef.current.getValue() : value;
return (
isEditing &&
isEditing && readState === 'ready' &&
content.replace(/\r\n/g, '\n') !==
savedContentRef.current.replace(/\r\n/g, '\n')
);
@@ -101,36 +94,28 @@ const Script = () => {
setIsEditing(value && canPreviewInMonaco(filename));
};
const getScripts = (needLoading: boolean = true) => {
needLoading && setLoading(true);
request
.get(`${config.apiPrefix}scripts`)
.then(({ code, data }) => {
if (code === 200) {
setData(data);
initState();
initGetScript(data);
}
})
.finally(() => needLoading && setLoading(false));
};
const getDetail = (node: any, options: any = {}) => {
detailRequest.current?.abort();
const controller = new AbortController();
detailRequest.current = controller;
setReadState('loading');
request
.get(
`${config.apiPrefix}scripts/detail?file=${encodeURIComponent(
node.title,
)}&path=${encodeURIComponent(node.parent || '')}`,
)}&path=${encodeURIComponent(node.parent || '')}`, { signal: controller.signal, retryInPlace: true },
)
.then(({ code, data }) => {
if (code === 200 && currentKeyRef.current === node.key) {
if (controller.signal.aborted || currentKeyRef.current !== node.key) return;
if (code === 200) {
setReadState('ready');
savedContentRef.current = data;
setValue(data);
if (options.callback) {
options.callback();
}
}
});
} else setReadState('failed');
}).catch(() => { if (!controller.signal.aborted) setReadState('failed'); });
};
const downloadScript = () => {
@@ -148,31 +133,14 @@ const Script = () => {
});
};
const initGetScript = (_data: any) => {
const { p, s } = parse(history.location.search);
if (s) {
const vkey = `${p}/${s}`;
const obj = {
node: {
title: s,
key: p ? vkey : s,
parent: p,
},
};
const item = findNode(_data, (c) => c.key === obj.node.key);
if (item) {
obj.node = item;
setExpandedKeys([p as string]);
onTreeSelect([vkey], obj);
}
}
};
const onSelect = (value: any, node: any) => {
if (node.key === select || !value) {
return;
}
detailRequest.current?.abort();
setReadState('loading');
currentKeyRef.current = node.key;
setSelect(node.key);
setCurrentNode(node);
@@ -192,13 +160,7 @@ const Script = () => {
setMode(isPhone && newMode === 'typescript' ? 'javascript' : newMode);
setValue(intl.get('加载中...'));
getDetail(node, {
callback: () => {
if (isEditing) {
setIsEditing(true);
}
},
});
getDetail(node);
};
const onTreeSelect = useCallback(
@@ -213,7 +175,7 @@ const Script = () => {
: value;
const originalContent = savedContentRef.current.replace(/\r\n/g, '\n');
if (currentContent !== originalContent && isEditing) {
if (currentContent !== originalContent && isEditing && readState === 'ready') {
Modal.confirm({
title: intl.get('确认离开'),
content: <>{intl.get('当前文件未保存,确认离开吗')}</>,
@@ -227,50 +189,17 @@ const Script = () => {
onSelect(keys[0], e.node);
}
},
[value, select, isEditing],
[value, select, isEditing, readState],
);
const onSearch = useCallback(
(e) => {
const keyword = e.target.value;
debounceSearch(keyword);
},
[data],
);
const debounceSearch = useCallback(
debounce((keyword) => {
setSearchValue(keyword);
}, 300),
[data],
);
const { treeData: filterData, keys: searchExpandedKeys } = useFilterTreeData(
data,
searchValue,
{ treeNodeFilterProp: 'title' },
);
useEffect(() => {
setExpandedKeys(uniq([...expandedKeys, ...searchExpandedKeys]));
}, [searchExpandedKeys]);
const onExpand = (expKeys: any) => {
setExpandedKeys(expKeys);
};
const onDoubleClick = (e: any, node: any) => {
if (node.type === 'file') {
setSelect(node.key);
setCurrentNode(node);
if (node.type === 'file' && node.key === currentKeyRef.current) {
handleIsEditing(node.title, true);
}
};
const editFile = () => {
setTimeout(() => {
handleIsEditing(currentNode.title, true);
}, 300);
handleIsEditing(currentNode.title, true);
};
const cancelEdit = () => {
@@ -280,8 +209,9 @@ const Script = () => {
};
const saveFile = async () => {
if (savingRef.current || !currentNode) return;
if (savingRef.current || !currentNode || readState !== 'ready') return;
const node = currentNode;
const selection = detailRequest.current;
const content =
!isPhone && editorRef.current
? editorRef.current.getValue().replace(/\r\n/g, '\n')
@@ -298,7 +228,7 @@ const Script = () => {
content,
},
);
if (result?.code === 200 && currentKeyRef.current === node.key) {
if (result?.code === 200 && currentKeyRef.current === node.key && selection === detailRequest.current && !selection?.signal.aborted) {
savedContentRef.current = content;
setValue(content);
handleIsEditing(node.title, false);
@@ -338,21 +268,7 @@ const Script = () => {
.then(({ code }) => {
if (code === 200) {
message.success(intl.get('删除成功'));
let newData = [...data];
if (currentNode.parent) {
newData = depthFirstSearch(
newData,
(c) => c.key === currentNode.key,
);
} else {
const index = newData.findIndex(
(x) => x.key === currentNode.key,
);
if (index !== -1) {
newData.splice(index, 1);
}
}
setData(newData);
setRevision(n => n + 1);
initState();
}
});
@@ -366,7 +282,8 @@ const Script = () => {
const handleRenameFileCancel = () => {
setIsRenameFileModalVisible(false);
getScripts(false);
setRevision(n => n + 1);
initState();
};
const addFile = () => {
@@ -386,46 +303,32 @@ const Script = () => {
},
) => {
if (filename) {
const res = await request.get(`${config.apiPrefix}scripts`);
let newData = res.data;
if (type === 'directory' && filename.includes('/')) {
const parts = filename.split('/');
parts.pop();
const parentPath = parts.join('/');
path = path ? `${path}/${parentPath}` : parentPath;
}
const item = findNode(newData, (c) => c.key === key);
if (path) {
const keys = path.split('/');
const sKeys: string[] = [];
keys.reduce((p, c) => {
sKeys.push(p);
return `${p}/${c}`;
});
setExpandedKeys([...expandedKeys, ...sKeys, path]);
}
setData(newData);
onSelect(item.title, item);
const parts = key.split('/');
const item = { key, title: parts.pop()!, parent: parts.join('/'), type };
setDirectory(item.parent);
setRevision(n => n + 1);
onSelect(key, item);
handleIsEditing(item.title, true);
}
setIsAddFileModalVisible(false);
};
const initState = () => {
detailRequest.current?.abort();
setSelect(intl.get('请选择脚本文件'));
setCurrentNode(null);
setValue(intl.get('请选择脚本文件'));
};
useEffect(() => {
getScripts();
}, []);
useEffect(() => {
if (treeDom.current) {
setHeight(treeDom.current.clientHeight - 6);
const { p, s } = parse(history.location.search);
if (typeof s === 'string' && s) {
const parent = typeof p === 'string' ? p : '';
const key = parent ? parent + '/' + s : s;
setDirectory(parent);
onSelect(key, { key, parent, title: s, type: 'file' });
}
}, [treeDom.current, data]);
}, []);
useHotkeys(
'mod+s',
@@ -563,7 +466,8 @@ const Script = () => {
title={
<>
{select}
{currentNode?.type === 'file' && (
{currentNode && readState === 'failed' && <Button type="link" onClick={() => getDetail(currentNode)}>{intl.get('重试')}</Button>}
{currentNode?.size != null && (
<span
style={{
marginLeft: 6,
@@ -578,7 +482,6 @@ const Script = () => {
)}
</>
}
loading={loading}
extra={[
<Space key="word-wrap" size={8}>
<span>{intl.get('自动换行')}</span>
@@ -602,26 +505,14 @@ const Script = () => {
: []),
...(isPhone
? [
<TreeSelect
treeExpandAction="click"
className="log-select"
value={select}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
treeData={data}
placeholder={intl.get('请选择脚本')}
fieldNames={{ value: 'key' }}
treeNodeFilterProp="title"
showSearch
allowClear
onSelect={(key, node) => onTreeSelect([key], { node })}
/>,
<FilePicker source="scripts" value={select} revision={revision} initialDirectory={directory} onSelect={node => onTreeSelect([node.key], { node })} />,
<Dropdown menu={menu} trigger={['click']}>
<Button type="primary" icon={<EllipsisOutlined />} />
</Dropdown>,
]
: isEditing
? [
<Button type="primary" onClick={saveFile} loading={saving}>
<Button type="primary" onClick={saveFile} loading={saving} disabled={readState !== 'ready'}>
{intl.get('保存')}
</Button>,
<Button type="primary" onClick={cancelEdit}>
@@ -693,6 +584,9 @@ const Script = () => {
hasUnsavedChanges={hasUnsavedChanges}
onClose={() => setHistoryVisible(false)}
onRestored={(content) => {
detailRequest.current?.abort();
detailRequest.current = undefined;
setReadState('ready');
savedContentRef.current = content;
setValue(content);
setIsEditing(false);
@@ -704,45 +598,7 @@ const Script = () => {
/*// @ts-ignore*/
<SplitPane split="vertical" size={200} maxSize={-100}>
<div className={styles['left-tree-container']}>
{data.length > 0 ? (
<>
<Input.Search
className={styles['left-tree-search']}
onChange={onSearch}
placeholder={intl.get('请输入脚本名')}
allowClear
></Input.Search>
<div className={styles['left-tree-scroller']} ref={treeDom}>
<Tree
expandAction="click"
className={styles['left-tree']}
treeData={filterData}
showIcon={true}
height={height}
selectedKeys={[select]}
expandedKeys={expandedKeys}
onExpand={onExpand}
showLine={{ showLeafIcon: true }}
onSelect={onTreeSelect}
onDoubleClick={onDoubleClick}
></Tree>
</div>
</>
) : (
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100%',
}}
>
<Empty
description={intl.get('暂无脚本')}
image={Empty.PRESENTED_IMAGE_SIMPLE}
/>
</div>
)}
<FileBrowser source="scripts" value={select} revision={revision} initialDirectory={directory} onSelect={node => onTreeSelect([node.key], { node })} onDoubleClick={node => onDoubleClick(null, node)} />
</div>
{showMonaco ? (
<Editor
@@ -750,7 +606,7 @@ const Script = () => {
value={value}
theme={theme}
options={{
readOnly: !isEditing || saving,
readOnly: !isEditing || saving || readState !== 'ready',
fontSize: 12,
lineNumbersMinChars: 3,
glyphMargin: false,
@@ -774,7 +630,7 @@ const Script = () => {
...(wordWrap ? [EditorView.lineWrapping] : []),
]}
theme={theme.includes('dark') ? 'dark' : 'light'}
readOnly={!isEditing || saving}
readOnly={!isEditing || saving || readState !== 'ready'}
onChange={(value) => {
setValue(value);
}}
@@ -782,7 +638,6 @@ const Script = () => {
)}
{isLogModalVisible && isLogModalVisible && (
<EditModal
treeData={data}
currentNode={currentNode}
content={value}
wordWrap={wordWrap}
@@ -794,7 +649,6 @@ const Script = () => {
)}
{isAddFileModalVisible && (
<EditScriptNameModal
treeData={data}
handleCancel={addFileModalClose}
/>
)}
+12 -4
View File
@@ -65,6 +65,7 @@ const Other = ({
runningInstanceRetentionDays?: number | null;
cronStatRetentionDays?: number | null;
}>();
const [limits, setLimits] = useState<{ concurrency: number; cpus: number }>();
const [form] = Form.useForm();
const [exportLoading, setExportLoading] = useState(false);
const showUploadProgress = useProgress(intl.get('上传'));
@@ -117,6 +118,7 @@ const Other = ({
.then(({ code, data }) => {
if (code === 200 && data.info) {
setSystemConfig(data.info);
setLimits({ concurrency: data.effectiveCronConcurrency, cpus: data.availableCpus });
}
})
.catch((error: any) => {
@@ -133,6 +135,7 @@ const Other = ({
.then(({ code, data }) => {
if (code === 200) {
message.success(intl.get('更新成功'));
if (path === 'cron-concurrency') getSystemConfig();
if (path === 'panel-title') {
reloadSystemConfig();
}
@@ -195,6 +198,9 @@ const Other = ({
<p>
{intl.get('将删除历史运行实例')}: {data.runningInstances}
</p>
<p>
{intl.get('将删除触发记录')}: {data.triggers}
</p>
<p>
{intl.get('将删除任务统计')}: {data.cronStats}
</p>
@@ -459,13 +465,15 @@ const Other = ({
{intl.get('预览清理')}
</Button>
</Form.Item>
<Form.Item label={intl.get('定时任务并发数')} name="frequency">
<Form.Item label={intl.get('定时任务并发数')} extra={limits && intl.get('定时和手动任务各有一条队列,每条最多同时运行 {slots} 个实例。当前可用 CPU 核数为 {cpus}。', { slots: limits.concurrency, cpus: limits.cpus })}>
<Input.Group compact>
<InputNumber
style={{ width: 180 }}
min={4}
value={systemConfig?.cronConcurrency}
placeholder={intl.get('默认为 CPU 个数')}
min={1}
precision={0}
max={2147483647}
value={systemConfig?.cronConcurrency || null}
placeholder={intl.get('自动设置')}
onChange={(value) => {
setSystemConfig({ ...systemConfig, cronConcurrency: value });
}}
+4
View File
@@ -26,6 +26,7 @@ export type Override<
: Omit<T, keyof K> & K;
export interface ICustomConfig {
retryInPlace?: boolean;
onError?: (res: AxiosResponse<unknown, any>) => void;
}
@@ -40,6 +41,9 @@ const errorHandler = function (
{ config: InternalAxiosRequestConfig & ICustomConfig }
>,
) {
if (error.config?.retryInPlace && error.response?.status !== 401) {
return Promise.reject(error);
}
if (error.response) {
const msg = error.response.data
? error.response.data.message || error.message
-29
View File
@@ -1,7 +1,5 @@
import intl from 'react-intl-universal';
import { LANG_MAP, LOG_END_SYMBOL } from './const';
import CronExpressionParser from 'cron-parser';
import { ICrontab } from '@/pages/crontab/type';
export default function browserType() {
// 权重:系统 + 系统版本 > 平台 > 内核 + 载体 + 内核版本 + 载体版本 > 外壳 + 外壳版本
@@ -335,33 +333,6 @@ export function getCommandScript(
return [s, p];
}
export function parseCrontab(schedule: string): Date | null {
try {
const time = CronExpressionParser.parse(schedule);
if (time) {
return time.next().toDate();
}
} catch (error) {}
return null;
}
export function getCrontabsNextDate(
schedule: string,
extra_schedules: ICrontab['extra_schedules'],
): Date | null {
let date = parseCrontab(schedule);
if (extra_schedules?.length) {
extra_schedules.forEach((x) => {
const _date = parseCrontab(x.schedule);
if (_date && (!date || _date < date)) {
date = _date;
}
});
}
return date;
}
export function getExtension(filename: string) {
if (!filename) return '';
const arr = filename.split('.');