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