Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

EventLoopMonitor.ts

244 lines9.6 KB

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;
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 return Effect.sync(() => {
79 const nextElu = NodePerfHooks.performance.eventLoopUtilization();
80 const nextUsage = process.resourceUsage();
81 const nextSampledAt = NodePerfHooks.performance.now();
82 const memory = process.memoryUsage();
83 const loop = NodePerfHooks.performance.eventLoopUtilization(nextElu, elu);
84 const readings: EventLoopReadings = {
85 delayMaxNs: histogram.max,
86 activeMs: loop.active,
87 utilization: loop.utilization,
88 usage: {
89 userCPUTime: nextUsage.userCPUTime - usage.userCPUTime,
90 systemCPUTime: nextUsage.systemCPUTime - usage.systemCPUTime,
91 majorPageFault: nextUsage.majorPageFault - usage.majorPageFault,
92 minorPageFault: nextUsage.minorPageFault - usage.minorPageFault,
93 involuntaryContextSwitches:
94 nextUsage.involuntaryContextSwitches - usage.involuntaryContextSwitches,
95 },
96 rssBytes: memory.rss,
97 heapUsedBytes: memory.heapUsed,
98 elapsedMs: nextSampledAt - sampledAt,
99 // Windows has no load average and reports 0, which a running process never sees elsewhere.
100 loadAverage: NodeOS.loadavg()[0] || undefined,
101 cpuCount: NodeOS.availableParallelism(),
102 };
103 histogram.reset();
104 elu = nextElu;
105 usage = nextUsage;
106 sampledAt = nextSampledAt;
107 return readings;
108 });
109});
110​
111export const stallMs = ({ delayMaxNs, activeMs }: EventLoopReadings) => {
112 const delayMs = Math.round(delayMaxNs / 1e6) - RESOLUTION_MS;
113 // libuv clocks run during macOS/Windows sleep; idle poll time distinguishes it from stalls.
114 if (delayMs <= STALL_THRESHOLD_MS || activeMs < delayMs) return undefined;
115 return delayMs;
116};
117​
118// Untraced: it runs inside every 30-second tick, which already has the monitor's own span.
119const recordGauges = Effect.fnUntraced(function* (readings: EventLoopReadings) {
120 const cpuMs = (readings.usage.userCPUTime + readings.usage.systemCPUTime) / 1000;
121 yield* Metric.update(Metrics.serverResidentBytes, readings.rssBytes);
122 yield* Metric.update(Metrics.serverHeapUsedBytes, readings.heapUsedBytes);
123 yield* Metric.update(Metrics.serverEventLoopUtilization, readings.utilization);
124 yield* Metric.update(
125 Metrics.serverEventLoopDelayMax,
126 Math.max(0, Math.round(readings.delayMaxNs / 1e6) - RESOLUTION_MS),
127 );
128 if (readings.elapsedMs > 0) {
129 yield* Metric.update(Metrics.serverCpuUtilization, cpuMs / readings.elapsedMs);
130 }
131});
132​
133const encodeStallLine = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
134​
135export interface StallLogOptions {
136 readonly filePath: string;
137 readonly maxBytes: number;
139​
140const layerWith = (
141 makeSampler: Effect.Effect<Effect.Effect<EventLoopReadings>, never, Scope.Scope>,
142 stallLog: StallLogOptions,
143) =>
144 Layer.effect(
145 EventLoopMonitor,
146 Effect.gen(function* () {
147 const sample = yield* makeSampler;
148 // Clients sample on connect as well as the timer, and the sampler resets shared state.
149 const sampling = yield* Semaphore.make(1);
150 const warmedUp = yield* Ref.make(false);
151 const latestNoticeableStall = yield* Ref.make<
152 { readonly stall: ServerEventLoopStall; readonly detectedAtMs: number } | undefined
153 >(undefined);
154 const stallSink = yield* Effect.try(
155 () =>
156 new RotatingFileSink({
157 filePath: stallLog.filePath,
158 maxBytes: stallLog.maxBytes,
159 maxFiles: 1,
160 throwOnError: true,
161 }),
162 ).pipe(
163 Effect.catch(() =>
164 Effect.logWarning("event loop stall log unavailable", {
165 filePath: stallLog.filePath,
166 }).pipe(Effect.as(undefined)),
167 ),
168 );
169 const tick = Effect.gen(function* () {
170 const readings = yield* sample;
171 yield* recordGauges(readings);
172 const delayMaxMs = stallMs(readings);
173 if (delayMaxMs === undefined) return;
174 const { utilization, usage, rssBytes, loadAverage, cpuCount } = readings;
175 const now = yield* DateTime.now;
176 const detectedAt = DateTime.formatIso(now);
177 if (delayMaxMs >= NOTICEABLE_STALL_MS) {
178 yield* Ref.set(latestNoticeableStall, {
179 detectedAtMs: DateTime.toEpochMillis(now),
180 stall: {
181 detectedAt,
182 durationMs: delayMaxMs,
183 ...(loadAverage === undefined
184 ? {}
185 : { loadAverage: Math.round(loadAverage * 10) / 10 }),
186 cpuCount,
187 },
188 });
189 }
190 const attributes = {
191 delayMaxMs,
192 utilization: Math.round(utilization * 100) / 100,
193 cpuUserMs: Math.round(usage.userCPUTime / 1000),
194 cpuSystemMs: Math.round(usage.systemCPUTime / 1000),
195 majorPageFaults: usage.majorPageFault,
196 minorPageFaults: usage.minorPageFault,
197 involuntaryContextSwitches: usage.involuntaryContextSwitches,
198 rssMb: Math.round(rssBytes / 1024 / 1024),
199 };
200 yield* Effect.logWarning(`event loop stalled for ${delayMaxMs} ms`).pipe(
201 Effect.withSpan("server.eventLoop.stall", { root: true, level: "Warn", attributes }),
202 );
203 if (stallSink !== undefined) {
204 yield* encodeStallLine({ time: detectedAt, ...attributes }).pipe(
205 Effect.flatMap((line) => Effect.try(() => stallSink.write(`${line}\n`))),
206 Effect.catch(() =>
207 Effect.logWarning("event loop stall log write failed", {
208 filePath: stallLog.filePath,
209 }),
210 ),
211 );
212 }
213 }).pipe(sampling.withPermits(1));
214 const wait = Effect.sleep(SAMPLE_INTERVAL);
215 // The first sample includes migrations and bootstrap; skip expected startup stalls.
216 yield* wait.pipe(
217 Effect.andThen(sampling.withPermits(1)(sample)),
218 Effect.andThen(Ref.set(warmedUp, true)),
219 Effect.andThen(wait.pipe(Effect.andThen(tick), Effect.forever)),
220 Effect.forkScoped,
221 );
222​
223 return EventLoopMonitor.of({
224 latestNoticeableStall: Effect.gen(function* () {
225 if (yield* Ref.get(warmedUp)) yield* tick;
226 const latest = yield* Ref.get(latestNoticeableStall);
227 if (latest === undefined) return undefined;
228 const ageMs = DateTime.toEpochMillis(yield* DateTime.now) - latest.detectedAtMs;
229 return ageMs <= NOTICEABLE_STALL_MAX_AGE_MS ? latest.stall : undefined;
230 }),
231 });
232 }),
233 );
234​
235export const layer = Layer.unwrap(
236 Effect.gen(function* () {
237 const { serverTracePath } = yield* ServerConfig.ServerConfig;
238 const path = yield* Path.Path;
239 return layerWith(makeNodeSampler, {
240 filePath: path.join(path.dirname(serverTracePath), "event-loop-stalls.ndjson"),
241 maxBytes: STALL_LOG_MAX_BYTES,
242 });
243 }),
244);