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

TraceDiagnostics.ts

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