Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Logger from "effect/Logger";
7import * as Tracer from "effect/Tracer";
8import * as TestClock from "effect/testing/TestClock";
9
10import * as EventLoopMonitor from "./EventLoopMonitor.ts";
11
12const ms = (value: number) => value * 1e6;
13
14// Node reports a stall of S as a gap of up to S + 100 ms, the histogram resolution.
15const stalled: EventLoopMonitor.EventLoopReadings = {
16 delayMaxNs: ms(5_950),
17 activeMs: 6_200,
18 utilization: 0.176,
19 usage: {
20 userCPUTime: 310_400,
21 systemCPUTime: 95_600,
22 majorPageFault: 8_412,
23 minorPageFault: 20_031,
24 involuntaryContextSwitches: 57,
25 },
26 rssBytes: 1536 * 1024 * 1024,
27};
28// Over the threshold as read, but not once the resolution is subtracted.
29const quiet: EventLoopMonitor.EventLoopReadings = { ...stalled, delayMaxNs: ms(300) };
30
31const monitor = (
32 samples: Array<EventLoopMonitor.EventLoopReadings>,
33 stallLog: EventLoopMonitor.StallLogOptions = { filePath: "\0", maxBytes: 1 },
34) =>
35 Layer.build(
36 EventLoopMonitor.layerWith(
37 Effect.succeed(Effect.sync(() => samples.shift() ?? quiet)),
38 stallLog,
39 ),
40 );
41
42describe("EventLoopMonitor", () => {
43 it.effect("records a warning span only for samples that saw a stall", () =>
44 Effect.gen(function* () {
45 const spans: Array<Tracer.NativeSpan> = [];
46 const tracer = Tracer.make({
47 span: (options) => {
48 const span = new Tracer.NativeSpan(options);
49 spans.push(span);
50 return span;
51 },
52 });
53 yield* Effect.gen(function* () {
54 yield* monitor([stalled, quiet, stalled]);
55 yield* TestClock.adjust("1 second");
56 assert.lengthOf(spans, 1);
57 yield* TestClock.adjust("1 second");
58 assert.lengthOf(spans, 1);
59 yield* TestClock.adjust("1 second");
60 }).pipe(Effect.scoped, Effect.withTracer(tracer));
61
62 assert.deepStrictEqual(
63 spans.map((span) => span.name),
64 ["server.eventLoop.stall", "server.eventLoop.stall"],
65 );
66 const [span] = spans;
67 assert.deepStrictEqual(Object.fromEntries(span!.attributes), {
68 delayMaxMs: 5_850,
69 utilization: 0.18,
70 cpuUserMs: 310,
71 cpuSystemMs: 96,
72 majorPageFaults: 8_412,
73 minorPageFaults: 20_031,
74 involuntaryContextSwitches: 57,
75 rssMb: 1536,
76 });
77 assert.deepStrictEqual(
78 span!.events.map(([name, , attributes]) => [name, attributes["effect.logLevel"]]),
79 [["event loop stalled for 5850 ms", "WARN"]],
80 );
81 }),
82 );
83
84 it.effect("keeps each stall as one line in a capped stall log", () =>
85 Effect.gen(function* () {
86 const fs = yield* FileSystem.FileSystem;
87 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-event-loop-" });
88 const filePath = `${directory}/event-loop-stalls.ndjson`;
89 yield* monitor([stalled, stalled, stalled, { ...stalled, delayMaxNs: ms(7_000) }], {
90 filePath,
91 maxBytes: 300,
92 });
93 yield* TestClock.adjust("4 seconds");
94
95 const lines = (yield* fs.readFileString(filePath)).trim().split("\n");
96 assert.deepStrictEqual(
97 lines.map((line) => JSON.parse(line)),
98 [
99 {
100 time: "1970-01-01T00:00:04.000Z",
101 delayMaxMs: 6_900,
102 utilization: 0.18,
103 cpuUserMs: 310,
104 cpuSystemMs: 96,
105 majorPageFaults: 8_412,
106 minorPageFaults: 20_031,
107 involuntaryContextSwitches: 57,
108 rssMb: 1536,
109 },
110 ],
111 );
112 assert.lengthOf((yield* fs.readFileString(`${filePath}.1`)).trim().split("\n"), 1);
113 assert.isFalse(yield* fs.exists(`${filePath}.2`));
114 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
115 );
116
117 it.effect("warns when a stall cannot be written to the stall log", () => {
118 const warnings: Array<unknown> = [];
119 const logger = Logger.make(({ message }) => {
120 warnings.push(Array.isArray(message) ? message[0] : message);
121 });
122 return Effect.gen(function* () {
123 const fs = yield* FileSystem.FileSystem;
124 const filePath = yield* fs.makeTempDirectoryScoped({ prefix: "t3-event-loop-" });
125 yield* monitor([stalled, stalled], { filePath, maxBytes: 1024 * 1024 });
126 yield* TestClock.adjust("1 second");
127 assert.deepStrictEqual(warnings, [
128 "event loop stalled for 5850 ms",
129 "event loop stall log write failed",
130 ]);
131 }).pipe(
132 Effect.scoped,
133 Effect.provide(
134 Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),
135 ),
136 );
137 });
138
139 it.effect("samples every second at startup and every 30 seconds after", () =>
140 Effect.gen(function* () {
141 let samples = 0;
142 yield* Layer.build(
143 EventLoopMonitor.layerWith(Effect.succeed(Effect.sync(() => (++samples, quiet))), {
144 filePath: "/missing/event-loop-stalls.ndjson",
145 maxBytes: 1024,
146 }),
147 );
148 yield* TestClock.adjust("30 seconds");
149 assert.strictEqual(samples, 30);
150 yield* TestClock.adjust("29 seconds");
151 assert.strictEqual(samples, 30);
152 yield* TestClock.adjust("1 second");
153 assert.strictEqual(samples, 31);
154 }).pipe(Effect.scoped),
155 );
156
157 it("reports only stalls over 2 s after startup", () => {
158 // Read at the steady 1 s resolution.
159 assert.isUndefined(
160 EventLoopMonitor.stallMs({ ...stalled, delayMaxNs: ms(2_900), steady: true }),
161 );
162 assert.strictEqual(
163 EventLoopMonitor.stallMs({ ...stalled, delayMaxNs: ms(4_000), steady: true }),
164 3_000,
165 );
166 });
167
168 it("reports short stalls even when ELU active time lags the delay reading", () => {
169 const short: EventLoopMonitor.EventLoopReadings = {
170 ...stalled,
171 delayMaxNs: ms(850),
172 activeMs: 100,
173 };
174 assert.strictEqual(EventLoopMonitor.stallMs(short), 750);
175 // Before the loop starts, ELU reads 0 and CPU time shows the loop was busy.
176 const busyBeforeLoop = {
177 ...quiet,
178 activeMs: 0,
179 usage: { ...quiet.usage, userCPUTime: 52_000_000, systemCPUTime: 900_000 },
180 };
181 assert.strictEqual(
182 EventLoopMonitor.stallMs({ ...busyBeforeLoop, tickDelayMs: 53_000 }),
183 53_000,
184 );
185 assert.isUndefined(EventLoopMonitor.stallMs(quiet));
186 });
187
188 it("ignores a long gap the loop spent idle, such as a system sleep", () => {
189 // Waking from sleep reads as a long gap, but the loop was idle in poll for it.
190 const asleep: EventLoopMonitor.EventLoopReadings = {
191 ...stalled,
192 delayMaxNs: ms(600_000),
193 activeMs: 900,
194 };
195 assert.isUndefined(EventLoopMonitor.stallMs(asleep));
196 assert.isUndefined(EventLoopMonitor.stallMs({ ...quiet, tickDelayMs: 7_200_000 }));
197 assert.strictEqual(EventLoopMonitor.stallMs({ ...asleep, activeMs: 600_000 }), 599_900);
198 });
199});