Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - only node:perf_hooks exposes the event loop delay histogram, and node:os the load average.
2import * as NodeOS from "node:os";
3import * as NodePerfHooks from "node:perf_hooks";
4
5import type { ServerEventLoopStall } from "@t3tools/contracts";
6import { RotatingFileSink } from "@t3tools/shared/logging";
7import * as Context from "effect/Context";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Metric from "effect/Metric";
12import * as Path from "effect/Path";
13import * as Ref from "effect/Ref";
14import * as Schema from "effect/Schema";
15import type * as Scope from "effect/Scope";
16import * as Semaphore from "effect/Semaphore";
17
18import * as ServerConfig from "../config.ts";
19import * as Metrics from "./Metrics.ts";
20
21// Subtract the histogram's timer resolution; this can undercount stalls by up to RESOLUTION_MS.
22const RESOLUTION_MS = 1000;
23const STALL_THRESHOLD_MS = 2000;
24const SAMPLE_INTERVAL = "30 seconds";
25const STALL_LOG_MAX_BYTES = 256 * 1024;
26// Long enough that users felt it. Shorter stalls stay in the log only.
27const NOTICEABLE_STALL_MS = 5000;
28// Clients show what they get, so an old stall must not explain a new drop.
29const NOTICEABLE_STALL_MAX_AGE_MS = 5 * 60_000;
30
31export class EventLoopMonitor extends Context.Reference<{
32 /**
33 * The latest stall of 5 s or more, if seen in the last 5 minutes. It samples
34 * first, so a stall that ended just before a client reconnected is included.
35 */
36 readonly latestNoticeableStall: Effect.Effect<ServerEventLoopStall | undefined>;
37}>("t3/observability/EventLoopMonitor", {
38 // @effect-diagnostics-next-line effectSucceedWithVoid:off - This optional result requires undefined, not the wider void type.
39 defaultValue: () => ({ latestNoticeableStall: Effect.succeed(undefined) }),
40}) {}
41
42/** Delay in ns, active time in ms, CPU in µs. */
43export interface EventLoopReadings {
44 readonly delayMaxNs: number;
45 readonly activeMs: number;
46 readonly utilization: number;
47 readonly usage: Pick<
48 NodeJS.ResourceUsage,
49 | "userCPUTime"
50 | "systemCPUTime"
51 | "majorPageFault"
52 | "minorPageFault"
53 | "involuntaryContextSwitches"
54 >;
55 readonly rssBytes: number;
56 readonly heapUsedBytes: number;
57 /** Wall time the readings cover. */
58 readonly elapsedMs: number;
59 /** One-minute load average, undefined on Windows. */
60 readonly loadAverage: number | undefined;
61 readonly cpuCount: number;
62}
63
64// Node skips the first gap after a reset, so a stall right at a sample boundary can be missed.
65const makeNodeSampler = Effect.gen(function* () {
66 const histogram = yield* Effect.acquireRelease(
67 Effect.sync(() => {
68 const histogram = NodePerfHooks.monitorEventLoopDelay({ resolution: RESOLUTION_MS });
69 histogram.enable();
70 return histogram;
71 }),
72 (histogram) => Effect.sync(() => histogram.disable()),
73 );
74 let elu = NodePerfHooks.performance.eventLoopUtilization();
75 let usage = process.resourceUsage();
76 let sampledAt = NodePerfHooks.performance.now();
77
78 // @effect-diagnostics-next-line returnEffectInGen:off - the read effect is the result.
79 return Effect.sync(() => {
80 const nextElu = NodePerfHooks.performance.eventLoopUtilization();
81 const nextUsage = process.resourceUsage();
82 const nextSampledAt = NodePerfHooks.performance.now();
83 const memory = process.memoryUsage();
84 const loop = NodePerfHooks.performance.eventLoopUtilization(nextElu, elu);
85 const readings: EventLoopReadings = {
86 delayMaxNs: histogram.max,
87 activeMs: loop.active,
88 utilization: loop.utilization,
89 usage: {
90 userCPUTime: nextUsage.userCPUTime - usage.userCPUTime,
91 systemCPUTime: nextUsage.systemCPUTime - usage.systemCPUTime,
92 majorPageFault: nextUsage.majorPageFault - usage.majorPageFault,
93 minorPageFault: nextUsage.minorPageFault - usage.minorPageFault,
94 involuntaryContextSwitches:
95 nextUsage.involuntaryContextSwitches - usage.involuntaryContextSwitches,
96 },
97 rssBytes: memory.rss,
98 heapUsedBytes: memory.heapUsed,
99 elapsedMs: nextSampledAt - sampledAt,
100 // Windows has no load average and reports 0, which a running process never sees elsewhere.
101 loadAverage: NodeOS.loadavg()[0] || undefined,
102 cpuCount: NodeOS.availableParallelism(),
103 };
104 histogram.reset();
105 elu = nextElu;
106 usage = nextUsage;
107 sampledAt = nextSampledAt;
108 return readings;
109 });
110});
111
112export const stallMs = ({ delayMaxNs, activeMs }: EventLoopReadings) => {
113 const delayMs = Math.round(delayMaxNs / 1e6) - RESOLUTION_MS;
114 // libuv clocks run during macOS/Windows sleep; idle poll time distinguishes it from stalls.
115 if (delayMs <= STALL_THRESHOLD_MS || activeMs < delayMs) return undefined;
116 return delayMs;
117};
118
119// Untraced: it runs inside every 30-second tick, which already has the monitor's own span.
120const recordGauges = Effect.fnUntraced(function* (readings: EventLoopReadings) {
121 const cpuMs = (readings.usage.userCPUTime + readings.usage.systemCPUTime) / 1000;
122 yield* Metric.update(Metrics.serverResidentBytes, readings.rssBytes);
123 yield* Metric.update(Metrics.serverHeapUsedBytes, readings.heapUsedBytes);
124 yield* Metric.update(Metrics.serverEventLoopUtilization, readings.utilization);
125 yield* Metric.update(
126 Metrics.serverEventLoopDelayMax,
127 Math.max(0, Math.round(readings.delayMaxNs / 1e6) - RESOLUTION_MS),
128 );
129 if (readings.elapsedMs > 0) {
130 yield* Metric.update(Metrics.serverCpuUtilization, cpuMs / readings.elapsedMs);
131 }
132});
133
134const encodeStallLine = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
135
136export interface StallLogOptions {
137 readonly filePath: string;
138 readonly maxBytes: number;
139}
140
141const layerWith = (
142 makeSampler: Effect.Effect<Effect.Effect<EventLoopReadings>, never, Scope.Scope>,
143 stallLog: StallLogOptions,
144) =>
145 Layer.effect(
146 EventLoopMonitor,
147 Effect.gen(function* () {
148 const sample = yield* makeSampler;
149 // Clients sample on connect as well as the timer, and the sampler resets shared state.
150 const sampling = yield* Semaphore.make(1);
151 const warmedUp = yield* Ref.make(false);
152 const latestNoticeableStall = yield* Ref.make<
153 { readonly stall: ServerEventLoopStall; readonly detectedAtMs: number } | undefined
154 >(undefined);
155 const stallSink = yield* Effect.try(
156 () =>
157 new RotatingFileSink({
158 filePath: stallLog.filePath,
159 maxBytes: stallLog.maxBytes,
160 maxFiles: 1,
161 throwOnError: true,
162 }),
163 ).pipe(
164 Effect.catch(() =>
165 Effect.logWarning("event loop stall log unavailable", {
166 filePath: stallLog.filePath,
167 }).pipe(Effect.as(undefined)),
168 ),
169 );
170 const tick = Effect.gen(function* () {
171 const readings = yield* sample;
172 yield* recordGauges(readings);
173 const delayMaxMs = stallMs(readings);
174 if (delayMaxMs === undefined) return;
175 const { utilization, usage, rssBytes, loadAverage, cpuCount } = readings;
176 const now = yield* DateTime.now;
177 const detectedAt = DateTime.formatIso(now);
178 if (delayMaxMs >= NOTICEABLE_STALL_MS) {
179 yield* Ref.set(latestNoticeableStall, {
180 detectedAtMs: DateTime.toEpochMillis(now),
181 stall: {
182 detectedAt,
183 durationMs: delayMaxMs,
184 ...(loadAverage === undefined
185 ? {}
186 : { loadAverage: Math.round(loadAverage * 10) / 10 }),
187 cpuCount,
188 },
189 });
190 }
191 const attributes = {
192 delayMaxMs,
193 utilization: Math.round(utilization * 100) / 100,
194 cpuUserMs: Math.round(usage.userCPUTime / 1000),
195 cpuSystemMs: Math.round(usage.systemCPUTime / 1000),
196 majorPageFaults: usage.majorPageFault,
197 minorPageFaults: usage.minorPageFault,
198 involuntaryContextSwitches: usage.involuntaryContextSwitches,
199 rssMb: Math.round(rssBytes / 1024 / 1024),
200 };
201 yield* Effect.logWarning(`event loop stalled for ${delayMaxMs} ms`).pipe(
202 Effect.withSpan("server.eventLoop.stall", { root: true, level: "Warn", attributes }),
203 );
204 if (stallSink !== undefined) {
205 yield* encodeStallLine({ time: detectedAt, ...attributes }).pipe(
206 Effect.flatMap((line) => Effect.try(() => stallSink.write(`${line}\n`))),
207 Effect.catch(() =>
208 Effect.logWarning("event loop stall log write failed", {
209 filePath: stallLog.filePath,
210 }),
211 ),
212 );
213 }
214 }).pipe(sampling.withPermits(1));
215 const wait = Effect.sleep(SAMPLE_INTERVAL);
216 // The first sample includes migrations and bootstrap; skip expected startup stalls.
217 yield* wait.pipe(
218 Effect.andThen(sampling.withPermits(1)(sample)),
219 Effect.andThen(Ref.set(warmedUp, true)),
220 Effect.andThen(wait.pipe(Effect.andThen(tick), Effect.forever)),
221 Effect.forkScoped,
222 );
223
224 return EventLoopMonitor.of({
225 latestNoticeableStall: Effect.gen(function* () {
226 if (yield* Ref.get(warmedUp)) yield* tick;
227 const latest = yield* Ref.get(latestNoticeableStall);
228 if (latest === undefined) return undefined;
229 const ageMs = DateTime.toEpochMillis(yield* DateTime.now) - latest.detectedAtMs;
230 return ageMs <= NOTICEABLE_STALL_MAX_AGE_MS ? latest.stall : undefined;
231 }),
232 });
233 }),
234 );
235
236export const layer = Layer.unwrap(
237 Effect.gen(function* () {
238 const { serverTracePath } = yield* ServerConfig.ServerConfig;
239 const path = yield* Path.Path;
240 return layerWith(makeNodeSampler, {
241 filePath: path.join(path.dirname(serverTracePath), "event-loop-stalls.ndjson"),
242 maxBytes: STALL_LOG_MAX_BYTES,
243 });
244 }),
245);