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 { type EventLoopReadings, layerWith, stallMs } 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: 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: 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(layerWith(Effect.succeed(Effect.sync(() => samples.shift() ?? quiet))));
44 yield* TestClock.adjust("60 seconds");
45 assert.lengthOf(spans, 0);
46 yield* TestClock.adjust("30 seconds");
47 }).pipe(Effect.scoped, Effect.withTracer(tracer));
48
49 assert.deepStrictEqual(
50 spans.map((span) => span.name),
51 ["server.eventLoop.stall"],
52 );
53 const [span] = spans;
54 assert.deepStrictEqual(Object.fromEntries(span!.attributes), {
55 delayMaxMs: 4_950,
56 utilization: 0.18,
57 cpuUserMs: 310,
58 cpuSystemMs: 96,
59 majorPageFaults: 8_412,
60 minorPageFaults: 20_031,
61 involuntaryContextSwitches: 57,
62 rssMb: 1536,
63 });
64 assert.deepStrictEqual(
65 span!.events.map(([name, , attributes]) => [name, attributes["effect.logLevel"]]),
66 [["event loop stalled for 4950 ms", "WARN"]],
67 );
68 }),
69 );
70
71 it("ignores delay the loop spent idle, such as a system sleep", () => {
72 // Waking from sleep reads as a long gap, but the loop was idle in poll for it.
73 const asleep: EventLoopReadings = { ...stalled, delayMaxNs: ms(600_000), activeMs: 900 };
74 assert.isUndefined(stallMs(asleep));
75 assert.strictEqual(stallMs({ ...asleep, activeMs: 600_000 }), 599_000);
76 });
77});