Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
+514
View File
@@ -0,0 +1,514 @@
/*
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, { useMemo } from 'react';
import { Button, Skeleton, Tooltip } from '@douyinfe/semi-ui';
import { useActualTheme } from '../../context/Theme';
import { VChart } from '@visactor/react-vchart';
import { Activity, AlertTriangle, Info, PieChart } from 'lucide-react';
import {
DEGRADE_TEXT,
FAULTS,
OUTCOMES,
fmtInt,
fmtMs,
fmtTs,
outcomeColors,
pct,
qualityErrorText,
readCssVar,
toneColor,
} from './qualityConstants';
const Delta = ({ current, previous, higherIsBetter = true, asRate, t }) => {
if (previous === undefined || previous === null) return null;
const diff = current - previous;
if (!Number.isFinite(diff) || Math.abs(diff) < (asRate ? 0.0005 : 0.5)) {
return <span>{t('与上一周期持平')}</span>;
}
const good = higherIsBetter ? diff > 0 : diff < 0;
const text = asRate
? `${diff > 0 ? '+' : ''}${(diff * 100).toFixed(1)}pp`
: `${diff > 0 ? '+' : ''}${fmtInt(Math.round(diff))}`;
return (
<span className={good ? 'quality-delta-up' : 'quality-delta-down'}>
{t('环比')} {text}
</span>
);
};
/** 数据来源 / 降级 / 完整度提示条 */
export const QualityMetaNotice = ({ meta, scope, t }) => {
if (!meta) return null;
const notes = [];
// 未知原因码不直显(避免英文内部标识出现在界面上)
const reasons = String(meta.degraded_reason || '')
.split(',')
.filter((r) => DEGRADE_TEXT[r])
.map((r) => t(DEGRADE_TEXT[r]));
if (reasons.length > 0 || meta.data_source === 'logs') {
notes.push({
tone: 'info',
text:
reasons.join(';') ||
t('当前条件下直接统计调用日志,时间范围最长 7 天'),
});
}
if (meta.narrowed) {
notes.push({
tone: 'info',
text: t(
'已按结局 / 责任方收窄:耗时分位与用量为收窄前的整体值,仅供参考',
),
});
}
const c = meta.completeness || {};
if (scope !== 'org' && c.enabled === false) {
notes.push({
tone: 'warn',
text: t(
'质量采集已关闭(MONITOR_QUALITY_ENABLED=false),新调用不会进入看板',
),
});
}
if (scope !== 'org' && (c.dropped_events > 0 || c.dropped_rows > 0)) {
notes.push({
tone: 'warn',
text: t(
'本节点自启动以来丢弃了 {{events}} 条事件 / {{rows}} 行聚合,统计可能偏低',
{
events: fmtInt(c.dropped_events),
rows: fmtInt(c.dropped_rows),
},
),
});
}
if (meta.detail_available === false) {
notes.push({
tone: 'warn',
text: t('日志表尚未完成质量字段升级,明细与按用户 / 令牌分析暂不可用'),
});
}
if (notes.length === 0) return null;
return (
<div className='flex flex-col gap-2'>
{notes.map((n, i) => (
<div key={i} className='quality-notice' data-tone={n.tone}>
{n.tone === 'warn' ? (
<AlertTriangle size={14} className='mt-0.5 flex-shrink-0' />
) : (
<Info size={14} className='mt-0.5 flex-shrink-0' />
)}
<span>{n.text}</span>
</div>
))}
</div>
);
};
export const QualityErrorState = ({ error, onRetry, t }) => (
<div className='quality-card'>
<div className='quality-empty flex flex-col items-center gap-3'>
<AlertTriangle size={22} className='text-[var(--semi-color-danger)]' />
<div>{qualityErrorText(t, error)}</div>
{onRetry && (
<Button size='small' onClick={onRetry}>
{t('重试')}
</Button>
)}
</div>
</div>
);
/** KPI 卡:点击结局类卡片直接下钻到对应明细 */
export const QualityKpiCards = ({ summary, loading, onDrillOutcome, t }) => {
if (loading && !summary) {
return (
<div className='quality-kpis'>
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className='quality-kpi'>
<Skeleton.Paragraph rows={2} />
</div>
))}
</div>
);
}
const cur = summary?.current || {};
// 直查日志时后端不计算上一周期,不能拿全 0 当环比基数
const prev = summary?.meta?.no_previous ? undefined : summary?.previous;
const cards = [
{
key: 'total',
label: t('请求总数'),
value: fmtInt(cur.total),
color: toneColor('primary'),
foot: (
<>
<Delta current={cur.total} previous={prev?.total} t={t} />
{cur.total_raw !== cur.total && (
<Tooltip content={t('含客户端中断与内容拦截的原始请求数')}>
<span>
{t('原始')} {fmtInt(cur.total_raw)}
</span>
</Tooltip>
)}
</>
),
},
{
key: 'success_rate',
label: t('成功率'),
value: pct(cur.success_rate, 2),
color: toneColor('success'),
foot: (
<>
<Delta
current={cur.success_rate}
previous={prev?.success_rate}
asRate
t={t}
/>
<span>
{t('直接成功率')} {pct(cur.direct_rate)}
</span>
</>
),
},
{
key: 'fallback_saved',
label: t('兜底成功'),
value: fmtInt(cur.fallback_saved),
color: toneColor('primary'),
outcome: '2',
foot: (
<>
<span>
{t('触发兜底')} {fmtInt(cur.fallback_triggered)}
</span>
<span>
{t('挽救率')} {pct(cur.fallback_save_rate)}
</span>
</>
),
},
{
key: 'fallback_failed',
label: t('兜底失败'),
value: fmtInt(cur.fallback_failed),
color: toneColor('danger'),
outcome: '3',
foot: (
<Delta
current={cur.fallback_failed}
previous={prev?.fallback_failed}
higherIsBetter={false}
t={t}
/>
),
},
{
key: 'failed_no_fallback',
label: t('失败(未兜底)'),
value: fmtInt(cur.failed_no_fallback),
color: toneColor('warning'),
outcome: '4',
foot: (
<span>
{t('上游故障率')} {pct(cur.upstream_fault_rate)}
</span>
),
},
{
key: 'p95',
label: t('P95 耗时'),
value: fmtMs(cur.p95_ms),
color: toneColor('tertiary'),
foot: (
<>
<span>P50 {fmtMs(cur.p50_ms)}</span>
<span>
{t('平均')} {fmtMs(cur.avg_ms)}
</span>
</>
),
},
{
key: 'abort',
label: t('客户端中断 / 内容拦截'),
value: `${fmtInt(cur.client_abort)} / ${fmtInt(cur.blocked)}`,
color: toneColor('purple'),
outcome: '5,6',
foot: (
<span>
{t('拦截率')} {pct(cur.block_rate)}
</span>
),
},
];
return (
<div className='quality-kpis'>
{cards.map((card) => {
const clickable = Boolean(card.outcome && onDrillOutcome);
return (
<div
key={card.key}
className='quality-kpi'
style={{ '--kpi-color': card.color }}
data-clickable={clickable}
role={clickable ? 'button' : undefined}
tabIndex={clickable ? 0 : undefined}
onClick={clickable ? () => onDrillOutcome(card.outcome) : undefined}
onKeyDown={
clickable
? (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
onDrillOutcome(card.outcome);
}
}
: undefined
}
>
<span className='quality-kpi-label'>{card.label}</span>
<span className='quality-kpi-value'>{card.value}</span>
<span className='quality-kpi-foot'>{card.foot}</span>
</div>
);
})}
</div>
);
};
/** 趋势:结局堆叠柱 + 成功率折线;点击柱子把时间范围放大到该桶 */
export const QualityTrendChart = ({ trend, loading, onZoom, t }) => {
const actualTheme = useActualTheme();
const points = useMemo(() => trend?.points || [], [trend]);
const gran = trend?.meta?.granularity || 3600;
const spec = useMemo(() => {
if (points.length === 0) return null;
const colors = outcomeColors();
const bars = [];
points.forEach((p) => {
OUTCOMES.forEach((o) => {
bars.push({
ts: p.ts,
time: fmtTs(p.ts),
outcome: t(o.label),
value: p[o.key] || 0,
});
});
});
const rateLabel = t('成功率');
const line = points.map((p) => ({
ts: p.ts,
time: fmtTs(p.ts),
series: rateLabel,
rate: p.total > 0 ? Number((p.success_rate * 100).toFixed(2)) : null,
}));
return {
type: 'common',
data: [
{ id: 'bars', values: bars },
{ id: 'line', values: line },
],
// 第 7 个颜色给成功率折线,图例色块与线色一致
color: [...colors, readCssVar('--semi-color-success', '#3bb346')],
series: [
{
type: 'bar',
id: 'outcomeBar',
dataIndex: 0,
xField: 'time',
yField: 'value',
seriesField: 'outcome',
stack: true,
},
{
type: 'line',
id: 'rateLine',
dataIndex: 1,
xField: 'time',
yField: 'rate',
seriesField: 'series',
line: {
style: {
stroke: readCssVar('--semi-color-success', '#3bb346'),
lineWidth: 2,
},
},
point: {
style: {
fill: readCssVar('--semi-color-success', '#3bb346'),
size: 4,
},
},
},
],
axes: [
{ orient: 'left', seriesId: ['outcomeBar'], title: { visible: false } },
{
orient: 'right',
seriesId: ['rateLine'],
min: 0,
max: 100,
grid: { visible: false },
label: { formatMethod: (v) => `${v}%` },
},
{ orient: 'bottom', type: 'band' },
],
legends: { visible: true, orient: 'top', position: 'start' },
tooltip: {
dimension: {
content: [
{
seriesId: 'outcomeBar',
key: (d) => d?.outcome,
value: (d) => fmtInt(d?.value),
},
{
seriesId: 'rateLine',
key: t('成功率'),
value: (d) => (d?.rate === null ? '-' : `${d?.rate}%`),
},
],
},
},
};
// actualTheme:切换亮 / 暗色时重新读取主题色
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [points, t, actualTheme]);
return (
<div className='quality-card'>
<div className='quality-card-head'>
<span className='quality-card-title'>
<Activity size={16} />
{t('调用结局趋势')}
<span className='quality-card-sub'>
{t('粒度')}{' '}
{gran >= 86400
? t('1 天')
: gran >= 3600
? t('1 小时')
: t('5 分钟')}
{' · '}
{t('点击柱子放大到该时段')}
</span>
</span>
</div>
<div className='quality-card-body' style={{ height: 340 }}>
{loading && !spec ? (
<Skeleton.Image style={{ width: '100%', height: '100%' }} />
) : spec ? (
<VChart
spec={spec}
option={{ mode: 'desktop-browser' }}
onClick={(e) => {
const ts = e?.datum?.ts;
if (ts && onZoom) onZoom(ts, ts + gran);
}}
/>
) : (
<div className='quality-empty'>{t('所选时间范围内暂无调用')}</div>
)}
</div>
</div>
);
};
/** 责任方分布:点击扇区按责任方筛选 */
export const QualityFaultChart = ({
summary,
scope,
loading,
onDrillFault,
t,
}) => {
const actualTheme = useActualTheme();
const fault = summary?.current?.fault || {};
const isOrg = scope === 'org';
// 颜色按责任方固定,不随"哪些类别为 0 被过滤掉"而错位
const faultColor = {
upstream: ['--semi-color-danger', '#f93920'],
platform: ['--semi-color-warning', '#fc8800'],
client: ['--semi-color-primary', '#0064fa'],
quota: ['--semi-color-secondary', '#8b5cf6'],
abort: ['--semi-color-tertiary', '#6b7075'],
};
const data = FAULTS.filter((f) => !(isOrg && f.value === 2))
.map((f) => ({
value: f.value,
key: f.key,
name: t(isOrg ? f.orgLabel : f.label),
count: fault[f.key] || 0,
}))
.filter((d) => d.count > 0);
const spec = useMemo(
() =>
data.length === 0
? null
: {
type: 'pie',
data: [{ id: 'fault', values: data }],
valueField: 'count',
categoryField: 'name',
outerRadius: 0.8,
innerRadius: 0.55,
color: data.map((d) => readCssVar(...faultColor[d.key])),
legends: { visible: true, orient: 'bottom' },
label: { visible: true, formatMethod: (_t, d) => fmtInt(d?.count) },
tooltip: {
mark: {
content: [
{ key: (d) => d?.name, value: (d) => fmtInt(d?.count) },
],
},
},
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[JSON.stringify(data), actualTheme],
);
return (
<div className='quality-card'>
<div className='quality-card-head'>
<span className='quality-card-title'>
<PieChart size={16} />
{t('失败责任方')}
<span className='quality-card-sub'>{t('点击扇区筛选')}</span>
</span>
</div>
<div className='quality-card-body' style={{ height: 340 }}>
{loading && !summary ? (
<Skeleton.Image style={{ width: '100%', height: '100%' }} />
) : spec ? (
<VChart
spec={spec}
option={{ mode: 'desktop-browser' }}
onClick={(e) => {
const v = e?.datum?.value;
if (v && onDrillFault) onDrillFault(String(v));
}}
/>
) : (
<div className='quality-empty'>{t('所选范围内没有失败请求')}</div>
)}
</div>
</div>
);
};