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

EventLoopMonitor.test.ts

199 lines7.0 KB

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