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

TraceDiagnostics.ts

485 lines15.6 KB

1import type {
2 ServerTraceDiagnosticsErrorKind,
3 ServerTraceDiagnosticsFailureSummary,
4 ServerTraceDiagnosticsLogEvent,
5 ServerTraceDiagnosticsRecentFailure,
6 ServerTraceDiagnosticsResult,
7 ServerTraceDiagnosticsSpanOccurrence,
8 ServerTraceDiagnosticsSpanSummary,
9} from "@t3tools/contracts";
10import { WsRpcGroup } from "@t3tools/contracts";
11import * as Context from "effect/Context";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as PlatformError from "effect/PlatformError";
18import * as Result from "effect/Result";
19import * as RpcSchema from "effect/rpc/RpcSchema";
20import * as Schema from "effect/Schema";
21import * as Stream from "effect/Stream";
22​
23interface TraceEventLike {
24 readonly name?: unknown;
25 readonly timeUnixNano?: unknown;
26 readonly attributes?: unknown;
28​
29export interface TraceDiagnosticsOptions {
30 readonly traceFilePath: string;
31 readonly maxFiles: number;
32 readonly slowSpanThresholdMs?: number;
33 readonly readAt?: DateTime.Utc;
35​
36export class TraceFileReadError extends Schema.TaggedError<TraceFileReadError>()(
37 "TraceFileReadError",
38 {
39 traceFilePath: Schema.String,
40 causeTag: Schema.String,
41 cause: Schema.Defect(),
42 },
43) {
44 override get message(): string {
45 return `Failed to read local trace file '${this.traceFilePath}'.`;
46 }
48​
49export class TraceDiagnostics extends Context.Service<
50 TraceDiagnostics,
51 {
52 readonly read: (
53 options: TraceDiagnosticsOptions,
54 ) => Effect.Effect<ServerTraceDiagnosticsResult>;
55 }
56>()("t3/diagnostics/TraceDiagnostics") {}
57​
58interface TraceDiagnosticsErrorSummary {
59 readonly kind: ServerTraceDiagnosticsErrorKind;
60 readonly message: string;
62​
63const DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1_000;
64const TOP_LIMIT = 10;
65const RECENT_LIMIT = 20;
66​
67const STREAMING_RPC_METHODS: ReadonlySet<string> = new Set(
68 [...WsRpcGroup.requests.values()]
69 .filter((rpc) => RpcSchema.isStreamSchema(rpc.successSchema))
70 .map((rpc) => rpc._tag),
71);
72​
73export function toRotatedTracePaths(
74 traceFilePath: string,
75 maxFiles: number,
76): ReadonlyArray<string> {
77 const backupCount = Math.max(0, Math.floor(maxFiles));
78 const backups = Array.from(
79 { length: backupCount },
80 (_, index) => `${traceFilePath}.${backupCount - index}`,
81 );
82 return [...backups, traceFilePath];
84​
85function isRecordObject(value: unknown): value is Readonly<Record<string, unknown>> {
86 return typeof value === "object" && value !== null;
88​
89function toStringValue(value: unknown): string | null {
90 return typeof value === "string" && value.trim().length > 0 ? value : null;
92​
93function toNumberValue(value: unknown): number | null {
94 return typeof value === "number" && Number.isFinite(value) ? value : null;
96​
97function unixNanoToDateTime(value: unknown): DateTime.Utc | null {
98 const text = toStringValue(value);
99 if (!text) return null;
100 try {
101 const millis = Number(BigInt(text) / 1_000_000n);
102 return Option.getOrNull(DateTime.make(millis));
103 } catch {
104 return null;
105 }
107​
108function readExitTag(exit: unknown): string | null {
109 if (!isRecordObject(exit) || !("_tag" in exit)) return null;
110 return toStringValue(exit._tag);
112​
113function readExitCause(exit: unknown): string {
114 if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
115 return toStringValue(exit.cause)?.trim() ?? "Failure";
117​
118function isTraceEvent(value: unknown): value is TraceEventLike {
119 return typeof value === "object" && value !== null;
121​
122function readEventAttributes(event: TraceEventLike): Readonly<Record<string, unknown>> {
123 return typeof event.attributes === "object" && event.attributes !== null
124 ? (event.attributes as Readonly<Record<string, unknown>>)
125 : {};
127​
128function makeEmptyDiagnostics(input: {
129 readonly traceFilePath: string;
130 readonly scannedFilePaths: ReadonlyArray<string>;
131 readonly readAt: DateTime.Utc;
132 readonly slowSpanThresholdMs: number;
133 readonly error?: TraceDiagnosticsErrorSummary;
134 readonly partialFailure?: boolean;
135}): ServerTraceDiagnosticsResult {
136 return {
137 traceFilePath: input.traceFilePath,
138 scannedFilePaths: [...input.scannedFilePaths],
139 readAt: input.readAt,
140 recordCount: 0,
141 parseErrorCount: 0,
142 firstSpanAt: Option.none(),
143 lastSpanAt: Option.none(),
144 failureCount: 0,
145 interruptionCount: 0,
146 slowSpanThresholdMs: input.slowSpanThresholdMs,
147 slowSpanCount: 0,
148 logLevelCounts: {},
149 topSpansByCount: [],
150 slowestSpans: [],
151 commonFailures: [],
152 latestFailures: [],
153 latestWarningAndErrorLogs: [],
154 partialFailure: input.partialFailure ? Option.some(true) : Option.none(),
155 error: Option.fromNullishOr(input.error),
156 };
158​
159function isNotFoundError(error: PlatformError.PlatformError): boolean {
160 return error.reason._tag === "NotFound";
162​
163function insertBounded<A>(
164 items: A[],
165 item: A,
166 limit: number,
167 order: (left: A, right: A) => number,
168): void {
169 if (items.length >= limit && order(item, items[items.length - 1]!) >= 0) {
170 return;
171 }
172​
173 items.push(item);
174 items.sort(order);
175 if (items.length > limit) {
176 items.length = limit;
177 }
179​
180const slowestFirst = (
181 left: ServerTraceDiagnosticsSpanOccurrence,
182 right: ServerTraceDiagnosticsSpanOccurrence,
183) => right.durationMs - left.durationMs;
184​
185const latestEndedFirst = (
186 left: ServerTraceDiagnosticsRecentFailure,
187 right: ServerTraceDiagnosticsRecentFailure,
188) => DateTime.toEpochMillis(right.endedAt) - DateTime.toEpochMillis(left.endedAt);
189​
190const latestSeenFirst = (
191 left: ServerTraceDiagnosticsLogEvent,
192 right: ServerTraceDiagnosticsLogEvent,
193) => DateTime.toEpochMillis(right.seenAt) - DateTime.toEpochMillis(left.seenAt);
194​
195export function makeTraceDiagnosticsAggregator(
196 slowSpanThresholdMs = DEFAULT_SLOW_SPAN_THRESHOLD_MS,
197) {
198 let parseErrorCount = 0;
199 let recordCount = 0;
200 let failureCount = 0;
201 let interruptionCount = 0;
202 let slowSpanCount = 0;
203 let firstSpanAt: DateTime.Utc | null = null;
204 let lastSpanAt: DateTime.Utc | null = null;
205​
206 const spansByName = new Map<
207 string,
208 { count: number; failureCount: number; totalDurationMs: number; maxDurationMs: number }
209 >();
210 const failuresByKey = new Map<string, ServerTraceDiagnosticsFailureSummary>();
211 const latestFailures: ServerTraceDiagnosticsRecentFailure[] = [];
212 const slowestSpans: ServerTraceDiagnosticsSpanOccurrence[] = [];
213 const latestWarningAndErrorLogs: ServerTraceDiagnosticsLogEvent[] = [];
214 const logLevelCounts: Record<string, number> = {};
215​
216 const addLine = (line: string) => {
217 if (line.trim().length === 0) return;
218​
219 let parsed: unknown;
220 try {
221 parsed = JSON.parse(line);
222 } catch {
223 parseErrorCount += 1;
224 return;
225 }
226​
227 if (!isRecordObject(parsed)) {
228 parseErrorCount += 1;
229 return;
230 }
231​
232 const name = toStringValue(parsed.name);
233 const traceId = toStringValue(parsed.traceId);
234 const spanId = toStringValue(parsed.spanId);
235 const durationMs = toNumberValue(parsed.durationMs);
236 const endedAt = unixNanoToDateTime(parsed.endTimeUnixNano);
237 const startedAt = unixNanoToDateTime(parsed.startTimeUnixNano);
238​
239 if (!name || !traceId || !spanId || durationMs === null || !endedAt) {
240 parseErrorCount += 1;
241 return;
242 }
243​
244 recordCount += 1;
245 firstSpanAt =
246 startedAt && (firstSpanAt === null || DateTime.isLessThan(startedAt, firstSpanAt))
247 ? startedAt
248 : firstSpanAt;
249 lastSpanAt =
250 lastSpanAt === null || DateTime.isGreaterThan(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
251​
252 const exitTag = readExitTag(parsed.exit);
253 const status = isRecordObject(parsed.status) ? parsed.status : {};
254 const attributes = isRecordObject(parsed.attributes) ? parsed.attributes : {};
255 const isFailure = exitTag === "Failure" || status.code === "2";
256 const isInterrupted =
257 exitTag === "Interrupted" ||
258 attributes["effect.fiber.interrupted"] === true ||
259 (status.code === "1" && status.message === "Interrupted");
260 if (isFailure) failureCount += 1;
261 if (isInterrupted) interruptionCount += 1;
262​
263 const spanSummary = spansByName.get(name) ?? {
264 count: 0,
265 failureCount: 0,
266 totalDurationMs: 0,
267 maxDurationMs: 0,
268 };
269 spanSummary.count += 1;
270 spanSummary.totalDurationMs += durationMs;
271 spanSummary.maxDurationMs = Math.max(spanSummary.maxDurationMs, durationMs);
272 if (isFailure) spanSummary.failureCount += 1;
273 spansByName.set(name, spanSummary);
274​
275 const spanItem = { name, durationMs, endedAt, traceId, spanId };
276 // A subscription's span lasts until the client unsubscribes, so its duration is not latency.
277 const isClosedSubscription =
278 isInterrupted && STREAMING_RPC_METHODS.has(toStringValue(attributes["rpc.method"]) ?? "");
279 if (!isClosedSubscription) {
280 if (durationMs >= slowSpanThresholdMs) {
281 slowSpanCount += 1;
282 }
283 insertBounded(slowestSpans, spanItem, TOP_LIMIT, slowestFirst);
284 }
285​
286 if (isFailure) {
287 const cause =
288 exitTag === "Failure"
289 ? readExitCause(parsed.exit)
290 : (toStringValue(status.message)?.trim() ?? "Failure");
291 insertBounded(latestFailures, { ...spanItem, cause }, RECENT_LIMIT, latestEndedFirst);
292​
293 const failureKey = `${name}\0${cause}`;
294 const existing = failuresByKey.get(failureKey);
295 const isLatestFailure = !existing || DateTime.isGreaterThan(endedAt, existing.lastSeenAt);
296 failuresByKey.set(failureKey, {
297 name,
298 cause,
299 count: (existing?.count ?? 0) + 1,
300 lastSeenAt: isLatestFailure ? endedAt : existing!.lastSeenAt,
301 traceId: isLatestFailure ? traceId : existing!.traceId,
302 spanId: isLatestFailure ? spanId : existing!.spanId,
303 });
304 }
305​
306 if (Array.isArray(parsed.events)) {
307 for (const rawEvent of parsed.events) {
308 if (!isTraceEvent(rawEvent)) continue;
309 const attributes = readEventAttributes(rawEvent);
310 const level = toStringValue(attributes["effect.logLevel"]);
311 if (!level) continue;
312​
313 logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
314 const normalizedLevel = level.toLowerCase();
315 if (
316 normalizedLevel !== "warning" &&
317 normalizedLevel !== "warn" &&
318 normalizedLevel !== "error" &&
319 normalizedLevel !== "fatal"
320 ) {
321 continue;
322 }
323​
324 const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;
325 const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
326 insertBounded(
327 latestWarningAndErrorLogs,
328 { spanName: name, level, message, seenAt, traceId, spanId },
329 RECENT_LIMIT,
330 latestSeenFirst,
331 );
332 }
333 }
334 };
335​
336 const finish = (input: {
337 readonly traceFilePath: string;
338 readonly scannedFilePaths: ReadonlyArray<string>;
339 readonly readAt: DateTime.Utc;
340 readonly error?: TraceDiagnosticsErrorSummary;
341 readonly partialFailure?: boolean;
342 }): ServerTraceDiagnosticsResult => {
343 const topSpansByCount: ServerTraceDiagnosticsSpanSummary[] = [...spansByName.entries()]
344 .map(([name, span]) => ({
345 name,
346 count: span.count,
347 failureCount: span.failureCount,
348 totalDurationMs: span.totalDurationMs,
349 averageDurationMs: span.count > 0 ? span.totalDurationMs / span.count : 0,
350 maxDurationMs: span.maxDurationMs,
351 }))
352 .toSorted(
353 (left, right) => right.count - left.count || right.maxDurationMs - left.maxDurationMs,
354 )
355 .slice(0, TOP_LIMIT);
356​
357 return {
358 traceFilePath: input.traceFilePath,
359 scannedFilePaths: input.scannedFilePaths,
360 readAt: input.readAt,
361 recordCount,
362 parseErrorCount,
363 firstSpanAt: Option.fromNullishOr(firstSpanAt),
364 lastSpanAt: Option.fromNullishOr(lastSpanAt),
365 failureCount,
366 interruptionCount,
367 slowSpanThresholdMs,
368 slowSpanCount,
369 logLevelCounts,
370 topSpansByCount,
371 slowestSpans,
372 commonFailures: [...failuresByKey.values()]
373 .toSorted(
374 (left, right) =>
375 right.count - left.count ||
376 DateTime.toEpochMillis(right.lastSeenAt) - DateTime.toEpochMillis(left.lastSeenAt),
377 )
378 .slice(0, TOP_LIMIT),
379 latestFailures,
380 latestWarningAndErrorLogs,
381 partialFailure: input.partialFailure ? Option.some(true) : Option.none(),
382 error: Option.fromNullishOr(input.error),
383 };
384 };
385​
386 return { addLine, finish };
388​
389/** Succeeds with false if the file is absent. */
390export function streamTraceFileLines(
391 fileSystem: FileSystem.FileSystem,
392 path: string,
393 onLine: (line: string) => void,
394): Effect.Effect<boolean, TraceFileReadError> {
395 return fileSystem.stream(path).pipe(
396 Stream.decodeText,
397 Stream.splitLines,
398 Stream.runForEachArray((lines) => Effect.sync(() => lines.forEach(onLine))),
399 Effect.as(true),
400 Effect.catchTags({
401 PlatformError: (cause) =>
402 isNotFoundError(cause)
403 ? Effect.succeed(false)
404 : Effect.fail(
405 new TraceFileReadError({
406 traceFilePath: path,
407 causeTag: cause.reason._tag,
408 cause,
409 }),
410 ),
411 }),
412 );
414​
415/** @public */
416export const make = Effect.gen(function* () {
417 const fileSystem = yield* FileSystem.FileSystem;
418​
419 const read: TraceDiagnostics["Service"]["read"] = Effect.fn("TraceDiagnostics.read")(
420 function* (options) {
421 const readAt = options.readAt ?? (yield* DateTime.now);
422 const slowSpanThresholdMs = options.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
423 const paths = toRotatedTracePaths(options.traceFilePath, options.maxFiles);
424 const aggregator = makeTraceDiagnosticsAggregator(slowSpanThresholdMs);
425 const results = yield* Effect.forEach(
426 paths,
427 (path) =>
428 streamTraceFileLines(fileSystem, path, aggregator.addLine).pipe(
429 Effect.tapError((cause) =>
430 Effect.logWarning("Failed to read local trace file.").pipe(
431 Effect.annotateLogs({
432 traceFilePath: cause.traceFilePath,
433 errorTag: cause._tag,
434 causeTag: cause.causeTag,
435 }),
436 ),
437 ),
438 Effect.result,
439 ),
440 { concurrency: 1 },
441 );
442 const foundFile = results.some((result) => Result.isSuccess(result) && result.success);
443 const readFailure = results.find(Result.isFailure);
444 const readFailureError = readFailure
445 ? ({
446 kind: "trace-file-read-failed",
447 message: readFailure.failure.message,
448 } satisfies TraceDiagnosticsErrorSummary)
449 : undefined;
450​
451 if (!foundFile) {
452 return makeEmptyDiagnostics({
453 traceFilePath: options.traceFilePath,
454 scannedFilePaths: paths,
455 readAt,
456 slowSpanThresholdMs,
457 error:
458 readFailureError ??
459 ({
460 kind: "trace-file-not-found",
461 message: "No local trace files were found.",
462 } satisfies TraceDiagnosticsErrorSummary),
463 });
464 }
465​
466 return aggregator.finish({
467 traceFilePath: options.traceFilePath,
468 scannedFilePaths: paths,
469 readAt,
470 ...(readFailureError ? { partialFailure: true, error: readFailureError } : {}),
471 });
472 },
473 );
474​
475 return TraceDiagnostics.of({ read });
476});
477​
478export const layer = Layer.effect(TraceDiagnostics, make);
479​
480export const readTraceDiagnostics = Effect.fn("TraceDiagnostics.readTraceDiagnostics")(function* (
481 options: TraceDiagnosticsOptions,
482): Effect.fn.Return<ServerTraceDiagnosticsResult, never, TraceDiagnostics> {
483 const diagnostics = yield* TraceDiagnostics;
484 return yield* diagnostics.read(options);
485});