Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Effect from "effect/Effect";
3import type * as Exit from "effect/Exit";
4import * as ExitRuntime from "effect/Exit";
5import * as Option from "effect/Option";
6import * as Tracer from "effect/Tracer";
7import { OtlpResource, OtlpTracer } from "effect/unstable/observability";
8
9import { RotatingFileSink } from "./logging.ts";
10
11const FLUSH_BUFFER_THRESHOLD = 256;
12const textEncoder = new TextEncoder();
13
14export type TraceAttributes = Readonly<Record<string, unknown>>;
15
16export interface TraceRecordEvent {
17 readonly name: string;
18 readonly timeUnixNano: string;
19 readonly attributes: Readonly<Record<string, unknown>>;
20}
21
22export interface TraceRecordLink {
23 readonly traceId: string;
24 readonly spanId: string;
25 readonly attributes: Readonly<Record<string, unknown>>;
26}
27
28interface BaseTraceRecord {
29 readonly name: string;
30 readonly kind: string;
31 readonly traceId: string;
32 readonly spanId: string;
33 readonly parentSpanId?: string;
34 readonly sampled: boolean;
35 readonly startTimeUnixNano: string;
36 readonly endTimeUnixNano: string;
37 readonly durationMs: number;
38 readonly attributes: Readonly<Record<string, unknown>>;
39 readonly events: ReadonlyArray<TraceRecordEvent>;
40 readonly links: ReadonlyArray<TraceRecordLink>;
41}
42
43export interface EffectTraceRecord extends BaseTraceRecord {
44 readonly type: "effect-span";
45 readonly exit:
46 | {
47 readonly _tag: "Success";
48 }
49 | {
50 readonly _tag: "Interrupted";
51 readonly cause: string;
52 }
53 | {
54 readonly _tag: "Failure";
55 readonly cause: string;
56 };
57}
58
59export interface OtlpTraceRecord extends BaseTraceRecord {
60 readonly type: "otlp-span";
61 readonly resourceAttributes: Readonly<Record<string, unknown>>;
62 readonly scope: Readonly<{
63 readonly name?: string;
64 readonly version?: string;
65 readonly attributes: Readonly<Record<string, unknown>>;
66 }>;
67 readonly status?:
68 | {
69 readonly code?: string;
70 readonly message?: string;
71 }
72 | undefined;
73}
74
75export type TraceRecord = EffectTraceRecord | OtlpTraceRecord;
76
77function isStructuralTag(value: unknown): value is string {
78 return (
79 typeof value === "string" &&
80 value.length > 0 &&
81 value.length <= 128 &&
82 /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value)
83 );
84}
85
86export function errorTag(error: unknown): string {
87 try {
88 if (typeof error === "object" && error !== null && "_tag" in error) {
89 return isStructuralTag(error._tag) ? error._tag : "TaggedError";
90 }
91 if (error instanceof Error) {
92 return isStructuralTag(error.name) ? error.name : "Error";
93 }
94 } catch {
95 return "UnknownError";
96 }
97 return typeof error;
98}
99
100export function causeErrorTag(cause: Cause.Cause<unknown>): string {
101 const failure = Cause.findErrorOption(cause);
102 if (Option.isSome(failure)) {
103 return errorTag(failure.value);
104 }
105 return cause.reasons[0]?._tag ?? "Empty";
106}
107
108export interface TraceSinkOptions {
109 readonly filePath: string;
110 readonly maxBytes: number;
111 readonly maxFiles: number;
112 readonly batchWindowMs: number;
113 readonly onFlush?: (stats: TraceSinkFlushStats) => Effect.Effect<void>;
114}
115
116export interface TraceSinkFlushStats {
117 readonly logicalWriteBytes: number;
118 readonly count: number;
119 readonly durationMs: number;
120}
121
122export interface TraceSink {
123 readonly filePath: string;
124 push: (record: TraceRecord) => void;
125 flush: Effect.Effect<void>;
126 close: () => Effect.Effect<void>;
127}
128
129export interface LocalFileTracerOptions extends TraceSinkOptions {
130 readonly delegate?: Tracer.Tracer;
131 readonly sink?: TraceSink;
132}
133
134type OtlpSpan = OtlpTracer.ScopeSpan["spans"][number];
135type OtlpSpanEvent = OtlpSpan["events"][number];
136type OtlpSpanLink = OtlpSpan["links"][number];
137type OtlpSpanStatus = OtlpSpan["status"];
138
139interface SerializableSpan {
140 readonly name: string;
141 readonly traceId: string;
142 readonly spanId: string;
143 readonly parent: Option.Option<Tracer.AnySpan>;
144 readonly status: Tracer.SpanStatus;
145 readonly sampled: boolean;
146 readonly kind: Tracer.SpanKind;
147 readonly attributes: ReadonlyMap<string, unknown>;
148 readonly links: ReadonlyArray<Tracer.SpanLink>;
149 readonly events: ReadonlyArray<
150 readonly [name: string, startTime: bigint, attributes: Record<string, unknown>]
151 >;
152}
153
154function isPlainObject(value: unknown): value is Record<string, unknown> {
155 return typeof value === "object" && value !== null && !Array.isArray(value);
156}
157
158function markSeen(value: object, seen: WeakSet<object>): boolean {
159 if (seen.has(value)) {
160 return true;
161 }
162 seen.add(value);
163 return false;
164}
165
166function normalizeJsonValue(value: unknown, seen: WeakSet<object> = new WeakSet()): unknown {
167 if (
168 value === null ||
169 value === undefined ||
170 typeof value === "string" ||
171 typeof value === "number" ||
172 typeof value === "boolean"
173 ) {
174 return value ?? null;
175 }
176 if (typeof value === "bigint") {
177 return value.toString();
178 }
179 if (value instanceof Date) {
180 return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
181 }
182 if (value instanceof Error) {
183 return {
184 name: value.name,
185 message: value.message,
186 ...(value.stack ? { stack: value.stack } : {}),
187 };
188 }
189 if (Array.isArray(value)) {
190 if (markSeen(value, seen)) {
191 return "[Circular]";
192 }
193 return value.map((entry) => normalizeJsonValue(entry, seen));
194 }
195 if (value instanceof Map) {
196 if (markSeen(value, seen)) {
197 return "[Circular]";
198 }
199 return Object.fromEntries(
200 Array.from(value.entries(), ([key, entryValue]) => [
201 String(key),
202 normalizeJsonValue(entryValue, seen),
203 ]),
204 );
205 }
206 if (value instanceof Set) {
207 if (markSeen(value, seen)) {
208 return "[Circular]";
209 }
210 return Array.from(value.values(), (entry) => normalizeJsonValue(entry, seen));
211 }
212 if (!isPlainObject(value)) {
213 return String(value);
214 }
215 if (markSeen(value, seen)) {
216 return "[Circular]";
217 }
218 return Object.fromEntries(
219 Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, seen)]),
220 );
221}
222
223export function compactTraceAttributes(
224 attributes: Readonly<Record<string, unknown>>,
225): TraceAttributes {
226 const entries: Array<[string, unknown]> = [];
227 for (const [key, value] of Object.entries(attributes)) {
228 if (value !== undefined) {
229 entries.push([key, normalizeJsonValue(value)]);
230 }
231 }
232 return Object.fromEntries(entries);
233}
234
235function formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord["exit"] {
236 if (ExitRuntime.isSuccess(exit)) {
237 return { _tag: "Success" };
238 }
239 if (Cause.hasInterruptsOnly(exit.cause)) {
240 return {
241 _tag: "Interrupted",
242 cause: Cause.pretty(exit.cause),
243 };
244 }
245 return {
246 _tag: "Failure",
247 cause: Cause.pretty(exit.cause),
248 };
249}
250
251export function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {
252 const status = span.status as Extract<Tracer.SpanStatus, { _tag: "Ended" }>;
253 const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;
254
255 return {
256 type: "effect-span",
257 name: span.name,
258 traceId: span.traceId,
259 spanId: span.spanId,
260 ...(parentSpanId ? { parentSpanId } : {}),
261 sampled: span.sampled,
262 kind: span.kind,
263 startTimeUnixNano: String(status.startTime),
264 endTimeUnixNano: String(status.endTime),
265 durationMs: Number(status.endTime - status.startTime) / 1_000_000,
266 attributes: compactTraceAttributes(Object.fromEntries(span.attributes)),
267 events: span.events.map(([name, startTime, attributes]) => ({
268 name,
269 timeUnixNano: String(startTime),
270 attributes: compactTraceAttributes(attributes),
271 })),
272 links: span.links.map((link) => ({
273 traceId: link.span.traceId,
274 spanId: link.span.spanId,
275 attributes: compactTraceAttributes(link.attributes),
276 })),
277 exit: formatTraceExit(status.exit),
278 };
279}
280
281export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) {
282 const sink = new RotatingFileSink({
283 filePath: options.filePath,
284 maxBytes: options.maxBytes,
285 maxFiles: options.maxFiles,
286 throwOnError: true,
287 });
288
289 let buffer: Array<string> = [];
290 let pendingFlushStats: TraceSinkFlushStats = {
291 logicalWriteBytes: 0,
292 count: 0,
293 durationMs: 0,
294 };
295
296 const flushUnsafe = () => {
297 if (buffer.length === 0) {
298 return;
299 }
300
301 const records = buffer;
302 buffer = [];
303 let persistedCount = 0;
304
305 while (persistedCount < records.length) {
306 const firstRecordBytes = textEncoder.encode(records[persistedCount]).byteLength;
307 if (firstRecordBytes > options.maxBytes) {
308 persistedCount += 1;
309 continue;
310 }
311
312 let nextIndex = persistedCount + 1;
313 let chunkBytes = firstRecordBytes;
314 while (nextIndex < records.length) {
315 const nextRecordBytes = textEncoder.encode(records[nextIndex]).byteLength;
316 if (chunkBytes + nextRecordBytes > options.maxBytes) break;
317 chunkBytes += nextRecordBytes;
318 nextIndex += 1;
319 }
320
321 const chunk = records.slice(persistedCount, nextIndex).join("");
322 const startedAt = performance.now();
323 try {
324 sink.write(chunk);
325 } catch {
326 buffer.unshift(...records.slice(persistedCount));
327 return;
328 }
329 pendingFlushStats = {
330 logicalWriteBytes: pendingFlushStats.logicalWriteBytes + chunkBytes,
331 count: pendingFlushStats.count + nextIndex - persistedCount,
332 durationMs: pendingFlushStats.durationMs + Math.max(0, performance.now() - startedAt),
333 };
334 persistedCount = nextIndex;
335 }
336 };
337
338 const flush = Effect.sync(() => {
339 flushUnsafe();
340 const stats = pendingFlushStats;
341 pendingFlushStats = {
342 logicalWriteBytes: 0,
343 count: 0,
344 durationMs: 0,
345 };
346 return stats;
347 }).pipe(
348 Effect.flatMap((stats) =>
349 stats.count > 0 && options.onFlush ? options.onFlush(stats).pipe(Effect.ignore) : Effect.void,
350 ),
351 Effect.withTracerEnabled(false),
352 );
353
354 yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));
355 yield* Effect.forkScoped(
356 Effect.sleep(`${options.batchWindowMs} millis`).pipe(Effect.andThen(flush), Effect.forever),
357 );
358
359 return {
360 filePath: options.filePath,
361 push(record) {
362 try {
363 buffer.push(`${JSON.stringify(record)}\n`);
364 if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {
365 flushUnsafe();
366 }
367 } catch {
368 return;
369 }
370 },
371 flush,
372 close: () => flush,
373 } satisfies TraceSink;
374});
375
376class LocalFileSpan implements Tracer.Span {
377 readonly _tag = "Span";
378 readonly name: string;
379 readonly spanId: string;
380 readonly traceId: string;
381 readonly parent: Option.Option<Tracer.AnySpan>;
382 readonly annotations: Tracer.Span["annotations"];
383 readonly links: Array<Tracer.SpanLink>;
384 readonly sampled: boolean;
385 readonly kind: Tracer.SpanKind;
386
387 status: Tracer.SpanStatus;
388 attributes: Map<string, unknown>;
389 events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
390 private readonly delegate: Tracer.Span;
391 private readonly push: (record: EffectTraceRecord) => void;
392
393 constructor(
394 options: Parameters<Tracer.Tracer["span"]>[0],
395 delegate: Tracer.Span,
396 push: (record: EffectTraceRecord) => void,
397 ) {
398 this.delegate = delegate;
399 this.push = push;
400 this.name = delegate.name;
401 this.spanId = delegate.spanId;
402 this.traceId = delegate.traceId;
403 this.parent = options.parent;
404 this.annotations = options.annotations;
405 this.links = [...options.links];
406 this.sampled = delegate.sampled;
407 this.kind = delegate.kind;
408 this.status = {
409 _tag: "Started",
410 startTime: options.startTime,
411 };
412 this.attributes = new Map();
413 this.events = [];
414 }
415
416 end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
417 this.status = {
418 _tag: "Ended",
419 startTime: this.status.startTime,
420 endTime,
421 exit,
422 };
423 this.delegate.end(endTime, exit);
424
425 if (this.sampled) {
426 this.push(spanToTraceRecord(this));
427 }
428 }
429
430 attribute(key: string, value: unknown): void {
431 this.attributes.set(key, value);
432 this.delegate.attribute(key, value);
433 }
434
435 event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
436 const nextAttributes = attributes ?? {};
437 this.events.push([name, startTime, nextAttributes]);
438 this.delegate.event(name, startTime, nextAttributes);
439 }
440
441 addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
442 this.links.push(...links);
443 this.delegate.addLinks(links);
444 }
445}
446
447export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
448 options: LocalFileTracerOptions,
449) {
450 const sink =
451 options.sink ??
452 (yield* makeTraceSink({
453 filePath: options.filePath,
454 maxBytes: options.maxBytes,
455 maxFiles: options.maxFiles,
456 batchWindowMs: options.batchWindowMs,
457 ...(options.onFlush ? { onFlush: options.onFlush } : {}),
458 }));
459
460 const delegate =
461 options.delegate ??
462 Tracer.make({
463 span: (spanOptions) => new Tracer.NativeSpan(spanOptions),
464 });
465
466 return Tracer.make({
467 span(spanOptions) {
468 return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);
469 },
470 ...(delegate.context ? { context: delegate.context } : {}),
471 });
472});
473
474const SPAN_KIND_MAP: Record<number, OtlpTraceRecord["kind"]> = {
475 1: "internal",
476 2: "server",
477 3: "client",
478 4: "producer",
479 5: "consumer",
480};
481
482export function decodeOtlpTraceRecords(
483 payload: OtlpTracer.TraceData,
484): ReadonlyArray<OtlpTraceRecord> {
485 const records: Array<OtlpTraceRecord> = [];
486
487 for (const resourceSpan of payload.resourceSpans) {
488 const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes ?? []);
489
490 for (const scopeSpan of resourceSpan.scopeSpans) {
491 for (const span of scopeSpan.spans) {
492 records.push(
493 otlpSpanToTraceRecord({
494 resourceAttributes,
495 scopeAttributes: decodeAttributes(
496 "attributes" in scopeSpan.scope && Array.isArray(scopeSpan.scope.attributes)
497 ? scopeSpan.scope.attributes
498 : [],
499 ),
500 scopeName: scopeSpan.scope.name,
501 scopeVersion:
502 "version" in scopeSpan.scope && typeof scopeSpan.scope.version === "string"
503 ? scopeSpan.scope.version
504 : undefined,
505 span,
506 }),
507 );
508 }
509 }
510 }
511
512 return records;
513}
514
515function otlpSpanToTraceRecord(input: {
516 readonly resourceAttributes: Readonly<Record<string, unknown>>;
517 readonly scopeAttributes: Readonly<Record<string, unknown>>;
518 readonly scopeName: string | undefined;
519 readonly scopeVersion: string | undefined;
520 readonly span: OtlpSpan;
521}): OtlpTraceRecord {
522 return {
523 type: "otlp-span",
524 name: input.span.name,
525 traceId: input.span.traceId,
526 spanId: input.span.spanId,
527 ...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}),
528 sampled: true,
529 kind: normalizeSpanKind(input.span.kind),
530 startTimeUnixNano: input.span.startTimeUnixNano,
531 endTimeUnixNano: input.span.endTimeUnixNano,
532 durationMs:
533 Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) /
534 1_000_000,
535 attributes: decodeAttributes(input.span.attributes),
536 resourceAttributes: input.resourceAttributes,
537 scope: {
538 ...(input.scopeName ? { name: input.scopeName } : {}),
539 ...(input.scopeVersion ? { version: input.scopeVersion } : {}),
540 attributes: input.scopeAttributes,
541 },
542 events: decodeEvents(input.span.events),
543 links: decodeLinks(input.span.links),
544 status: decodeStatus(input.span.status),
545 };
546}
547
548function decodeStatus(input: OtlpSpanStatus): OtlpTraceRecord["status"] {
549 const code = String(input.code);
550 const message = input.message;
551
552 return {
553 code,
554 ...(message ? { message } : {}),
555 };
556}
557
558function decodeEvents(input: ReadonlyArray<OtlpSpanEvent>): ReadonlyArray<TraceRecordEvent> {
559 return input.map((current) => ({
560 name: current.name,
561 timeUnixNano: current.timeUnixNano,
562 attributes: decodeAttributes(current.attributes),
563 }));
564}
565
566function decodeLinks(input: ReadonlyArray<OtlpSpanLink>): ReadonlyArray<TraceRecordLink> {
567 return input.flatMap((current) => {
568 const traceId = current.traceId;
569 const spanId = current.spanId;
570 return {
571 traceId,
572 spanId,
573 attributes: decodeAttributes(current.attributes),
574 };
575 });
576}
577
578function decodeAttributes(
579 input: ReadonlyArray<OtlpResource.KeyValue>,
580): Readonly<Record<string, unknown>> {
581 const entries: Record<string, unknown> = {};
582
583 for (const attribute of input) {
584 entries[attribute.key] = decodeValue(attribute.value);
585 }
586
587 return compactTraceAttributes(entries);
588}
589
590function decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown {
591 if (input == null) {
592 return null;
593 }
594 if ("stringValue" in input) {
595 return input.stringValue;
596 }
597 if ("boolValue" in input) {
598 return input.boolValue;
599 }
600 if ("intValue" in input) {
601 return input.intValue;
602 }
603 if ("doubleValue" in input) {
604 return input.doubleValue;
605 }
606 if ("bytesValue" in input) {
607 return input.bytesValue;
608 }
609 if (input.arrayValue) {
610 return input.arrayValue.values.map((entry) => decodeValue(entry));
611 }
612 if (input.kvlistValue) {
613 return decodeAttributes(input.kvlistValue.values);
614 }
615 return null;
616}
617
618function normalizeSpanKind(input: number): OtlpTraceRecord["kind"] {
619 return SPAN_KIND_MAP[input] || "internal";
620}
621
622function parseBigInt(input: string): bigint {
623 try {
624 return BigInt(input);
625 } catch {
626 return 0n;
627 }
628}