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 firstEndNanos: bigint | undefined;
50 let lastEndNanos: bigint | undefined;
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 // Epoch nanoseconds exceed float precision, so rate bounds stay exact until subtracted.
75 const endNanos =
76 typeof span.endTimeUnixNano === "bigint"
77 ? span.endTimeUnixNano
78 : BigInt(Math.round(span.endTimeUnixNano));
79 if (firstEndNanos === undefined || endNanos < firstEndNanos) firstEndNanos = endNanos;
80 if (lastEndNanos === undefined || endNanos > lastEndNanos) lastEndNanos = endNanos;
81 const printedMs =
82 typeof span.endTimeUnixNano === "bigint" ? Number(span.endTimeUnixNano / 1_000_000n) : endMs;
83 firstPrintedMs = Math.min(firstPrintedMs, printedMs);
84 lastPrintedMs = Math.max(lastPrintedMs, printedMs);
85 const stats = byName.get(span.name) ?? { durations: [], interrupted: 0, failures: 0 };
86 stats.durations.push(span.durationMs);
87 if (
88 span.exit?._tag === "Interrupted" ||
89 span.attributes?.["effect.fiber.interrupted"] === true ||
90 (span.status?.code === "1" && span.status.message === "Interrupted")
91 ) {
92 stats.interrupted += 1;
93 }
94 if (span.exit?._tag === "Failure" || span.status?.code === "2") stats.failures += 1;
95 byName.set(span.name, stats);
96 };
97
98 const finish = () => {
99 const minutes = Number((lastEndNanos ?? 0n) - (firstEndNanos ?? 0n)) / 60_000_000_000;
100 const spans = [...byName]
101 .map(([name, { durations, interrupted, failures }]) => {
102 const sorted = durations.toSorted((left, right) => left - right);
103 const percentile = (p: number) => sorted[Math.ceil(p * sorted.length) - 1]!;
104 return {
105 name,
106 count: sorted.length,
107 perMinute: minutes > 0 ? sorted.length / minutes : undefined,
108 p50Ms: percentile(0.5),
109 p90Ms: percentile(0.9),
110 maxMs: sorted[sorted.length - 1]!,
111 interrupted,
112 failures,
113 };
114 })
115 .toSorted((left, right) => right.count - left.count || left.name.localeCompare(right.name));
116
117 return {
118 spanCount,
119 skippedLineCount,
120 firstEndMs: firstPrintedMs,
121 lastEndMs: lastPrintedMs,
122 minutes,
123 spans,
124 };
125 };
126
127 return { addLine, finish };
128}
129
130const formatSkippedLines = (count: number) =>
131 count === 1 ? "Skipped 1 line that is not a span." : `Skipped ${count} lines that are not spans.`;
132
133const formatMs = (ms: number) =>
134 Math.round(ms) < 1_000 ? `${Math.round(ms)}ms` : `${Math.round(ms / 100) / 10}s`;
135
136export function formatTraceSummary(
137 summary: ReturnType<ReturnType<typeof makeTraceSpanSummary>["finish"]>,
138 limit: number,
139) {
140 const header = ["span", "count", "/min", "p50", "p90", "max", "interrupted", "failed"];
141 const rows = summary.spans
142 .slice(0, limit)
143 .map((span) => [
144 span.name,
145 String(span.count),
146 span.perMinute === undefined
147 ? "-"
148 : span.perMinute < 0.1
149 ? "<0.1"
150 : span.perMinute.toFixed(1),
151 formatMs(span.p50Ms),
152 formatMs(span.p90Ms),
153 formatMs(span.maxMs),
154 String(span.interrupted),
155 String(span.failures),
156 ]);
157 const table = [header, ...rows];
158 const widths = header.map((_, column) =>
159 table.reduce((max, row) => Math.max(max, row[column]!.length), 0),
160 );
161 const formatIso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms));
162 const hiddenCount = summary.spans.length - limit;
163 return [
164 `${summary.spanCount} ${summary.spanCount === 1 ? "span" : "spans"} ended from ${formatIso(summary.firstEndMs)} to ${formatIso(summary.lastEndMs)} (${summary.minutes.toFixed(1).replace(/\.0+$/, "")} min).`,
165 ...(summary.skippedLineCount > 0 ? [formatSkippedLines(summary.skippedLineCount)] : []),
166 "",
167 ...table.map((row) =>
168 row
169 .map((cell, column) =>
170 column === 0 ? cell.padEnd(widths[column]!) : cell.padStart(widths[column]!),
171 )
172 .join(" "),
173 ),
174 ...(hiddenCount > 0
175 ? [
176 "",
177 `${hiddenCount} more ${hiddenCount === 1 ? "span name" : "span names"}. Use --limit to show more.`,
178 ]
179 : []),
180 ].join("\n");
181}
182
183const traceSummaryCommand = Command.make("summary", {
184 baseDir: baseDirFlag,
185 since: Flag.String("since").pipe(
186 Flag.withSchema(DurationFromString),
187 Flag.withDescription("Only count spans that ended in this window, for example 30m or 2h."),
188 Flag.optional,
189 ),
190 limit: Flag.Int("limit").pipe(
191 Flag.withSchema(PositiveInt),
192 Flag.withDescription("Number of span names to show, busiest first."),
193 Flag.withDefault(25),
194 ),
195}).pipe(
196 Command.withDescription("Summarize the local server trace file: counts, rates, and latency."),
197 Command.withHandler(
198 Effect.fn("cli.trace.summary")(function* (flags) {
199 const fs = yield* FileSystem.FileSystem;
200 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
201 const baseDir = yield* resolveBaseDir(
202 Option.getOrUndefined(Option.orElse(flags.baseDir, () => envHome)),
203 );
204 const traceFilePath =
205 (yield* traceFileConfig) ??
206 (yield* ServerConfig.deriveServerPaths(baseDir, undefined)).serverTracePath;
207 const window = Option.isSome(flags.since)
208 ? { nowMs: yield* Clock.currentTimeMillis, duration: flags.since.value }
209 : undefined;
210 const summarizer = makeTraceSpanSummary(window);
211 const reads = yield* Effect.forEach(
212 toRotatedTracePaths(traceFilePath, yield* traceMaxFilesConfig),
213 (path) => streamTraceFileLines(fs, path, summarizer.addLine).pipe(Effect.result),
214 );
215 const summary = summarizer.finish();
216 const failures = reads.filter(Result.isFailure);
217 const firstFailure = failures[0];
218 if (
219 firstFailure &&
220 summary.spanCount === 0 &&
221 !reads.some((read) => Result.isSuccess(read) && read.success)
222 ) {
223 return yield* firstFailure.failure;
224 }
225 for (const { failure } of failures) {
226 yield* Console.error(failure.message);
227 }
228
229 yield* Console.log(
230 summary.spanCount === 0
231 ? `No spans found in ${traceFilePath} or its rotated files${window === undefined ? "" : " in that window"}.${summary.skippedLineCount > 0 ? ` ${formatSkippedLines(summary.skippedLineCount)}` : ""}`
232 : formatTraceSummary(summary, flags.limit),
233 );
234 }),
235 ),
236);
237
238export const traceCommand = Command.make("trace").pipe(
239 Command.withDescription("Inspect the local server trace file."),
240 Command.withSubcommands([traceSummaryCommand]),
241);