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

EventLoopMonitor.ts

135 lines5.6 KB

1// @effect-diagnostics nodeBuiltinImport:off - only node:perf_hooks exposes the event loop delay histogram.
2import * as NodePerfHooks from "node:perf_hooks";
3​
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import type * as Scope from "effect/Scope";
7​
8// Node's delay histogram wakes a native timer every RESOLUTION_MS and records the
9// gap between wakeups, so an idle loop reads about RESOLUTION_MS and a stall of S
10// reads between S and S + RESOLUTION_MS. We subtract the resolution, so a delay can
11// undercount a stall by up to RESOLUTION_MS. With these values every stall over 3 s
12// is caught, at 1 wakeup per second that never enters JS.
13const RESOLUTION_MS = 1000;
14const STALL_THRESHOLD_MS = 2000;
15const SAMPLE_INTERVAL = "30 seconds";
16​
17/** One sample interval as Node reports it. Delay in ns, active time in ms, CPU in µs. */
18export interface EventLoopReadings {
19 readonly delayMaxNs: number;
20 readonly activeMs: number;
21 readonly utilization: number;
22 readonly usage: Pick<
23 NodeJS.ResourceUsage,
24 | "userCPUTime"
25 | "systemCPUTime"
26 | "majorPageFault"
27 | "minorPageFault"
28 | "involuntaryContextSwitches"
29 >;
30 readonly rssBytes: number;
32​
33// Enables the delay histogram for the layer's lifetime. Each read returns the
34// readings since the previous read and resets the histogram. Node skips the first
35// gap after a reset, so a stall right at a sample boundary can be missed.
36const makeNodeSampler = Effect.gen(function* () {
37 const histogram = yield* Effect.acquireRelease(
38 Effect.sync(() => {
39 const histogram = NodePerfHooks.monitorEventLoopDelay({ resolution: RESOLUTION_MS });
40 histogram.enable();
41 return histogram;
42 }),
43 (histogram) => Effect.sync(() => histogram.disable()),
44 );
45 let elu = NodePerfHooks.performance.eventLoopUtilization();
46 let usage = process.resourceUsage();
47​
48 // @effect-diagnostics-next-line returnEffectInGen:off - the read effect is the result.
49 return Effect.sync(() => {
50 const nextElu = NodePerfHooks.performance.eventLoopUtilization();
51 const nextUsage = process.resourceUsage();
52 const loop = NodePerfHooks.performance.eventLoopUtilization(nextElu, elu);
53 const readings: EventLoopReadings = {
54 delayMaxNs: histogram.max,
55 activeMs: loop.active,
56 utilization: loop.utilization,
57 usage: {
58 userCPUTime: nextUsage.userCPUTime - usage.userCPUTime,
59 systemCPUTime: nextUsage.systemCPUTime - usage.systemCPUTime,
60 majorPageFault: nextUsage.majorPageFault - usage.majorPageFault,
61 minorPageFault: nextUsage.minorPageFault - usage.minorPageFault,
62 involuntaryContextSwitches:
63 nextUsage.involuntaryContextSwitches - usage.involuntaryContextSwitches,
64 },
65 rssBytes: process.memoryUsage.rss(),
66 };
67 histogram.reset();
68 elu = nextElu;
69 usage = nextUsage;
70 return readings;
71 });
72});
73​
74/**
75 * Returns the stall to report for one sample in ms, or undefined when there was none.
76 */
77export const stallMs = ({ delayMaxNs, activeMs }: EventLoopReadings) => {
78 const delayMs = Math.round(delayMaxNs / 1e6) - RESOLUTION_MS;
79 // A stall is time the loop spent running code, so it counts as active time. libuv's
80 // clock keeps running while the system sleeps on macOS and Windows, so a sleep also
81 // 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​
86/**
87 * Samples event loop health every 30 s and records a `server.eventLoop.stall` span
88 * with a warning when the loop stalled for more than 2 s, so stalls land in
89 * the local trace file and Settings > Diagnostics without OTLP. Takes the sampler
90 * so tests can inject readings.
91 */
92export const layerWith = (
93 makeSampler: Effect.Effect<Effect.Effect<EventLoopReadings>, never, Scope.Scope>,
94) =>
95 Layer.effectDiscard(
96 Effect.gen(function* () {
97 const sample = yield* makeSampler;
98 const tick = Effect.gen(function* () {
99 const readings = yield* sample;
100 const delayMaxMs = stallMs(readings);
101 if (delayMaxMs === undefined) return;
102 const { utilization, usage, rssBytes } = readings;
103 // Root, as the stall has no caller to attach to. Warn level keeps it when
104 // T3CODE_TRACE_MIN_LEVEL is raised to cut trace noise.
105 yield* Effect.logWarning(`event loop stalled for ${delayMaxMs} ms`).pipe(
106 Effect.withSpan("server.eventLoop.stall", {
107 root: true,
108 level: "Warn",
109 attributes: {
110 delayMaxMs,
111 utilization: Math.round(utilization * 100) / 100,
112 cpuUserMs: Math.round(usage.userCPUTime / 1000),
113 cpuSystemMs: Math.round(usage.systemCPUTime / 1000),
114 majorPageFaults: usage.majorPageFault,
115 minorPageFaults: usage.minorPageFault,
116 involuntaryContextSwitches: usage.involuntaryContextSwitches,
117 rssMb: Math.round(rssBytes / 1024 / 1024),
118 },
119 }),
120 );
121 });
122 const wait = Effect.sleep(SAMPLE_INTERVAL);
123 // The layer builds before the rest of the server, so the first sample covers
124 // startup work such as migrations and projection bootstrap. That can block the
125 // loop for seconds on a large database, so skip it rather than warn at every
126 // launch. Layers build outside any span, so this fiber retains no parent span.
127 yield* wait.pipe(
128 Effect.andThen(sample),
129 Effect.andThen(wait.pipe(Effect.andThen(tick), Effect.forever)),
130 Effect.forkScoped,
131 );
132 }),
133 );
134​
135export const layer = layerWith(makeNodeSampler);