feat: 流量/CPU/内存三图并列的性能趋势

This commit is contained in:
jinghui committed 2026-10-26 18:38:28 +08:00
1 parent c31379c8b0
commit 1b1b413cf3
5 files changed
+115 -64

No files matched your search

+45 -16
View File
@@ -105,7 +105,8 @@ const localYmd = (d = new Date(), offsetDays = 0) => {
const t = new Date(d.getTime() + 8 * 3600e3 + offsetDays * 86400e3);
return t.toISOString().slice(0, 10);
};
const emptyHours = () => Array.from({ length: 24 }, () => ({ rx: 0, tx: 0 }));
const emptyHour = () => ({ rx: 0, tx: 0, cpuSum: 0, cpuN: 0, memSum: 0, memMax: 0, memN: 0 });
const emptyHours = () => Array.from({ length: 24 }, () => emptyHour());
async function loadTrafficDay(date) {
if (trafficDays.has(date)) return trafficDays.get(date);
@@ -114,7 +115,14 @@ async function loadTrafficDay(date) {
const raw = await fsp.readFile(path.join(TRAFFIC_DIR, `${date}.json`), 'utf8');
const j = JSON.parse(raw);
if (j && Array.isArray(j.hours)) {
for (let i = 0; i < 24; i++) data.hours[i] = { rx: j.hours[i]?.rx || 0, tx: j.hours[i]?.tx || 0 };
for (let i = 0; i < 24; i++) {
const h = j.hours[i] || {};
data.hours[i] = {
rx: h.rx || 0, tx: h.tx || 0,
cpuSum: h.cpuSum || 0, cpuN: h.cpuN || 0,
memSum: h.memSum || 0, memMax: h.memMax || 0, memN: h.memN || 0,
};
}
}
} catch (e) {}
if (date !== localYmd()) trafficDays.set(date, data); // 历史天可长缓存
@@ -130,11 +138,13 @@ async function trafficToday() {
return trafficDay;
}
function addTraffic(rxBytes, txBytes) {
function addTraffic(rxBytes, txBytes, cpuPct, memBytes) {
if (!trafficDay) return;
const h = new Date().getHours();
const b = trafficDay.hours[h];
b.rx += Math.max(0, rxBytes); b.tx += Math.max(0, txBytes);
if (Number.isFinite(cpuPct)) { b.cpuSum += cpuPct; b.cpuN += 1; }
if (Number.isFinite(memBytes)) { b.memSum += memBytes; b.memMax = Math.max(b.memMax, memBytes); b.memN += 1; }
trafficDirty = true;
}
@@ -200,7 +210,10 @@ async function sampleOnce() {
sumRx += st.dRx || 0;
sumTx += st.dTx || 0;
}
addTraffic(sumRx, sumTx);
const coresAll = os.cpus().length || 1;
let sumCpu = 0, sumMem = 0;
for (const st of stats.values()) { sumCpu += st.cpu || 0; sumMem += st.mem || 0; }
addTraffic(sumRx, sumTx, sumCpu / coresAll, sumMem);
const rxNow = [...stats.values()].reduce((a, x) => a + (x.rxBps || 0), 0);
const txNow = [...stats.values()].reduce((a, x) => a + (x.txBps || 0), 0);
rtTraffic.push({ t: Date.now(), rx: rxNow, tx: txNow });
@@ -527,7 +540,20 @@ app.get('/api/traffic', async (req, res) => {
try {
const range = String(req.query.range || 'today');
const today = localYmd();
const sum = (arr, k) => arr.reduce((s, x) => s + (x[k] || 0), 0);
const agg = (rows) => rows.reduce((a, h) => ({
rx: a.rx + (h.rx || 0), tx: a.tx + (h.tx || 0),
cpuSum: a.cpuSum + (h.cpuSum || 0), cpuN: a.cpuN + (h.cpuN || 0),
memSum: a.memSum + (h.memSum || 0), memN: a.memN + (h.memN || 0),
memMax: Math.max(a.memMax, h.memMax || 0),
}), { rx: 0, tx: 0, cpuSum: 0, cpuN: 0, memSum: 0, memN: 0, memMax: 0 });
const shape = (a) => ({
rx: a.rx, tx: a.tx,
cpu: a.cpuN ? a.cpuSum / a.cpuN : 0,
mem: a.memN ? a.memSum / a.memN : 0,
memMax: a.memMax,
});
const sumOf = (pts, k) => pts.reduce((s, x) => s + (x[k] || 0), 0);
let points = [], label = '', unit = 'hour', from = today, to = today;
if (range === 'today' || range === 'yesterday' || range === 'day') {
@@ -536,31 +562,30 @@ app.get('/api/traffic', async (req, res) => {
: range === 'yesterday' ? localYmd(new Date(), -1) : today;
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return res.status(400).json({ error: '日期格式应为 YYYY-MM-DD' });
const day = date === today ? await trafficToday() : await loadTrafficDay(date);
points = day.hours.map((b, i) => ({ label: `${String(i).padStart(2, '0')}:00`, rx: b.rx, tx: b.tx }));
points = day.hours.map((h, i) => ({ label: `${String(i).padStart(2, '0')}:00`, ...shape(h) }));
label = range === 'today' ? '今天' : range === 'yesterday' ? '昨天' : date;
from = to = date;
} else if (range === 'month') {
for (let i = 29; i >= 0; i--) {
const d = localYmd(new Date(), -i);
const day = d === today ? await trafficToday() : await loadTrafficDay(d);
points.push({ label: d.slice(5), date: d, rx: sum(day.hours, 'rx'), tx: sum(day.hours, 'tx') });
points.push({ label: d.slice(5), date: d, ...shape(agg(day.hours)) });
}
label = '近 30 天'; unit = 'day'; from = localYmd(new Date(), -29);
} else if (range === 'year') {
const now = new Date();
const base = new Date(now.getTime() + 8 * 3600e3);
const base = new Date(Date.now() + 8 * 3600e3);
for (let i = 11; i >= 0; i--) {
const m = new Date(Date.UTC(base.getUTCFullYear(), base.getUTCMonth() - i, 1));
const y = m.getUTCFullYear(), mo = m.getUTCMonth() + 1;
const daysInMonth = new Date(Date.UTC(y, mo, 0)).getUTCDate();
let rx = 0, tx = 0;
const rows = [];
for (let d = 1; d <= daysInMonth; d++) {
const key = `${y}-${String(mo).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
if (key > today) break;
const day = key === today ? await trafficToday() : await loadTrafficDay(key);
rx += sum(day.hours, 'rx'); tx += sum(day.hours, 'tx');
rows.push(...day.hours);
}
points.push({ label: `${String(mo).padStart(2, '0')}月`, month: `${y}-${String(mo).padStart(2, '0')}`, rx, tx });
points.push({ label: `${String(mo).padStart(2, '0')}月`, month: `${y}-${String(mo).padStart(2, '0')}`, ...shape(agg(rows)) });
}
label = '近 12 个月'; unit = 'month'; from = localYmd(new Date(), -364);
} else {
@@ -568,12 +593,16 @@ app.get('/api/traffic', async (req, res) => {
}
const cov = await trafficCoverage();
const nowRx = rtTraffic.length ? rtTraffic[rtTraffic.length - 1].rx : 0;
const nowTx = rtTraffic.length ? rtTraffic[rtTraffic.length - 1].tx : 0;
const cores = os.cpus().length || 1;
let nowCpu = 0, nowMem = 0, nowRx = 0, nowTx = 0;
for (const st of stats.values()) { nowCpu += st.cpu || 0; nowMem += st.mem || 0; nowRx += st.rxBps || 0; nowTx += st.txBps || 0; }
res.json({
range, label, unit, from, to, points,
total: { rx: sum(points, 'rx'), tx: sum(points, 'tx') },
now: { rx: nowRx, tx: nowTx },
total: { rx: sumOf(points, 'rx'), tx: sumOf(points, 'tx') },
avg: { cpu: points.length ? sumOf(points, 'cpu') / points.filter(p => p.cpu).length || 0 : 0, mem: sumOf(points, 'mem') / Math.max(1, points.filter(p => p.mem).length) },
peak: { mem: Math.max(0, ...points.map(p => p.memMax || 0)), cpu: Math.max(0, ...points.map(p => p.cpu || 0)) },
now: { rx: nowRx, tx: nowTx, cpu: nowCpu / cores, mem: nowMem },
cores,
realtime: rtTraffic.slice(-120),
coverage: { from: cov.from, days: cov.days, today },
});