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

observability.ts

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