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

EventLoopMonitor.test.ts

172 lines5.9 KB

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