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