优化计算逻辑

This commit is contained in:
CN-JS-HuiBai
2026-04-04 20:01:27 +08:00
parent 9b113b6986
commit 763f90e8e5

View File

@@ -504,20 +504,18 @@ app.get('/api/metrics/overview', async (req, res) => {
allServers = allServers.concat(m.servers); allServers = allServers.concat(m.servers);
} }
// --- 24h Traffic from DB --- // --- 24h Traffic from DB (Integrating Bandwidth) ---
try { try {
// Get the oldest record within 24h and the latest overall // Each record represents a 5-second interval
const [oldest] = await db.query('SELECT rx_bytes, tx_bytes, timestamp FROM traffic_stats WHERE timestamp >= NOW() - INTERVAL 1 DAY ORDER BY timestamp ASC LIMIT 1'); const [sumRows] = await db.query('SELECT SUM(rx_bandwidth) as sumRx, SUM(tx_bandwidth) as sumTx FROM traffic_stats WHERE timestamp >= NOW() - INTERVAL 1 DAY');
const [latest] = await db.query('SELECT rx_bytes, tx_bytes, timestamp FROM traffic_stats ORDER BY timestamp DESC LIMIT 1');
if (sumRows.length > 0 && sumRows[0].sumRx !== null) {
if (oldest.length > 0 && latest.length > 0) { // Total bytes = Sum of (bytes/sec) * 5 seconds
// Calculate difference. Handle counter resets (though unlikely for aggregated total) traffic24hRx = sumRows[0].sumRx * 5;
traffic24hRx = latest[0].rx_bytes > oldest[0].rx_bytes ? (latest[0].rx_bytes - oldest[0].rx_bytes) : 0; traffic24hTx = sumRows[0].sumTx * 5;
traffic24hTx = latest[0].tx_bytes > oldest[0].tx_bytes ? (latest[0].tx_bytes - oldest[0].tx_bytes) : 0;
} }
} catch (err) { } catch (err) {
console.error('Error calculating 24h traffic from DB:', err); console.error('Error calculating 24h traffic from DB integration:', err);
// Fallback to what we got from Prometheus directly in each source if DB fails
} }
res.json({ res.json({