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 + 1 s, 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};
28const quiet: EventLoopMonitor.EventLoopReadings = { ...stalled, delayMaxNs: ms(2_950) };
29
30const monitor = (
31 samples: Array<EventLoopMonitor.EventLoopReadings>,
32 stallLog: EventLoopMonitor.StallLogOptions = { filePath: "\0", maxBytes: 1 },
33) =>
34 Layer.build(
35 EventLoopMonitor.layerWith(
36 Effect.succeed(Effect.sync(() => samples.shift() ?? quiet)),
37 stallLog,
38 ),
39 );
40
41describe("EventLoopMonitor", () => {
42 it.effect("records a warning span only for samples that saw a stall", () =>
43 Effect.gen(function* () {
44 const spans: Array<Tracer.NativeSpan> = [];
45 const tracer = Tracer.make({
46 span: (options) => {
47 const span = new Tracer.NativeSpan(options);
48 spans.push(span);
49 return span;
50 },
51 });
52 yield* Effect.gen(function* () {
53 yield* monitor([stalled, quiet, stalled]);
54 yield* TestClock.adjust("60 seconds");
55 assert.lengthOf(spans, 0);
56 yield* TestClock.adjust("30 seconds");
57 }).pipe(Effect.scoped, Effect.withTracer(tracer));
58
59 assert.deepStrictEqual(
60 spans.map((span) => span.name),
61 ["server.eventLoop.stall"],
62 );
63 const [span] = spans;
64 assert.deepStrictEqual(Object.fromEntries(span!.attributes), {
65 delayMaxMs: 4_950,
66 utilization: 0.18,
67 cpuUserMs: 310,
68 cpuSystemMs: 96,
69 majorPageFaults: 8_412,
70 minorPageFaults: 20_031,
71 involuntaryContextSwitches: 57,
72 rssMb: 1536,
73 });
74 assert.deepStrictEqual(
75 span!.events.map(([name, , attributes]) => [name, attributes["effect.logLevel"]]),
76 [["event loop stalled for 4950 ms", "WARN"]],
77 );
78 }),
79 );
80
81 it.effect("keeps each stall as one line in a capped stall log", () =>
82 Effect.gen(function* () {
83 const fs = yield* FileSystem.FileSystem;
84 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-event-loop-" });
85 const filePath = `${directory}/event-loop-stalls.ndjson`;
86 yield* monitor([stalled, stalled, stalled, { ...stalled, delayMaxNs: ms(7_000) }], {
87 filePath,
88 maxBytes: 300,
89 });
90 yield* TestClock.adjust("120 seconds");
91
92 const lines = (yield* fs.readFileString(filePath)).trim().split("\n");
93 assert.deepStrictEqual(
94 lines.map((line) => JSON.parse(line)),
95 [
96 {
97 time: "1970-01-01T00:02:00.000Z",
98 delayMaxMs: 6_000,
99 utilization: 0.18,
100 cpuUserMs: 310,
101 cpuSystemMs: 96,
102 majorPageFaults: 8_412,
103 minorPageFaults: 20_031,
104 involuntaryContextSwitches: 57,
105 rssMb: 1536,
106 },
107 ],
108 );
109 assert.lengthOf((yield* fs.readFileString(`${filePath}.1`)).trim().split("\n"), 1);
110 assert.isFalse(yield* fs.exists(`${filePath}.2`));
111 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
112 );
113
114 it.effect("warns when a stall cannot be written to the stall log", () => {
115 const warnings: Array<unknown> = [];
116 const logger = Logger.make(({ message }) => {
117 warnings.push(Array.isArray(message) ? message[0] : message);
118 });
119 return Effect.gen(function* () {
120 const fs = yield* FileSystem.FileSystem;
121 const filePath = yield* fs.makeTempDirectoryScoped({ prefix: "t3-event-loop-" });
122 yield* monitor([stalled, stalled], { filePath, maxBytes: 1024 * 1024 });
123 yield* TestClock.adjust("60 seconds");
124 assert.deepStrictEqual(warnings, [
125 "event loop stalled for 4950 ms",
126 "event loop stall log write failed",
127 ]);
128 }).pipe(
129 Effect.scoped,
130 Effect.provide(
131 Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })),
132 ),
133 );
134 });
135
136 it("ignores delay the loop spent idle, such as a system sleep", () => {
137 // Waking from sleep reads as a long gap, but the loop was idle in poll for it.
138 const asleep: EventLoopMonitor.EventLoopReadings = {
139 ...stalled,
140 delayMaxNs: ms(600_000),
141 activeMs: 900,
142 };
143 assert.isUndefined(EventLoopMonitor.stallMs(asleep));
144 assert.strictEqual(EventLoopMonitor.stallMs({ ...asleep, activeMs: 600_000 }), 599_000);
145 });
146});