diff --git a/node-health/src/checks.ts b/node-health/src/checks.ts new file mode 100644 index 0000000..084b853 --- /dev/null +++ b/node-health/src/checks.ts @@ -0,0 +1,26 @@ +import { IntervalHistogram, monitorEventLoopDelay } from 'node:perf_hooks'; +import { ReadinessDetail, ReadinessFunction, ReadinessStatus } from './readiness'; + +let hist: IntervalHistogram | null = null; + +/** + * Builds a readiness check function that monitors event loop lag. + * @param degradedMs - The threshold in milliseconds above which the status is 'degraded' (default 200 ms). + * @returns A ReadinessFunction that checks event loop lag. + */ +export const buildEventLoopLagCheck = (degradedMs: number = 200): ReadinessFunction => { + if (!hist) { + hist = monitorEventLoopDelay({ resolution: 10 }); + hist.enable(); + } + + return (): ReadinessDetail => { + const lag = hist!.mean / 1e6; // Convert from nanoseconds to milliseconds + const status: ReadinessStatus = lag < degradedMs ? 'ok' : 'degraded'; + return { + name: 'event-loop-lag', + status, + message: `Event loop lag is ${lag.toFixed(2)} ms`, + }; + }; +};