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

trace.ts

220 lines8.1 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 formatMs = (ms: number) =>
126 Math.round(ms) < 1_000 ? `${Math.round(ms)}ms` : `${Math.round(ms / 100) / 10}s`;
127​
128export function formatTraceSummary(
129 summary: ReturnType<ReturnType<typeof makeTraceSpanSummary>["finish"]>,
130 limit: number,
131) {
132 const header = ["span", "count", "/min", "p50", "p90", "max", "interrupted", "failed"];
133 const rows = summary.spans
134 .slice(0, limit)
135 .map((span) => [
136 span.name,
137 String(span.count),
138 span.perMinute === undefined
139 ? "-"
140 : span.perMinute < 0.1
141 ? "<0.1"
142 : span.perMinute.toFixed(1),
143 formatMs(span.p50Ms),
144 formatMs(span.p90Ms),
145 formatMs(span.maxMs),
146 String(span.interrupted),
147 String(span.failures),
148 ]);
149 const table = [header, ...rows];
150 const widths = header.map((_, column) =>
151 table.reduce((max, row) => Math.max(max, row[column]!.length), 0),
152 );
153 const formatIso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms));
154 return [
155 `${summary.spanCount} spans ended from ${formatIso(summary.firstEndMs)} to ${formatIso(summary.lastEndMs)} (${summary.minutes.toFixed(1).replace(/\.0+$/, "")} min).`,
156 ...(summary.skippedLineCount > 0
157 ? [`Skipped ${summary.skippedLineCount} lines that are not spans.`]
158 : []),
159 "",
160 ...table.map((row) =>
161 row
162 .map((cell, column) =>
163 column === 0 ? cell.padEnd(widths[column]!) : cell.padStart(widths[column]!),
164 )
165 .join(" "),
166 ),
167 ...(summary.spans.length > limit
168 ? ["", `${summary.spans.length - limit} more span names. Use --limit to show more.`]
169 : []),
170 ].join("\n");
172​
173const traceSummaryCommand = Command.make("summary", {
174 baseDir: baseDirFlag,
175 since: Flag.String("since").pipe(
176 Flag.withSchema(DurationFromString),
177 Flag.withDescription("Only count spans that ended in this window, for example 30m or 2h."),
178 Flag.optional,
179 ),
180 limit: Flag.Int("limit").pipe(
181 Flag.withSchema(PositiveInt),
182 Flag.withDescription("Number of span names to show, busiest first."),
183 Flag.withDefault(25),
184 ),
185}).pipe(
186 Command.withDescription("Summarize the local server trace file: counts, rates, and latency."),
187 Command.withHandler(
188 Effect.fn("cli.trace.summary")(function* (flags) {
189 const fs = yield* FileSystem.FileSystem;
190 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
191 const baseDir = yield* resolveBaseDir(
192 Option.getOrUndefined(Option.orElse(flags.baseDir, () => envHome)),
193 );
194 const traceFilePath =
195 (yield* traceFileConfig) ??
196 (yield* ServerConfig.deriveServerPaths(baseDir, undefined)).serverTracePath;
197 const window = Option.isSome(flags.since)
198 ? { nowMs: yield* Clock.currentTimeMillis, duration: flags.since.value }
199 : undefined;
200 const summarizer = makeTraceSpanSummary(window);
201 yield* Effect.forEach(
202 toRotatedTracePaths(traceFilePath, yield* traceMaxFilesConfig),
203 (path) => streamTraceFileLines(fs, path, summarizer.addLine),
204 { discard: true },
205 );
206 const summary = summarizer.finish();
207​
208 yield* Console.log(
209 summary.spanCount === 0
210 ? `No spans found in ${traceFilePath} or its rotated files${window === undefined ? "" : " in that window"}.${summary.skippedLineCount > 0 ? ` Skipped ${summary.skippedLineCount} lines that are not spans.` : ""}`
211 : formatTraceSummary(summary, flags.limit),
212 );
213 }),
214 ),
215);
216​
217export const traceCommand = Command.make("trace").pipe(
218 Command.withDescription("Inspect the local server trace file."),
219 Command.withSubcommands([traceSummaryCommand]),
220);