Files
monkey-ai-web/src/components/quality/QualityBreakdown.jsx
T

262 lines
8.4 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, { useEffect, useMemo, useRef, useState } from 'react';
import { Select, Table, TabPane, Tabs, Tooltip } from '@/components/ui';
import { Layers } from 'lucide-react';
import {
ORDER_OPTIONS,
ORG_DIMS,
PLATFORM_DIMS,
fmtInt,
fmtMs,
pct,
qualityErrorText,
} from './qualityConstants';
import { QualityMetaNotice } from './QualityOverview';
export const RateBar = ({ value }) => (
<div className='quality-rate'>
<div className='quality-rate-track'>
<div
className='quality-rate-fill'
style={{ width: `${Math.max(0, Math.min(1, value || 0)) * 100}%` }}
/>
</div>
<span className='quality-num text-xs'>{pct(value)}</span>
</div>
);
/** 维度分布:每行可点击,把该维度值加入筛选(下钻) */
const QualityBreakdown = ({ quality, t }) => {
const { scope, get, params, setFilters } = quality;
const dims = scope === 'org' ? ORG_DIMS : PLATFORM_DIMS;
const [dim, setDim] = useState('model');
const [orderBy, setOrderBy] = useState('total');
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const seq = useRef(0);
useEffect(() => {
const current = ++seq.current;
setLoading(true);
setError('');
get('/breakdown', { ...params, dim, order_by: orderBy, limit: 50 })
.then((d) => current === seq.current && setData(d))
.catch((e) => {
if (current !== seq.current) return;
setData(null);
setError(e.code || 'query_failed');
})
.finally(() => current === seq.current && setLoading(false));
}, [get, params, dim, orderBy]);
const dimSpec = dims.find((d) => d.value === dim);
const labelOf = (row) => {
if ((dim === 'dept' || dim === 'project') && row.key === '0') {
return dim === 'dept' ? t('未分配部门') : t('未绑定项目');
}
if (dim === 'model' && row.key === '__unknown__') return t('未知模型');
if (dim === 'error') {
// 错误码维度按 (错误码, 状态码) 分组,同一错误码不同状态码必须区分显示
const code =
row.key === 'service_error'
? t('服务侧错误')
: row.key || t('(无错误码)');
return row.key2 ? `${code} · HTTP ${row.key2}` : code;
}
if (row.key === '') return t('(空)');
return row.label || row.key;
};
const columns = useMemo(
() => [
{
title: t(dimSpec?.label || '维度'),
dataIndex: 'key',
width: 220,
render: (_v, row) => (
<Tooltip content={row.key}>
<span className='block truncate max-w-[220px] font-medium'>
{labelOf(row)}
</span>
</Tooltip>
),
},
{
title: t('请求数'),
dataIndex: 'metrics.total',
align: 'right',
render: (_v, row) => (
<span className='quality-num'>{fmtInt(row.metrics.total)}</span>
),
},
{
title: t('成功率'),
dataIndex: 'metrics.success_rate',
width: 170,
render: (_v, row) => <RateBar value={row.metrics.success_rate} />,
},
{
title: t('兜底成功'),
align: 'right',
dataIndex: 'metrics.fallback_saved',
render: (_v, row) => (
<span className='quality-num'>
{fmtInt(row.metrics.fallback_saved)}
</span>
),
},
{
title: t('兜底失败'),
align: 'right',
dataIndex: 'metrics.fallback_failed',
render: (_v, row) => (
<span
className={`quality-num ${row.metrics.fallback_failed > 0 ? 'text-[var(--ui-color-danger)] font-semibold' : ''}`}
>
{fmtInt(row.metrics.fallback_failed)}
</span>
),
},
{
title: t('失败(未兜底)'),
align: 'right',
dataIndex: 'metrics.failed_no_fallback',
render: (_v, row) => (
<span className='quality-num'>
{fmtInt(row.metrics.failed_no_fallback)}
</span>
),
},
{
title: scope === 'org' ? t('服务侧故障率') : t('上游故障率'),
align: 'right',
dataIndex: 'metrics.upstream_fault_rate',
render: (_v, row) => (
<span className='quality-num'>
{pct(row.metrics.upstream_fault_rate)}
</span>
),
},
{
title: 'P95',
align: 'right',
dataIndex: 'metrics.p95_ms',
render: (_v, row) => (
<span className='quality-num'>{fmtMs(row.metrics.p95_ms)}</span>
),
},
],
// eslint-disable-next-line react-hooks/exhaustive-deps
[dim, t, scope],
);
// 行下钻:只对能表达成筛选条件的值生效
const canDrill = (row) => {
if (!dimSpec) return false;
if (dim === 'error')
return row.key !== 'service_error' && (row.key || row.key2);
if (row.key === '' || row.key === '__unknown__') return false;
// 渠道 / 企业 / 用户 / 密钥的 0 表示"无",筛选参数里 0 等于不过滤
if (['channel', 'org', 'user', 'token'].includes(dim) && row.key === '0')
return false;
return true;
};
const drill = (row) => {
if (!canDrill(row)) return;
if (dim === 'error') {
setFilters({ error_code: row.key || '', status_code: row.key2 || '' });
return;
}
setFilters({ [dimSpec.filterKey]: row.key });
};
return (
<div className='quality-card'>
<div className='quality-card-head'>
<span className='quality-card-title'>
<Layers size={16} />
{t('维度分布')}
<span className='quality-card-sub'>{t('点击行下钻到该维度')}</span>
</span>
<Select
value={orderBy}
style={{ width: 190 }}
optionList={ORDER_OPTIONS.map((o) => ({
value: o.value,
label: t(o.label),
}))}
onChange={setOrderBy}
/>
</div>
<div className='quality-card-body quality-nested-tabs'>
<Tabs type='button' size='small' activeKey={dim} onChange={setDim}>
{dims.map((d) => (
<TabPane key={d.value} itemKey={d.value} tab={t(d.label)} />
))}
</Tabs>
{data?.meta && (
<QualityMetaNotice meta={data.meta} scope={scope} t={t} />
)}
{error ? (
<div className='quality-empty'>{qualityErrorText(t, error)}</div>
) : (
<div className='overflow-x-auto app-scrollbar mt-2'>
<Table
size='small'
rowKey={(row) => `${row.key}|${row.key2 || ''}`}
loading={loading}
columns={columns}
dataSource={data?.rows || []}
pagination={false}
scroll={{ x: 960 }}
onRow={(row) =>
canDrill(row)
? {
className: 'quality-row-clickable',
tabIndex: 0,
onClick: () => drill(row),
onKeyDown: (e) => {
if (e.key === 'Enter') drill(row);
},
}
: {}
}
empty={<div className='quality-empty'>{t('暂无数据')}</div>}
/>
{data && data.total_rows > (data.rows || []).length && (
<div className='mt-2 text-xs text-[var(--text-secondary)]'>
{t('共 {{total}} 项,仅展示排序后的前 {{shown}} 项', {
total: data.total_rows,
shown: (data.rows || []).length,
})}
</div>
)}
</div>
)}
</div>
</div>
);
};
export default QualityBreakdown;