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