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

observability.ts

813 lines24.6 KB

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;
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>>;
71​
72export interface TraceRecordLink {
73 readonly traceId: string;
74 readonly spanId: string;
75 readonly attributes: Readonly<Record<string, unknown>>;
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>;
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 };
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;
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 );
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;
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";
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>;
165​
166export interface TraceSinkFlushStats {
167 readonly logicalWriteBytes: number;
168 readonly count: number;
169 readonly durationMs: number;
171​
172export interface TraceSink {
173 readonly filePath: string;
174 push: (record: TraceRecord) => void;
175 flush: Effect.Effect<void>;
176 close: () => Effect.Effect<void>;
178​
179export interface LocalFileTracerOptions extends TraceSinkOptions {
180 readonly delegate?: Tracer.Tracer;
181 readonly sink?: TraceSink;
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 >;
203​
204function isPlainObject(value: unknown): value is Record<string, unknown> {
205 return typeof value === "object" && value !== null && !Array.isArray(value);
207​
208function markSeen(value: object, seen: WeakSet<object>): boolean {
209 if (seen.has(value)) {
210 return true;
211 }
212 seen.add(value);
213 return false;
215​
216function normalizeJsonValue(value: unknown, seen: WeakSet<object> = new WeakSet()): unknown {
217 if (
218 value === null ||
219 value === undefined ||
220 typeof value === "string" ||
221 typeof value === "number" ||
222 typeof value === "boolean"
223 ) {
224 return value ?? null;
225 }
226 if (typeof value === "bigint") {
227 return value.toString();
228 }
229 if (value instanceof Date) {
230 return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
231 }
232 if (value instanceof Error) {
233 return {
234 name: value.name,
235 message: value.message,
236 ...(value.stack ? { stack: value.stack } : {}),
237 };
238 }
239 if (Array.isArray(value)) {
240 if (markSeen(value, seen)) {
241 return "[Circular]";
242 }
243 return value.map((entry) => normalizeJsonValue(entry, seen));
244 }
245 if (value instanceof Map) {
246 if (markSeen(value, seen)) {
247 return "[Circular]";
248 }
249 return Object.fromEntries(
250 Array.from(value.entries(), ([key, entryValue]) => [
251 String(key),
252 normalizeJsonValue(entryValue, seen),
253 ]),
254 );
255 }
256 if (value instanceof Set) {
257 if (markSeen(value, seen)) {
258 return "[Circular]";
259 }
260 return Array.from(value.values(), (entry) => normalizeJsonValue(entry, seen));
261 }
262 if (!isPlainObject(value)) {
263 return String(value);
264 }
265 if (markSeen(value, seen)) {
266 return "[Circular]";
267 }
268 return Object.fromEntries(
269 Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, seen)]),
270 );
272​
273export function compactTraceAttributes(
274 attributes: Readonly<Record<string, unknown>>,
275): TraceAttributes {
276 const entries: Array<[string, unknown]> = [];
277 for (const [key, value] of Object.entries(attributes)) {
278 if (value !== undefined) {
279 entries.push([key, normalizeJsonValue(value)]);
280 }
281 }
282 return Object.fromEntries(entries);
284​
285function formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord["exit"] {
286 if (ExitRuntime.isSuccess(exit)) {
287 return { _tag: "Success" };
288 }
289 if (Cause.hasInterruptsOnly(exit.cause)) {
290 return {
291 _tag: "Interrupted",
292 cause: Cause.pretty(exit.cause),
293 };
294 }
295 return {
296 _tag: "Failure",
297 cause: Cause.pretty(exit.cause),
298 };
300​
301const TRACE_ATTRIBUTE_MAX_LENGTH = 500;
302const TRACE_ATTRIBUTE_TRUNCATED_LENGTH = 200;
303const TRACE_ATTRIBUTE_TRUNCATION_SUFFIX = "…[truncated]";
304const ALWAYS_TRUNCATED_TRACE_ATTRIBUTES: ReadonlySet<string> = new Set(["db.query.text"]);
305​
306function truncateNestedValue(value: unknown): unknown {
307 if (typeof value === "string") {
308 return value.length <= TRACE_ATTRIBUTE_MAX_LENGTH
309 ? value
310 : `${value.slice(0, TRACE_ATTRIBUTE_MAX_LENGTH)}${TRACE_ATTRIBUTE_TRUNCATION_SUFFIX}`;
311 }
312 if (Array.isArray(value)) {
313 const truncated = value.map(truncateNestedValue);
314 return truncated.some((entry, index) => entry !== value[index]) ? truncated : value;
315 }
316 if (isPlainObject(value)) {
317 let truncated: Record<string, unknown> | undefined;
318 for (const [key, entry] of Object.entries(value)) {
319 const next = truncateNestedValue(entry);
320 if (next === entry) continue;
321 truncated ??= { ...value };
322 truncated[key] = next;
323 }
324 return truncated ?? value;
325 }
326 return value;
328​
329/** Clones only when clamping; never mutates attributes shared with other tracers. */
330export function truncateTraceAttributes(attributes: TraceAttributes): TraceAttributes {
331 let truncated: Record<string, unknown> | undefined;
332 for (const [key, value] of Object.entries(attributes)) {
333 if (typeof value === "string" && ALWAYS_TRUNCATED_TRACE_ATTRIBUTES.has(key)) {
334 if (value.length <= TRACE_ATTRIBUTE_TRUNCATED_LENGTH) continue;
335 truncated ??= { ...attributes };
336 truncated[key] =
337 `${value.slice(0, TRACE_ATTRIBUTE_TRUNCATED_LENGTH)}${TRACE_ATTRIBUTE_TRUNCATION_SUFFIX}`;
338 continue;
339 }
340 const next = truncateNestedValue(value);
341 if (next === value) continue;
342 truncated ??= { ...attributes };
343 truncated[key] = next;
344 }
345 return truncated ?? attributes;
347​
348function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {
349 const status = span.status as Extract<Tracer.SpanStatus, { _tag: "Ended" }>;
350 const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;
351​
352 return {
353 type: "effect-span",
354 name: span.name,
355 traceId: span.traceId,
356 spanId: span.spanId,
357 ...(parentSpanId ? { parentSpanId } : {}),
358 sampled: span.sampled,
359 kind: span.kind,
360 startTimeUnixNano: String(status.startTime),
361 endTimeUnixNano: String(status.endTime),
362 durationMs: Number(status.endTime - status.startTime) / 1_000_000,
363 attributes: truncateTraceAttributes(
364 compactTraceAttributes(Object.fromEntries(span.attributes)),
365 ),
366 events: span.events.map(([name, startTime, attributes]) => ({
367 name,
368 timeUnixNano: String(startTime),
369 attributes: truncateTraceAttributes(compactTraceAttributes(attributes)),
370 })),
371 links: span.links.map((link) => ({
372 traceId: link.span.traceId,
373 spanId: link.span.spanId,
374 attributes: truncateTraceAttributes(compactTraceAttributes(link.attributes)),
375 })),
376 exit: formatTraceExit(status.exit),
377 };
379​
380export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) {
381 const sink = yield* makeAsyncRotatingFileSink({
382 filePath: options.filePath,
383 maxBytes: options.maxBytes,
384 maxFiles: options.maxFiles,
385 }).pipe(Effect.orDie);
386​
387 let buffer: Array<{ readonly text: string; readonly bytes: number }> = [];
388 let bufferBytes = 0;
389 const maxBufferBytes = Math.max(options.maxBytes, 4 * 1024 * 1024);
390 const flushRequests = yield* Queue.sliding<void>(1);
391 const flushSemaphore = yield* Semaphore.make(1);
392 let writeFailing = false;
393 let droppedCount = 0;
394 let failureReported = false;
395 let pendingFlushStats: TraceSinkFlushStats = {
396 logicalWriteBytes: 0,
397 count: 0,
398 durationMs: 0,
399 };
400​
401 const flushBuffered = Effect.gen(function* () {
402 if (buffer.length === 0) {
403 return;
404 }
405​
406 const records = buffer;
407 buffer = [];
408 bufferBytes = 0;
409 let persistedCount = 0;
410​
411 while (persistedCount < records.length) {
412 const firstRecordBytes = records[persistedCount]!.bytes;
413 let nextIndex = persistedCount + 1;
414 let chunkBytes = firstRecordBytes;
415 while (nextIndex < records.length) {
416 const nextRecordBytes = records[nextIndex]!.bytes;
417 if (chunkBytes + nextRecordBytes > options.maxBytes) break;
418 chunkBytes += nextRecordBytes;
419 nextIndex += 1;
420 }
421​
422 const chunk = records
423 .slice(persistedCount, nextIndex)
424 .map((record) => record.text)
425 .join("");
426 const startedAt = performance.now();
427 const written = yield* sink.write(chunk).pipe(Effect.result);
428 if (Result.isFailure(written)) {
429 // Drop the batch after disk failure to avoid an ever-growing retry backlog.
430 writeFailing = true;
431 droppedCount += records.length - persistedCount;
432 return;
433 }
434 writeFailing = false;
435 pendingFlushStats = {
436 logicalWriteBytes: pendingFlushStats.logicalWriteBytes + chunkBytes,
437 count: pendingFlushStats.count + nextIndex - persistedCount,
438 durationMs: pendingFlushStats.durationMs + Math.max(0, performance.now() - startedAt),
439 };
440 persistedCount = nextIndex;
441 }
442 });
443​
444 const flush = flushSemaphore
445 .withPermits(1)(
446 Effect.gen(function* () {
447 const droppedAtStart = droppedCount;
448 yield* flushBuffered;
449 const stats = pendingFlushStats;
450 pendingFlushStats = {
451 logicalWriteBytes: 0,
452 count: 0,
453 durationMs: 0,
454 };
455 if (stats.count > 0 && options.onFlush) {
456 yield* options.onFlush(stats).pipe(Effect.ignore);
457 }
458 if (droppedCount > 0 && !failureReported) {
459 failureReported = true;
460 yield* Effect.logWarning(
461 "Trace writer could not keep up, dropping records until it recovers",
462 {
463 filePath: options.filePath,
464 },
465 );
466 } else if (failureReported && !writeFailing && droppedCount === droppedAtStart) {
467 yield* Effect.logInfo("Trace writes recovered", {
468 filePath: options.filePath,
469 droppedCount,
470 });
471 failureReported = false;
472 droppedCount = 0;
473 }
474 }),
475 )
476 .pipe(
477 // Cancelled OS writes still finish; await completion before rotation or finalizer drain.
478 Effect.uninterruptible,
479 Effect.withTracerEnabled(false),
480 // Drop the ended makeTraceSink parent span so timed-fiber logs cannot accumulate on it.
481 Effect.updateContext(Context.omit(Tracer.ParentSpan)<never>),
482 );
483​
484 yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));
485 yield* Effect.forkScoped(
486 Queue.take(flushRequests).pipe(
487 Effect.timeoutOption(`${options.batchWindowMs} millis`),
488 Effect.andThen(flush),
489 Effect.forever,
490 ),
491 );
492​
493 return {
494 filePath: options.filePath,
495 push(record) {
496 try {
497 const text = `${JSON.stringify(record)}\n`;
498 const bytes = Buffer.byteLength(text);
499 if (bytes > options.maxBytes) return;
500 if (bufferBytes + bytes > maxBufferBytes) {
501 droppedCount++;
502 return;
503 }
504 buffer.push({ text, bytes });
505 bufferBytes += bytes;
506 if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {
507 Queue.offerUnsafe(flushRequests, undefined);
508 }
509 } catch {
510 return;
511 }
512 },
513 flush,
514 close: () => flush,
515 } satisfies TraceSink;
516});
517​
518class LocalFileSpan implements Tracer.Span {
519 readonly _tag = "Span";
520 readonly name: string;
521 readonly spanId: string;
522 readonly traceId: string;
523 readonly parent: Option.Option<Tracer.AnySpan>;
524 readonly annotations: Tracer.Span["annotations"];
525 readonly links: Array<Tracer.SpanLink>;
526 readonly sampled: boolean;
527 readonly kind: Tracer.SpanKind;
528​
529 status: Tracer.SpanStatus;
530 attributes: Map<string, unknown>;
531 events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
532 private readonly delegate: Tracer.Span;
533 private readonly push: (record: EffectTraceRecord) => void;
534​
535 constructor(
536 options: Parameters<Tracer.Tracer["span"]>[0],
537 delegate: Tracer.Span,
538 push: (record: EffectTraceRecord) => void,
539 ) {
540 this.delegate = delegate;
541 this.push = push;
542 this.name = delegate.name;
543 this.spanId = delegate.spanId;
544 this.traceId = delegate.traceId;
545 this.parent = options.parent;
546 this.annotations = options.annotations;
547 this.links = [...options.links];
548 this.sampled = delegate.sampled;
549 this.kind = delegate.kind;
550 this.status = {
551 _tag: "Started",
552 startTime: options.startTime,
553 };
554 this.attributes = new Map();
555 this.events = [];
556 }
557​
558 end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
559 // Cached lookup fibers retain parent spans. Traces need success status, not result payloads.
560 const traceExit = ExitRuntime.isSuccess(exit) ? ExitRuntime.void : exit;
561 this.status = {
562 _tag: "Ended",
563 startTime: this.status.startTime,
564 endTime,
565 exit: traceExit,
566 };
567 this.delegate.end(endTime, traceExit);
568​
569 if (this.sampled) {
570 this.push(spanToTraceRecord(this));
571 }
572 }
573​
574 attribute(key: string, value: unknown): void {
575 this.attributes.set(key, value);
576 this.delegate.attribute(key, value);
577 }
578​
579 event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
580 const nextAttributes = attributes ?? {};
581 this.events.push([name, startTime, nextAttributes]);
582 this.delegate.event(name, startTime, nextAttributes);
583 }
584​
585 addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
586 this.links.push(...links);
587 this.delegate.addLinks(links);
588 }
590​
591export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
592 options: LocalFileTracerOptions,
593) {
594 const sink =
595 options.sink ??
596 (yield* makeTraceSink({
597 filePath: options.filePath,
598 maxBytes: options.maxBytes,
599 maxFiles: options.maxFiles,
600 batchWindowMs: options.batchWindowMs,
601 ...(options.onFlush ? { onFlush: options.onFlush } : {}),
602 }));
603​
604 const delegate =
605 options.delegate ??
606 Tracer.make({
607 span: (spanOptions) => new Tracer.NativeSpan(spanOptions),
608 });
609​
610 return Tracer.make({
611 span(spanOptions) {
612 return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);
613 },
614 ...(delegate.context ? { context: delegate.context } : {}),
615 });
616});
617​
618const SPAN_KIND_MAP: Record<number, OtlpTraceRecord["kind"]> = {
619 1: "internal",
620 2: "server",
621 3: "client",
622 4: "producer",
623 5: "consumer",
624};
625​
626export function decodeOtlpTraceRecords(
627 payload: OtlpTracer.TraceData,
628): ReadonlyArray<OtlpTraceRecord> {
629 const records: Array<OtlpTraceRecord> = [];
630​
631 for (const resourceSpan of payload.resourceSpans) {
632 const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes ?? []);
633​
634 for (const scopeSpan of resourceSpan.scopeSpans) {
635 for (const span of scopeSpan.spans) {
636 records.push(
637 otlpSpanToTraceRecord({
638 resourceAttributes,
639 scopeAttributes: decodeAttributes(
640 "attributes" in scopeSpan.scope && Array.isArray(scopeSpan.scope.attributes)
641 ? scopeSpan.scope.attributes
642 : [],
643 ),
644 scopeName: scopeSpan.scope.name,
645 scopeVersion:
646 "version" in scopeSpan.scope && typeof scopeSpan.scope.version === "string"
647 ? scopeSpan.scope.version
648 : undefined,
649 span,
650 }),
651 );
652 }
653 }
654 }
655​
656 return records;
658​
659function otlpSpanToTraceRecord(input: {
660 readonly resourceAttributes: Readonly<Record<string, unknown>>;
661 readonly scopeAttributes: Readonly<Record<string, unknown>>;
662 readonly scopeName: string | undefined;
663 readonly scopeVersion: string | undefined;
664 readonly span: OtlpSpan;
665}): OtlpTraceRecord {
666 return {
667 type: "otlp-span",
668 name: input.span.name,
669 traceId: input.span.traceId,
670 spanId: input.span.spanId,
671 ...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}),
672 sampled: true,
673 kind: normalizeSpanKind(input.span.kind),
674 startTimeUnixNano: input.span.startTimeUnixNano,
675 endTimeUnixNano: input.span.endTimeUnixNano,
676 durationMs:
677 Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) /
678 1_000_000,
679 attributes: decodeAttributes(input.span.attributes),
680 resourceAttributes: input.resourceAttributes,
681 scope: {
682 ...(input.scopeName ? { name: input.scopeName } : {}),
683 ...(input.scopeVersion ? { version: input.scopeVersion } : {}),
684 attributes: input.scopeAttributes,
685 },
686 events: decodeEvents(input.span.events),
687 links: decodeLinks(input.span.links),
688 status: decodeStatus(input.span.status),
689 };
691​
692function decodeStatus(input: OtlpSpanStatus): OtlpTraceRecord["status"] {
693 const code = String(input.code);
694 const message = input.message;
695​
696 return {
697 code,
698 ...(message ? { message } : {}),
699 };
701​
702function decodeEvents(input: ReadonlyArray<OtlpSpanEvent>): ReadonlyArray<TraceRecordEvent> {
703 return input.map((current) => ({
704 name: current.name,
705 timeUnixNano: current.timeUnixNano,
706 attributes: decodeAttributes(current.attributes),
707 }));
709​
710function decodeLinks(input: ReadonlyArray<OtlpSpanLink>): ReadonlyArray<TraceRecordLink> {
711 return input.flatMap((current) => {
712 const traceId = current.traceId;
713 const spanId = current.spanId;
714 return {
715 traceId,
716 spanId,
717 attributes: decodeAttributes(current.attributes),
718 };
719 });
721​
722function decodeAttributes(
723 input: ReadonlyArray<OtlpResource.KeyValue>,
724): Readonly<Record<string, unknown>> {
725 const entries: Record<string, unknown> = {};
726​
727 for (const attribute of input) {
728 entries[attribute.key] = decodeValue(attribute.value);
729 }
730​
731 return truncateTraceAttributes(compactTraceAttributes(entries));
733​
734function decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown {
735 if (input == null) {
736 return null;
737 }
738 if ("stringValue" in input) {
739 return input.stringValue;
740 }
741 if ("boolValue" in input) {
742 return input.boolValue;
743 }
744 if ("intValue" in input) {
745 return input.intValue;
746 }
747 if ("doubleValue" in input) {
748 return input.doubleValue;
749 }
750 if ("bytesValue" in input) {
751 return input.bytesValue;
752 }
753 if (input.arrayValue) {
754 return input.arrayValue.values.map((entry) => decodeValue(entry));
755 }
756 if (input.kvlistValue) {
757 return decodeAttributes(input.kvlistValue.values);
758 }
759 return null;
761​
762function normalizeSpanKind(input: number): OtlpTraceRecord["kind"] {
763 return SPAN_KIND_MAP[input] || "internal";
765​
766function parseBigInt(input: string): bigint {
767 try {
768 return BigInt(input);
769 } catch {
770 return 0n;
771 }
773​
774export const OtlpHeadersFromString = Schema.String.pipe(
775 Schema.decodeTo(
776 Schema.Record(Schema.String, Schema.String),
777 SchemaTransformation.transformEffect({
778 decode: (input) => {
779 const headers: Record<string, string> = {};
780 for (const pair of input.split(",")) {
781 if (pair.trim() === "") {
782 continue;
783 }
784 const separator = pair.indexOf("=");
785 const key = separator === -1 ? "" : pair.slice(0, separator).trim();
786 if (key === "") {
787 return Effect.fail(
788 new SchemaIssue.InvalidValue({
789 message: `Expected key=value but received ${JSON.stringify(pair.trim())}.`,
790 }),
791 );
792 }
793 try {
794 headers[key] = decodeURIComponent(pair.slice(separator + 1).trim());
795 } catch {
796 return Effect.fail(
797 new SchemaIssue.InvalidValue({
798 message: `Header ${JSON.stringify(key)} has a malformed percent-encoded value.`,
799 }),
800 );
801 }
802 }
803 return Effect.succeed(headers);
804 },
805 encode: (headers) =>
806 Effect.succeed(
807 Object.entries(headers)
808 .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
809 .join(","),
810 ),
811 }),
812 ),
813);