Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - only node:perf_hooks exposes the event loop delay histogram.
2import * as NodePerfHooks from "node:perf_hooks";
3
4import { RotatingFileSink } from "@t3tools/shared/logging";
5import * as DateTime from "effect/DateTime";
6import * as Effect from "effect/Effect";
7import * as Layer from "effect/Layer";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10import type * as Scope from "effect/Scope";
11
12import * as ServerConfig from "../config.ts";
13
14// Subtract the histogram resolution to exclude idle delay; stalls can undercount by that much.
15// Sample startup more closely, then reduce wakeups so an idle backend stays idle.
16const STARTUP = { resolutionMs: 100, stallThresholdMs: 250, sampleIntervalMs: 1000 };
17const STEADY = { resolutionMs: 1000, stallThresholdMs: 2000, sampleIntervalMs: 30_000 };
18const STARTUP_SAMPLES = 30;
19const SLEEP_CHECK_MS = 5000;
20const STALL_LOG_MAX_BYTES = 256 * 1024;
21
22/** Delay in ns, active time in ms, CPU in µs. */
23export interface EventLoopReadings {
24 readonly delayMaxNs: number;
25 /** Timer drift also covers startup and the histogram's first gap after reset. */
26 readonly tickDelayMs?: number;
27 readonly activeMs: number;
28 readonly utilization: number;
29 readonly usage: Pick<
30 NodeJS.ResourceUsage,
31 | "userCPUTime"
32 | "systemCPUTime"
33 | "majorPageFault"
34 | "minorPageFault"
35 | "involuntaryContextSwitches"
36 >;
37 readonly rssBytes: number;
38 readonly steady?: boolean;
39}
40
41// Node skips the first gap after a reset, so a stall right at a sample boundary can be missed.
42const makeNodeSampler = Effect.gen(function* () {
43 const monitor = (resolution: number) => {
44 const histogram = NodePerfHooks.monitorEventLoopDelay({ resolution });
45 histogram.enable();
46 return histogram;
47 };
48 let histogram = monitor(STARTUP.resolutionMs);
49 yield* Effect.addFinalizer(() => Effect.sync(() => histogram.disable()));
50 let samplesRead = 0;
51 let elu = NodePerfHooks.performance.eventLoopUtilization();
52 let usage = process.resourceUsage();
53 let sampledAt = NodePerfHooks.performance.now();
54 // Cover stalls before the histogram's first wakeup.
55 const armedAt = sampledAt;
56 let startupDelayMs = 0;
57 // @effect-diagnostics-next-line globalTimersInEffect:off -- The native boot probe must arm before Effect scheduling can run startup work.
58 const startupProbe = setTimeout(() => {
59 startupDelayMs = Math.max(0, NodePerfHooks.performance.now() - armedAt - STARTUP.resolutionMs);
60 }, STARTUP.resolutionMs);
61 yield* Effect.addFinalizer(() => Effect.sync(() => clearTimeout(startupProbe)));
62
63 // @effect-diagnostics-next-line returnEffectInGen:off - the read effect is the result.
64 return Effect.sync(() => {
65 const nextElu = NodePerfHooks.performance.eventLoopUtilization();
66 const nextUsage = process.resourceUsage();
67 const now = NodePerfHooks.performance.now();
68 const loop = NodePerfHooks.performance.eventLoopUtilization(nextElu, elu);
69 const steady = samplesRead >= STARTUP_SAMPLES;
70 const intervalMs = (steady ? STEADY : STARTUP).sampleIntervalMs;
71 const readings: EventLoopReadings = {
72 delayMaxNs: histogram.max,
73 tickDelayMs: Math.max(startupDelayMs, now - sampledAt - intervalMs, 0),
74 activeMs: loop.active,
75 utilization: loop.utilization,
76 usage: {
77 userCPUTime: nextUsage.userCPUTime - usage.userCPUTime,
78 systemCPUTime: nextUsage.systemCPUTime - usage.systemCPUTime,
79 majorPageFault: nextUsage.majorPageFault - usage.majorPageFault,
80 minorPageFault: nextUsage.minorPageFault - usage.minorPageFault,
81 involuntaryContextSwitches:
82 nextUsage.involuntaryContextSwitches - usage.involuntaryContextSwitches,
83 },
84 rssBytes: process.memoryUsage.rss(),
85 ...(steady ? { steady } : {}),
86 };
87 samplesRead += 1;
88 if (samplesRead === STARTUP_SAMPLES) {
89 histogram.disable();
90 histogram = monitor(STEADY.resolutionMs);
91 } else {
92 histogram.reset();
93 }
94 startupDelayMs = 0;
95 elu = nextElu;
96 usage = nextUsage;
97 sampledAt = now;
98 return readings;
99 });
100});
101
102/**
103 * Returns the stall to report for one sample in ms, or undefined when there was none.
104 */
105export const stallMs = ({
106 delayMaxNs,
107 tickDelayMs = 0,
108 activeMs,
109 usage,
110 steady,
111}: EventLoopReadings) => {
112 const { resolutionMs, stallThresholdMs } = steady ? STEADY : STARTUP;
113 const delayMs = Math.round(Math.max(delayMaxNs / 1e6 - resolutionMs, tickDelayMs));
114 if (delayMs <= stallThresholdMs) return undefined;
115 // System sleep produces an idle gap. CPU time covers startup before ELU counts active time;
116 // short stalls bypass this check because those readings can lag.
117 const busyMs = Math.max(activeMs, (usage.userCPUTime + usage.systemCPUTime) / 1000);
118 if (delayMs > SLEEP_CHECK_MS && busyMs < delayMs / 2) return undefined;
119 return delayMs;
120};
121
122const encodeStallLine = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
123
124export interface StallLogOptions {
125 readonly filePath: string;
126 readonly maxBytes: number;
127}
128
129export const layerWith = (
130 makeSampler: Effect.Effect<Effect.Effect<EventLoopReadings>, never, Scope.Scope>,
131 stallLog: StallLogOptions,
132) =>
133 Layer.effectDiscard(
134 Effect.gen(function* () {
135 const sample = yield* makeSampler;
136 const stallSink = yield* Effect.try(
137 () =>
138 new RotatingFileSink({
139 filePath: stallLog.filePath,
140 maxBytes: stallLog.maxBytes,
141 maxFiles: 1,
142 throwOnError: true,
143 }),
144 ).pipe(
145 Effect.catch(() =>
146 Effect.logWarning("event loop stall log unavailable", {
147 filePath: stallLog.filePath,
148 }).pipe(Effect.as(undefined)),
149 ),
150 );
151 const tick = Effect.gen(function* () {
152 const readings = yield* sample;
153 const delayMaxMs = stallMs(readings);
154 if (delayMaxMs === undefined) return;
155 const { utilization, usage, rssBytes } = readings;
156 const attributes = {
157 delayMaxMs,
158 utilization: Math.round(utilization * 100) / 100,
159 cpuUserMs: Math.round(usage.userCPUTime / 1000),
160 cpuSystemMs: Math.round(usage.systemCPUTime / 1000),
161 majorPageFaults: usage.majorPageFault,
162 minorPageFaults: usage.minorPageFault,
163 involuntaryContextSwitches: usage.involuntaryContextSwitches,
164 rssMb: Math.round(rssBytes / 1024 / 1024),
165 };
166 yield* Effect.logWarning(`event loop stalled for ${delayMaxMs} ms`).pipe(
167 Effect.withSpan("server.eventLoop.stall", { root: true, level: "Warn", attributes }),
168 );
169 if (stallSink !== undefined) {
170 const time = DateTime.formatIso(yield* DateTime.now);
171 yield* encodeStallLine({ time, ...attributes }).pipe(
172 Effect.flatMap((line) => Effect.try(() => stallSink.write(`${line}\n`))),
173 Effect.catch(() =>
174 Effect.logWarning("event loop stall log write failed", {
175 filePath: stallLog.filePath,
176 }),
177 ),
178 );
179 }
180 });
181 const sampleAfter = (intervalMs: number) =>
182 Effect.sleep(intervalMs).pipe(Effect.andThen(tick));
183 yield* Effect.gen(function* () {
184 for (let sample = 0; sample < STARTUP_SAMPLES; sample++) {
185 yield* sampleAfter(STARTUP.sampleIntervalMs);
186 }
187 return yield* sampleAfter(STEADY.sampleIntervalMs).pipe(Effect.forever);
188 }).pipe(Effect.forkScoped);
189 }),
190 );
191
192export const layer = Layer.unwrap(
193 Effect.gen(function* () {
194 const { serverTracePath } = yield* ServerConfig.ServerConfig;
195 const path = yield* Path.Path;
196 return layerWith(makeNodeSampler, {
197 filePath: path.join(path.dirname(serverTracePath), "event-loop-stalls.ndjson"),
198 maxBytes: STALL_LOG_MAX_BYTES,
199 });
200 }),
201);