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 Metric from "effect/Metric";
9import * as Path from "effect/Path";
10import * as Schema from "effect/Schema";
11import type * as Scope from "effect/Scope";
12
13import * as ServerConfig from "../config.ts";
14import * as Metrics from "./Metrics.ts";
15
16// Node's delay histogram wakes a native timer every RESOLUTION_MS and records the
17// gap between wakeups, so an idle loop reads about RESOLUTION_MS and a stall of S
18// reads between S and S + RESOLUTION_MS. We subtract the resolution, so a delay can
19// undercount a stall by up to RESOLUTION_MS.
20const RESOLUTION_MS = 1000;
21const STALL_THRESHOLD_MS = 2000;
22const SAMPLE_INTERVAL = "30 seconds";
23const STALL_LOG_MAX_BYTES = 256 * 1024;
24
25/** Delay in ns, active time in ms, CPU in µs. */
26export interface EventLoopReadings {
27 readonly delayMaxNs: number;
28 readonly activeMs: number;
29 readonly utilization: number;
30 readonly usage: Pick<
31 NodeJS.ResourceUsage,
32 | "userCPUTime"
33 | "systemCPUTime"
34 | "majorPageFault"
35 | "minorPageFault"
36 | "involuntaryContextSwitches"
37 >;
38 readonly rssBytes: number;
39 readonly heapUsedBytes: number;
40 /** Wall time the readings cover. */
41 readonly elapsedMs: number;
42}
43
44// Node skips the first gap after a reset, so a stall right at a sample boundary can be missed.
45const makeNodeSampler = Effect.gen(function* () {
46 const histogram = yield* Effect.acquireRelease(
47 Effect.sync(() => {
48 const histogram = NodePerfHooks.monitorEventLoopDelay({ resolution: RESOLUTION_MS });
49 histogram.enable();
50 return histogram;
51 }),
52 (histogram) => Effect.sync(() => histogram.disable()),
53 );
54 let elu = NodePerfHooks.performance.eventLoopUtilization();
55 let usage = process.resourceUsage();
56 let sampledAt = NodePerfHooks.performance.now();
57
58 // @effect-diagnostics-next-line returnEffectInGen:off - the read effect is the result.
59 return Effect.sync(() => {
60 const nextElu = NodePerfHooks.performance.eventLoopUtilization();
61 const nextUsage = process.resourceUsage();
62 const nextSampledAt = NodePerfHooks.performance.now();
63 const memory = process.memoryUsage();
64 const loop = NodePerfHooks.performance.eventLoopUtilization(nextElu, elu);
65 const readings: EventLoopReadings = {
66 delayMaxNs: histogram.max,
67 activeMs: loop.active,
68 utilization: loop.utilization,
69 usage: {
70 userCPUTime: nextUsage.userCPUTime - usage.userCPUTime,
71 systemCPUTime: nextUsage.systemCPUTime - usage.systemCPUTime,
72 majorPageFault: nextUsage.majorPageFault - usage.majorPageFault,
73 minorPageFault: nextUsage.minorPageFault - usage.minorPageFault,
74 involuntaryContextSwitches:
75 nextUsage.involuntaryContextSwitches - usage.involuntaryContextSwitches,
76 },
77 rssBytes: memory.rss,
78 heapUsedBytes: memory.heapUsed,
79 elapsedMs: nextSampledAt - sampledAt,
80 };
81 histogram.reset();
82 elu = nextElu;
83 usage = nextUsage;
84 sampledAt = nextSampledAt;
85 return readings;
86 });
87});
88
89export const stallMs = ({ delayMaxNs, activeMs }: EventLoopReadings) => {
90 const delayMs = Math.round(delayMaxNs / 1e6) - RESOLUTION_MS;
91 // libuv's clock keeps running while the system sleeps on macOS and Windows, so a
92 // sleep also reads as delay, but the loop spent it idle in poll.
93 if (delayMs <= STALL_THRESHOLD_MS || activeMs < delayMs) return undefined;
94 return delayMs;
95};
96
97// Untraced: it runs inside every 30-second tick, which already has the monitor's own span.
98const recordGauges = Effect.fnUntraced(function* (readings: EventLoopReadings) {
99 const cpuMs = (readings.usage.userCPUTime + readings.usage.systemCPUTime) / 1000;
100 yield* Metric.update(Metrics.serverResidentBytes, readings.rssBytes);
101 yield* Metric.update(Metrics.serverHeapUsedBytes, readings.heapUsedBytes);
102 yield* Metric.update(Metrics.serverEventLoopUtilization, readings.utilization);
103 yield* Metric.update(
104 Metrics.serverEventLoopDelayMax,
105 Math.max(0, Math.round(readings.delayMaxNs / 1e6) - RESOLUTION_MS),
106 );
107 if (readings.elapsedMs > 0) {
108 yield* Metric.update(Metrics.serverCpuUtilization, cpuMs / readings.elapsedMs);
109 }
110});
111
112const encodeStallLine = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
113
114export interface StallLogOptions {
115 readonly filePath: string;
116 readonly maxBytes: number;
117}
118
119export const layerWith = (
120 makeSampler: Effect.Effect<Effect.Effect<EventLoopReadings>, never, Scope.Scope>,
121 stallLog: StallLogOptions,
122) =>
123 Layer.effectDiscard(
124 Effect.gen(function* () {
125 const sample = yield* makeSampler;
126 const stallSink = yield* Effect.try(
127 () =>
128 new RotatingFileSink({
129 filePath: stallLog.filePath,
130 maxBytes: stallLog.maxBytes,
131 maxFiles: 1,
132 throwOnError: true,
133 }),
134 ).pipe(
135 Effect.catch(() =>
136 Effect.logWarning("event loop stall log unavailable", {
137 filePath: stallLog.filePath,
138 }).pipe(Effect.as(undefined)),
139 ),
140 );
141 const tick = Effect.gen(function* () {
142 const readings = yield* sample;
143 yield* recordGauges(readings);
144 const delayMaxMs = stallMs(readings);
145 if (delayMaxMs === undefined) return;
146 const { utilization, usage, rssBytes } = readings;
147 const attributes = {
148 delayMaxMs,
149 utilization: Math.round(utilization * 100) / 100,
150 cpuUserMs: Math.round(usage.userCPUTime / 1000),
151 cpuSystemMs: Math.round(usage.systemCPUTime / 1000),
152 majorPageFaults: usage.majorPageFault,
153 minorPageFaults: usage.minorPageFault,
154 involuntaryContextSwitches: usage.involuntaryContextSwitches,
155 rssMb: Math.round(rssBytes / 1024 / 1024),
156 };
157 yield* Effect.logWarning(`event loop stalled for ${delayMaxMs} ms`).pipe(
158 Effect.withSpan("server.eventLoop.stall", { root: true, level: "Warn", attributes }),
159 );
160 if (stallSink !== undefined) {
161 const time = DateTime.formatIso(yield* DateTime.now);
162 yield* encodeStallLine({ time, ...attributes }).pipe(
163 Effect.flatMap((line) => Effect.try(() => stallSink.write(`${line}\n`))),
164 Effect.catch(() =>
165 Effect.logWarning("event loop stall log write failed", {
166 filePath: stallLog.filePath,
167 }),
168 ),
169 );
170 }
171 });
172 const wait = Effect.sleep(SAMPLE_INTERVAL);
173 // The layer builds before the rest of the server, so the first sample covers
174 // startup work such as migrations and projection bootstrap. That can block the
175 // loop for seconds on a large database, so skip it rather than warn at every
176 // launch.
177 yield* wait.pipe(
178 Effect.andThen(sample),
179 Effect.andThen(wait.pipe(Effect.andThen(tick), Effect.forever)),
180 Effect.forkScoped,
181 );
182 }),
183 );
184
185export const layer = Layer.unwrap(
186 Effect.gen(function* () {
187 const { serverTracePath } = yield* ServerConfig.ServerConfig;
188 const path = yield* Path.Path;
189 return layerWith(makeNodeSampler, {
190 filePath: path.join(path.dirname(serverTracePath), "event-loop-stalls.ndjson"),
191 maxBytes: STALL_LOG_MAX_BYTES,
192 });
193 }),
194);