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

trace.test.ts

221 lines7.4 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as ConfigProvider from "effect/ConfigProvider";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as TestConsole from "effect/testing/TestConsole";
9import { Command } from "effect/cli";
10​
11import { formatTraceSummary, makeTraceSpanSummary, traceCommand } from "./trace.ts";
12​
13const MINUTE_MS = 60_000;
14​
15function span(name: string, durationMs: number, endMs: number, exitTag = "Success") {
16 return JSON.stringify({
17 type: "effect-span",
18 name,
19 traceId: "trace",
20 spanId: "span",
21 durationMs,
22 endTimeUnixNano: String(BigInt(endMs) * 1_000_000n),
23 exit: { _tag: exitTag, cause: "cause" },
24 });
26​
27function browserSpan(
28 name: string,
29 status: { code: string; message?: string },
30 attributes: Record<string, unknown> = {},
31) {
32 return JSON.stringify({
33 type: "otlp-span",
34 name,
35 durationMs: 1,
36 endTimeUnixNano: "1000000",
37 status,
38 attributes,
39 });
41​
42const traceSummaryFixture = Effect.gen(function* () {
43 const fs = yield* FileSystem.FileSystem;
44 const path = yield* Path.Path;
45 const baseDir = yield* fs.makeTempDirectoryScoped();
46 const traceFilePath = path.join(baseDir, "trace.ndjson");
47 const rotatedPath = `${traceFilePath}.1`;
48 yield* fs.makeDirectory(rotatedPath);
49​
50 const run = Command.runWith(traceCommand, { version: "0.0.0" })([
51 "summary",
52 "--base-dir",
53 baseDir,
54 ]).pipe(
55 Effect.provide(
56 ConfigProvider.layer(
57 ConfigProvider.fromEnv({
58 env: { T3CODE_TRACE_FILE: traceFilePath, T3CODE_TRACE_MAX_FILES: "2" },
59 }),
60 ),
61 ),
62 );
63 return { fs, traceFilePath, rotatedPath, run };
64});
65​
66it.effect("summarizes the current trace when a rotated file cannot be read", () =>
67 Effect.gen(function* () {
68 const { fs, traceFilePath, rotatedPath, run } = yield* traceSummaryFixture;
69 yield* fs.writeFileString(traceFilePath, `${span("sample.span", 5, MINUTE_MS)}\n`);
70​
71 yield* run;
72​
73 assert.include((yield* TestConsole.logLines).join("\n"), "sample.span");
74 assert.deepStrictEqual(yield* TestConsole.errorLines, [
75 `Failed to read local trace file '${rotatedPath}'.`,
76 ]);
77 }).pipe(Effect.provide(NodeServices.layer)),
78);
79​
80it.effect("reports a read error when no trace files can be read", () =>
81 Effect.gen(function* () {
82 const { rotatedPath, run } = yield* traceSummaryFixture;
83​
84 const error = yield* Effect.flip(run);
85​
86 assert.propertyVal(error, "message", `Failed to read local trace file '${rotatedPath}'.`);
87 assert.isEmpty(yield* TestConsole.logLines);
88 }).pipe(Effect.provide(NodeServices.layer)),
89);
90​
91it("drops spans that ended before the window and counts unreadable lines", () => {
92 const nowMs = Date.UTC(2026, 10, 24);
93 const cutoff = BigInt(nowMs) * 1_000_000n - 1n;
94 const summarizer = makeTraceSpanSummary({ nowMs, duration: Duration.nanos(1n) });
95 [
96 span("old", 1, 0),
97 JSON.stringify({
98 name: "just-before",
99 durationMs: 1,
100 endTimeUnixNano: String(cutoff - 1n),
101 }),
102 "",
103 "{not json",
104 JSON.stringify({ name: "no-duration" }),
105 JSON.stringify({ name: "far-future", durationMs: 1, endTimeUnixNano: "9".repeat(22) }),
106 JSON.stringify({ name: "at-cutoff", durationMs: 4, endTimeUnixNano: String(cutoff) }),
107 ].forEach(summarizer.addLine);
108 const summary = summarizer.finish();
109​
110 assert.strictEqual(summary.skippedLineCount, 3);
111 assert.deepStrictEqual(
112 summary.spans.map((entry) => [entry.name, entry.count, entry.perMinute]),
113 [["at-cutoff", 1, undefined]],
114 );
115});
116​
117it("reads failures and interrupts of browser spans from their OTLP status", () => {
118 const summarizer = makeTraceSpanSummary();
119 [
120 browserSpan("render", { code: "2", message: "Interrupted" }),
121 browserSpan("render", { code: "0" }, { "effect.fiber.interrupted": true }),
122 browserSpan("render", { code: "1", message: "Interrupted" }),
123 browserSpan("render", { code: "1" }),
124 ].forEach(summarizer.addLine);
125​
126 const [render] = summarizer.finish().spans;
127 assert.deepStrictEqual([render?.count, render?.interrupted, render?.failures], [4, 2, 1]);
128});
129​
130it("prints durations that round up to a second in seconds", () => {
131 const summarizer = makeTraceSpanSummary();
132 [span("rpc", 999.4, MINUTE_MS), span("rpc", 999.6, 2 * MINUTE_MS)].forEach(summarizer.addLine);
133​
134 const row = formatTraceSummary(summarizer.finish(), 25)
135 .split("\n")
136 .find((line) => line.startsWith("rpc"));
137 assert.deepStrictEqual(row?.trim().split(/\s+/).slice(3, 6), ["999ms", "1s", "1s"]);
138});
139​
140it("keeps sub-millisecond windows and rates without rounding printed dates", () => {
141 const summarizer = makeTraceSpanSummary({
142 nowMs: 1_795_478_400_000,
143 duration: Duration.millis(1.75),
144 });
145 ["1795478399998000000", "1795478399998999950", "1795478399999999999"]
146 .map((endTimeUnixNano) => JSON.stringify({ name: "rpc", durationMs: 1, endTimeUnixNano }))
147 .forEach(summarizer.addLine);
148 const summary = summarizer.finish();
149 const formatted = formatTraceSummary(summary, 25);
150 const row = formatted.split("\n").find((line) => line.startsWith("rpc"));
151​
152 assert.strictEqual(summary.spanCount, 2);
153 assert.strictEqual(row?.trim().split(/\s+/)[2], "120000.0");
154 assert.include(formatted, "from 2026-11-23T23:59:59.998Z to 2026-11-23T23:59:59.999Z");
155});
156​
157it("includes an end time in scientific notation at the window boundary", () => {
158 const summarizer = makeTraceSpanSummary({ nowMs: 1_795_478_400_001, duration: Duration.zero });
159 summarizer.addLine(
160 JSON.stringify({ name: "rpc", durationMs: 1, endTimeUnixNano: "1795478400001e6" }),
161 );
162​
163 assert.include(formatTraceSummary(summarizer.finish(), 25), "to 2026-11-24T00:00:00.001Z");
164});
165​
166it("formats large summaries without overflowing the call stack", () => {
167 const rowCount = 150_000;
168 const entry = {
169 name: "long-span-name",
170 count: 1,
171 perMinute: 1,
172 p50Ms: 1,
173 p90Ms: 1,
174 maxMs: 1,
175 interrupted: 0,
176 failures: 0,
177 };
178 const spans = Array.from({ length: rowCount }, () => entry);
179​
180 const lines = formatTraceSummary(
181 {
182 spanCount: rowCount,
183 skippedLineCount: 0,
184 firstEndMs: 0,
185 lastEndMs: MINUTE_MS,
186 minutes: 1,
187 spans,
188 },
189 rowCount,
190 ).split("\n");
191​
192 assert.strictEqual(lines.length, rowCount + 3);
193 assert.strictEqual(lines[2], "span count /min p50 p90 max interrupted failed");
194 assert.strictEqual(
195 lines.at(-1),
196 "long-span-name 1 1.0 1ms 1ms 1ms 0 0",
197 );
198});
199​
200it("uses singular nouns only for counts of one", () => {
201 const summarize = (lines: ReadonlyArray<string>) => {
202 const summarizer = makeTraceSpanSummary();
203 lines.forEach(summarizer.addLine);
204 return formatTraceSummary(summarizer.finish(), 0).split("\n");
205 };
206 const one = summarize([span("a", 1, MINUTE_MS), "{not json"]);
207 const two = summarize([span("a", 1, MINUTE_MS), span("b", 1, MINUTE_MS), "x", "y"]);
208​
209 assert.deepStrictEqual(
210 [one[0]?.split(" ended")[0], one[1], one.at(-1)],
211 ["1 span", "Skipped 1 line that is not a span.", "1 more span name. Use --limit to show more."],
212 );
213 assert.deepStrictEqual(
214 [two[0]?.split(" ended")[0], two[1], two.at(-1)],
215 [
216 "2 spans",
217 "Skipped 2 lines that are not spans.",
218 "2 more span names. Use --limit to show more.",
219 ],
220 );
221});