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