Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import type * as Exit from "effect/Exit";
5import * as ExitRuntime from "effect/Exit";
6import * as Option from "effect/Option";
7import * as Queue from "effect/Queue";
8import * as Result from "effect/Result";
9import * as Semaphore from "effect/Semaphore";
10import * as Schema from "effect/Schema";
11import * as SchemaIssue from "effect/SchemaIssue";
12import * as SchemaTransformation from "effect/SchemaTransformation";
13import * as Tracer from "effect/Tracer";
14import { OtlpResource, OtlpTracer, OtlpSerialization } from "effect/observability";
15
16import { makeAsyncRotatingFileSink } from "./logging.ts";
17
18export const OtlpProtocol = Schema.Literals(["http/json", "http/protobuf"]);
19export type OtlpProtocol = typeof OtlpProtocol.Type;
20export const layerOtlpSerialization = (protocol: OtlpProtocol) =>
21 protocol === "http/protobuf" ? OtlpSerialization.layerProtobuf : OtlpSerialization.layerJson;
22
23export interface SignalExport {
24 readonly protocol: OtlpProtocol;
25 readonly headers: Readonly<Record<string, string>> | undefined;
26 readonly exportIntervalMs: number;
27}
28
29/**
30 * `process.runtime.*` resource attributes for a Node process, matching the
31 * OpenTelemetry Node process detector. Electron embeds Node, so an Electron
32 * process reports Node and names Electron in the description.
33 */
34export const nodeProcessRuntimeAttributes = (): Record<string, string> => ({
35 "process.runtime.name": "nodejs",
36 "process.runtime.version": process.versions.node,
37 "process.runtime.description": process.versions.electron
38 ? `Electron ${process.versions.electron}`
39 : "Node.js",
40});
41let generatedServiceInstanceId: string | undefined;
42
43/**
44 * `service.instance.id` shared by every resource this process exports. Effect lets code
45 * attributes beat `OTEL_RESOURCE_ATTRIBUTES`, so callers pass the operator's in to keep it winning.
46 */
47export const processServiceInstanceId = (
48 operatorAttributes: Readonly<Record<string, string>> = {},
49): string => {
50 if (operatorAttributes["service.instance.id"]) return operatorAttributes["service.instance.id"];
51 // @effect-diagnostics-next-line cryptoRandomUUID:off -- Resources are built synchronously, outside any Effect.
52 generatedServiceInstanceId ??= crypto.randomUUID();
53 return generatedServiceInstanceId;
54};
55
56export const DEFAULT_SIGNAL_EXPORT: SignalExport = {
57 protocol: "http/json",
58 headers: undefined,
59 exportIntervalMs: 10_000,
60};
61
62const FLUSH_BUFFER_THRESHOLD = 256;
63
64export type TraceAttributes = Readonly<Record<string, unknown>>;
65
66export interface TraceRecordEvent {
67 readonly name: string;
68 readonly timeUnixNano: string;
69 readonly attributes: Readonly<Record<string, unknown>>;
70}
71
72export interface TraceRecordLink {
73 readonly traceId: string;
74 readonly spanId: string;
75 readonly attributes: Readonly<Record<string, unknown>>;
76}
77
78interface BaseTraceRecord {
79 readonly name: string;
80 readonly kind: string;
81 readonly traceId: string;
82 readonly spanId: string;
83 readonly parentSpanId?: string;
84 readonly sampled: boolean;
85 readonly startTimeUnixNano: string;
86 readonly endTimeUnixNano: string;
87 readonly durationMs: number;
88 readonly attributes: Readonly<Record<string, unknown>>;
89 readonly events: ReadonlyArray<TraceRecordEvent>;
90 readonly links: ReadonlyArray<TraceRecordLink>;
91}
92
93export interface EffectTraceRecord extends BaseTraceRecord {
94 readonly type: "effect-span";
95 readonly exit:
96 | {
97 readonly _tag: "Success";
98 }
99 | {
100 readonly _tag: "Interrupted";
101 readonly cause: string;
102 }
103 | {
104 readonly _tag: "Failure";
105 readonly cause: string;
106 };
107}
108
109export interface OtlpTraceRecord extends BaseTraceRecord {
110 readonly type: "otlp-span";
111 readonly resourceAttributes: Readonly<Record<string, unknown>>;
112 readonly scope: Readonly<{
113 readonly name?: string;
114 readonly version?: string;
115 readonly attributes: Readonly<Record<string, unknown>>;
116 }>;
117 readonly status?:
118 | {
119 readonly code?: string;
120 readonly message?: string;
121 }
122 | undefined;
123}
124
125export type TraceRecord = EffectTraceRecord | OtlpTraceRecord;
126
127function isStructuralTag(value: unknown): value is string {
128 return (
129 typeof value === "string" &&
130 value.length > 0 &&
131 value.length <= 128 &&
132 /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value)
133 );
134}
135
136export function errorTag(error: unknown): string {
137 try {
138 if (typeof error === "object" && error !== null && "_tag" in error) {
139 return isStructuralTag(error._tag) ? error._tag : "TaggedError";
140 }
141 if (error instanceof Error) {
142 return isStructuralTag(error.name) ? error.name : "Error";
143 }
144 } catch {
145 return "UnknownError";
146 }
147 return typeof error;
148}
149
150export function causeErrorTag(cause: Cause.Cause<unknown>): string {
151 const failure = Cause.findErrorOption(cause);
152 if (Option.isSome(failure)) {
153 return errorTag(failure.value);
154 }
155 return cause.reasons[0]?._tag ?? "Empty";
156}
157
158export interface TraceSinkOptions {
159 readonly filePath: string;
160 readonly maxBytes: number;
161 readonly maxFiles: number;
162 readonly batchWindowMs: number;
163 readonly onFlush?: (stats: TraceSinkFlushStats) => Effect.Effect<void>;
164}
165
166export interface TraceSinkFlushStats {
167 readonly logicalWriteBytes: number;
168 readonly count: number;
169 readonly durationMs: number;
170}
171
172export interface TraceSink {
173 readonly filePath: string;
174 push: (record: TraceRecord) => void;
175 flush: Effect.Effect<void>;
176 close: () => Effect.Effect<void>;
177}
178
179export interface LocalFileTracerOptions extends TraceSinkOptions {
180 readonly delegate?: Tracer.Tracer;
181 readonly sink?: TraceSink;
182}
183
184type OtlpSpan = OtlpTracer.ScopeSpan["spans"][number];
185type OtlpSpanEvent = OtlpSpan["events"][number];
186type OtlpSpanLink = OtlpSpan["links"][number];
187type OtlpSpanStatus = OtlpSpan["status"];
188
189interface SerializableSpan {
190 readonly name: string;
191 readonly traceId: string;
192 readonly spanId: string;
193 readonly parent: Option.Option<Tracer.AnySpan>;
194 readonly status: Tracer.SpanStatus;
195 readonly sampled: boolean;
196 readonly kind: Tracer.SpanKind;
197 readonly attributes: ReadonlyMap<string, unknown>;
198 readonly links: ReadonlyArray<Tracer.SpanLink>;
199 readonly events: ReadonlyArray<
200 readonly [name: string, startTime: bigint, attributes: Record<string, unknown>]
201 >;
202}
203
204function isPlainObject(value: unknown): value is Record<string, unknown> {
205 return typeof value === "object" && value !== null && !Array.isArray(value);
206}
207
208// Repeated references expand once per path, so a small shared graph can grow exponentially.
209const TRACE_ATTRIBUTE_MAX_NODES = 10_000;
210
211interface NormalizeState {
212 // Only the current ancestors, so a value repeated under two keys is not a cycle.
213 readonly seen: WeakSet<object>;
214 remainingNodes: number;
215}
216
217function enterNode(value: object, state: NormalizeState): string | undefined {
218 if (state.seen.has(value)) {
219 return "[Circular]";
220 }
221 if (state.remainingNodes <= 0) {
222 return "[Truncated]";
223 }
224 state.remainingNodes--;
225 state.seen.add(value);
226 return undefined;
227}
228
229function normalizeJsonValue(value: unknown, state: NormalizeState): unknown {
230 if (
231 value === null ||
232 value === undefined ||
233 typeof value === "string" ||
234 typeof value === "number" ||
235 typeof value === "boolean"
236 ) {
237 return value ?? null;
238 }
239 if (typeof value === "bigint") {
240 return value.toString();
241 }
242 if (value instanceof Date) {
243 return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
244 }
245 if (value instanceof Error) {
246 return {
247 name: value.name,
248 message: value.message,
249 ...(value.stack ? { stack: value.stack } : {}),
250 };
251 }
252 if (Array.isArray(value)) {
253 const marker = enterNode(value, state);
254 if (marker) {
255 return marker;
256 }
257 const normalized = value.map((entry) => normalizeJsonValue(entry, state));
258 state.seen.delete(value);
259 return normalized;
260 }
261 if (value instanceof Map) {
262 const marker = enterNode(value, state);
263 if (marker) {
264 return marker;
265 }
266 const normalized = Object.fromEntries(
267 Array.from(value.entries(), ([key, entryValue]) => [
268 String(key),
269 normalizeJsonValue(entryValue, state),
270 ]),
271 );
272 state.seen.delete(value);
273 return normalized;
274 }
275 if (value instanceof Set) {
276 const marker = enterNode(value, state);
277 if (marker) {
278 return marker;
279 }
280 const normalized = Array.from(value.values(), (entry) => normalizeJsonValue(entry, state));
281 state.seen.delete(value);
282 return normalized;
283 }
284 if (!isPlainObject(value)) {
285 return String(value);
286 }
287 const marker = enterNode(value, state);
288 if (marker) {
289 return marker;
290 }
291 const normalized = Object.fromEntries(
292 Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, state)]),
293 );
294 state.seen.delete(value);
295 return normalized;
296}
297
298export function compactTraceAttributes(
299 attributes: Readonly<Record<string, unknown>>,
300): TraceAttributes {
301 const state: NormalizeState = { seen: new WeakSet(), remainingNodes: TRACE_ATTRIBUTE_MAX_NODES };
302 const entries: Array<[string, unknown]> = [];
303 for (const [key, value] of Object.entries(attributes)) {
304 if (value !== undefined) {
305 entries.push([key, normalizeJsonValue(value, state)]);
306 }
307 }
308 return Object.fromEntries(entries);
309}
310
311function formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord["exit"] {
312 if (ExitRuntime.isSuccess(exit)) {
313 return { _tag: "Success" };
314 }
315 if (Cause.hasInterruptsOnly(exit.cause)) {
316 return {
317 _tag: "Interrupted",
318 cause: Cause.pretty(exit.cause),
319 };
320 }
321 return {
322 _tag: "Failure",
323 cause: Cause.pretty(exit.cause),
324 };
325}
326
327const TRACE_ATTRIBUTE_MAX_LENGTH = 500;
328const TRACE_ATTRIBUTE_TRUNCATED_LENGTH = 200;
329const TRACE_ATTRIBUTE_TRUNCATION_SUFFIX = "…[truncated]";
330const ALWAYS_TRUNCATED_TRACE_ATTRIBUTES: ReadonlySet<string> = new Set(["db.query.text"]);
331
332function truncateNestedValue(value: unknown): unknown {
333 if (typeof value === "string") {
334 return value.length <= TRACE_ATTRIBUTE_MAX_LENGTH
335 ? value
336 : `${value.slice(0, TRACE_ATTRIBUTE_MAX_LENGTH)}${TRACE_ATTRIBUTE_TRUNCATION_SUFFIX}`;
337 }
338 if (Array.isArray(value)) {
339 const truncated = value.map(truncateNestedValue);
340 return truncated.some((entry, index) => entry !== value[index]) ? truncated : value;
341 }
342 if (isPlainObject(value)) {
343 let truncated: Record<string, unknown> | undefined;
344 for (const [key, entry] of Object.entries(value)) {
345 const next = truncateNestedValue(entry);
346 if (next === entry) continue;
347 truncated ??= { ...value };
348 truncated[key] = next;
349 }
350 return truncated ?? value;
351 }
352 return value;
353}
354
355/** Clones only when clamping; never mutates attributes shared with other tracers. */
356export function truncateTraceAttributes(attributes: TraceAttributes): TraceAttributes {
357 let truncated: Record<string, unknown> | undefined;
358 for (const [key, value] of Object.entries(attributes)) {
359 if (typeof value === "string" && ALWAYS_TRUNCATED_TRACE_ATTRIBUTES.has(key)) {
360 if (value.length <= TRACE_ATTRIBUTE_TRUNCATED_LENGTH) continue;
361 truncated ??= { ...attributes };
362 truncated[key] =
363 `${value.slice(0, TRACE_ATTRIBUTE_TRUNCATED_LENGTH)}${TRACE_ATTRIBUTE_TRUNCATION_SUFFIX}`;
364 continue;
365 }
366 const next = truncateNestedValue(value);
367 if (next === value) continue;
368 truncated ??= { ...attributes };
369 truncated[key] = next;
370 }
371 return truncated ?? attributes;
372}
373
374function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {
375 const status = span.status as Extract<Tracer.SpanStatus, { _tag: "Ended" }>;
376 const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;
377
378 return {
379 type: "effect-span",
380 name: span.name,
381 traceId: span.traceId,
382 spanId: span.spanId,
383 ...(parentSpanId ? { parentSpanId } : {}),
384 sampled: span.sampled,
385 kind: span.kind,
386 startTimeUnixNano: String(status.startTime),
387 endTimeUnixNano: String(status.endTime),
388 durationMs: Number(status.endTime - status.startTime) / 1_000_000,
389 attributes: truncateTraceAttributes(
390 compactTraceAttributes(Object.fromEntries(span.attributes)),
391 ),
392 events: span.events.map(([name, startTime, attributes]) => ({
393 name,
394 timeUnixNano: String(startTime),
395 attributes: truncateTraceAttributes(compactTraceAttributes(attributes)),
396 })),
397 links: span.links.map((link) => ({
398 traceId: link.span.traceId,
399 spanId: link.span.spanId,
400 attributes: truncateTraceAttributes(compactTraceAttributes(link.attributes)),
401 })),
402 exit: formatTraceExit(status.exit),
403 };
404}
405
406// WebSocket tickets and their DPoP proofs ride in URL queries and stay valid after the request.
407const URL_CREDENTIAL_PARAMS = /(^|[?&"\s])(wsTicket|dpop)=[^&#"\\\s]*/g;
408
409const redactUrlCredentials = (text: string) =>
410 text.replace(URL_CREDENTIAL_PARAMS, "$1$2=<redacted>");
411
412export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) {
413 const sink = yield* makeAsyncRotatingFileSink({
414 filePath: options.filePath,
415 maxBytes: options.maxBytes,
416 maxFiles: options.maxFiles,
417 }).pipe(Effect.orDie);
418
419 let buffer: Array<{ readonly text: string; readonly bytes: number }> = [];
420 let bufferBytes = 0;
421 const maxBufferBytes = Math.max(options.maxBytes, 4 * 1024 * 1024);
422 const flushRequests = yield* Queue.sliding<void>(1);
423 const flushSemaphore = yield* Semaphore.make(1);
424 let writeFailing = false;
425 let droppedCount = 0;
426 let failureReported = false;
427 let pendingFlushStats: TraceSinkFlushStats = {
428 logicalWriteBytes: 0,
429 count: 0,
430 durationMs: 0,
431 };
432
433 const flushBuffered = Effect.gen(function* () {
434 if (buffer.length === 0) {
435 return;
436 }
437
438 const records = buffer;
439 buffer = [];
440 bufferBytes = 0;
441 let persistedCount = 0;
442
443 while (persistedCount < records.length) {
444 const firstRecordBytes = records[persistedCount]!.bytes;
445 let nextIndex = persistedCount + 1;
446 let chunkBytes = firstRecordBytes;
447 while (nextIndex < records.length) {
448 const nextRecordBytes = records[nextIndex]!.bytes;
449 if (chunkBytes + nextRecordBytes > options.maxBytes) break;
450 chunkBytes += nextRecordBytes;
451 nextIndex += 1;
452 }
453
454 const chunk = records
455 .slice(persistedCount, nextIndex)
456 .map((record) => record.text)
457 .join("");
458 const startedAt = performance.now();
459 const written = yield* sink.write(chunk).pipe(Effect.result);
460 if (Result.isFailure(written)) {
461 // Drop the batch after disk failure to avoid an ever-growing retry backlog.
462 writeFailing = true;
463 droppedCount += records.length - persistedCount;
464 return;
465 }
466 writeFailing = false;
467 pendingFlushStats = {
468 logicalWriteBytes: pendingFlushStats.logicalWriteBytes + chunkBytes,
469 count: pendingFlushStats.count + nextIndex - persistedCount,
470 durationMs: pendingFlushStats.durationMs + Math.max(0, performance.now() - startedAt),
471 };
472 persistedCount = nextIndex;
473 }
474 });
475
476 const flush = flushSemaphore
477 .withPermits(1)(
478 Effect.gen(function* () {
479 const droppedAtStart = droppedCount;
480 yield* flushBuffered;
481 const stats = pendingFlushStats;
482 pendingFlushStats = {
483 logicalWriteBytes: 0,
484 count: 0,
485 durationMs: 0,
486 };
487 if (stats.count > 0 && options.onFlush) {
488 yield* options.onFlush(stats).pipe(Effect.ignore);
489 }
490 if (droppedCount > 0 && !failureReported) {
491 failureReported = true;
492 yield* Effect.logWarning(
493 "Trace writer could not keep up, dropping records until it recovers",
494 {
495 filePath: options.filePath,
496 },
497 );
498 } else if (failureReported && !writeFailing && droppedCount === droppedAtStart) {
499 yield* Effect.logInfo("Trace writes recovered", {
500 filePath: options.filePath,
501 droppedCount,
502 });
503 failureReported = false;
504 droppedCount = 0;
505 }
506 }),
507 )
508 .pipe(
509 // Cancelled OS writes still finish; await completion before rotation or finalizer drain.
510 Effect.uninterruptible,
511 Effect.withTracerEnabled(false),
512 // Drop the ended makeTraceSink parent span so timed-fiber logs cannot accumulate on it.
513 Effect.updateContext(Context.omit(Tracer.ParentSpan)<never>),
514 );
515
516 yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));
517 yield* Effect.forkScoped(
518 Queue.take(flushRequests).pipe(
519 Effect.timeoutOption(`${options.batchWindowMs} millis`),
520 Effect.andThen(flush),
521 Effect.forever,
522 ),
523 );
524
525 return {
526 filePath: options.filePath,
527 push(record) {
528 try {
529 const text = `${redactUrlCredentials(JSON.stringify(record))}\n`;
530 const bytes = Buffer.byteLength(text);
531 if (bytes > options.maxBytes) return;
532 if (bufferBytes + bytes > maxBufferBytes) {
533 droppedCount++;
534 return;
535 }
536 buffer.push({ text, bytes });
537 bufferBytes += bytes;
538 if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {
539 Queue.offerUnsafe(flushRequests, undefined);
540 }
541 } catch {
542 return;
543 }
544 },
545 flush,
546 close: () => flush,
547 } satisfies TraceSink;
548});
549
550// Effect's HTTP errors, including failed upgrades, put the request URL in their message.
551export function redactCauseCredentials(cause: Cause.Cause<unknown>): Cause.Cause<unknown> {
552 if (cause.reasons.length === 0 || Cause.hasInterruptsOnly(cause)) {
553 return cause;
554 }
555 const pretty = Cause.pretty(cause);
556 const redacted = redactUrlCredentials(pretty);
557 return redacted === pretty ? cause : Cause.die(new Error(redacted));
558}
559
560function redactExitCredentials(exit: Exit.Exit<unknown, unknown>): Exit.Exit<unknown, unknown> {
561 if (ExitRuntime.isSuccess(exit)) {
562 return exit;
563 }
564 const cause = redactCauseCredentials(exit.cause);
565 return cause === exit.cause ? exit : ExitRuntime.failCause(cause);
566}
567
568class LocalFileSpan implements Tracer.Span {
569 readonly _tag = "Span";
570 readonly name: string;
571 readonly spanId: string;
572 readonly traceId: string;
573 readonly parent: Option.Option<Tracer.AnySpan>;
574 readonly annotations: Tracer.Span["annotations"];
575 readonly links: Array<Tracer.SpanLink>;
576 readonly sampled: boolean;
577 readonly kind: Tracer.SpanKind;
578
579 status: Tracer.SpanStatus;
580 attributes: Map<string, unknown>;
581 events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
582 private readonly delegate: Tracer.Span;
583 private readonly push: (record: EffectTraceRecord) => void;
584
585 constructor(
586 options: Parameters<Tracer.Tracer["span"]>[0],
587 delegate: Tracer.Span,
588 push: (record: EffectTraceRecord) => void,
589 ) {
590 this.delegate = delegate;
591 this.push = push;
592 this.name = delegate.name;
593 this.spanId = delegate.spanId;
594 this.traceId = delegate.traceId;
595 this.parent = options.parent;
596 this.annotations = options.annotations;
597 this.links = [...options.links];
598 this.sampled = delegate.sampled;
599 this.kind = delegate.kind;
600 this.status = {
601 _tag: "Started",
602 startTime: options.startTime,
603 };
604 this.attributes = new Map();
605 this.events = [];
606 }
607
608 end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
609 // Cached lookup fibers retain parent spans. Traces need success status, not result payloads.
610 const traceExit = ExitRuntime.isSuccess(exit) ? ExitRuntime.void : exit;
611 this.status = {
612 _tag: "Ended",
613 startTime: this.status.startTime,
614 endTime,
615 exit: traceExit,
616 };
617 this.delegate.end(endTime, redactExitCredentials(traceExit));
618
619 if (this.sampled) {
620 this.push(spanToTraceRecord(this));
621 }
622 }
623
624 attribute(key: string, value: unknown): void {
625 const recorded =
626 (key === "url.full" || key === "url.query") && typeof value === "string"
627 ? redactUrlCredentials(value)
628 : value;
629 this.attributes.set(key, recorded);
630 this.delegate.attribute(key, recorded);
631 }
632
633 event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
634 const cause = attributes?.["effect.cause"];
635 const nextAttributes =
636 typeof cause === "string"
637 ? { ...attributes, "effect.cause": redactUrlCredentials(cause) }
638 : (attributes ?? {});
639 this.events.push([name, startTime, nextAttributes]);
640 this.delegate.event(name, startTime, nextAttributes);
641 }
642
643 addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
644 this.links.push(...links);
645 this.delegate.addLinks(links);
646 }
647}
648
649export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
650 options: LocalFileTracerOptions,
651) {
652 const sink =
653 options.sink ??
654 (yield* makeTraceSink({
655 filePath: options.filePath,
656 maxBytes: options.maxBytes,
657 maxFiles: options.maxFiles,
658 batchWindowMs: options.batchWindowMs,
659 ...(options.onFlush ? { onFlush: options.onFlush } : {}),
660 }));
661
662 const delegate =
663 options.delegate ??
664 Tracer.make({
665 span: (spanOptions) => new Tracer.NativeSpan(spanOptions),
666 });
667
668 return Tracer.make({
669 span(spanOptions) {
670 return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);
671 },
672 ...(delegate.context ? { context: delegate.context } : {}),
673 });
674});
675
676const SPAN_KIND_MAP: Record<number, OtlpTraceRecord["kind"]> = {
677 1: "internal",
678 2: "server",
679 3: "client",
680 4: "producer",
681 5: "consumer",
682};
683
684export function decodeOtlpTraceRecords(
685 payload: OtlpTracer.TraceData,
686): ReadonlyArray<OtlpTraceRecord> {
687 const records: Array<OtlpTraceRecord> = [];
688
689 for (const resourceSpan of payload.resourceSpans) {
690 const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes ?? []);
691
692 for (const scopeSpan of resourceSpan.scopeSpans) {
693 for (const span of scopeSpan.spans) {
694 records.push(
695 otlpSpanToTraceRecord({
696 resourceAttributes,
697 scopeAttributes: decodeAttributes(
698 "attributes" in scopeSpan.scope && Array.isArray(scopeSpan.scope.attributes)
699 ? scopeSpan.scope.attributes
700 : [],
701 ),
702 scopeName: scopeSpan.scope.name,
703 scopeVersion:
704 "version" in scopeSpan.scope && typeof scopeSpan.scope.version === "string"
705 ? scopeSpan.scope.version
706 : undefined,
707 span,
708 }),
709 );
710 }
711 }
712 }
713
714 return records;
715}
716
717function otlpSpanToTraceRecord(input: {
718 readonly resourceAttributes: Readonly<Record<string, unknown>>;
719 readonly scopeAttributes: Readonly<Record<string, unknown>>;
720 readonly scopeName: string | undefined;
721 readonly scopeVersion: string | undefined;
722 readonly span: OtlpSpan;
723}): OtlpTraceRecord {
724 return {
725 type: "otlp-span",
726 name: input.span.name,
727 traceId: input.span.traceId,
728 spanId: input.span.spanId,
729 ...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}),
730 sampled: true,
731 kind: normalizeSpanKind(input.span.kind),
732 startTimeUnixNano: input.span.startTimeUnixNano,
733 endTimeUnixNano: input.span.endTimeUnixNano,
734 durationMs:
735 Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) /
736 1_000_000,
737 attributes: decodeAttributes(input.span.attributes),
738 resourceAttributes: input.resourceAttributes,
739 scope: {
740 ...(input.scopeName ? { name: input.scopeName } : {}),
741 ...(input.scopeVersion ? { version: input.scopeVersion } : {}),
742 attributes: input.scopeAttributes,
743 },
744 events: decodeEvents(input.span.events),
745 links: decodeLinks(input.span.links),
746 status: decodeStatus(input.span.status),
747 };
748}
749
750function decodeStatus(input: OtlpSpanStatus): OtlpTraceRecord["status"] {
751 const code = String(input.code);
752 const message = input.message;
753
754 return {
755 code,
756 ...(message ? { message } : {}),
757 };
758}
759
760function decodeEvents(input: ReadonlyArray<OtlpSpanEvent>): ReadonlyArray<TraceRecordEvent> {
761 return input.map((current) => ({
762 name: current.name,
763 timeUnixNano: current.timeUnixNano,
764 attributes: decodeAttributes(current.attributes),
765 }));
766}
767
768function decodeLinks(input: ReadonlyArray<OtlpSpanLink>): ReadonlyArray<TraceRecordLink> {
769 return input.flatMap((current) => {
770 const traceId = current.traceId;
771 const spanId = current.spanId;
772 return {
773 traceId,
774 spanId,
775 attributes: decodeAttributes(current.attributes),
776 };
777 });
778}
779
780function decodeAttributes(
781 input: ReadonlyArray<OtlpResource.KeyValue>,
782): Readonly<Record<string, unknown>> {
783 const entries: Record<string, unknown> = {};
784
785 for (const attribute of input) {
786 entries[attribute.key] = decodeValue(attribute.value);
787 }
788
789 return truncateTraceAttributes(compactTraceAttributes(entries));
790}
791
792function decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown {
793 if (input == null) {
794 return null;
795 }
796 if ("stringValue" in input) {
797 return input.stringValue;
798 }
799 if ("boolValue" in input) {
800 return input.boolValue;
801 }
802 if ("intValue" in input) {
803 return input.intValue;
804 }
805 if ("doubleValue" in input) {
806 return input.doubleValue;
807 }
808 if ("bytesValue" in input) {
809 return input.bytesValue;
810 }
811 if (input.arrayValue) {
812 return input.arrayValue.values.map((entry) => decodeValue(entry));
813 }
814 if (input.kvlistValue) {
815 return decodeAttributes(input.kvlistValue.values);
816 }
817 return null;
818}
819
820function normalizeSpanKind(input: number): OtlpTraceRecord["kind"] {
821 return SPAN_KIND_MAP[input] || "internal";
822}
823
824function parseBigInt(input: string): bigint {
825 try {
826 return BigInt(input);
827 } catch {
828 return 0n;
829 }
830}
831
832export const OtlpHeadersFromString = Schema.String.pipe(
833 Schema.decodeTo(
834 Schema.Record(Schema.String, Schema.String),
835 SchemaTransformation.transformEffect({
836 decode: (input) => {
837 const headers: Record<string, string> = {};
838 for (const pair of input.split(",")) {
839 if (pair.trim() === "") {
840 continue;
841 }
842 const separator = pair.indexOf("=");
843 const key = separator === -1 ? "" : pair.slice(0, separator).trim();
844 if (key === "") {
845 return Effect.fail(
846 new SchemaIssue.InvalidValue({
847 message: `Expected key=value but received ${JSON.stringify(pair.trim())}.`,
848 }),
849 );
850 }
851 try {
852 headers[key] = decodeURIComponent(pair.slice(separator + 1).trim());
853 } catch {
854 return Effect.fail(
855 new SchemaIssue.InvalidValue({
856 message: `Header ${JSON.stringify(key)} has a malformed percent-encoded value.`,
857 }),
858 );
859 }
860 }
861 return Effect.succeed(headers);
862 },
863 encode: (headers) =>
864 Effect.succeed(
865 Object.entries(headers)
866 .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
867 .join(","),
868 ),
869 }),
870 ),
871);