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