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