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