import { loadavg, totalmem, freemem, uptime } from "node:os"; import { execSync } from "node:child_process"; import { snapshots } from "./schema.ts"; export async function compute(db, _peers) { const [load1, load5, load15] = loadavg(); const memTotal = totalmem(); const memFree = freemem(); const memUsed = memTotal - memFree; const memTotalMB = Math.round(memTotal / 1024 / 1024); const memUsedMB = Math.round(memUsed / 1024 / 1024); const memUsedPct = Math.round((memUsed / memTotal) * 10000) / 100; let diskTotalGB = 0, diskUsedGB = 0, diskUsedPct = 0; try { const df = execSync("df -B1 / | tail -1", { encoding: "utf-8" }).trim(); const parts = df.split(/\s+/); const total = Number(parts[1]); const used = Number(parts[2]); diskTotalGB = Math.round(total / 1024 / 1024 / 1024 * 100) / 100; diskUsedGB = Math.round(used / 1024 / 1024 / 1024 * 100) / 100; diskUsedPct = total > 0 ? Math.round((used / total) * 10000) / 100 : 0; } catch {} const ts = Date.now(); const uptimeSec = Math.round(uptime()); await db.insert(snapshots).values({ ts, cpuLoad1m: load1, cpuLoad5m: load5, cpuLoad15m: load15, memTotalMB, memUsedMB, memUsedPct, diskTotalGB, diskUsedGB, diskUsedPct, uptimeSec, }); return { cpu: { load1m: load1, load5m: load5, load15m: load15 }, memory: { totalMB: memTotalMB, usedMB: memUsedMB, usedPct: memUsedPct }, disk: { totalGB: diskTotalGB, usedGB: diskUsedGB, usedPct: diskUsedPct }, uptimeSec, }; }