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

observability.ts

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