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

TraceDiagnostics.ts

492 lines15.6 KB

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