/* 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 . For commercial licensing, please contact support@quantumnous.com */ import React, { useMemo } from 'react'; import { Button, Skeleton, Tooltip } from '@/components/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 {t('与上一周期持平')}; } const good = higherIsBetter ? diff > 0 : diff < 0; const text = asRate ? `${diff > 0 ? '+' : ''}${(diff * 100).toFixed(1)}pp` : `${diff > 0 ? '+' : ''}${fmtInt(Math.round(diff))}`; return ( {t('环比')} {text} ); }; /** 数据来源 / 降级 / 完整度提示条 */ 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 (
{notes.map((n, i) => (
{n.tone === 'warn' ? ( ) : ( )} {n.text}
))}
); }; export const QualityErrorState = ({ error, onRetry, t }) => (
{qualityErrorText(t, error)}
{onRetry && ( )}
); /** KPI 卡:点击结局类卡片直接下钻到对应明细 */ export const QualityKpiCards = ({ summary, loading, onDrillOutcome, t }) => { if (loading && !summary) { return (
{Array.from({ length: 6 }).map((_, i) => (
))}
); } 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: ( <> {cur.total_raw !== cur.total && ( {t('原始')} {fmtInt(cur.total_raw)} )} ), }, { key: 'success_rate', label: t('成功率'), value: pct(cur.success_rate, 2), color: toneColor('success'), foot: ( <> {t('直接成功率')} {pct(cur.direct_rate)} ), }, { key: 'fallback_saved', label: t('兜底成功'), value: fmtInt(cur.fallback_saved), color: toneColor('primary'), outcome: '2', foot: ( <> {t('触发兜底')} {fmtInt(cur.fallback_triggered)} {t('挽救率')} {pct(cur.fallback_save_rate)} ), }, { key: 'fallback_failed', label: t('兜底失败'), value: fmtInt(cur.fallback_failed), color: toneColor('danger'), outcome: '3', foot: ( ), }, { key: 'failed_no_fallback', label: t('失败(未兜底)'), value: fmtInt(cur.failed_no_fallback), color: toneColor('warning'), outcome: '4', foot: ( {t('上游故障率')} {pct(cur.upstream_fault_rate)} ), }, { key: 'p95', label: t('P95 耗时'), value: fmtMs(cur.p95_ms), color: toneColor('tertiary'), foot: ( <> P50 {fmtMs(cur.p50_ms)} {t('平均')} {fmtMs(cur.avg_ms)} ), }, { key: 'abort', label: t('客户端中断 / 内容拦截'), value: `${fmtInt(cur.client_abort)} / ${fmtInt(cur.blocked)}`, color: toneColor('purple'), outcome: '5,6', foot: ( {t('拦截率')} {pct(cur.block_rate)} ), }, ]; return (
{cards.map((card) => { const clickable = Boolean(card.outcome && onDrillOutcome); return (
onDrillOutcome(card.outcome) : undefined} onKeyDown={ clickable ? (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onDrillOutcome(card.outcome); } } : undefined } > {card.label} {card.value} {card.foot}
); })}
); }; /** 趋势:结局堆叠柱 + 成功率折线;点击柱子把时间范围放大到该桶 */ 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('--ui-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('--ui-color-success', '#3bb346'), lineWidth: 2, }, }, point: { style: { fill: readCssVar('--ui-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 (
{t('调用结局趋势')} {t('粒度')}{' '} {gran >= 86400 ? t('1 天') : gran >= 3600 ? t('1 小时') : t('5 分钟')} {' · '} {t('点击柱子放大到该时段')}
{loading && !spec ? ( ) : spec ? ( { const ts = e?.datum?.ts; if (ts && onZoom) onZoom(ts, ts + gran); }} /> ) : (
{t('所选时间范围内暂无调用')}
)}
); }; /** 责任方分布:点击扇区按责任方筛选 */ export const QualityFaultChart = ({ summary, scope, loading, onDrillFault, t, }) => { const actualTheme = useActualTheme(); const fault = summary?.current?.fault || {}; const isOrg = scope === 'org'; // 颜色按责任方固定,不随"哪些类别为 0 被过滤掉"而错位 const faultColor = { upstream: ['--ui-color-danger', '#f93920'], platform: ['--ui-color-warning', '#fc8800'], client: ['--ui-color-primary', '#0064fa'], quota: ['--ui-color-secondary', '#8b5cf6'], abort: ['--ui-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 (
{t('失败责任方')} {t('点击扇区筛选')}
{loading && !summary ? ( ) : spec ? ( { const v = e?.datum?.value; if (v && onDrillFault) onDrillFault(String(v)); }} /> ) : (
{t('所选范围内没有失败请求')}
)}
); };