Open History to see the last commit
1import { assert, describe, expect, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Arr from "effect/Array";
4import * as Cause from "effect/Cause";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Logger from "effect/Logger";
10import * as Order from "effect/Order";
11import * as Path from "effect/Path";
12import * as Ref from "effect/Ref";
13import * as References from "effect/References";
14import * as Schema from "effect/Schema";
15import * as Tracer from "effect/Tracer";
16import * as TestClock from "effect/testing/TestClock";
17import { vi } from "vite-plus/test";
18
19import { RotatingFileSink } from "./logging.ts";
20import {
21 causeErrorTag,
22 compactTraceAttributes,
23 decodeOtlpTraceRecords,
24 errorTag,
25 makeLocalFileTracer,
26 makeTraceSink,
27 type EffectTraceRecord,
28 type TraceRecord,
29 type TraceSinkFlushStats,
30 OtlpHeadersFromString,
31 truncateTraceAttributes,
32} from "./observability.ts";
33
34describe("errorTag", () => {
35 it("reports structural tags without retaining arbitrary values", () => {
36 assert.equal(errorTag({ _tag: "AcpRequestError" }), "AcpRequestError");
37 assert.equal(errorTag(new TypeError("secret-token-value")), "TypeError");
38 assert.equal(errorTag({ _tag: "secret token value" }), "TaggedError");
39 });
40});
41
42describe("causeErrorTag", () => {
43 it("reports the tagged failure value instead of the Cause reason wrapper", () => {
44 assert.equal(
45 causeErrorTag(Cause.fail({ _tag: "ServerAuthInvalidCredentialError" })),
46 "ServerAuthInvalidCredentialError",
47 );
48 });
49
50 it("reports structural cause kinds when no typed failure exists", () => {
51 assert.equal(causeErrorTag(Cause.die(new Error("unexpected"))), "Die");
52 assert.equal(causeErrorTag(Cause.interrupt()), "Interrupt");
53 });
54});
55
56const TraceRecordLine = Schema.Struct({
57 name: Schema.String,
58 spanId: Schema.String,
59 parentSpanId: Schema.optional(Schema.String),
60 attributes: Schema.Record(Schema.String, Schema.Unknown),
61 events: Schema.Array(
62 Schema.Struct({
63 name: Schema.String,
64 attributes: Schema.Record(Schema.String, Schema.Unknown),
65 }),
66 ),
67 exit: Schema.optional(
68 Schema.Struct({
69 _tag: Schema.String,
70 }),
71 ),
72});
73
74const decodeTraceRecordLine = Schema.decodeUnknownSync(Schema.fromJsonString(TraceRecordLine));
75
76const makeRecord = (name: string, suffix = ""): TraceRecord => ({
77 type: "effect-span",
78 name,
79 traceId: `trace-${name}-${suffix}`,
80 spanId: `span-${name}-${suffix}`,
81 sampled: true,
82 kind: "internal",
83 startTimeUnixNano: "1",
84 endTimeUnixNano: "2",
85 durationMs: 1,
86 attributes: {
87 payload: suffix,
88 },
89 events: [],
90 links: [],
91 exit: {
92 _tag: "Success",
93 },
94});
95
96const readTraceRecords = Effect.fn("readTraceRecords")(function* (tracePath: string) {
97 const fileSystem = yield* FileSystem.FileSystem;
98 return (yield* fileSystem.readFileString(tracePath))
99 .trim()
100 .split("\n")
101 .filter((line) => line.length > 0)
102 .map((line) => decodeTraceRecordLine(line));
103});
104
105const layerTest = (tracePath: string) =>
106 Layer.mergeAll(
107 Layer.effect(
108 Tracer.Tracer,
109 makeLocalFileTracer({
110 filePath: tracePath,
111 maxBytes: 1024 * 1024,
112 maxFiles: 2,
113 batchWindowMs: 10_000,
114 }),
115 ),
116 Logger.layer([Logger.tracerLogger], { mergeWithExisting: false }),
117 Layer.succeed(References.MinimumLogLevel, "Info"),
118 );
119
120const nodeServicesIt = it.layer(NodeServices.layer);
121
122describe("truncateTraceAttributes", () => {
123 it("clamps oversized strings at any depth without mutating the input", () => {
124 const stack = "s".repeat(2_000);
125 const attributes = {
126 "db.query.text": "q".repeat(2_000),
127 short: "ok",
128 error: { name: "Error", stack, nested: ["a".repeat(2_000)] },
129 };
130 const truncated = truncateTraceAttributes(attributes);
131
132 assert.equal((truncated["db.query.text"] as string).length, 200 + "…[truncated]".length);
133 assert.equal(truncated["short"], "ok");
134 const error = truncated["error"] as { stack: string; nested: Array<string> };
135 assert.equal(error.stack.length, 500 + "…[truncated]".length);
136 assert.equal(error.nested[0]?.length, 500 + "…[truncated]".length);
137 // Input is untouched: the live span's attributes are shared.
138 assert.equal(attributes.error.stack, stack);
139 });
140
141 it("returns the same reference when nothing exceeds the limits", () => {
142 const attributes = { short: "ok", nested: { fine: "also ok" } };
143 assert.equal(truncateTraceAttributes(attributes), attributes);
144 });
145});
146
147describe("decodeOtlpTraceRecords", () => {
148 it("clamps oversized renderer span and event attributes", () => {
149 const long = "x".repeat(2_000);
150 const clamped = `${"x".repeat(500)}…[truncated]`;
151 const [record] = decodeOtlpTraceRecords({
152 resourceSpans: [
153 {
154 resource: { attributes: [], droppedAttributesCount: 0 },
155 scopeSpans: [
156 {
157 scope: { name: "effect" },
158 spans: [
159 {
160 traceId: "11111111111111111111111111111111",
161 spanId: "2222222222222222",
162 parentSpanId: undefined,
163 name: "client.span",
164 kind: 1,
165 startTimeUnixNano: "1000000",
166 endTimeUnixNano: "2000000",
167 attributes: [{ key: "payload", value: { stringValue: long } }],
168 droppedAttributesCount: 0,
169 events: [
170 {
171 name: "log",
172 timeUnixNano: "1500000",
173 attributes: [{ key: "effect.cause", value: { stringValue: long } }],
174 droppedAttributesCount: 0,
175 },
176 ],
177 droppedEventsCount: 0,
178 status: { code: 1 },
179 links: [],
180 droppedLinksCount: 0,
181 },
182 ],
183 },
184 ],
185 },
186 ],
187 });
188
189 assert.equal(record?.attributes["payload"], clamped);
190 assert.equal(record?.events[0]?.attributes["effect.cause"], clamped);
191 });
192});
193
194describe("observability", () => {
195 it.effect(
196 "preserves successful results without retaining them in sampled or unsampled spans",
197 () =>
198 Effect.gen(function* () {
199 for (const sampled of [true, false]) {
200 const delegates: Array<Tracer.Span> = [];
201 const records: Array<EffectTraceRecord> = [];
202 const tracer = yield* makeLocalFileTracer({
203 filePath: "unused",
204 maxBytes: 1024,
205 maxFiles: 1,
206 batchWindowMs: 10_000,
207 sink: {
208 filePath: "unused",
209 push: (record) => {
210 if (record.type === "effect-span") records.push(record);
211 },
212 flush: Effect.void,
213 close: () => Effect.void,
214 },
215 delegate: Tracer.make({
216 span: (options) => {
217 const span = new Tracer.NativeSpan({ ...options, sampled });
218 delegates.push(span);
219 return span;
220 },
221 }),
222 });
223 const payload = { turnItems: [{ output: [{ text: "synthetic-result" }] }] };
224 let span: Tracer.Span | undefined;
225 const result = yield* Effect.gen(function* () {
226 span = yield* Effect.currentSpan;
227 return payload;
228 }).pipe(
229 Effect.withSpan("read-thread-projection"),
230 Effect.provideService(Tracer.Tracer, tracer),
231 );
232 assert.strictEqual(result, payload);
233 assert.isDefined(span);
234 for (const completed of [span!, ...delegates]) {
235 assert.equal(completed.status._tag, "Ended");
236 if (completed.status._tag === "Ended") {
237 assert.deepStrictEqual(completed.status.exit, Exit.void);
238 }
239 }
240 assert.deepStrictEqual(
241 records.map((record) => record.exit),
242 sampled ? [{ _tag: "Success" }] : [],
243 );
244 }
245 }),
246 );
247
248 it.effect("preserves failure and interruption causes in spans and exported traces", () =>
249 Effect.gen(function* () {
250 for (const cause of [Cause.fail({ _tag: "SyntheticFailure" }), Cause.interrupt()]) {
251 const delegates: Array<Tracer.Span> = [];
252 const records: Array<EffectTraceRecord> = [];
253 const tracer = yield* makeLocalFileTracer({
254 filePath: "unused",
255 maxBytes: 1024,
256 maxFiles: 1,
257 batchWindowMs: 10_000,
258 sink: {
259 filePath: "unused",
260 push: (record) => {
261 if (record.type === "effect-span") records.push(record);
262 },
263 flush: Effect.void,
264 close: () => Effect.void,
265 },
266 delegate: Tracer.make({
267 span: (options) => {
268 const span = new Tracer.NativeSpan(options);
269 delegates.push(span);
270 return span;
271 },
272 }),
273 });
274 let span: Tracer.Span | undefined;
275 const result = yield* Effect.gen(function* () {
276 span = yield* Effect.currentSpan;
277 return yield* Effect.failCause(cause);
278 }).pipe(
279 Effect.withSpan("failed-operation"),
280 Effect.provideService(Tracer.Tracer, tracer),
281 Effect.exit,
282 );
283 assert.isTrue(Exit.isFailure(result));
284 assert.isDefined(span);
285 for (const completed of [span!, ...delegates]) {
286 assert.equal(completed.status._tag, "Ended");
287 if (completed.status._tag === "Ended") {
288 assert.strictEqual(completed.status.exit, result);
289 }
290 }
291 assert.equal(records[0]?.exit._tag, Cause.hasInterrupts(cause) ? "Interrupted" : "Failure");
292 }
293 }),
294 );
295
296 it("normalizes circular arrays, maps, and sets without recursing forever", () => {
297 const array: Array<unknown> = ["alpha"];
298 array.push(array);
299
300 const map = new Map<string, unknown>();
301 map.set("self", map);
302
303 const set = new Set<unknown>();
304 set.add(set);
305
306 assert.deepStrictEqual(
307 compactTraceAttributes({
308 array,
309 map,
310 set,
311 }),
312 {
313 array: ["alpha", "[Circular]"],
314 map: { self: "[Circular]" },
315 set: ["[Circular]"],
316 },
317 );
318 });
319
320 it("normalizes invalid dates without throwing", () => {
321 // @effect-diagnostics-next-line globalDate:off
322 const invalidDate = new Date("not-a-real-date");
323 assert.deepStrictEqual(
324 compactTraceAttributes({
325 invalidDate,
326 }),
327 {
328 invalidDate: "Invalid Date",
329 },
330 );
331 });
332
333 nodeServicesIt("node services", (it) => {
334 it.effect("flushes buffered trace records on close", () =>
335 Effect.scoped(
336 Effect.gen(function* () {
337 const fileSystem = yield* FileSystem.FileSystem;
338 const path = yield* Path.Path;
339 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
340 const tracePath = path.join(tempDir, "shared.trace.ndjson");
341
342 const sink = yield* makeTraceSink({
343 filePath: tracePath,
344 maxBytes: 1024,
345 maxFiles: 2,
346 batchWindowMs: 10_000,
347 });
348
349 sink.push(makeRecord("alpha"));
350 sink.push(makeRecord("beta"));
351 yield* sink.close();
352
353 const lines = yield* readTraceRecords(tracePath);
354
355 assert.equal(lines.length, 2);
356 assert.equal(lines[0]?.name, "alpha");
357 assert.equal(lines[1]?.name, "beta");
358 }),
359 ),
360 );
361
362 it.effect("reports successful logical trace writes", () =>
363 Effect.scoped(
364 Effect.gen(function* () {
365 const fileSystem = yield* FileSystem.FileSystem;
366 const path = yield* Path.Path;
367 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
368 const tracePath = path.join(tempDir, "shared.trace.ndjson");
369 const reported = yield* Ref.make<ReadonlyArray<TraceSinkFlushStats>>([]);
370
371 const sink = yield* makeTraceSink({
372 filePath: tracePath,
373 maxBytes: 1024,
374 maxFiles: 2,
375 batchWindowMs: 10_000,
376 onFlush: (stats) => Ref.update(reported, (current) => [...current, stats]),
377 });
378
379 sink.push(makeRecord("attributed"));
380 yield* sink.flush;
381
382 const stats = yield* Ref.get(reported);
383 assert.equal(stats.length, 1);
384 assert.equal(stats[0]?.count, 1);
385 assert.isAbove(stats[0]?.logicalWriteBytes ?? 0, 0);
386 }),
387 ),
388 );
389
390 it.effect("rotates the trace file when the configured max size is exceeded", () =>
391 Effect.scoped(
392 Effect.gen(function* () {
393 const fileSystem = yield* FileSystem.FileSystem;
394 const path = yield* Path.Path;
395 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
396 const tracePath = path.join(tempDir, "shared.trace.ndjson");
397
398 const sink = yield* makeTraceSink({
399 filePath: tracePath,
400 maxBytes: 500,
401 maxFiles: 2,
402 batchWindowMs: 10_000,
403 });
404
405 for (let index = 0; index < 8; index += 1) {
406 sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`));
407 yield* sink.flush;
408 }
409 yield* sink.close();
410
411 const matchingFiles = Arr.sort(
412 (yield* fileSystem.readDirectory(tempDir)).filter(
413 (entry) =>
414 entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
415 ),
416 Order.String,
417 );
418
419 assert.equal(
420 matchingFiles.some((entry) => entry === "shared.trace.ndjson.1"),
421 true,
422 );
423 assert.equal(
424 matchingFiles.some((entry) => entry === "shared.trace.ndjson.3"),
425 false,
426 );
427 }),
428 ),
429 );
430
431 it.effect("keeps every trace file within the configured limit for threshold flushes", () =>
432 Effect.scoped(
433 Effect.gen(function* () {
434 const fileSystem = yield* FileSystem.FileSystem;
435 const path = yield* Path.Path;
436 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
437 const tracePath = path.join(tempDir, "shared.trace.ndjson");
438 const maxBytes = 1_024;
439
440 const sink = yield* makeTraceSink({
441 filePath: tracePath,
442 maxBytes,
443 maxFiles: 2,
444 batchWindowMs: 10_000,
445 });
446
447 for (let index = 0; index < 256; index += 1) {
448 sink.push(makeRecord("threshold", `${index}-${"x".repeat(48)}`));
449 }
450 yield* sink.close();
451
452 const matchingFiles = (yield* fileSystem.readDirectory(tempDir)).filter(
453 (entry) => entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
454 );
455 assert.include(matchingFiles, "shared.trace.ndjson.1");
456 for (const entry of matchingFiles) {
457 const stat = yield* fileSystem.stat(path.join(tempDir, entry));
458 assert.isAtMost(Number(stat.size), maxBytes, entry);
459 }
460 }),
461 ),
462 );
463
464 it.effect("drops a single trace record that cannot fit within the configured limit", () =>
465 Effect.scoped(
466 Effect.gen(function* () {
467 const fileSystem = yield* FileSystem.FileSystem;
468 const path = yield* Path.Path;
469 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
470 const tracePath = path.join(tempDir, "shared.trace.ndjson");
471 const maxBytes = 1_024;
472
473 const sink = yield* makeTraceSink({
474 filePath: tracePath,
475 maxBytes,
476 maxFiles: 2,
477 batchWindowMs: 10_000,
478 });
479
480 sink.push(makeRecord("oversized", "x".repeat(maxBytes * 2)));
481 sink.push(makeRecord("retained"));
482 yield* sink.close();
483
484 const records = yield* readTraceRecords(tracePath);
485 const stat = yield* fileSystem.stat(tracePath);
486 assert.deepEqual(
487 records.map((record) => record.name),
488 ["retained"],
489 );
490 assert.isAtMost(Number(stat.size), maxBytes);
491 }),
492 ),
493 );
494
495 it.effect("drops only the invalid trace record when serialization fails", () =>
496 Effect.scoped(
497 Effect.gen(function* () {
498 const fileSystem = yield* FileSystem.FileSystem;
499 const path = yield* Path.Path;
500 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
501 const tracePath = path.join(tempDir, "shared.trace.ndjson");
502
503 const sink = yield* makeTraceSink({
504 filePath: tracePath,
505 maxBytes: 1024,
506 maxFiles: 2,
507 batchWindowMs: 10_000,
508 });
509
510 const circular: Array<unknown> = [];
511 circular.push(circular);
512
513 sink.push(makeRecord("alpha"));
514 sink.push({
515 ...makeRecord("invalid"),
516 attributes: {
517 circular,
518 },
519 } as TraceRecord);
520 sink.push(makeRecord("beta"));
521 yield* sink.close();
522
523 const lines = yield* readTraceRecords(tracePath);
524
525 assert.deepStrictEqual(
526 lines.map((line) => line.name),
527 ["alpha", "beta"],
528 );
529 }),
530 ),
531 );
532
533 it.effect("drops records after a failed write and logs once per failure episode", () => {
534 const logs: Array<{ readonly logLevel: string; readonly message: unknown }> = [];
535 const captureLogs = Logger.make(({ logLevel, message }) => {
536 logs.push({ logLevel, message });
537 });
538 const spans: Array<Tracer.NativeSpan> = [];
539 const recordingTracer = Tracer.make({
540 span: (options) => {
541 const span = new Tracer.NativeSpan(options);
542 spans.push(span);
543 return span;
544 },
545 });
546
547 return Effect.gen(function* () {
548 const fileSystem = yield* FileSystem.FileSystem;
549 const path = yield* Path.Path;
550 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
551 const tracePath = path.join(tempDir, "shared.trace.ndjson");
552 // A directory at the trace path fails every append, like a full disk.
553 yield* fileSystem.makeDirectory(tracePath);
554 const write = vi.spyOn(RotatingFileSink.prototype, "write");
555 yield* Effect.addFinalizer(() => Effect.sync(() => write.mockRestore()));
556
557 const sink = yield* makeTraceSink({
558 filePath: tracePath,
559 maxBytes: 1024 * 1024,
560 maxFiles: 2,
561 batchWindowMs: 1_000,
562 }).pipe(Effect.withTracer(recordingTracer));
563
564 for (let index = 0; index < 1_024; index += 1) {
565 sink.push(makeRecord("lost", String(index)));
566 }
567 // Timed flushes run in the fiber forked inside the makeTraceSink span.
568 for (let index = 0; index < 5; index += 1) {
569 sink.push(makeRecord("lost"));
570 yield* TestClock.adjust("1 second");
571 }
572
573 // One write per batch, never a growing backlog.
574 assert.deepStrictEqual(
575 write.mock.calls.map(([chunk]) => String(chunk).split("\n").length - 1),
576 [256, 256, 256, 256, 1, 1, 1, 1, 1],
577 );
578 expect(logs).toEqual([
579 { logLevel: "Warn", message: [expect.any(String), { filePath: tracePath }] },
580 ]);
581
582 // Once the disk recovers, new records are written and the loss is reported.
583 yield* fileSystem.remove(tracePath, { recursive: true });
584 sink.push(makeRecord("recovered"));
585 yield* TestClock.adjust("1 second");
586
587 const records = yield* readTraceRecords(tracePath);
588 assert.deepStrictEqual(
589 records.map((record) => record.name),
590 ["recovered"],
591 );
592 expect(logs[1]).toEqual({
593 logLevel: "Info",
594 message: [expect.any(String), { filePath: tracePath, droppedCount: 1_029 }],
595 });
596
597 // Healthy flushes after the recovery log nothing.
598 sink.push(makeRecord("healthy"));
599 yield* TestClock.adjust("1 second");
600 expect(logs).toHaveLength(2);
601
602 // A new failure episode warns again.
603 yield* fileSystem.remove(tracePath);
604 yield* fileSystem.makeDirectory(tracePath);
605 sink.push(makeRecord("lost-again"));
606 yield* TestClock.adjust("1 second");
607 assert.deepStrictEqual(
608 logs.map((log) => log.logLevel),
609 ["Warn", "Info", "Warn"],
610 );
611
612 // The ended makeTraceSink span is never released, so it must not collect log events.
613 assert.deepStrictEqual(
614 spans.map((span) => [span.name, span.events.length]),
615 [["makeTraceSink", 0]],
616 );
617 }).pipe(
618 Effect.scoped,
619 Effect.provide(
620 Logger.layer([captureLogs, Logger.tracerLogger], { mergeWithExisting: false }),
621 ),
622 );
623 });
624
625 it.effect("writes nested spans to disk and captures log messages as span events", () =>
626 Effect.scoped(
627 Effect.gen(function* () {
628 const fileSystem = yield* FileSystem.FileSystem;
629 const path = yield* Path.Path;
630 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
631 const tracePath = path.join(tempDir, "shared.trace.ndjson");
632
633 yield* Effect.scoped(
634 Effect.gen(function* () {
635 const program = Effect.gen(function* () {
636 yield* Effect.annotateCurrentSpan({
637 "demo.parent": true,
638 });
639 yield* Effect.logInfo("parent event");
640 yield* Effect.gen(function* () {
641 yield* Effect.annotateCurrentSpan({
642 "demo.child": true,
643 });
644 yield* Effect.logInfo("child event");
645 }).pipe(Effect.withSpan("child-span"));
646 }).pipe(Effect.withSpan("parent-span"));
647
648 yield* program.pipe(Effect.provide(layerTest(tracePath)));
649 }),
650 );
651
652 const records = yield* readTraceRecords(tracePath);
653 assert.equal(records.length, 2);
654
655 const parent = records.find((record) => record.name === "parent-span");
656 const child = records.find((record) => record.name === "child-span");
657
658 assert.notEqual(parent, undefined);
659 assert.notEqual(child, undefined);
660 if (!parent || !child) {
661 return;
662 }
663
664 assert.equal(child.parentSpanId, parent.spanId);
665 assert.equal(parent.attributes["demo.parent"], true);
666 assert.equal(child.attributes["demo.child"], true);
667 assert.equal(
668 parent.events.some((event) => event.name === "parent event"),
669 true,
670 );
671 assert.equal(
672 child.events.some((event) => event.name === "child event"),
673 true,
674 );
675 assert.equal(
676 child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
677 true,
678 );
679 }),
680 ),
681 );
682
683 it.effect("serializes interrupted spans with an interrupted exit status", () =>
684 Effect.scoped(
685 Effect.gen(function* () {
686 const fileSystem = yield* FileSystem.FileSystem;
687 const path = yield* Path.Path;
688 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
689 const tracePath = path.join(tempDir, "shared.trace.ndjson");
690
691 yield* Effect.scoped(
692 Effect.exit(
693 Effect.interrupt.pipe(
694 Effect.withSpan("interrupt-span"),
695 Effect.provide(layerTest(tracePath)),
696 ),
697 ),
698 );
699
700 const records = yield* readTraceRecords(tracePath);
701 assert.equal(records.length, 1);
702 assert.equal(records[0]?.name, "interrupt-span");
703 assert.equal(records[0]?.exit?._tag, "Interrupted");
704 }),
705 ),
706 );
707 });
708});
709
710describe("OtlpHeadersFromString", () => {
711 const decode = Schema.decodeUnknownSync(OtlpHeadersFromString);
712
713 it.each([
714 {
715 name: "decodes percent-encoded values",
716 input: "authorization=Basic%20abc%3D%3D,x-tenant=t3",
717 expected: { authorization: "Basic abc==", "x-tenant": "t3" },
718 },
719 {
720 name: "ignores whitespace around separators",
721 input: "authorization=Basic%20abc%3D%3D, x-tenant = t3 ,",
722 expected: { authorization: "Basic abc==", "x-tenant": "t3" },
723 },
724 {
725 name: "keeps literal equals signs inside a value",
726 input: "authorization=Bearer abc==",
727 expected: { authorization: "Bearer abc==" },
728 },
729 {
730 name: "keeps an empty value",
731 input: "x-empty=",
732 expected: { "x-empty": "" },
733 },
734 ])("$name", ({ input, expected }) => {
735 expect(decode(input)).toEqual(expected);
736 });
737
738 it.each([
739 { name: "rejects a pair without a separator", input: "authorization" },
740 { name: "rejects a pair without a key", input: "=value" },
741 { name: "rejects a malformed percent-encoding", input: "authorization=%E0" },
742 ])("$name", ({ input }) => {
743 expect(() => decode(input)).toThrow();
744 });
745});