File size: 9,572 Bytes
4674012 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 |
/*
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 from 'react';
import { Progress, Divider, Empty } from '@douyinfe/semi-ui';
import {
IllustrationConstruction,
IllustrationConstructionDark,
} from '@douyinfe/semi-illustrations';
import {
timestamp2string,
timestamp2string1,
copy,
showSuccess,
} from './utils';
import {
STORAGE_KEYS,
DEFAULT_TIME_INTERVALS,
DEFAULTS,
ILLUSTRATION_SIZE,
} from '../constants/dashboard.constants';
// ========== 时间相关工具函数 ==========
export const getDefaultTime = () => {
return localStorage.getItem(STORAGE_KEYS.DATA_EXPORT_DEFAULT_TIME) || 'hour';
};
export const getTimeInterval = (timeType, isSeconds = false) => {
const intervals =
DEFAULT_TIME_INTERVALS[timeType] || DEFAULT_TIME_INTERVALS.hour;
return isSeconds ? intervals.seconds : intervals.minutes;
};
export const getInitialTimestamp = () => {
const defaultTime = getDefaultTime();
const now = new Date().getTime() / 1000;
switch (defaultTime) {
case 'hour':
return timestamp2string(now - 86400);
case 'week':
return timestamp2string(now - 86400 * 30);
default:
return timestamp2string(now - 86400 * 7);
}
};
// ========== 数据处理工具函数 ==========
export const updateMapValue = (map, key, value) => {
if (!map.has(key)) {
map.set(key, 0);
}
map.set(key, map.get(key) + value);
};
export const initializeMaps = (key, ...maps) => {
maps.forEach((map) => {
if (!map.has(key)) {
map.set(key, 0);
}
});
};
// ========== 图表相关工具函数 ==========
export const updateChartSpec = (
setterFunc,
newData,
subtitle,
newColors,
dataId,
) => {
setterFunc((prev) => ({
...prev,
data: [{ id: dataId, values: newData }],
title: {
...prev.title,
subtext: subtitle,
},
color: {
specified: newColors,
},
}));
};
export const getTrendSpec = (data, color) => ({
type: 'line',
data: [{ id: 'trend', values: data.map((val, idx) => ({ x: idx, y: val })) }],
xField: 'x',
yField: 'y',
height: 40,
width: 100,
axes: [
{
orient: 'bottom',
visible: false,
},
{
orient: 'left',
visible: false,
},
],
padding: 0,
autoFit: false,
legends: { visible: false },
tooltip: { visible: false },
crosshair: { visible: false },
line: {
style: {
stroke: color,
lineWidth: 2,
},
},
point: {
visible: false,
},
background: {
fill: 'transparent',
},
});
// ========== UI 工具函数 ==========
export const createSectionTitle = (Icon, text) => (
<div className='flex items-center gap-2'>
<Icon size={16} />
{text}
</div>
);
export const createFormField = (Component, props, FORM_FIELD_PROPS) => (
<Component {...FORM_FIELD_PROPS} {...props} />
);
// ========== 操作处理函数 ==========
export const handleCopyUrl = async (url, t) => {
if (await copy(url)) {
showSuccess(t('复制成功'));
}
};
export const handleSpeedTest = (apiUrl) => {
const encodedUrl = encodeURIComponent(apiUrl);
const speedTestUrl = `https://www.tcptest.cn/http/${encodedUrl}`;
window.open(speedTestUrl, '_blank', 'noopener,noreferrer');
};
// ========== 状态映射函数 ==========
export const getUptimeStatusColor = (status, uptimeStatusMap) =>
uptimeStatusMap[status]?.color || '#8b9aa7';
export const getUptimeStatusText = (status, uptimeStatusMap, t) =>
uptimeStatusMap[status]?.text || t('未知');
// ========== 监控列表渲染函数 ==========
export const renderMonitorList = (
monitors,
getUptimeStatusColor,
getUptimeStatusText,
t,
) => {
if (!monitors || monitors.length === 0) {
return (
<div className='flex justify-center items-center py-4'>
<Empty
image={<IllustrationConstruction style={ILLUSTRATION_SIZE} />}
darkModeImage={
<IllustrationConstructionDark style={ILLUSTRATION_SIZE} />
}
title={t('暂无监控数据')}
/>
</div>
);
}
const grouped = {};
monitors.forEach((m) => {
const g = m.group || '';
if (!grouped[g]) grouped[g] = [];
grouped[g].push(m);
});
const renderItem = (monitor, idx) => (
<div key={idx} className='p-2 hover:bg-white rounded-lg transition-colors'>
<div className='flex items-center justify-between mb-1'>
<div className='flex items-center gap-2'>
<div
className='w-2 h-2 rounded-full flex-shrink-0'
style={{ backgroundColor: getUptimeStatusColor(monitor.status) }}
/>
<span className='text-sm font-medium text-gray-900'>
{monitor.name}
</span>
</div>
<span className='text-xs text-gray-500'>
{((monitor.uptime || 0) * 100).toFixed(2)}%
</span>
</div>
<div className='flex items-center gap-2'>
<span className='text-xs text-gray-500'>
{getUptimeStatusText(monitor.status)}
</span>
<div className='flex-1'>
<Progress
percent={(monitor.uptime || 0) * 100}
showInfo={false}
aria-label={`${monitor.name} uptime`}
stroke={getUptimeStatusColor(monitor.status)}
/>
</div>
</div>
</div>
);
return Object.entries(grouped).map(([gname, list]) => (
<div key={gname || 'default'} className='mb-2'>
{gname && (
<>
<div className='text-md font-semibold text-gray-500 px-2 py-1'>
{gname}
</div>
<Divider />
</>
)}
{list.map(renderItem)}
</div>
));
};
// ========== 数据处理函数 ==========
export const processRawData = (
data,
dataExportDefaultTime,
initializeMaps,
updateMapValue,
) => {
const result = {
totalQuota: 0,
totalTimes: 0,
totalTokens: 0,
uniqueModels: new Set(),
timePoints: [],
timeQuotaMap: new Map(),
timeTokensMap: new Map(),
timeCountMap: new Map(),
};
data.forEach((item) => {
result.uniqueModels.add(item.model_name);
result.totalTokens += item.token_used;
result.totalQuota += item.quota;
result.totalTimes += item.count;
const timeKey = timestamp2string1(item.created_at, dataExportDefaultTime);
if (!result.timePoints.includes(timeKey)) {
result.timePoints.push(timeKey);
}
initializeMaps(
timeKey,
result.timeQuotaMap,
result.timeTokensMap,
result.timeCountMap,
);
updateMapValue(result.timeQuotaMap, timeKey, item.quota);
updateMapValue(result.timeTokensMap, timeKey, item.token_used);
updateMapValue(result.timeCountMap, timeKey, item.count);
});
result.timePoints.sort();
return result;
};
export const calculateTrendData = (
timePoints,
timeQuotaMap,
timeTokensMap,
timeCountMap,
dataExportDefaultTime,
) => {
const quotaTrend = timePoints.map((time) => timeQuotaMap.get(time) || 0);
const tokensTrend = timePoints.map((time) => timeTokensMap.get(time) || 0);
const countTrend = timePoints.map((time) => timeCountMap.get(time) || 0);
const rpmTrend = [];
const tpmTrend = [];
if (timePoints.length >= 2) {
const interval = getTimeInterval(dataExportDefaultTime);
for (let i = 0; i < timePoints.length; i++) {
rpmTrend.push(timeCountMap.get(timePoints[i]) / interval);
tpmTrend.push(timeTokensMap.get(timePoints[i]) / interval);
}
}
return {
balance: [],
usedQuota: [],
requestCount: [],
times: countTrend,
consumeQuota: quotaTrend,
tokens: tokensTrend,
rpm: rpmTrend,
tpm: tpmTrend,
};
};
export const aggregateDataByTimeAndModel = (data, dataExportDefaultTime) => {
const aggregatedData = new Map();
data.forEach((item) => {
const timeKey = timestamp2string1(item.created_at, dataExportDefaultTime);
const modelKey = item.model_name;
const key = `${timeKey}-${modelKey}`;
if (!aggregatedData.has(key)) {
aggregatedData.set(key, {
time: timeKey,
model: modelKey,
quota: 0,
count: 0,
});
}
const existing = aggregatedData.get(key);
existing.quota += item.quota;
existing.count += item.count;
});
return aggregatedData;
};
export const generateChartTimePoints = (
aggregatedData,
data,
dataExportDefaultTime,
) => {
let chartTimePoints = Array.from(
new Set([...aggregatedData.values()].map((d) => d.time)),
);
if (chartTimePoints.length < DEFAULTS.MAX_TREND_POINTS) {
const lastTime = Math.max(...data.map((item) => item.created_at));
const interval = getTimeInterval(dataExportDefaultTime, true);
chartTimePoints = Array.from(
{ length: DEFAULTS.MAX_TREND_POINTS },
(_, i) =>
timestamp2string1(lastTime - (6 - i) * interval, dataExportDefaultTime),
);
}
return chartTimePoints;
};
|