558 lines
17 KiB
React
558 lines
17 KiB
React
/*
|
|
Copyright (C) 2025 QuantumNous
|
|
|
|
This program is free software: you can redistribute it and/or modify
|
|
it under the terms of the GNU Affero General Public License as
|
|
published by the Free Software Foundation, either version 3 of the
|
|
License, or (at your option) any later version.
|
|
|
|
This program is distributed in the hope that it will be useful,
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
GNU Affero General Public License for more details.
|
|
|
|
You should have received a copy of the GNU Affero General Public License
|
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
For commercial licensing, please contact support@quantumnous.com
|
|
*/
|
|
|
|
import React, { useCallback, useEffect, useState } from 'react';
|
|
import {
|
|
Banner,
|
|
Button,
|
|
Input,
|
|
InputNumber,
|
|
Modal,
|
|
Popconfirm,
|
|
Select,
|
|
Switch,
|
|
Table,
|
|
Tag,
|
|
Toast,
|
|
} from '@/components/ui';
|
|
import { BellRing, Plus } from 'lucide-react';
|
|
import { useIsMobile } from '../../hooks/common/useIsMobile';
|
|
import {
|
|
ALERT_DIM_TYPES,
|
|
ALERT_METRICS,
|
|
fmtInt,
|
|
fmtTs,
|
|
qualityErrorText,
|
|
} from './qualityConstants';
|
|
|
|
const EMPTY_RULE = {
|
|
name: '',
|
|
enabled: true,
|
|
dim_type: 1,
|
|
dim_key: '',
|
|
metric: 'success_rate',
|
|
comparator: 'lt',
|
|
threshold: 95,
|
|
window_minutes: 15,
|
|
min_samples: 20,
|
|
silence_minutes: 60,
|
|
};
|
|
|
|
const metricUnit = (metric) =>
|
|
ALERT_METRICS.find((m) => m.value === metric)?.unit || '';
|
|
|
|
const QualityAlerts = ({ quality, t }) => {
|
|
const { get, send, options } = quality;
|
|
const [rules, setRules] = useState([]);
|
|
const [events, setEvents] = useState([]);
|
|
const [loading, setLoading] = useState(false);
|
|
const [error, setError] = useState('');
|
|
const [editing, setEditing] = useState(null);
|
|
const [saving, setSaving] = useState(false);
|
|
const [testResult, setTestResult] = useState(null);
|
|
const [testing, setTesting] = useState(false);
|
|
const isMobile = useIsMobile();
|
|
|
|
const load = useCallback(() => {
|
|
setLoading(true);
|
|
setError('');
|
|
Promise.all([get('/alerts/rules'), get('/alerts/events')])
|
|
.then(([r, e]) => {
|
|
setRules(r || []);
|
|
setEvents(e || []);
|
|
})
|
|
.catch((e) => setError(e.code || 'query_failed'))
|
|
.finally(() => setLoading(false));
|
|
}, [get]);
|
|
|
|
useEffect(() => {
|
|
load();
|
|
}, [load]);
|
|
|
|
const patch = (p) => setEditing((prev) => ({ ...prev, ...p }));
|
|
|
|
const payloadOf = (rule) => ({
|
|
...rule,
|
|
dim_type: Number(rule.dim_type),
|
|
threshold: Number(rule.threshold || 0),
|
|
window_minutes: Number(rule.window_minutes || 0),
|
|
min_samples: Number(rule.min_samples || 0),
|
|
silence_minutes: Number(rule.silence_minutes || 0),
|
|
});
|
|
|
|
// 阈值清空时不能静默按 0 保存("成功率低于 0%" 永远不会触发)
|
|
const thresholdMissing = (rule) =>
|
|
rule.threshold === null ||
|
|
rule.threshold === undefined ||
|
|
rule.threshold === '';
|
|
|
|
const save = async () => {
|
|
if (thresholdMissing(editing)) {
|
|
Toast.error(t('请填写阈值'));
|
|
return;
|
|
}
|
|
setSaving(true);
|
|
try {
|
|
if (editing.id) {
|
|
await send('put', `/alerts/rules/${editing.id}`, payloadOf(editing));
|
|
} else {
|
|
await send('post', '/alerts/rules', payloadOf(editing));
|
|
}
|
|
Toast.success(t('已保存'));
|
|
setEditing(null);
|
|
setTestResult(null);
|
|
load();
|
|
} catch (e) {
|
|
Toast.error(saveErrorText(e));
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
};
|
|
|
|
const saveErrorText = (e) =>
|
|
e.code === 'forbidden' || /权限|permission/i.test(e.message || '')
|
|
? t('仅超级管理员或已被授权「运营设置」的管理员可修改告警规则')
|
|
: qualityErrorText(t, e.code);
|
|
|
|
const test = async () => {
|
|
if (thresholdMissing(editing)) {
|
|
Toast.error(t('请填写阈值'));
|
|
return;
|
|
}
|
|
setTesting(true);
|
|
try {
|
|
const res = await send('post', '/alerts/rules/test', payloadOf(editing));
|
|
setTestResult(res);
|
|
} catch (e) {
|
|
setTestResult(null);
|
|
Toast.error(qualityErrorText(t, e.code));
|
|
} finally {
|
|
setTesting(false);
|
|
}
|
|
};
|
|
|
|
const toggle = async (rule, enabled) => {
|
|
try {
|
|
await send('put', `/alerts/rules/${rule.id}`, { ...rule, enabled });
|
|
load();
|
|
} catch (e) {
|
|
Toast.error(saveErrorText(e));
|
|
}
|
|
};
|
|
|
|
const remove = async (rule) => {
|
|
try {
|
|
await send('delete', `/alerts/rules/${rule.id}`);
|
|
Toast.success(t('已删除'));
|
|
load();
|
|
} catch (e) {
|
|
Toast.error(saveErrorText(e));
|
|
}
|
|
};
|
|
|
|
const describe = (rule) => {
|
|
const metric = ALERT_METRICS.find((m) => m.value === rule.metric);
|
|
const unit = metricUnit(rule.metric);
|
|
return `${t(metric?.label || rule.metric)} ${rule.comparator === 'lt' ? '<' : '>'} ${rule.threshold}${unit === '%' ? '%' : unit ? ' ' + unit : ''}`;
|
|
};
|
|
|
|
const scopeText = (rule) => {
|
|
const dim = ALERT_DIM_TYPES.find((d) => d.value === rule.dim_type);
|
|
if (rule.dim_type === 1) return t(dim?.label || '全平台');
|
|
if (rule.dim_type === 3) {
|
|
const ch = (options.channels || []).find(
|
|
(c) => String(c.id) === rule.dim_key,
|
|
);
|
|
return `${t(dim.label)}: ${ch ? ch.name : '#' + rule.dim_key}`;
|
|
}
|
|
return `${t(dim?.label || '')}: ${rule.dim_key}`;
|
|
};
|
|
|
|
const ruleColumns = [
|
|
{
|
|
title: t('启用'),
|
|
dataIndex: 'enabled',
|
|
width: 70,
|
|
render: (v, rule) => (
|
|
<Switch
|
|
size='small'
|
|
checked={v}
|
|
onChange={(checked) => toggle(rule, checked)}
|
|
/>
|
|
),
|
|
},
|
|
{ title: t('规则名称'), dataIndex: 'name', width: 180 },
|
|
{
|
|
title: t('监控范围'),
|
|
dataIndex: 'dim_type',
|
|
width: 180,
|
|
render: (_v, r) => scopeText(r),
|
|
},
|
|
{
|
|
title: t('触发条件'),
|
|
dataIndex: 'metric',
|
|
width: 200,
|
|
render: (_v, r) => describe(r),
|
|
},
|
|
{
|
|
title: t('窗口 / 最小样本 / 静默'),
|
|
dataIndex: 'window_minutes',
|
|
width: 260,
|
|
render: (_v, r) =>
|
|
t('{{w}} 分钟 / {{s}} 次 / {{q}} 分钟', {
|
|
w: r.window_minutes,
|
|
s: r.min_samples,
|
|
q: r.silence_minutes,
|
|
}),
|
|
},
|
|
{
|
|
title: '',
|
|
dataIndex: 'op',
|
|
width: 140,
|
|
render: (_v, rule) => (
|
|
<div className='flex gap-1'>
|
|
<Button
|
|
size='small'
|
|
theme='borderless'
|
|
onClick={() => {
|
|
setTestResult(null);
|
|
setEditing({ ...rule });
|
|
}}
|
|
>
|
|
{t('编辑')}
|
|
</Button>
|
|
<Popconfirm
|
|
title={t('确定删除该告警规则?')}
|
|
onConfirm={() => remove(rule)}
|
|
>
|
|
<Button size='small' theme='borderless' type='danger'>
|
|
{t('删除')}
|
|
</Button>
|
|
</Popconfirm>
|
|
</div>
|
|
),
|
|
},
|
|
];
|
|
|
|
const eventColumns = [
|
|
{
|
|
title: t('触发时间'),
|
|
dataIndex: 'created_at',
|
|
width: 140,
|
|
render: (v) => <span className='quality-num'>{fmtTs(v, true)}</span>,
|
|
},
|
|
{ title: t('规则'), dataIndex: 'rule_name', width: 180 },
|
|
{
|
|
title: t('观测值 / 阈值'),
|
|
dataIndex: 'observed_value',
|
|
width: 160,
|
|
render: (v, r) => (
|
|
<span className='quality-num'>
|
|
{Number(v).toFixed(2)} / {r.threshold}
|
|
</span>
|
|
),
|
|
},
|
|
{
|
|
title: t('样本数'),
|
|
dataIndex: 'samples',
|
|
width: 90,
|
|
render: (v) => <span className='quality-num'>{fmtInt(v)}</span>,
|
|
},
|
|
{
|
|
title: t('详情'),
|
|
dataIndex: 'message',
|
|
render: (v) => (
|
|
<span className='block truncate max-w-[420px]' title={v}>
|
|
{v}
|
|
</span>
|
|
),
|
|
},
|
|
];
|
|
|
|
const dimKeyInput = () => {
|
|
if (!editing || editing.dim_type === 1) return null;
|
|
if (editing.dim_type === 2) {
|
|
return (
|
|
<Select
|
|
filter
|
|
value={editing.dim_key || undefined}
|
|
placeholder={t('选择模型')}
|
|
optionList={(options.models || []).map((m) => ({
|
|
value: m,
|
|
label: m,
|
|
}))}
|
|
onChange={(v) => patch({ dim_key: v || '' })}
|
|
style={{ width: '100%' }}
|
|
/>
|
|
);
|
|
}
|
|
if (editing.dim_type === 3) {
|
|
return (
|
|
<Select
|
|
filter
|
|
value={editing.dim_key || undefined}
|
|
placeholder={t('选择渠道')}
|
|
optionList={(options.channels || []).map((c) => ({
|
|
value: String(c.id),
|
|
label: `${c.name} (#${c.id})`,
|
|
}))}
|
|
onChange={(v) => patch({ dim_key: v || '' })}
|
|
style={{ width: '100%' }}
|
|
/>
|
|
);
|
|
}
|
|
return (
|
|
<Input
|
|
value={editing.dim_key}
|
|
placeholder={t('企业 ID')}
|
|
onChange={(v) => patch({ dim_key: v.replace(/\D/g, '') })}
|
|
/>
|
|
);
|
|
};
|
|
|
|
return (
|
|
<div className='quality-card'>
|
|
<div className='quality-card-head'>
|
|
<span className='quality-card-title'>
|
|
<BellRing size={16} />
|
|
{t('阈值告警')}
|
|
<span className='quality-card-sub'>
|
|
{t('每 5 分钟评估一次,命中后通知超级管理员')}
|
|
</span>
|
|
</span>
|
|
<Button
|
|
icon={<Plus size={14} />}
|
|
theme='solid'
|
|
onClick={() => {
|
|
setTestResult(null);
|
|
setEditing({ ...EMPTY_RULE });
|
|
}}
|
|
>
|
|
{t('新建规则')}
|
|
</Button>
|
|
</div>
|
|
<div className='quality-card-body flex flex-col gap-4'>
|
|
{error ? (
|
|
<div className='quality-empty flex flex-col items-center gap-3'>
|
|
<span>{qualityErrorText(t, error)}</span>
|
|
<Button size='small' onClick={load}>
|
|
{t('重试')}
|
|
</Button>
|
|
</div>
|
|
) : (
|
|
<>
|
|
<Table
|
|
size='small'
|
|
rowKey='id'
|
|
loading={loading}
|
|
columns={ruleColumns}
|
|
dataSource={rules}
|
|
pagination={false}
|
|
scroll={{ x: 980 }}
|
|
empty={
|
|
<div className='quality-empty'>
|
|
{t(
|
|
'还没有告警规则,建议先为全平台成功率与兜底失败次数各建一条',
|
|
)}
|
|
</div>
|
|
}
|
|
/>
|
|
<div>
|
|
<div className='mb-2 text-sm font-semibold'>{t('最近告警')}</div>
|
|
<Table
|
|
size='small'
|
|
rowKey='id'
|
|
loading={loading}
|
|
columns={eventColumns}
|
|
dataSource={events}
|
|
pagination={{ pageSize: 10 }}
|
|
scroll={{ x: 900 }}
|
|
empty={<div className='quality-empty'>{t('暂无告警记录')}</div>}
|
|
/>
|
|
</div>
|
|
</>
|
|
)}
|
|
</div>
|
|
|
|
<Modal
|
|
visible={Boolean(editing)}
|
|
title={editing?.id ? t('编辑告警规则') : t('新建告警规则')}
|
|
onCancel={() => setEditing(null)}
|
|
width={isMobile ? '100%' : 560}
|
|
footer={
|
|
<div className='flex justify-between flex-wrap gap-2'>
|
|
<Button loading={testing} onClick={test}>
|
|
{t('按当前数据试算')}
|
|
</Button>
|
|
<div className='flex gap-2'>
|
|
<Button onClick={() => setEditing(null)}>{t('取消')}</Button>
|
|
<Button theme='solid' loading={saving} onClick={save}>
|
|
{t('保存')}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
}
|
|
>
|
|
{editing && (
|
|
<div className='flex flex-col gap-3'>
|
|
<label className='flex flex-col gap-1 text-sm'>
|
|
{t('规则名称')}
|
|
<Input
|
|
value={editing.name}
|
|
maxLength={64}
|
|
onChange={(v) => patch({ name: v })}
|
|
/>
|
|
</label>
|
|
<div className='grid grid-cols-1 sm:grid-cols-2 gap-3'>
|
|
<label className='flex flex-col gap-1 text-sm'>
|
|
{t('监控范围')}
|
|
<Select
|
|
value={editing.dim_type}
|
|
optionList={ALERT_DIM_TYPES.map((d) => ({
|
|
value: d.value,
|
|
label: t(d.label),
|
|
}))}
|
|
onChange={(v) => patch({ dim_type: v, dim_key: '' })}
|
|
/>
|
|
</label>
|
|
{editing.dim_type !== 1 && (
|
|
<label className='flex flex-col gap-1 text-sm'>
|
|
{t('监控对象')}
|
|
{dimKeyInput()}
|
|
</label>
|
|
)}
|
|
</div>
|
|
<div className='grid grid-cols-1 sm:grid-cols-3 gap-3'>
|
|
<label className='flex flex-col gap-1 text-sm sm:col-span-1'>
|
|
{t('指标')}
|
|
<Select
|
|
value={editing.metric}
|
|
optionList={ALERT_METRICS.map((m) => ({
|
|
value: m.value,
|
|
label: t(m.label),
|
|
}))}
|
|
onChange={(v) =>
|
|
patch({
|
|
metric: v,
|
|
comparator: v === 'success_rate' ? 'lt' : 'gt',
|
|
})
|
|
}
|
|
/>
|
|
</label>
|
|
<label className='flex flex-col gap-1 text-sm'>
|
|
{t('比较')}
|
|
<Select
|
|
value={editing.comparator}
|
|
optionList={[
|
|
{ value: 'lt', label: t('低于') },
|
|
{ value: 'gt', label: t('高于') },
|
|
]}
|
|
onChange={(v) => patch({ comparator: v })}
|
|
/>
|
|
</label>
|
|
<label className='flex flex-col gap-1 text-sm'>
|
|
{t('阈值')}
|
|
<InputNumber
|
|
min={0}
|
|
value={editing.threshold}
|
|
suffix={metricUnit(editing.metric)}
|
|
onChange={(v) => patch({ threshold: v })}
|
|
/>
|
|
</label>
|
|
</div>
|
|
<div className='grid grid-cols-1 sm:grid-cols-3 gap-3'>
|
|
<label className='flex flex-col gap-1 text-sm'>
|
|
{t('统计窗口(分钟)')}
|
|
<InputNumber
|
|
min={5}
|
|
max={1440}
|
|
step={5}
|
|
value={editing.window_minutes}
|
|
onChange={(v) => patch({ window_minutes: v })}
|
|
/>
|
|
</label>
|
|
<label className='flex flex-col gap-1 text-sm'>
|
|
{t('最小样本量')}
|
|
<InputNumber
|
|
min={1}
|
|
value={editing.min_samples}
|
|
onChange={(v) => patch({ min_samples: v })}
|
|
/>
|
|
</label>
|
|
<label className='flex flex-col gap-1 text-sm'>
|
|
{t('静默期(分钟)')}
|
|
<InputNumber
|
|
min={5}
|
|
max={10080}
|
|
value={editing.silence_minutes}
|
|
onChange={(v) => patch({ silence_minutes: v })}
|
|
/>
|
|
</label>
|
|
</div>
|
|
<div className='flex items-center gap-2 text-sm'>
|
|
<Switch
|
|
checked={editing.enabled}
|
|
onChange={(v) => patch({ enabled: v })}
|
|
/>
|
|
{t('启用')}
|
|
</div>
|
|
<div className='text-xs text-[var(--text-secondary)]'>
|
|
{t(
|
|
'样本量不足最小样本量时不告警,避免低峰期 1 次失败就误报;触发后静默期内不重复通知。',
|
|
)}
|
|
</div>
|
|
{testResult && (
|
|
<Banner
|
|
type={testResult.triggered ? 'danger' : 'success'}
|
|
closeIcon={null}
|
|
description={
|
|
<span className='quality-num'>
|
|
{t(
|
|
'窗口 {{start}} ~ {{end}}:观测值 {{value}},样本 {{samples}}',
|
|
{
|
|
start: fmtTs(testResult.start),
|
|
end: fmtTs(testResult.end),
|
|
value: Number(testResult.value).toFixed(2),
|
|
samples: fmtInt(testResult.samples),
|
|
},
|
|
)}
|
|
{' · '}
|
|
{testResult.samples < Number(editing.min_samples || 0)
|
|
? t('样本不足,不会触发')
|
|
: testResult.triggered
|
|
? t('会触发告警')
|
|
: t('不会触发')}
|
|
</span>
|
|
}
|
|
/>
|
|
)}
|
|
{editing.id ? (
|
|
<Tag size='small' color='grey' className='self-start'>
|
|
ID {editing.id}
|
|
</Tag>
|
|
) : null}
|
|
</div>
|
|
)}
|
|
</Modal>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default QualityAlerts;
|