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

observability.ts

743 lines21.9 KB

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>>;
29​
30export interface TraceRecordLink {
31 readonly traceId: string;
32 readonly spanId: string;
33 readonly attributes: Readonly<Record<string, unknown>>;
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>;
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 };
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;
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 );
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;
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";
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>;
123​
124export interface TraceSinkFlushStats {
125 readonly logicalWriteBytes: number;
126 readonly count: number;
127 readonly durationMs: number;
129​
130export interface TraceSink {
131 readonly filePath: string;
132 push: (record: TraceRecord) => void;
133 flush: Effect.Effect<void>;
134 close: () => Effect.Effect<void>;
136​
137export interface LocalFileTracerOptions extends TraceSinkOptions {
138 readonly delegate?: Tracer.Tracer;
139 readonly sink?: TraceSink;
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 >;
161​
162function isPlainObject(value: unknown): value is Record<string, unknown> {
163 return typeof value === "object" && value !== null && !Array.isArray(value);
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;
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 );
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);
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 };
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;
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;
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 };
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 // Cached lookup fibers retain parent spans. Traces need success status, not result payloads.
483 const traceExit = ExitRuntime.isSuccess(exit) ? ExitRuntime.void : exit;
484 this.status = {
485 _tag: "Ended",
486 startTime: this.status.startTime,
487 endTime,
488 exit: traceExit,
489 };
490 this.delegate.end(endTime, traceExit);
491​
492 if (this.sampled) {
493 this.push(spanToTraceRecord(this));
494 }
495 }
496​
497 attribute(key: string, value: unknown): void {
498 this.attributes.set(key, value);
499 this.delegate.attribute(key, value);
500 }
501​
502 event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
503 const nextAttributes = attributes ?? {};
504 this.events.push([name, startTime, nextAttributes]);
505 this.delegate.event(name, startTime, nextAttributes);
506 }
507​
508 addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
509 this.links.push(...links);
510 this.delegate.addLinks(links);
511 }
513​
514export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
515 options: LocalFileTracerOptions,
516) {
517 const sink =
518 options.sink ??
519 (yield* makeTraceSink({
520 filePath: options.filePath,
521 maxBytes: options.maxBytes,
522 maxFiles: options.maxFiles,
523 batchWindowMs: options.batchWindowMs,
524 ...(options.onFlush ? { onFlush: options.onFlush } : {}),
525 }));
526​
527 const delegate =
528 options.delegate ??
529 Tracer.make({
530 span: (spanOptions) => new Tracer.NativeSpan(spanOptions),
531 });
532​
533 return Tracer.make({
534 span(spanOptions) {
535 return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);
536 },
537 ...(delegate.context ? { context: delegate.context } : {}),
538 });
539});
540​
541const SPAN_KIND_MAP: Record<number, OtlpTraceRecord["kind"]> = {
542 1: "internal",
543 2: "server",
544 3: "client",
545 4: "producer",
546 5: "consumer",
547};
548​
549export function decodeOtlpTraceRecords(
550 payload: OtlpTracer.TraceData,
551): ReadonlyArray<OtlpTraceRecord> {
552 const records: Array<OtlpTraceRecord> = [];
553​
554 for (const resourceSpan of payload.resourceSpans) {
555 const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes ?? []);
556​
557 for (const scopeSpan of resourceSpan.scopeSpans) {
558 for (const span of scopeSpan.spans) {
559 records.push(
560 otlpSpanToTraceRecord({
561 resourceAttributes,
562 scopeAttributes: decodeAttributes(
563 "attributes" in scopeSpan.scope && Array.isArray(scopeSpan.scope.attributes)
564 ? scopeSpan.scope.attributes
565 : [],
566 ),
567 scopeName: scopeSpan.scope.name,
568 scopeVersion:
569 "version" in scopeSpan.scope && typeof scopeSpan.scope.version === "string"
570 ? scopeSpan.scope.version
571 : undefined,
572 span,
573 }),
574 );
575 }
576 }
577 }
578​
579 return records;
581​
582function otlpSpanToTraceRecord(input: {
583 readonly resourceAttributes: Readonly<Record<string, unknown>>;
584 readonly scopeAttributes: Readonly<Record<string, unknown>>;
585 readonly scopeName: string | undefined;
586 readonly scopeVersion: string | undefined;
587 readonly span: OtlpSpan;
588}): OtlpTraceRecord {
589 return {
590 type: "otlp-span",
591 name: input.span.name,
592 traceId: input.span.traceId,
593 spanId: input.span.spanId,
594 ...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}),
595 sampled: true,
596 kind: normalizeSpanKind(input.span.kind),
597 startTimeUnixNano: input.span.startTimeUnixNano,
598 endTimeUnixNano: input.span.endTimeUnixNano,
599 durationMs:
600 Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) /
601 1_000_000,
602 attributes: decodeAttributes(input.span.attributes),
603 resourceAttributes: input.resourceAttributes,
604 scope: {
605 ...(input.scopeName ? { name: input.scopeName } : {}),
606 ...(input.scopeVersion ? { version: input.scopeVersion } : {}),
607 attributes: input.scopeAttributes,
608 },
609 events: decodeEvents(input.span.events),
610 links: decodeLinks(input.span.links),
611 status: decodeStatus(input.span.status),
612 };
614​
615function decodeStatus(input: OtlpSpanStatus): OtlpTraceRecord["status"] {
616 const code = String(input.code);
617 const message = input.message;
618​
619 return {
620 code,
621 ...(message ? { message } : {}),
622 };
624​
625function decodeEvents(input: ReadonlyArray<OtlpSpanEvent>): ReadonlyArray<TraceRecordEvent> {
626 return input.map((current) => ({
627 name: current.name,
628 timeUnixNano: current.timeUnixNano,
629 attributes: decodeAttributes(current.attributes),
630 }));
632​
633function decodeLinks(input: ReadonlyArray<OtlpSpanLink>): ReadonlyArray<TraceRecordLink> {
634 return input.flatMap((current) => {
635 const traceId = current.traceId;
636 const spanId = current.spanId;
637 return {
638 traceId,
639 spanId,
640 attributes: decodeAttributes(current.attributes),
641 };
642 });
644​
645function decodeAttributes(
646 input: ReadonlyArray<OtlpResource.KeyValue>,
647): Readonly<Record<string, unknown>> {
648 const entries: Record<string, unknown> = {};
649​
650 for (const attribute of input) {
651 entries[attribute.key] = decodeValue(attribute.value);
652 }
653​
654 return compactTraceAttributes(entries);
656​
657function decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown {
658 if (input == null) {
659 return null;
660 }
661 if ("stringValue" in input) {
662 return input.stringValue;
663 }
664 if ("boolValue" in input) {
665 return input.boolValue;
666 }
667 if ("intValue" in input) {
668 return input.intValue;
669 }
670 if ("doubleValue" in input) {
671 return input.doubleValue;
672 }
673 if ("bytesValue" in input) {
674 return input.bytesValue;
675 }
676 if (input.arrayValue) {
677 return input.arrayValue.values.map((entry) => decodeValue(entry));
678 }
679 if (input.kvlistValue) {
680 return decodeAttributes(input.kvlistValue.values);
681 }
682 return null;
684​
685function normalizeSpanKind(input: number): OtlpTraceRecord["kind"] {
686 return SPAN_KIND_MAP[input] || "internal";
688​
689function parseBigInt(input: string): bigint {
690 try {
691 return BigInt(input);
692 } catch {
693 return 0n;
694 }
696​
697/**
698 * Parses the `OTEL_EXPORTER_OTLP_HEADERS` wire format used by
699 * `T3CODE_OTLP_HEADERS`: W3C Baggage `key=value` pairs joined by commas, with
700 * percent-encoded values. Each pair splits at its first `=` so an encoded or
701 * literal `=` inside a value survives, and whitespace around the separators is
702 * ignored.
703 */
704export const OtlpHeadersFromString = Schema.String.pipe(
705 Schema.decodeTo(
706 Schema.Record(Schema.String, Schema.String),
707 SchemaTransformation.transformEffect({
708 decode: (input) => {
709 const headers: Record<string, string> = {};
710 for (const pair of input.split(",")) {
711 if (pair.trim() === "") {
712 continue;
713 }
714 const separator = pair.indexOf("=");
715 const key = separator === -1 ? "" : pair.slice(0, separator).trim();
716 if (key === "") {
717 return Effect.fail(
718 new SchemaIssue.InvalidValue({
719 message: `Expected key=value but received ${JSON.stringify(pair.trim())}.`,
720 }),
721 );
722 }
723 try {
724 headers[key] = decodeURIComponent(pair.slice(separator + 1).trim());
725 } catch {
726 return Effect.fail(
727 new SchemaIssue.InvalidValue({
728 message: `Header ${JSON.stringify(key)} has a malformed percent-encoded value.`,
729 }),
730 );
731 }
732 }
733 return Effect.succeed(headers);
734 },
735 encode: (headers) =>
736 Effect.succeed(
737 Object.entries(headers)
738 .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
739 .join(","),
740 ),
741 }),
742 ),
743);