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