/*
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 {
Zap as ActionZap,
ChevronRight as ActionChevronRight,
RefreshCw as ActionRefreshCw,
} from '@/components/common/icons/ActionIcons';
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import Table from '../../components/ui/CenterActionTable';
import { Empty, Spin, Button, Modal, Tooltip, Statistic, theme } from 'antd';
import { Server, ChevronRight, Clock } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { API, showError } from '../../helpers';
import { isAdmin } from '../../helpers/utils';
// 条形码状态组件 - 美化版
const StatusBars = ({ dataPoints = [], loading = false, t }) => {
const { token } = theme.useToken();
// 补全或截取数据以适应展示 (展示最近60个点)
// 注意:useMemo 必须在任何 early return 之前调用,保证 hook 调用顺序稳定。
const displayCount = 60;
const normalizedData = useMemo(() => {
if (!dataPoints || dataPoints.length === 0) {
return Array(displayCount).fill(null);
}
// 如果数据点过多,取最后 displayCount 个
if (dataPoints.length > displayCount) {
return dataPoints.slice(-displayCount);
}
// 如果不足,前面补 null
const pad = Array(displayCount - dataPoints.length).fill(null);
return [...pad, ...dataPoints];
}, [dataPoints]);
if (loading) {
return (
{Array.from({ length: 60 }).map((_, i) => (
))}
);
}
return (
{normalizedData.map((point, i) => {
if (!point) {
return (
);
}
const isHealthy = point.uptime_percent >= 90;
const isWarning =
point.uptime_percent >= 50 && point.uptime_percent < 90;
let bgColor = token.colorError;
if (isHealthy) {
bgColor = token.colorPrimary;
} else if (isWarning) {
bgColor = token.colorWarning;
}
const height = isHealthy ? '20px' : '16px';
return (
{isHealthy ? t('正常') : t('异常')} (
{point.uptime_percent?.toFixed(1)}%)
{point.timestamp
? new Date(point.timestamp * 1000).toLocaleString()
: '-'}
}
>
);
})}
1h
{t('现在')}
);
};
// 模型测试单元格组件
const TestModelCell = ({ modelName, groupName, t }) => {
const { token } = theme.useToken();
const [testing, setTesting] = useState(false);
const [result, setResult] = useState(null);
const handleTest = async (e) => {
e.stopPropagation();
setTesting(true);
setResult(null);
try {
const res = await API.post(
'/api/monitor/test/model',
{
model: modelName,
group: groupName,
},
{
timeout: 60000,
skipErrorHandler: true,
},
);
const { success, message, time } = res.data;
const timeMs = Math.round((time || 0) * 1000);
if (success) {
setResult({ success: true, time: timeMs });
} else {
setResult({
success: false,
time: timeMs,
error: message || t('测试失败'),
});
}
} catch (error) {
const errorMsg =
error.response?.data?.message || error.message || t('测试失败');
setResult({ success: false, time: 0, error: errorMsg });
} finally {
setTesting(false);
}
};
return (
{testing ? t('测试中') : t('测试')}
{result && (
{result.success ? (
✓
{result.time}ms
) : (
✗
{result.time > 0 && {result.time}ms }
)}
)}
);
};
const GroupMonitor = () => {
const { t } = useTranslation();
const { token } = theme.useToken();
const [groups, setGroups] = useState([]);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [selectedGroup, setSelectedGroup] = useState(null);
const [modalVisible, setModalVisible] = useState(false);
const [lastUpdateTime, setLastUpdateTime] = useState(null);
const [nextRefreshTime, setNextRefreshTime] = useState(null);
const [timeRemaining, setTimeRemaining] = useState(0);
const [listHistoryData, setListHistoryData] = useState({});
const adminUser = isAdmin();
const formatDateTime = (date) => {
if (!date) return '';
const pad = (n) => n.toString().padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
};
const fetchGroupData = useCallback(
async (showRefreshIndicator = false) => {
if (showRefreshIndicator) {
setRefreshing(true);
} else {
setLoading(true);
}
try {
const res = await API.get('/api/monitor/groups');
if (res.data.success) {
const newGroups = res.data.data || [];
setGroups(newGroups);
const now = new Date();
setLastUpdateTime(now);
const next = new Date(now.getTime() + 60000);
setNextRefreshTime(next);
setTimeRemaining(60);
const newHistoryData = {};
newGroups.forEach((group) => {
if (group.data_points) {
newHistoryData[group.name] = { data_points: group.data_points };
}
});
setListHistoryData(newHistoryData);
} else {
showError(res.data.message || t('获取数据失败'));
}
} catch (error) {
showError(error.message || t('网络请求失败'));
} finally {
setLoading(false);
setRefreshing(false);
}
},
[t],
);
useEffect(() => {
fetchGroupData();
const interval = setInterval(() => {
fetchGroupData(true);
}, 60000);
return () => clearInterval(interval);
}, [fetchGroupData]);
useEffect(() => {
if (!nextRefreshTime) return;
const timer = setInterval(() => {
const now = new Date();
const diff = Math.max(0, Math.ceil((nextRefreshTime - now) / 1000));
setTimeRemaining(diff);
}, 1000);
return () => clearInterval(timer);
}, [nextRefreshTime]);
const handleGroupClick = (group) => {
if (!adminUser) return;
setSelectedGroup(group);
setModalVisible(true);
};
const handleCloseModal = () => {
setModalVisible(false);
};
const handleAfterClose = () => {
setSelectedGroup(null);
};
const getUptimeColor = useCallback(
(uptime) => {
const val = Number(uptime) || 0;
if (val >= 95) return token.colorPrimary;
if (val >= 80) return token.colorWarning;
return token.colorError;
},
[token.colorPrimary, token.colorWarning, token.colorError],
);
const getUptimeClass = (uptime) => {
const val = Number(uptime) || 0;
if (val >= 95) return 'service-status-normal';
if (val >= 80) return 'service-status-warning';
return 'service-status-error';
};
const modelColumns = useMemo(
() => [
{
title: t('模型'),
dataIndex: 'model',
key: 'model',
render: (text) => (
),
},
{
title: t('可用率'),
dataIndex: 'uptime_percent',
key: 'uptime_percent',
render: (value) => (
{(value || 0).toFixed(1)}%
),
sorter: (a, b) => (a.uptime_percent || 0) - (b.uptime_percent || 0),
},
{
title: t('可用/总数'),
key: 'count',
render: (_, record) => (
{record.available_count}
/
{record.total_count}
),
},
{
title: t('平均响应'),
dataIndex: 'avg_response_time',
key: 'avg_response_time',
render: (value) =>
value > 0 ? (
2000 ? 'text-orange-500' : 'text-gray-600 dark:text-gray-300'}`}
>
{value}ms
) : (
-
),
sorter: (a, b) => a.avg_response_time - b.avg_response_time,
},
{
title: t('操作'),
key: 'action',
width: 200,
render: (_, record) => (
),
},
],
[t, selectedGroup, getUptimeColor, token.colorPrimary],
);
const modalDataSource = useMemo(() => {
if (!selectedGroup?.model_stats) return [];
return selectedGroup.model_stats.filter(
(item) => item && typeof item === 'object',
);
}, [selectedGroup?.model_stats]);
const modalPagination = useMemo(
() => ({
pageSize: 10,
size: 'small',
showSizeChanger: false,
hideOnSinglePage: true,
}),
[],
);
if (loading) {
return (
);
}
if (groups.length === 0) {
return (
);
}
return (
{/* 分组列表 */}
{groups.map((group, index) => {
const history = listHistoryData[group.name];
const availableModelCount =
group.model_stats?.filter((m) => m.available_count > 0).length || 0;
const totalModelCount = group.model_stats?.length || 0;
const uptimePercent = group.uptime_percent || 0;
return (
handleGroupClick(group) : undefined}
>
{/* 左侧状态指示条 */}
{/* 桌面端布局 */}
{/* 分组名称 */}
{/* 可用率 */}
{uptimePercent.toFixed(2)}%
{/* 模型数量 */}
0 ? 'text-gray-800 dark:text-gray-100' : 'text-red-500'}`}
>
{availableModelCount}
/
{totalModelCount}
{t('模型')}
{/* 趋势图 */}
{/* 查看按钮 - 仅管理员可见 */}
{adminUser && (
{
e.stopPropagation();
handleGroupClick(group);
}}
>
{t('详情')}
)}
{/* 移动端布局 */}
{uptimePercent.toFixed(2)}%
0 ? 'text-gray-800 dark:text-gray-100' : 'text-red-500'}`}
>
{availableModelCount}
/
{totalModelCount}
{t('模型')}
{adminUser && (
)}
{/* 移动端趋势图 */}
);
})}
{/* 刷新信息 */}
{lastUpdateTime && (
{t('更新时间')}: {formatDateTime(lastUpdateTime)}
{Math.floor(timeRemaining / 60)
.toString()
.padStart(2, '0')}
:
{Math.floor(timeRemaining % 60)
.toString()
.padStart(2, '0')}
}
onClick={() => fetchGroupData(true)}
loading={refreshing}
type='text'
className='service-refresh-button'
>
{t('立即刷新')}
)}
{/* 详情弹窗 */}
{selectedGroup && (
<>
,
}}
/>
>
)}
);
};
export default GroupMonitor;