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

trace.ts

197 lines7.2 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.FiniteFromString,
24 exit: Schema.optional(Schema.Struct({ _tag: Schema.String })),
25 // Effect's OTLP tracer writes code "2" for errors. It marks interrupts
26 // with an `effect.fiber.interrupted` attribute; clients before Effect
27 // 4.0.2 wrote code "1" with message "Interrupted" instead.
28 status: Schema.optional(
29 Schema.Struct({
30 code: Schema.optional(Schema.String),
31 message: Schema.optional(Schema.String),
32 }),
33 ),
34 attributes: Schema.optional(
35 Schema.Struct({ "effect.fiber.interrupted": Schema.optional(Schema.Unknown) }),
36 ),
37 }),
38 ),
39);
40​
41export function makeTraceSpanSummary(sinceMs = -Infinity) {
42 const byName = new Map<string, { durations: number[]; interrupted: number; failures: number }>();
43 let spanCount = 0;
44 let skippedLineCount = 0;
45 let firstEndMs = Infinity;
46 let lastEndMs = -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 = 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 const stats = byName.get(span.name) ?? { durations: [], interrupted: 0, failures: 0 };
67 stats.durations.push(span.durationMs);
68 if (
69 span.exit?._tag === "Interrupted" ||
70 span.attributes?.["effect.fiber.interrupted"] === true ||
71 span.status?.message === "Interrupted"
72 ) {
73 stats.interrupted += 1;
74 }
75 if (span.exit?._tag === "Failure" || span.status?.code === "2") stats.failures += 1;
76 byName.set(span.name, stats);
77 };
78​
79 const finish = () => {
80 const minutes = (lastEndMs - firstEndMs) / 60_000;
81 const spans = [...byName]
82 .map(([name, { durations, interrupted, failures }]) => {
83 const sorted = durations.toSorted((left, right) => left - right);
84 const percentile = (p: number) => sorted[Math.ceil(p * sorted.length) - 1]!;
85 return {
86 name,
87 count: sorted.length,
88 perMinute: minutes > 0 ? sorted.length / minutes : undefined,
89 p50Ms: percentile(0.5),
90 p90Ms: percentile(0.9),
91 maxMs: sorted[sorted.length - 1]!,
92 interrupted,
93 failures,
94 };
95 })
96 .toSorted((left, right) => right.count - left.count || left.name.localeCompare(right.name));
97​
98 return { spanCount, skippedLineCount, firstEndMs, lastEndMs, minutes, spans };
99 };
100​
101 return { addLine, finish };
103​
104const formatMs = (ms: number) =>
105 ms < 1_000 ? `${Math.round(ms)}ms` : `${(ms / 1_000).toFixed(1)}s`;
106​
107function formatTraceSummary(
108 summary: ReturnType<ReturnType<typeof makeTraceSpanSummary>["finish"]>,
109 limit: number,
110) {
111 const header = ["span", "count", "/min", "p50", "p90", "max", "interrupted", "failed"];
112 const rows = summary.spans
113 .slice(0, limit)
114 .map((span) => [
115 span.name,
116 String(span.count),
117 span.perMinute === undefined
118 ? "-"
119 : span.perMinute < 0.1
120 ? "<0.1"
121 : span.perMinute.toFixed(1),
122 formatMs(span.p50Ms),
123 formatMs(span.p90Ms),
124 formatMs(span.maxMs),
125 String(span.interrupted),
126 String(span.failures),
127 ]);
128 const table = [header, ...rows];
129 const widths = header.map((_, column) => Math.max(...table.map((row) => row[column]!.length)));
130 const formatIso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms));
131 return [
132 `${summary.spanCount} spans ended from ${formatIso(summary.firstEndMs)} to ${formatIso(summary.lastEndMs)} (${summary.minutes.toFixed(1)} min).`,
133 ...(summary.skippedLineCount > 0
134 ? [`Skipped ${summary.skippedLineCount} lines that are not spans.`]
135 : []),
136 "",
137 ...table.map((row) =>
138 row
139 .map((cell, column) =>
140 column === 0 ? cell.padEnd(widths[column]!) : cell.padStart(widths[column]!),
141 )
142 .join(" "),
143 ),
144 ...(summary.spans.length > limit
145 ? ["", `${summary.spans.length - limit} more span names. Use --limit to show more.`]
146 : []),
147 ].join("\n");
149​
150const traceSummaryCommand = Command.make("summary", {
151 baseDir: baseDirFlag,
152 since: Flag.String("since").pipe(
153 Flag.withSchema(DurationFromString),
154 Flag.withDescription("Only count spans that ended in this window, for example 30m or 2h."),
155 Flag.optional,
156 ),
157 limit: Flag.Int("limit").pipe(
158 Flag.withSchema(PositiveInt),
159 Flag.withDescription("Number of span names to show, busiest first."),
160 Flag.withDefault(25),
161 ),
162}).pipe(
163 Command.withDescription("Summarize the local server trace file: counts, rates, and latency."),
164 Command.withHandler(
165 Effect.fn("cli.trace.summary")(function* (flags) {
166 const fs = yield* FileSystem.FileSystem;
167 const envHome = yield* Config.String("T3CODE_HOME").pipe(Config.option);
168 const baseDir = yield* resolveBaseDir(
169 Option.getOrUndefined(Option.orElse(flags.baseDir, () => envHome)),
170 );
171 const traceFilePath =
172 (yield* traceFileConfig) ??
173 (yield* ServerConfig.deriveServerPaths(baseDir, undefined)).serverTracePath;
174 const sinceMs = Option.isSome(flags.since)
175 ? (yield* Clock.currentTimeMillis) - Duration.toMillis(flags.since.value)
176 : undefined;
177 const summarizer = makeTraceSpanSummary(sinceMs);
178 yield* Effect.forEach(
179 toRotatedTracePaths(traceFilePath, yield* traceMaxFilesConfig),
180 (path) => streamTraceFileLines(fs, path, summarizer.addLine),
181 { discard: true },
182 );
183 const summary = summarizer.finish();
184​
185 yield* Console.log(
186 summary.spanCount === 0
187 ? `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.` : ""}`
188 : formatTraceSummary(summary, flags.limit),
189 );
190 }),
191 ),
192);
193​
194export const traceCommand = Command.make("trace").pipe(
195 Command.withDescription("Inspect the local server trace file."),
196 Command.withSubcommands([traceSummaryCommand]),
197);