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