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

observability.ts

793 lines23.7 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​
29export const DEFAULT_SIGNAL_EXPORT: SignalExport = {
30 protocol: "http/json",
31 headers: undefined,
32 exportIntervalMs: 10_000,
33};
34​
35const FLUSH_BUFFER_THRESHOLD = 256;
36​
37export type TraceAttributes = Readonly<Record<string, unknown>>;
38​
39export interface TraceRecordEvent {
40 readonly name: string;
41 readonly timeUnixNano: string;
42 readonly attributes: Readonly<Record<string, unknown>>;
44​
45export interface TraceRecordLink {
46 readonly traceId: string;
47 readonly spanId: string;
48 readonly attributes: Readonly<Record<string, unknown>>;
50​
51interface BaseTraceRecord {
52 readonly name: string;
53 readonly kind: string;
54 readonly traceId: string;
55 readonly spanId: string;
56 readonly parentSpanId?: string;
57 readonly sampled: boolean;
58 readonly startTimeUnixNano: string;
59 readonly endTimeUnixNano: string;
60 readonly durationMs: number;
61 readonly attributes: Readonly<Record<string, unknown>>;
62 readonly events: ReadonlyArray<TraceRecordEvent>;
63 readonly links: ReadonlyArray<TraceRecordLink>;
65​
66export interface EffectTraceRecord extends BaseTraceRecord {
67 readonly type: "effect-span";
68 readonly exit:
69 | {
70 readonly _tag: "Success";
71 }
72 | {
73 readonly _tag: "Interrupted";
74 readonly cause: string;
75 }
76 | {
77 readonly _tag: "Failure";
78 readonly cause: string;
79 };
81​
82export interface OtlpTraceRecord extends BaseTraceRecord {
83 readonly type: "otlp-span";
84 readonly resourceAttributes: Readonly<Record<string, unknown>>;
85 readonly scope: Readonly<{
86 readonly name?: string;
87 readonly version?: string;
88 readonly attributes: Readonly<Record<string, unknown>>;
89 }>;
90 readonly status?:
91 | {
92 readonly code?: string;
93 readonly message?: string;
94 }
95 | undefined;
97​
98export type TraceRecord = EffectTraceRecord | OtlpTraceRecord;
99​
100function isStructuralTag(value: unknown): value is string {
101 return (
102 typeof value === "string" &&
103 value.length > 0 &&
104 value.length <= 128 &&
105 /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value)
106 );
108​
109export function errorTag(error: unknown): string {
110 try {
111 if (typeof error === "object" && error !== null && "_tag" in error) {
112 return isStructuralTag(error._tag) ? error._tag : "TaggedError";
113 }
114 if (error instanceof Error) {
115 return isStructuralTag(error.name) ? error.name : "Error";
116 }
117 } catch {
118 return "UnknownError";
119 }
120 return typeof error;
122​
123export function causeErrorTag(cause: Cause.Cause<unknown>): string {
124 const failure = Cause.findErrorOption(cause);
125 if (Option.isSome(failure)) {
126 return errorTag(failure.value);
127 }
128 return cause.reasons[0]?._tag ?? "Empty";
130​
131export interface TraceSinkOptions {
132 readonly filePath: string;
133 readonly maxBytes: number;
134 readonly maxFiles: number;
135 readonly batchWindowMs: number;
136 readonly onFlush?: (stats: TraceSinkFlushStats) => Effect.Effect<void>;
138​
139export interface TraceSinkFlushStats {
140 readonly logicalWriteBytes: number;
141 readonly count: number;
142 readonly durationMs: number;
144​
145export interface TraceSink {
146 readonly filePath: string;
147 push: (record: TraceRecord) => void;
148 flush: Effect.Effect<void>;
149 close: () => Effect.Effect<void>;
151​
152export interface LocalFileTracerOptions extends TraceSinkOptions {
153 readonly delegate?: Tracer.Tracer;
154 readonly sink?: TraceSink;
156​
157type OtlpSpan = OtlpTracer.ScopeSpan["spans"][number];
158type OtlpSpanEvent = OtlpSpan["events"][number];
159type OtlpSpanLink = OtlpSpan["links"][number];
160type OtlpSpanStatus = OtlpSpan["status"];
161​
162interface SerializableSpan {
163 readonly name: string;
164 readonly traceId: string;
165 readonly spanId: string;
166 readonly parent: Option.Option<Tracer.AnySpan>;
167 readonly status: Tracer.SpanStatus;
168 readonly sampled: boolean;
169 readonly kind: Tracer.SpanKind;
170 readonly attributes: ReadonlyMap<string, unknown>;
171 readonly links: ReadonlyArray<Tracer.SpanLink>;
172 readonly events: ReadonlyArray<
173 readonly [name: string, startTime: bigint, attributes: Record<string, unknown>]
174 >;
176​
177function isPlainObject(value: unknown): value is Record<string, unknown> {
178 return typeof value === "object" && value !== null && !Array.isArray(value);
180​
181function markSeen(value: object, seen: WeakSet<object>): boolean {
182 if (seen.has(value)) {
183 return true;
184 }
185 seen.add(value);
186 return false;
188​
189function normalizeJsonValue(value: unknown, seen: WeakSet<object> = new WeakSet()): unknown {
190 if (
191 value === null ||
192 value === undefined ||
193 typeof value === "string" ||
194 typeof value === "number" ||
195 typeof value === "boolean"
196 ) {
197 return value ?? null;
198 }
199 if (typeof value === "bigint") {
200 return value.toString();
201 }
202 if (value instanceof Date) {
203 return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
204 }
205 if (value instanceof Error) {
206 return {
207 name: value.name,
208 message: value.message,
209 ...(value.stack ? { stack: value.stack } : {}),
210 };
211 }
212 if (Array.isArray(value)) {
213 if (markSeen(value, seen)) {
214 return "[Circular]";
215 }
216 return value.map((entry) => normalizeJsonValue(entry, seen));
217 }
218 if (value instanceof Map) {
219 if (markSeen(value, seen)) {
220 return "[Circular]";
221 }
222 return Object.fromEntries(
223 Array.from(value.entries(), ([key, entryValue]) => [
224 String(key),
225 normalizeJsonValue(entryValue, seen),
226 ]),
227 );
228 }
229 if (value instanceof Set) {
230 if (markSeen(value, seen)) {
231 return "[Circular]";
232 }
233 return Array.from(value.values(), (entry) => normalizeJsonValue(entry, seen));
234 }
235 if (!isPlainObject(value)) {
236 return String(value);
237 }
238 if (markSeen(value, seen)) {
239 return "[Circular]";
240 }
241 return Object.fromEntries(
242 Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, seen)]),
243 );
245​
246export function compactTraceAttributes(
247 attributes: Readonly<Record<string, unknown>>,
248): TraceAttributes {
249 const entries: Array<[string, unknown]> = [];
250 for (const [key, value] of Object.entries(attributes)) {
251 if (value !== undefined) {
252 entries.push([key, normalizeJsonValue(value)]);
253 }
254 }
255 return Object.fromEntries(entries);
257​
258function formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord["exit"] {
259 if (ExitRuntime.isSuccess(exit)) {
260 return { _tag: "Success" };
261 }
262 if (Cause.hasInterruptsOnly(exit.cause)) {
263 return {
264 _tag: "Interrupted",
265 cause: Cause.pretty(exit.cause),
266 };
267 }
268 return {
269 _tag: "Failure",
270 cause: Cause.pretty(exit.cause),
271 };
273​
274const TRACE_ATTRIBUTE_MAX_LENGTH = 500;
275const TRACE_ATTRIBUTE_TRUNCATED_LENGTH = 200;
276const TRACE_ATTRIBUTE_TRUNCATION_SUFFIX = "…[truncated]";
277const ALWAYS_TRUNCATED_TRACE_ATTRIBUTES: ReadonlySet<string> = new Set(["db.query.text"]);
278​
279function truncateNestedValue(value: unknown): unknown {
280 if (typeof value === "string") {
281 return value.length <= TRACE_ATTRIBUTE_MAX_LENGTH
282 ? value
283 : `${value.slice(0, TRACE_ATTRIBUTE_MAX_LENGTH)}${TRACE_ATTRIBUTE_TRUNCATION_SUFFIX}`;
284 }
285 if (Array.isArray(value)) {
286 const truncated = value.map(truncateNestedValue);
287 return truncated.some((entry, index) => entry !== value[index]) ? truncated : value;
288 }
289 if (isPlainObject(value)) {
290 let truncated: Record<string, unknown> | undefined;
291 for (const [key, entry] of Object.entries(value)) {
292 const next = truncateNestedValue(entry);
293 if (next === entry) continue;
294 truncated ??= { ...value };
295 truncated[key] = next;
296 }
297 return truncated ?? value;
298 }
299 return value;
301​
302/**
303 * Returns a new record when anything was clamped; never mutates the input (the live span's
304 * attributes are shared with other tracers).
305 */
306export function truncateTraceAttributes(attributes: TraceAttributes): TraceAttributes {
307 let truncated: Record<string, unknown> | undefined;
308 for (const [key, value] of Object.entries(attributes)) {
309 if (typeof value === "string" && ALWAYS_TRUNCATED_TRACE_ATTRIBUTES.has(key)) {
310 if (value.length <= TRACE_ATTRIBUTE_TRUNCATED_LENGTH) continue;
311 truncated ??= { ...attributes };
312 truncated[key] =
313 `${value.slice(0, TRACE_ATTRIBUTE_TRUNCATED_LENGTH)}${TRACE_ATTRIBUTE_TRUNCATION_SUFFIX}`;
314 continue;
315 }
316 const next = truncateNestedValue(value);
317 if (next === value) continue;
318 truncated ??= { ...attributes };
319 truncated[key] = next;
320 }
321 return truncated ?? attributes;
323​
324function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {
325 const status = span.status as Extract<Tracer.SpanStatus, { _tag: "Ended" }>;
326 const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;
327​
328 return {
329 type: "effect-span",
330 name: span.name,
331 traceId: span.traceId,
332 spanId: span.spanId,
333 ...(parentSpanId ? { parentSpanId } : {}),
334 sampled: span.sampled,
335 kind: span.kind,
336 startTimeUnixNano: String(status.startTime),
337 endTimeUnixNano: String(status.endTime),
338 durationMs: Number(status.endTime - status.startTime) / 1_000_000,
339 attributes: truncateTraceAttributes(
340 compactTraceAttributes(Object.fromEntries(span.attributes)),
341 ),
342 events: span.events.map(([name, startTime, attributes]) => ({
343 name,
344 timeUnixNano: String(startTime),
345 attributes: truncateTraceAttributes(compactTraceAttributes(attributes)),
346 })),
347 links: span.links.map((link) => ({
348 traceId: link.span.traceId,
349 spanId: link.span.spanId,
350 attributes: truncateTraceAttributes(compactTraceAttributes(link.attributes)),
351 })),
352 exit: formatTraceExit(status.exit),
353 };
355​
356export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) {
357 const sink = yield* makeAsyncRotatingFileSink({
358 filePath: options.filePath,
359 maxBytes: options.maxBytes,
360 maxFiles: options.maxFiles,
361 }).pipe(Effect.orDie);
362​
363 let buffer: Array<{ readonly text: string; readonly bytes: number }> = [];
364 let bufferBytes = 0;
365 const maxBufferBytes = Math.max(options.maxBytes, 4 * 1024 * 1024);
366 const flushRequests = yield* Queue.sliding<void>(1);
367 const flushSemaphore = yield* Semaphore.make(1);
368 let writeFailing = false;
369 let droppedCount = 0;
370 let failureReported = false;
371 let pendingFlushStats: TraceSinkFlushStats = {
372 logicalWriteBytes: 0,
373 count: 0,
374 durationMs: 0,
375 };
376​
377 const flushBuffered = Effect.gen(function* () {
378 if (buffer.length === 0) {
379 return;
380 }
381​
382 const records = buffer;
383 buffer = [];
384 bufferBytes = 0;
385 let persistedCount = 0;
386​
387 while (persistedCount < records.length) {
388 const firstRecordBytes = records[persistedCount]!.bytes;
389 let nextIndex = persistedCount + 1;
390 let chunkBytes = firstRecordBytes;
391 while (nextIndex < records.length) {
392 const nextRecordBytes = records[nextIndex]!.bytes;
393 if (chunkBytes + nextRecordBytes > options.maxBytes) break;
394 chunkBytes += nextRecordBytes;
395 nextIndex += 1;
396 }
397​
398 const chunk = records
399 .slice(persistedCount, nextIndex)
400 .map((record) => record.text)
401 .join("");
402 const startedAt = performance.now();
403 const written = yield* sink.write(chunk).pipe(Effect.result);
404 if (Result.isFailure(written)) {
405 // A failing disk (ENOSPC, EACCES, EIO) drops the rest of the batch.
406 // Retrying it would grow the backlog, and every later push would
407 // retry all of it.
408 writeFailing = true;
409 droppedCount += records.length - persistedCount;
410 return;
411 }
412 writeFailing = false;
413 pendingFlushStats = {
414 logicalWriteBytes: pendingFlushStats.logicalWriteBytes + chunkBytes,
415 count: pendingFlushStats.count + nextIndex - persistedCount,
416 durationMs: pendingFlushStats.durationMs + Math.max(0, performance.now() - startedAt),
417 };
418 persistedCount = nextIndex;
419 }
420 });
421​
422 const flush = flushSemaphore
423 .withPermits(1)(
424 Effect.gen(function* () {
425 const droppedAtStart = droppedCount;
426 yield* flushBuffered;
427 const stats = pendingFlushStats;
428 pendingFlushStats = {
429 logicalWriteBytes: 0,
430 count: 0,
431 durationMs: 0,
432 };
433 if (stats.count > 0 && options.onFlush) {
434 yield* options.onFlush(stats).pipe(Effect.ignore);
435 }
436 if (droppedCount > 0 && !failureReported) {
437 failureReported = true;
438 yield* Effect.logWarning(
439 "Trace writer could not keep up, dropping records until it recovers",
440 {
441 filePath: options.filePath,
442 },
443 );
444 } else if (failureReported && !writeFailing && droppedCount === droppedAtStart) {
445 yield* Effect.logInfo("Trace writes recovered", {
446 filePath: options.filePath,
447 droppedCount,
448 });
449 failureReported = false;
450 droppedCount = 0;
451 }
452 }),
453 )
454 .pipe(
455 // A cancelled write still completes in the OS. Finish it before another
456 // flush rotates the file or the scope's finalizer drains the remaining records.
457 Effect.uninterruptible,
458 Effect.withTracerEnabled(false),
459 // The timed fiber inherits the makeTraceSink span. That span has ended but
460 // lives as long as the sink, so the tracer logger must not add logs to it.
461 Effect.updateContext(Context.omit(Tracer.ParentSpan)<never>),
462 );
463​
464 yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));
465 yield* Effect.forkScoped(
466 Queue.take(flushRequests).pipe(
467 Effect.timeoutOption(`${options.batchWindowMs} millis`),
468 Effect.andThen(flush),
469 Effect.forever,
470 ),
471 );
472​
473 return {
474 filePath: options.filePath,
475 push(record) {
476 try {
477 const text = `${JSON.stringify(record)}\n`;
478 const bytes = Buffer.byteLength(text);
479 if (bytes > options.maxBytes) return;
480 if (bufferBytes + bytes > maxBufferBytes) {
481 droppedCount++;
482 return;
483 }
484 buffer.push({ text, bytes });
485 bufferBytes += bytes;
486 if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {
487 Queue.offerUnsafe(flushRequests, undefined);
488 }
489 } catch {
490 return;
491 }
492 },
493 flush,
494 close: () => flush,
495 } satisfies TraceSink;
496});
497​
498class LocalFileSpan implements Tracer.Span {
499 readonly _tag = "Span";
500 readonly name: string;
501 readonly spanId: string;
502 readonly traceId: string;
503 readonly parent: Option.Option<Tracer.AnySpan>;
504 readonly annotations: Tracer.Span["annotations"];
505 readonly links: Array<Tracer.SpanLink>;
506 readonly sampled: boolean;
507 readonly kind: Tracer.SpanKind;
508​
509 status: Tracer.SpanStatus;
510 attributes: Map<string, unknown>;
511 events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
512 private readonly delegate: Tracer.Span;
513 private readonly push: (record: EffectTraceRecord) => void;
514​
515 constructor(
516 options: Parameters<Tracer.Tracer["span"]>[0],
517 delegate: Tracer.Span,
518 push: (record: EffectTraceRecord) => void,
519 ) {
520 this.delegate = delegate;
521 this.push = push;
522 this.name = delegate.name;
523 this.spanId = delegate.spanId;
524 this.traceId = delegate.traceId;
525 this.parent = options.parent;
526 this.annotations = options.annotations;
527 this.links = [...options.links];
528 this.sampled = delegate.sampled;
529 this.kind = delegate.kind;
530 this.status = {
531 _tag: "Started",
532 startTime: options.startTime,
533 };
534 this.attributes = new Map();
535 this.events = [];
536 }
537​
538 end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
539 // Cached lookup fibers retain parent spans. Traces need success status, not result payloads.
540 const traceExit = ExitRuntime.isSuccess(exit) ? ExitRuntime.void : exit;
541 this.status = {
542 _tag: "Ended",
543 startTime: this.status.startTime,
544 endTime,
545 exit: traceExit,
546 };
547 this.delegate.end(endTime, traceExit);
548​
549 if (this.sampled) {
550 this.push(spanToTraceRecord(this));
551 }
552 }
553​
554 attribute(key: string, value: unknown): void {
555 this.attributes.set(key, value);
556 this.delegate.attribute(key, value);
557 }
558​
559 event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
560 const nextAttributes = attributes ?? {};
561 this.events.push([name, startTime, nextAttributes]);
562 this.delegate.event(name, startTime, nextAttributes);
563 }
564​
565 addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
566 this.links.push(...links);
567 this.delegate.addLinks(links);
568 }
570​
571export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
572 options: LocalFileTracerOptions,
573) {
574 const sink =
575 options.sink ??
576 (yield* makeTraceSink({
577 filePath: options.filePath,
578 maxBytes: options.maxBytes,
579 maxFiles: options.maxFiles,
580 batchWindowMs: options.batchWindowMs,
581 ...(options.onFlush ? { onFlush: options.onFlush } : {}),
582 }));
583​
584 const delegate =
585 options.delegate ??
586 Tracer.make({
587 span: (spanOptions) => new Tracer.NativeSpan(spanOptions),
588 });
589​
590 return Tracer.make({
591 span(spanOptions) {
592 return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);
593 },
594 ...(delegate.context ? { context: delegate.context } : {}),
595 });
596});
597​
598const SPAN_KIND_MAP: Record<number, OtlpTraceRecord["kind"]> = {
599 1: "internal",
600 2: "server",
601 3: "client",
602 4: "producer",
603 5: "consumer",
604};
605​
606export function decodeOtlpTraceRecords(
607 payload: OtlpTracer.TraceData,
608): ReadonlyArray<OtlpTraceRecord> {
609 const records: Array<OtlpTraceRecord> = [];
610​
611 for (const resourceSpan of payload.resourceSpans) {
612 const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes ?? []);
613​
614 for (const scopeSpan of resourceSpan.scopeSpans) {
615 for (const span of scopeSpan.spans) {
616 records.push(
617 otlpSpanToTraceRecord({
618 resourceAttributes,
619 scopeAttributes: decodeAttributes(
620 "attributes" in scopeSpan.scope && Array.isArray(scopeSpan.scope.attributes)
621 ? scopeSpan.scope.attributes
622 : [],
623 ),
624 scopeName: scopeSpan.scope.name,
625 scopeVersion:
626 "version" in scopeSpan.scope && typeof scopeSpan.scope.version === "string"
627 ? scopeSpan.scope.version
628 : undefined,
629 span,
630 }),
631 );
632 }
633 }
634 }
635​
636 return records;
638​
639function otlpSpanToTraceRecord(input: {
640 readonly resourceAttributes: Readonly<Record<string, unknown>>;
641 readonly scopeAttributes: Readonly<Record<string, unknown>>;
642 readonly scopeName: string | undefined;
643 readonly scopeVersion: string | undefined;
644 readonly span: OtlpSpan;
645}): OtlpTraceRecord {
646 return {
647 type: "otlp-span",
648 name: input.span.name,
649 traceId: input.span.traceId,
650 spanId: input.span.spanId,
651 ...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}),
652 sampled: true,
653 kind: normalizeSpanKind(input.span.kind),
654 startTimeUnixNano: input.span.startTimeUnixNano,
655 endTimeUnixNano: input.span.endTimeUnixNano,
656 durationMs:
657 Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) /
658 1_000_000,
659 attributes: decodeAttributes(input.span.attributes),
660 resourceAttributes: input.resourceAttributes,
661 scope: {
662 ...(input.scopeName ? { name: input.scopeName } : {}),
663 ...(input.scopeVersion ? { version: input.scopeVersion } : {}),
664 attributes: input.scopeAttributes,
665 },
666 events: decodeEvents(input.span.events),
667 links: decodeLinks(input.span.links),
668 status: decodeStatus(input.span.status),
669 };
671​
672function decodeStatus(input: OtlpSpanStatus): OtlpTraceRecord["status"] {
673 const code = String(input.code);
674 const message = input.message;
675​
676 return {
677 code,
678 ...(message ? { message } : {}),
679 };
681​
682function decodeEvents(input: ReadonlyArray<OtlpSpanEvent>): ReadonlyArray<TraceRecordEvent> {
683 return input.map((current) => ({
684 name: current.name,
685 timeUnixNano: current.timeUnixNano,
686 attributes: decodeAttributes(current.attributes),
687 }));
689​
690function decodeLinks(input: ReadonlyArray<OtlpSpanLink>): ReadonlyArray<TraceRecordLink> {
691 return input.flatMap((current) => {
692 const traceId = current.traceId;
693 const spanId = current.spanId;
694 return {
695 traceId,
696 spanId,
697 attributes: decodeAttributes(current.attributes),
698 };
699 });
701​
702function decodeAttributes(
703 input: ReadonlyArray<OtlpResource.KeyValue>,
704): Readonly<Record<string, unknown>> {
705 const entries: Record<string, unknown> = {};
706​
707 for (const attribute of input) {
708 entries[attribute.key] = decodeValue(attribute.value);
709 }
710​
711 return truncateTraceAttributes(compactTraceAttributes(entries));
713​
714function decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown {
715 if (input == null) {
716 return null;
717 }
718 if ("stringValue" in input) {
719 return input.stringValue;
720 }
721 if ("boolValue" in input) {
722 return input.boolValue;
723 }
724 if ("intValue" in input) {
725 return input.intValue;
726 }
727 if ("doubleValue" in input) {
728 return input.doubleValue;
729 }
730 if ("bytesValue" in input) {
731 return input.bytesValue;
732 }
733 if (input.arrayValue) {
734 return input.arrayValue.values.map((entry) => decodeValue(entry));
735 }
736 if (input.kvlistValue) {
737 return decodeAttributes(input.kvlistValue.values);
738 }
739 return null;
741​
742function normalizeSpanKind(input: number): OtlpTraceRecord["kind"] {
743 return SPAN_KIND_MAP[input] || "internal";
745​
746function parseBigInt(input: string): bigint {
747 try {
748 return BigInt(input);
749 } catch {
750 return 0n;
751 }
753​
754export const OtlpHeadersFromString = Schema.String.pipe(
755 Schema.decodeTo(
756 Schema.Record(Schema.String, Schema.String),
757 SchemaTransformation.transformEffect({
758 decode: (input) => {
759 const headers: Record<string, string> = {};
760 for (const pair of input.split(",")) {
761 if (pair.trim() === "") {
762 continue;
763 }
764 const separator = pair.indexOf("=");
765 const key = separator === -1 ? "" : pair.slice(0, separator).trim();
766 if (key === "") {
767 return Effect.fail(
768 new SchemaIssue.InvalidValue({
769 message: `Expected key=value but received ${JSON.stringify(pair.trim())}.`,
770 }),
771 );
772 }
773 try {
774 headers[key] = decodeURIComponent(pair.slice(separator + 1).trim());
775 } catch {
776 return Effect.fail(
777 new SchemaIssue.InvalidValue({
778 message: `Header ${JSON.stringify(key)} has a malformed percent-encoded value.`,
779 }),
780 );
781 }
782 }
783 return Effect.succeed(headers);
784 },
785 encode: (headers) =>
786 Effect.succeed(
787 Object.entries(headers)
788 .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
789 .join(","),
790 ),
791 }),
792 ),
793);