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