diff --git a/posimai-dev/server.js b/posimai-dev/server.js index 2f660c30..69579916 100644 --- a/posimai-dev/server.js +++ b/posimai-dev/server.js @@ -39,31 +39,43 @@ app.get('/api/sessions/:id', (req, res) => { // ── ヘルス & メトリクス API (/api/health) ────────────────────── // Atlas など外部から参照される。CORS ヘッダーを付与して Vercel 上の Atlas からも取得可能にする +function getCpuSample() { + return os.cpus().map((c) => { + const total = Object.values(c.times).reduce((a, b) => a + b, 0); + return { total, idle: c.times.idle }; + }); +} + app.get('/api/health', (req, res) => { res.setHeader('Access-Control-Allow-Origin', '*'); const mem = os.freemem(); const total = os.totalmem(); - const cpus = os.cpus(); - // CPU 使用率: 全コアの平均(起動時 idle から差し引く簡易計算) - const cpuUsage = cpus.reduce((sum, c) => { - const t = Object.values(c.times).reduce((a, b) => a + b, 0); - return sum + ((t - c.times.idle) / t) * 100; - }, 0) / cpus.length; + // CPU: 100ms 間隔の2サンプルで実使用率を計算 + const s1 = getCpuSample(); + setTimeout(() => { + const s2 = getCpuSample(); + const cpuPct = s1.reduce((sum, c1, i) => { + const c2 = s2[i]; + const dIdle = c2.idle - c1.idle; + const dTotal = c2.total - c1.total; + return sum + (dTotal > 0 ? (1 - dIdle / dTotal) * 100 : 0); + }, 0) / s1.length; - res.json({ - ok: true, - hostname: os.hostname(), - uptime_s: Math.floor(os.uptime()), - cpu_pct: Math.round(cpuUsage), - mem_used_mb: Math.round((total - mem) / 1024 / 1024), - mem_total_mb: Math.round(total / 1024 / 1024), - active_sessions: wss.clients ? wss.clients.size : 0, - node_version: process.version, - platform: os.platform(), - timestamp: new Date().toISOString(), - }); + res.json({ + ok: true, + hostname: os.hostname(), + uptime_s: Math.floor(os.uptime()), + cpu_pct: Math.round(cpuPct), + mem_used_mb: Math.round((total - mem) / 1024 / 1024), + mem_total_mb: Math.round(total / 1024 / 1024), + active_sessions: wss.clients ? wss.clients.size : 0, + node_version: process.version, + platform: os.platform(), + timestamp: new Date().toISOString(), + }); + }, 100); }); // Tailscale証明書を自動検出