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