Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Tracer from "effect/Tracer";
5import * as TestClock from "effect/testing/TestClock";
6
7import * as EventLoopMonitor from "./EventLoopMonitor.ts";
8
9const ms = (value: number) => value * 1e6;
10
11// Node reports a stall of S as a gap of up to S + 1 s, the histogram resolution.
12const stalled: EventLoopMonitor.EventLoopReadings = {
13 delayMaxNs: ms(5_950),
14 activeMs: 6_200,
15 utilization: 0.176,
16 usage: {
17 userCPUTime: 310_400,
18 systemCPUTime: 95_600,
19 majorPageFault: 8_412,
20 minorPageFault: 20_031,
21 involuntaryContextSwitches: 57,
22 },
23 rssBytes: 1536 * 1024 * 1024,
24};
25// Over the threshold as read, but not once the resolution is subtracted.
26const quiet: EventLoopMonitor.EventLoopReadings = { ...stalled, delayMaxNs: ms(2_950) };
27
28describe("EventLoopMonitor", () => {
29 it.effect("records a warning span only for samples that saw a stall", () =>
30 Effect.gen(function* () {
31 const spans: Array<Tracer.NativeSpan> = [];
32 const tracer = Tracer.make({
33 span: (options) => {
34 const span = new Tracer.NativeSpan(options);
35 spans.push(span);
36 return span;
37 },
38 });
39 // The first sample covers startup, so the monitor discards it.
40 const samples = [stalled, quiet, stalled];
41
42 yield* Effect.gen(function* () {
43 yield* Layer.build(
44 EventLoopMonitor.layerWith(Effect.succeed(Effect.sync(() => samples.shift() ?? quiet))),
45 );
46 yield* TestClock.adjust("60 seconds");
47 assert.lengthOf(spans, 0);
48 yield* TestClock.adjust("30 seconds");
49 }).pipe(Effect.scoped, Effect.withTracer(tracer));
50
51 assert.deepStrictEqual(
52 spans.map((span) => span.name),
53 ["server.eventLoop.stall"],
54 );
55 const [span] = spans;
56 assert.deepStrictEqual(Object.fromEntries(span!.attributes), {
57 delayMaxMs: 4_950,
58 utilization: 0.18,
59 cpuUserMs: 310,
60 cpuSystemMs: 96,
61 majorPageFaults: 8_412,
62 minorPageFaults: 20_031,
63 involuntaryContextSwitches: 57,
64 rssMb: 1536,
65 });
66 assert.deepStrictEqual(
67 span!.events.map(([name, , attributes]) => [name, attributes["effect.logLevel"]]),
68 [["event loop stalled for 4950 ms", "WARN"]],
69 );
70 }),
71 );
72
73 it("ignores delay the loop spent idle, such as a system sleep", () => {
74 // Waking from sleep reads as a long gap, but the loop was idle in poll for it.
75 const asleep: EventLoopMonitor.EventLoopReadings = {
76 ...stalled,
77 delayMaxNs: ms(600_000),
78 activeMs: 900,
79 };
80 assert.isUndefined(EventLoopMonitor.stallMs(asleep));
81 assert.strictEqual(EventLoopMonitor.stallMs({ ...asleep, activeMs: 600_000 }), 599_000);
82 });
83});