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