All checks were successful
CI / verification (pull_request) Successful in 59s
GET /health only gave a snapshot, so the monitoring missed the 2026-11-03
saturation and the nights before it. A one-minute tick, armed in the
require.main block, now records host load, CPU by /proc/stat difference
and, when TLS_PROBE_HOSTS is set, the TLS handshake time of each listed
host into an in-memory buffer of 1440 samples (load-history.js, pure).
- /health gains `saturation` ({state: ok|saturated|unknown, since,
coverageMinutes, load1, cores}) and `tls`, appended after the existing
keys. Saturated = the last five samples of an unbroken series all have
load1 > cores; unknown under five samples, after a gap over 3 minutes,
or when the last sample is over 3 minutes old. No sample at start-up,
so the state stays unknown for the first five minutes after a deploy.
- GET /health/history (read token) serves {since, coverageMinutes, cores,
samples}. The buffer restarts from zero at every deploy.
- probeTls() verifies the certificate, times out after 3 s and reports an
error code only. TLS_PROBE_HOSTS is empty by default: no network call in
the tests, the CI or boot-from-copy.sh.
- Dockerfile COPY, REVIEW.md Haut table (and review-levels.py), CLAUDE.md,
docs and .env.example updated.
Refs #73
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
280 lines
11 KiB
JavaScript
280 lines
11 KiB
JavaScript
const http = require("node:http");
|
|
const net = require("node:net");
|
|
const tls = require("node:tls");
|
|
const { setTimeout: delay } = require("node:timers/promises");
|
|
|
|
const { getCpuPercent, getDisk, collectMetrics, cpuPercentBetween } = require("../metrics.js");
|
|
|
|
const TOKEN = "test-token";
|
|
|
|
let logtoServer;
|
|
let logtoUrl;
|
|
let logtoDelayMs;
|
|
let server;
|
|
let baseUrl;
|
|
let handler;
|
|
let api;
|
|
|
|
// Stand-in for the Logto .well-known endpoint, with a settable delay so we can
|
|
// simulate a slow IdP without touching the network.
|
|
function startLogtoStub() {
|
|
logtoDelayMs = 0;
|
|
logtoServer = http.createServer(async (req, res) => {
|
|
if (logtoDelayMs > 0) await delay(logtoDelayMs);
|
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
res.end(JSON.stringify({ issuer: "http://127.0.0.1/oidc" }));
|
|
});
|
|
return new Promise((resolve) => {
|
|
logtoServer.listen(0, "127.0.0.1", () => {
|
|
const { port } = logtoServer.address();
|
|
logtoUrl = `http://127.0.0.1:${port}/oidc/.well-known/openid-configuration`;
|
|
resolve();
|
|
});
|
|
});
|
|
}
|
|
|
|
function startServer() {
|
|
// Fresh import so module-level constants pick up the stubbed env.
|
|
delete require.cache[require.resolve("../index.js")];
|
|
api = require("../index.js");
|
|
({ handler } = api);
|
|
server = http.createServer(handler);
|
|
return new Promise((resolve) => {
|
|
server.listen(0, () => {
|
|
const { port } = server.address();
|
|
baseUrl = `http://127.0.0.1:${port}`;
|
|
resolve();
|
|
});
|
|
});
|
|
}
|
|
|
|
function close(target) {
|
|
return new Promise((resolve) => {
|
|
if (!target) return resolve();
|
|
target.close(() => resolve());
|
|
});
|
|
}
|
|
|
|
async function get(path, { auth = `Bearer ${TOKEN}` } = {}) {
|
|
const headers = {};
|
|
if (auth) headers.Authorization = auth;
|
|
const res = await fetch(`${baseUrl}${path}`, { headers });
|
|
const body = await res.json().catch(() => ({}));
|
|
return { status: res.status, body };
|
|
}
|
|
|
|
beforeEach(async () => {
|
|
await startLogtoStub();
|
|
process.env.HEALTH_TOKEN = TOKEN;
|
|
process.env.LOGTO_HEALTH_URL = logtoUrl;
|
|
// Unset on purpose: the default (no probe) is what the CI and the boot check
|
|
// run, and it must make no network call.
|
|
delete process.env.TLS_PROBE_HOSTS;
|
|
await startServer();
|
|
});
|
|
|
|
afterEach(async () => {
|
|
vi.restoreAllMocks();
|
|
vi.useRealTimers();
|
|
await close(server);
|
|
await close(logtoServer);
|
|
});
|
|
|
|
describe("metrics module", () => {
|
|
test("exposes getCpuPercent, getDisk and collectMetrics", () => {
|
|
expect(typeof getCpuPercent).toBe("function");
|
|
expect(typeof getDisk).toBe("function");
|
|
expect(typeof collectMetrics).toBe("function");
|
|
});
|
|
|
|
test("getDisk returns the four numeric disk fields", () => {
|
|
const disk = getDisk();
|
|
expect(Object.keys(disk)).toEqual(["totalGB", "usedGB", "freeGB", "usagePercent"]);
|
|
for (const value of Object.values(disk)) expect(typeof value).toBe("number");
|
|
});
|
|
|
|
test("collectMetrics returns the cpu/memory/disk slice of /health", async () => {
|
|
const metrics = await collectMetrics();
|
|
expect(Object.keys(metrics)).toEqual(["cpu", "memory", "disk"]);
|
|
expect(Object.keys(metrics.cpu)).toEqual(["model", "cores", "loadAvg", "usagePercent"]);
|
|
expect(Object.keys(metrics.memory)).toEqual(["totalGB", "usedGB", "freeGB", "usagePercent"]);
|
|
expect(metrics.cpu.cores).toBeGreaterThan(0);
|
|
expect(Array.isArray(metrics.cpu.loadAvg)).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe("GET /health", () => {
|
|
test("401 on invalid token", async () => {
|
|
const { status } = await get("/health", { auth: "Bearer wrong" });
|
|
expect(status).toBe(401);
|
|
});
|
|
|
|
test("200 returns the documented payload, field for field", async () => {
|
|
const { status, body } = await get("/health");
|
|
expect(status).toBe(200);
|
|
// Key order is part of the contract consumed by the admin dashboard.
|
|
expect(Object.keys(body)).toEqual([
|
|
"timestamp",
|
|
"hostname",
|
|
"uptime",
|
|
"cpu",
|
|
"memory",
|
|
"disk",
|
|
"logto",
|
|
// #73: appended after the original keys, never in between.
|
|
"saturation",
|
|
"tls",
|
|
]);
|
|
expect(Object.keys(body.cpu)).toEqual(["model", "cores", "loadAvg", "usagePercent"]);
|
|
expect(Object.keys(body.memory)).toEqual(["totalGB", "usedGB", "freeGB", "usagePercent"]);
|
|
expect(Object.keys(body.disk)).toEqual(["totalGB", "usedGB", "freeGB", "usagePercent"]);
|
|
expect(body.logto.status).toBe("up");
|
|
expect(typeof body.logto.responseTimeMs).toBe("number");
|
|
expect(typeof body.uptime).toBe("number");
|
|
expect(typeof body.hostname).toBe("string");
|
|
expect(new Date(body.timestamp).toISOString()).toBe(body.timestamp);
|
|
expect(Object.keys(body.saturation)).toEqual(["state", "since", "coverageMinutes", "load1", "cores"]);
|
|
});
|
|
|
|
test("a fresh start: saturation unknown, coverage 0, tls null (probes disabled)", async () => {
|
|
const { body } = await get("/health");
|
|
expect(body.saturation).toEqual({
|
|
state: "unknown",
|
|
since: null,
|
|
coverageMinutes: 0,
|
|
load1: null,
|
|
cores: body.cpu.cores,
|
|
});
|
|
expect(body.tls).toBeNull();
|
|
});
|
|
|
|
// Latency regression guard. Metrics collection (500ms CPU sample) and the
|
|
// Logto check must run concurrently: serializing them would make /health take
|
|
// 500ms + the Logto response time. With a 1200ms Logto, concurrent lands at
|
|
// ~1200ms while serialized lands at ~1700ms — only the former clears 1.5s.
|
|
test("stays under 1.5s with a slow Logto (metrics stay concurrent)", async () => {
|
|
logtoDelayMs = 1200;
|
|
const start = performance.now();
|
|
const { status, body } = await get("/health");
|
|
const elapsed = performance.now() - start;
|
|
expect(status).toBe(200);
|
|
expect(body.logto.status).toBe("up");
|
|
expect(elapsed).toBeLessThan(1500);
|
|
}, 15000);
|
|
});
|
|
|
|
describe("cpuPercentBetween", () => {
|
|
test("busy share between two readings, null when a reading is missing or no tick elapsed", () => {
|
|
expect(cpuPercentBetween({ idle: 100, total: 200 }, { idle: 125, total: 300 })).toBe(75);
|
|
expect(cpuPercentBetween(null, { idle: 1, total: 2 })).toBeNull();
|
|
expect(cpuPercentBetween({ idle: 1, total: 2 }, null)).toBeNull();
|
|
expect(cpuPercentBetween({ idle: 1, total: 2 }, { idle: 1, total: 2 })).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe("load sampler (#73)", () => {
|
|
test("a tick records load and CPU by difference; the first has no CPU baseline", async () => {
|
|
await api.recordLoadSample();
|
|
await delay(20);
|
|
await api.recordLoadSample();
|
|
const { status, body } = await get("/health/history");
|
|
expect(status).toBe(200);
|
|
expect(Object.keys(body)).toEqual(["since", "coverageMinutes", "cores", "samples"]);
|
|
expect(body.samples).toHaveLength(2);
|
|
expect(Object.keys(body.samples[0])).toEqual(["at", "load1", "load5", "cpuPercent", "tls"]);
|
|
expect(body.samples[0].cpuPercent).toBeNull();
|
|
expect(typeof body.samples[1].cpuPercent).toBe("number");
|
|
expect(typeof body.samples[1].load1).toBe("number");
|
|
expect(body.samples[1].tls).toBeNull();
|
|
expect(body.since).toBe(body.samples[0].at);
|
|
expect(body.coverageMinutes).toBe(0);
|
|
});
|
|
|
|
test("with TLS_PROBE_HOSTS unset a tick opens no TLS connection", async () => {
|
|
const connect = vi.spyOn(tls, "connect");
|
|
await api.recordLoadSample();
|
|
expect(connect).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("the armed sampler leaves saturation unknown for four minutes, known at five", async () => {
|
|
vi.useFakeTimers({ toFake: ["setInterval", "clearInterval", "Date"] });
|
|
const timer = api.startLoadSampler();
|
|
try {
|
|
await vi.advanceTimersByTimeAsync(4 * 60 * 1000);
|
|
expect(api.loadHistory.size()).toBe(4);
|
|
expect((await get("/health")).body.saturation.state).toBe("unknown");
|
|
await vi.advanceTimersByTimeAsync(60 * 1000);
|
|
expect(api.loadHistory.size()).toBe(5);
|
|
const { body } = await get("/health");
|
|
expect(["ok", "saturated"]).toContain(body.saturation.state);
|
|
expect(body.saturation.coverageMinutes).toBe(4);
|
|
} finally {
|
|
clearInterval(timer);
|
|
}
|
|
}, 15000);
|
|
|
|
test("GET /health/history never serves more than 1440 samples", async () => {
|
|
const start = Date.now() - 2000 * 60000;
|
|
for (let i = 0; i < 1500; i++) {
|
|
api.loadHistory.record({ at: start + i * 60000, load1: 1, load5: 1, cpuPercent: 10 });
|
|
}
|
|
const { status, body } = await get("/health/history");
|
|
expect(status).toBe(200);
|
|
expect(body.samples).toHaveLength(1440);
|
|
expect(body.since).toBe(new Date(start + 60 * 60000).toISOString());
|
|
expect(body.coverageMinutes).toBe(1439);
|
|
});
|
|
|
|
test("401 on /health/history without a token", async () => {
|
|
expect((await get("/health/history", { auth: null })).status).toBe(401);
|
|
});
|
|
});
|
|
|
|
describe("TLS_PROBE_HOSTS parsing (#73)", () => {
|
|
test("keeps hostnames, lowercased and deduplicated; drops IPs, ports, paths and junk", () => {
|
|
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
|
|
expect(
|
|
api.parseTlsProbeHosts(
|
|
" git.lacompagniemaximus.com,AUTH.lacompagniemaximus.com,,git.lacompagniemaximus.com," +
|
|
"100.86.30.21,host.example.com:443,host.example.com/x,localhost,-bad.example.com,::1",
|
|
),
|
|
).toEqual(["git.lacompagniemaximus.com", "auth.lacompagniemaximus.com"]);
|
|
expect(warn).toHaveBeenCalledTimes(6);
|
|
expect(api.parseTlsProbeHosts(undefined)).toEqual([]);
|
|
expect(api.parseTlsProbeHosts("")).toEqual([]);
|
|
});
|
|
});
|
|
|
|
// Local sockets only: the positive handshake path needs a certificate a test
|
|
// cannot mint without a dependency; it is checked in production after deploy.
|
|
describe("probeTls (#73)", () => {
|
|
function listen(onConnection) {
|
|
const srv = net.createServer(onConnection);
|
|
return new Promise((resolve) => srv.listen(0, "127.0.0.1", () => resolve(srv)));
|
|
}
|
|
|
|
test("a closed port comes back as its error code", async () => {
|
|
const srv = await listen(() => {});
|
|
const { port } = srv.address();
|
|
await close(srv);
|
|
const result = await api.probeTls("127.0.0.1", { port });
|
|
expect(result).toEqual({ host: "127.0.0.1", handshakeMs: null, error: "ECONNREFUSED" });
|
|
});
|
|
|
|
test("a peer that hangs up before the handshake: a code, never a message", async () => {
|
|
const srv = await listen((socket) => socket.destroy());
|
|
const result = await api.probeTls("127.0.0.1", { port: srv.address().port });
|
|
await close(srv);
|
|
expect(result.handshakeMs).toBeNull();
|
|
expect(result.error).toMatch(/^[A-Z_]+$/);
|
|
});
|
|
|
|
test("a peer that never answers times out", async () => {
|
|
const sockets = [];
|
|
const srv = await listen((socket) => sockets.push(socket));
|
|
const result = await api.probeTls("127.0.0.1", { port: srv.address().port, timeoutMs: 150 });
|
|
for (const socket of sockets) socket.destroy();
|
|
await close(srv);
|
|
expect(result).toEqual({ host: "127.0.0.1", handshakeMs: null, error: "timeout" });
|
|
});
|
|
});
|