/** * @file loop-delay.js * @description How long this server's event loop was held up — what an * operator sees as a laggy dashboard or terminal: every request, hook and * keystroke echo waits for it. One `monitorEventLoopDelay` histogram for the * whole process, sampled every 20 ms and reset each minute, so `loopDelay()` * describes the last full minute (the running one until the first minute * ends). Read by `GET /api/metrics` (Prometheus gauges) and * `GET /api/settings/info` (the System Health score). * @author Nguyễn Ngọc Trí Vĩ */ const { monitorEventLoopDelay } = require("perf_hooks"); const WINDOW_MS = 60_000; const histogram = monitorEventLoopDelay({ resolution: 20 }); histogram.enable(); const read = () => ({ p50: histogram.percentile(50), p99: histogram.percentile(99), max: histogram.max, }); let lastWindow = null; // the last full minute, reported until the next one ends setInterval(() => { lastWindow = read(); histogram.reset(); }, WINDOW_MS).unref(); /** `{p50, p99, max}` in nanoseconds over the last minute. */ function loopDelay() { return lastWindow || read(); } module.exports = { loopDelay, WINDOW_MS };