Open History to see the last commit
1/**
2 * `t3 trace summary` - per-span counts, rates, and latency percentiles from
3 * the local server trace file and its rotated backups. It reads the files
4 * directly, so it works while the server is stalled or stopped.
5 */
6import { PositiveInt } from "@t3tools/contracts";
7import * as Clock from "effect/Clock";
8import * as Config from "effect/Config";
9import * as Console from "effect/Console";
10import * as DateTime from "effect/DateTime";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Option from "effect/Option";
15import * as Schema from "effect/Schema";
16import * as Stream from "effect/Stream";
17import { Command, Flag } from "effect/unstable/cli";
18
19import * as ServerConfig from "../config.ts";
20import { toRotatedTracePaths, TraceFileReadError } from "../diagnostics/TraceDiagnostics.ts";
21import { resolveBaseDir } from "../os-jank.ts";
22import { baseDirFlag, DurationFromString, traceFileConfig, traceMaxFilesConfig } from "./config.ts";
23
24// Only the fields the summary needs. Other record fields are ignored.
25const decodeTraceSpanLine = Schema.decodeUnknownOption(
26 Schema.fromJsonString(
27 Schema.Struct({
28 name: Schema.String,
29 durationMs: Schema.Finite,
30 endTimeUnixNano: Schema.FiniteFromString,
31 // Server (`effect-span`) records.
32 exit: Schema.optional(Schema.Struct({ _tag: Schema.String })),
33 // Browser (`otlp-span`) records. Effect's OTLP tracer writes code "2" for
34 // errors and code "1" with message "Interrupted" for interrupts.
35 status: Schema.optional(
36 Schema.Struct({
37 code: Schema.optional(Schema.String),
38 message: Schema.optional(Schema.String),
39 }),
40 ),
41 }),
42 ),
43);
44
45/**
46 * Groups trace NDJSON by span name. Call `addLine` once per line as the files
47 * stream in, then `finish` for the summary. Spans that ended before `sinceMs`
48 * are left out. Rates are per minute between the first and last span end,
49 * since spans are written when they end.
50 */
51export function makeTraceSpanSummary(sinceMs = -Infinity) {
52 // Keep each span's duration (8 bytes, a few MB for the default 110 MB of
53 // rotated traces) for exact percentiles. A bounded sketch would save little
54 // and make p50 and p90 approximate.
55 const byName = new Map<string, { durations: number[]; interrupted: number; failures: number }>();
56 let spanCount = 0;
57 let skippedLineCount = 0;
58 let firstEndMs = Infinity;
59 let lastEndMs = -Infinity;
60
61 const addLine = (line: string) => {
62 if (line.trim().length === 0) return;
63 const span = Option.getOrUndefined(decodeTraceSpanLine(line));
64 if (span === undefined) {
65 skippedLineCount += 1;
66 return;
67 }
68 const endMs = span.endTimeUnixNano / 1_000_000;
69 // The report prints end times as dates, so skip ones outside the Date range.
70 if (Option.isNone(DateTime.make(endMs))) {
71 skippedLineCount += 1;
72 return;
73 }
74 if (endMs < sinceMs) return;
75
76 spanCount += 1;
77 firstEndMs = Math.min(firstEndMs, endMs);
78 lastEndMs = Math.max(lastEndMs, endMs);
79 const stats = byName.get(span.name) ?? { durations: [], interrupted: 0, failures: 0 };
80 stats.durations.push(span.durationMs);
81 if (span.exit?._tag === "Interrupted" || span.status?.message === "Interrupted") {
82 stats.interrupted += 1;
83 }
84 if (span.exit?._tag === "Failure" || span.status?.code === "2") stats.failures += 1;
85 byName.set(span.name, stats);
86 };
87
88 const finish = () => {
89 const minutes = (lastEndMs - firstEndMs) / 60_000;
90 const spans = [...byName]
91 .map(([name, { durations, interrupted, failures }]) => {
92 const sorted = durations.toSorted((left, right) => left - right);
93 // Nearest-rank percentile.
94 const percentile = (p: number) => sorted[Math.ceil(p * sorted.length) - 1]!;
95 return {
96 name,
97 count: sorted.length,
98 perMinute: minutes > 0 ? sorted.length / minutes : undefined,
99 p50Ms: percentile(0.5),
100 p90Ms: percentile(0.9),
101 maxMs: sorted[sorted.length - 1]!,
102 interrupted,
103 failures,
104 };
105 })
106 .toSorted((left, right) => right.count - left.count || left.name.localeCompare(right.name));
107
108 return { spanCount, skippedLineCount, firstEndMs, lastEndMs, minutes, spans };
109 };
110
111 return { addLine, finish };
112}
113
114const formatMs = (ms: number) =>
115 ms < 1_000 ? `${Math.round(ms)}ms` : `${(ms / 1_000).toFixed(1)}s`;
116
117function formatTraceSummary(
118 summary: ReturnType<ReturnType<typeof makeTraceSpanSummary>["finish"]>,
119 limit: number,
120) {
121 const header = ["span", "count", "/min", "p50", "p90", "max", "interrupted", "failed"];
122 const rows = summary.spans
123 .slice(0, limit)
124 .map((span) => [
125 span.name,
126 String(span.count),
127 span.perMinute === undefined
128 ? "-"
129 : span.perMinute < 0.1
130 ? "<0.1"
131 : span.perMinute.toFixed(1),
132 formatMs(span.p50Ms),
133 formatMs(span.p90Ms),
134 formatMs(span.maxMs),
135 String(span.interrupted),
136 String(span.failures),
137 ]);
138 const table = [header, ...rows];
139 const widths = header.map((_, column) => Math.max(...table.map((row) => row[column]!.length)));
140 const formatIso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms));
141 return [
142 `${summary.spanCount} spans ended from ${formatIso(summary.firstEndMs)} to ${formatIso(summary.lastEndMs)} (${summary.minutes.toFixed(1)} min).`,
143 ...(summary.skippedLineCount > 0
144 ? [`Skipped ${summary.skippedLineCount} lines that are not spans.`]
145 : []),
146 "",
147 ...table.map((row) =>
148 row
149 .map((cell, column) =>
150 column === 0 ? cell.padEnd(widths[column]!) : cell.padStart(widths[column]!),
151 )
152 .join(" "),
153 ),
154 ...(summary.spans.length > limit
155 ? ["", `${summary.spans.length - limit} more span names. Use --limit to show more.`]
156 : []),
157 ].join("\n");
158}
159
160const traceSummaryCommand = Command.make("summary", {
161 baseDir: baseDirFlag,
162 since: Flag.String("since").pipe(
163 Flag.withSchema(DurationFromString),
164 Flag.withDescription("Only count spans that ended in this window, for example 30m or 2h."),
165 Flag.optional,
166 ),
167 limit: Flag.Int("limit").pipe(
168 Flag.withSchema(PositiveInt),
169 Flag.withDescription("Number of span names to show, busiest first."),
170 Flag.withDefault(25),
171 ),
172}).pipe(
173 Command.withDescription("Summarize the local server trace file: counts, rates, and latency."),
174 Command.withHandler(
175 Effect.fn("cli.trace.summary")(function* (flags) {
176 const fs = yield* FileSystem.FileSystem;
177 // T3CODE_TRACE_FILE, else the userdata trace file for --base-dir or
178 // T3CODE_HOME. Implicit dev runs write elsewhere; set T3CODE_TRACE_FILE.
179 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
180 const baseDir = yield* resolveBaseDir(
181 Option.getOrUndefined(Option.orElse(flags.baseDir, () => envHome)),
182 );
183 const traceFilePath =
184 (yield* traceFileConfig) ??
185 (yield* ServerConfig.deriveServerPaths(baseDir, undefined)).serverTracePath;
186 const sinceMs = Option.isSome(flags.since)
187 ? (yield* Clock.currentTimeMillis) - Duration.toMillis(flags.since.value)
188 : undefined;
189 const summarizer = makeTraceSpanSummary(sinceMs);
190 // Stream each file so only one chunk of text is in memory at a time.
191 yield* Effect.forEach(
192 toRotatedTracePaths(traceFilePath, yield* traceMaxFilesConfig),
193 (path) =>
194 fs.stream(path).pipe(
195 Stream.decodeText,
196 Stream.splitLines,
197 Stream.runForEachArray((lines) => Effect.sync(() => lines.forEach(summarizer.addLine))),
198 Effect.catchTags({
199 PlatformError: (cause) =>
200 cause.reason._tag === "NotFound"
201 ? Effect.void
202 : Effect.fail(
203 new TraceFileReadError({
204 traceFilePath: path,
205 causeTag: cause.reason._tag,
206 cause,
207 }),
208 ),
209 }),
210 ),
211 { discard: true },
212 );
213 const summary = summarizer.finish();
214
215 yield* Console.log(
216 summary.spanCount === 0
217 ? `No spans found in ${traceFilePath} or its rotated files${sinceMs === undefined ? "" : " in that window"}.${summary.skippedLineCount > 0 ? ` Skipped ${summary.skippedLineCount} lines that are not spans.` : ""}`
218 : formatTraceSummary(summary, flags.limit),
219 );
220 }),
221 ),
222);
223
224export const traceCommand = Command.make("trace").pipe(
225 Command.withDescription("Inspect the local server trace file."),
226 Command.withSubcommands([traceSummaryCommand]),
227);