Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

trace.ts

225 lines8.4 KB

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