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

observability.test.ts

704 lines23.9 KB

1import { assert, describe, expect, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Cause from "effect/Cause";
4import * as Effect from "effect/Effect";
5import * as Deferred from "effect/Deferred";
6import * as Fiber from "effect/Fiber";
7import * as Exit from "effect/Exit";
8import * as FileSystem from "effect/FileSystem";
9import { cast } from "effect/Function";
10import * as Layer from "effect/Layer";
11import * as Logger from "effect/Logger";
12import * as Path from "effect/Path";
13import * as Ref from "effect/Ref";
14import * as References from "effect/References";
15import * as Schema from "effect/Schema";
16import * as Tracer from "effect/Tracer";
17import type { OtlpTracer } from "effect/observability";
18​
19import {
20 causeErrorTag,
21 compactTraceAttributes,
22 decodeOtlpTraceRecords,
23 errorTag,
24 makeLocalFileTracer,
25 makeTraceSink,
26 type EffectTraceRecord,
27 type TraceRecord,
28 OtlpHeadersFromString,
29 truncateTraceAttributes,
30 processServiceInstanceId,
31} from "./observability.ts";
32​
33describe("processServiceInstanceId", () => {
34 it("stays the same for the process unless the operator set one", () => {
35 expect(processServiceInstanceId()).toBe(processServiceInstanceId({}));
36 expect(processServiceInstanceId({ "service.instance.id": "pod-7" })).toBe("pod-7");
37 });
38});
39​
40describe("errorTag", () => {
41 it("reports structural tags without retaining arbitrary values", () => {
42 assert.equal(errorTag({ _tag: "AcpRequestError" }), "AcpRequestError");
43 assert.equal(errorTag(new TypeError("secret-token-value")), "TypeError");
44 assert.equal(errorTag({ _tag: "secret token value" }), "TaggedError");
45 });
46});
47​
48describe("causeErrorTag", () => {
49 it("reports the tagged failure value instead of the Cause reason wrapper", () => {
50 assert.equal(
51 causeErrorTag(Cause.fail({ _tag: "ServerAuthInvalidCredentialError" })),
52 "ServerAuthInvalidCredentialError",
53 );
54 });
55});
56​
57const TraceRecordLine = Schema.Struct({
58 name: Schema.String,
59 spanId: Schema.String,
60 parentSpanId: Schema.optional(Schema.String),
61 attributes: Schema.Record(Schema.String, Schema.Unknown),
62 events: Schema.Array(
63 Schema.Struct({
64 name: Schema.String,
65 attributes: Schema.Record(Schema.String, Schema.Unknown),
66 }),
67 ),
68 exit: Schema.optional(
69 Schema.Struct({
70 _tag: Schema.String,
71 }),
72 ),
73});
74​
75const decodeTraceRecordLine = Schema.decodeUnknownSync(Schema.fromJsonString(TraceRecordLine));
76​
77const makeRecord = (name: string, suffix = ""): TraceRecord => ({
78 type: "effect-span",
79 name,
80 traceId: `trace-${name}-${suffix}`,
81 spanId: `span-${name}-${suffix}`,
82 sampled: true,
83 kind: "internal",
84 startTimeUnixNano: "1",
85 endTimeUnixNano: "2",
86 durationMs: 1,
87 attributes: {
88 payload: suffix,
89 },
90 events: [],
91 links: [],
92 exit: {
93 _tag: "Success",
94 },
95});
96​
97const readTraceRecords = Effect.fn("readTraceRecords")(function* (tracePath: string) {
98 const fileSystem = yield* FileSystem.FileSystem;
99 return (yield* fileSystem.readFileString(tracePath))
100 .trim()
101 .split("\n")
102 .filter((line) => line.length > 0)
103 .map((line) => decodeTraceRecordLine(line));
104});
105​
106const layerTest = (tracePath: string) =>
107 Layer.mergeAll(
108 Layer.effect(
109 Tracer.Tracer,
110 makeLocalFileTracer({
111 filePath: tracePath,
112 maxBytes: 1024 * 1024,
113 maxFiles: 2,
114 batchWindowMs: 10_000,
115 }),
116 ),
117 Logger.layer([Logger.tracerLogger], { mergeWithExisting: false }),
118 Layer.succeed(References.MinimumLogLevel, "Info"),
119 );
120​
121const nodeServicesIt = it.layer(NodeServices.layer);
122​
123describe("truncateTraceAttributes", () => {
124 it("clamps oversized strings at any depth without mutating the input", () => {
125 const stack = "s".repeat(2_000);
126 const attributes = {
127 "db.query.text": "q".repeat(2_000),
128 short: "ok",
129 error: { name: "Error", stack, nested: ["a".repeat(2_000)] },
130 };
131 const truncated = truncateTraceAttributes(attributes);
132​
133 assert.equal((truncated["db.query.text"] as string).length, 200 + "…[truncated]".length);
134 assert.equal(truncated["short"], "ok");
135 const error = truncated["error"] as { stack: string; nested: Array<string> };
136 assert.equal(error.stack.length, 500 + "…[truncated]".length);
137 assert.equal(error.nested[0]?.length, 500 + "…[truncated]".length);
138 assert.equal(attributes.error.stack, stack);
139 });
140});
141​
142describe("observability", () => {
143 it.effect("samples only fast successful routine spans in the local file", () =>
144 Effect.gen(function* () {
145 const names: Array<string> = [];
146 const delegates: Array<Tracer.Span> = [];
147 const tracer = yield* makeLocalFileTracer({
148 filePath: "unused",
149 maxBytes: 1024,
150 maxFiles: 1,
151 batchWindowMs: 1000,
152 sampleRoutineSpans: true,
153 sink: {
154 filePath: "unused",
155 push: (r) => names.push(r.name),
156 flush: Effect.void,
157 flushSync: () => {},
158 close: () => Effect.void,
159 },
160 delegate: Tracer.make({
161 span: (options) => {
162 const span = new Tracer.NativeSpan(options);
163 span._spanId = "1".repeat(14) + (options.name === "sample" ? "00" : "01");
164 delegates.push(span);
165 return span;
166 },
167 }),
168 });
169 for (const name of ["fast", "routine", "sample", "slow", "failed", "logged", "other"]) {
170 const span = yield* Effect.makeSpan(name).pipe(
171 Effect.provideService(Tracer.Tracer, tracer),
172 );
173 if (name === "routine") span.attribute("t3.trace.routine", true);
174 else if (name !== "other") span.attribute("db.system.name", "sqlite");
175 if (name === "logged") span.event("diagnostic", span.status.startTime);
176 span.end(
177 span.status.startTime + (name === "slow" ? 10_000_000n : 9_999_999n),
178 name === "failed" ? Exit.fail("busy") : Exit.void,
179 );
180 }
181 assert.deepEqual(names, ["sample", "slow", "failed", "logged", "other"]);
182 assert.deepEqual(
183 delegates.map((span) => span.status._tag),
184 Array(7).fill("Ended"),
185 );
186 }).pipe(Effect.provide(NodeServices.layer)),
187 );
188​
189 it.effect(
190 "preserves successful results without retaining them in sampled or unsampled spans",
191 () =>
192 Effect.gen(function* () {
193 for (const sampled of [true, false]) {
194 const delegates: Array<Tracer.Span> = [];
195 const records: Array<EffectTraceRecord> = [];
196 const tracer = yield* makeLocalFileTracer({
197 filePath: "unused",
198 maxBytes: 1024,
199 maxFiles: 1,
200 batchWindowMs: 10_000,
201 sink: {
202 filePath: "unused",
203 push: (record) => {
204 if (record.type === "effect-span") records.push(record);
205 },
206 flush: Effect.void,
207 flushSync: () => {},
208 close: () => Effect.void,
209 },
210 delegate: Tracer.make({
211 span: (options) => {
212 const span = new Tracer.NativeSpan({ ...options, sampled });
213 delegates.push(span);
214 return span;
215 },
216 }),
217 });
218 const payload = { turnItems: [{ output: [{ text: "synthetic-result" }] }] };
219 let span: Tracer.Span | undefined;
220 const result = yield* Effect.gen(function* () {
221 span = yield* Effect.currentSpan;
222 return payload;
223 }).pipe(
224 Effect.withSpan("read-thread-projection"),
225 Effect.provideService(Tracer.Tracer, tracer),
226 );
227 assert.strictEqual(result, payload);
228 assert.isDefined(span);
229 for (const completed of [span!, ...delegates]) {
230 assert.equal(completed.status._tag, "Ended");
231 if (completed.status._tag === "Ended") {
232 assert.deepStrictEqual(completed.status.exit, Exit.void);
233 }
234 }
235 assert.deepStrictEqual(
236 records.map((record) => record.exit),
237 sampled ? [{ _tag: "Success" }] : [],
238 );
239 }
240 }).pipe(Effect.provide(NodeServices.layer)),
241 );
242​
243 it("normalizes circular arrays, maps, and sets without recursing forever", () => {
244 const array: Array<unknown> = ["alpha"];
245 array.push(array);
246​
247 const map = new Map<string, unknown>();
248 map.set("self", map);
249​
250 const set = new Set<unknown>();
251 set.add(set);
252​
253 assert.deepStrictEqual(
254 compactTraceAttributes({
255 array,
256 map,
257 set,
258 }),
259 {
260 array: ["alpha", "[Circular]"],
261 map: { self: "[Circular]" },
262 set: ["[Circular]"],
263 },
264 );
265 });
266​
267 it("keeps an object that appears twice without marking it circular", () => {
268 const shared = { cwd: "/repo" };
269 const sharedMap = new Map([["cwd", "/repo"]]);
270 const sharedSet = new Set(["/repo"]);
271​
272 assert.deepStrictEqual(
273 compactTraceAttributes({
274 ctx: { first: shared, second: shared },
275 list: [shared, shared],
276 maps: [sharedMap, sharedMap],
277 sets: [sharedSet, sharedSet],
278 }),
279 {
280 ctx: { first: { cwd: "/repo" }, second: { cwd: "/repo" } },
281 list: [{ cwd: "/repo" }, { cwd: "/repo" }],
282 maps: [{ cwd: "/repo" }, { cwd: "/repo" }],
283 sets: [["/repo"], ["/repo"]],
284 },
285 );
286 });
287​
288 it("caps shared references that would expand exponentially", () => {
289 let graph: Record<string, unknown> = { cwd: "/repo" };
290 for (let depth = 0; depth < 20; depth++) {
291 graph = { left: graph, right: graph };
292 }
293​
294 const serialized = JSON.stringify(compactTraceAttributes({ graph }));
295​
296 assert.include(serialized, '"[Truncated]"');
297 assert.isBelow(serialized.length, 1_000_000);
298 });
299​
300 nodeServicesIt("node services", (it) => {
301 it.effect(
302 "keeps trace producers responsive during a slow write, bounds the backlog, and drains on close",
303 () =>
304 Effect.gen(function* () {
305 const fs = yield* FileSystem.FileSystem;
306 const path = yield* Path.Path;
307 const directory = yield* fs.makeTempDirectoryScoped({
308 prefix: "t3-trace-backpressure-",
309 });
310 const tracePath = path.join(directory, "trace.ndjson");
311 const started = yield* Deferred.make<void>();
312 const release = yield* Deferred.make<void>();
313 const closed = yield* Ref.make(false);
314 const sink = yield* makeTraceSink({
315 filePath: tracePath,
316 maxBytes: 5_000_000,
317 maxFiles: 2,
318 batchWindowMs: 10_000,
319 }).pipe(
320 Effect.provideService(FileSystem.FileSystem, {
321 ...fs,
322 writeFile: (file, data, options) =>
323 Effect.gen(function* () {
324 yield* Deferred.succeed(started, undefined);
325 yield* Deferred.await(release);
326 yield* fs.writeFile(file, data, options);
327 }),
328 }),
329 );
330 sink.push(makeRecord("first"));
331 const flushing = yield* Effect.forkChild(sink.flush);
332 yield* Deferred.await(started);
333 for (let index = 0; index < 2_000; index++) sink.push(makeRecord("small", String(index)));
334 for (let index = 0; index < 3; index++)
335 sink.push({ ...makeRecord("large"), attributes: { payload: "x".repeat(2_000_000) } });
336 const closing = yield* Effect.forkChild(
337 sink.close().pipe(Effect.tap(() => Ref.set(closed, true))),
338 );
339 yield* Effect.yieldNow;
340 assert.isFalse(yield* Ref.get(closed));
341 yield* Deferred.succeed(release, undefined);
342 yield* Fiber.join(flushing);
343 yield* Fiber.join(closing);
344 const records = yield* readTraceRecords(tracePath);
345 assert.deepStrictEqual(
346 records.map((record) => record.name),
347 ["first", ...Array.from({ length: 2_000 }, () => "small"), "large", "large"],
348 );
349 assert.isTrue(yield* Ref.get(closed));
350 }),
351 );
352​
353 it.effect("writes buffered records synchronously for process exit", () =>
354 Effect.gen(function* () {
355 const fileSystem = yield* FileSystem.FileSystem;
356 const path = yield* Path.Path;
357 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
358 const tracePath = path.join(tempDir, "exit.trace.ndjson");
359 const sink = yield* makeTraceSink({
360 filePath: tracePath,
361 maxBytes: 1_000_000,
362 maxFiles: 2,
363 batchWindowMs: 10_000,
364 });
365​
366 sink.push(makeRecord("before-exit"));
367 sink.flushSync();
368 sink.flushSync();
369​
370 const records = yield* readTraceRecords(tracePath);
371 assert.deepStrictEqual(
372 records.map((record) => record.name),
373 ["before-exit"],
374 );
375 }),
376 );
377​
378 it.effect("keeps every trace file within the configured limit for threshold flushes", () =>
379 Effect.gen(function* () {
380 const fileSystem = yield* FileSystem.FileSystem;
381 const path = yield* Path.Path;
382 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
383 const tracePath = path.join(tempDir, "shared.trace.ndjson");
384 const maxBytes = 1_024;
385​
386 const sink = yield* makeTraceSink({
387 filePath: tracePath,
388 maxBytes,
389 maxFiles: 2,
390 batchWindowMs: 10_000,
391 });
392​
393 for (let index = 0; index < 256; index += 1) {
394 sink.push(makeRecord("threshold", `${index}-${"x".repeat(48)}`));
395 }
396 yield* sink.close();
397​
398 const matchingFiles = (yield* fileSystem.readDirectory(tempDir)).filter(
399 (entry) => entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
400 );
401 assert.include(matchingFiles, "shared.trace.ndjson.1");
402 for (const entry of matchingFiles) {
403 const stat = yield* fileSystem.stat(path.join(tempDir, entry));
404 assert.isAtMost(Number(stat.size), maxBytes, entry);
405 }
406 }),
407 );
408​
409 it.effect("drops a single trace record that cannot fit within the configured limit", () =>
410 Effect.gen(function* () {
411 const fileSystem = yield* FileSystem.FileSystem;
412 const path = yield* Path.Path;
413 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
414 const tracePath = path.join(tempDir, "shared.trace.ndjson");
415 const maxBytes = 1_024;
416​
417 const sink = yield* makeTraceSink({
418 filePath: tracePath,
419 maxBytes,
420 maxFiles: 2,
421 batchWindowMs: 10_000,
422 });
423​
424 sink.push(makeRecord("oversized", "x".repeat(maxBytes * 2)));
425 sink.push(makeRecord("retained"));
426 yield* sink.close();
427​
428 const records = yield* readTraceRecords(tracePath);
429 const stat = yield* fileSystem.stat(tracePath);
430 assert.deepEqual(
431 records.map((record) => record.name),
432 ["retained"],
433 );
434 assert.isAtMost(Number(stat.size), maxBytes);
435 }),
436 );
437​
438 it.effect("keeps WebSocket credentials out of trace files and exported spans", () =>
439 Effect.gen(function* () {
440 const fileSystem = yield* FileSystem.FileSystem;
441 const path = yield* Path.Path;
442 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
443 const tracePath = path.join(tempDir, "shared.trace.ndjson");
444 const sink = yield* makeTraceSink({
445 filePath: tracePath,
446 maxBytes: 1024 * 1024,
447 maxFiles: 2,
448 batchWindowMs: 10_000,
449 });
450 const delegates: Array<Tracer.NativeSpan> = [];
451 const tracer = yield* makeLocalFileTracer({
452 filePath: tracePath,
453 maxBytes: 1024 * 1024,
454 maxFiles: 2,
455 batchWindowMs: 10_000,
456 sink,
457 delegate: Tracer.make({
458 span: (options) => {
459 const span = new Tracer.NativeSpan(options);
460 delegates.push(span);
461 return span;
462 },
463 }),
464 });
465 const url = "/ws?wsTicket=ticket-secret&dpop=proof-secret&clientSurface=web";
466​
467 yield* Effect.annotateCurrentSpan({
468 "url.full": `http://127.0.0.1:3773${url}`,
469 "url.query": url.slice(4),
470 }).pipe(
471 Effect.withSpan("GET", { kind: "server" }),
472 Effect.provideService(Tracer.Tracer, tracer),
473 );
474 yield* Effect.die(new Error(`RequestParseError (GET ${url})`)).pipe(
475 Effect.tapCause((cause) => Effect.logError(cause)),
476 Effect.withSpan("DeviceHubProxy.proxyWebSocket"),
477 Effect.provideService(Tracer.Tracer, tracer),
478 Effect.provide(Logger.layer([Logger.tracerLogger], { mergeWithExisting: false })),
479 Effect.exit,
480 );
481 yield* sink.close();
482​
483 const written = yield* fileSystem.readFileString(tracePath);
484 const exported = delegates.map((span) =>
485 JSON.stringify({
486 attributes: Object.fromEntries(span.attributes),
487 events: span.events.map(([, , attributes]) => attributes),
488 exit:
489 span.status._tag === "Ended" && Exit.isFailure(span.status.exit)
490 ? Cause.pretty(span.status.exit.cause)
491 : "",
492 }),
493 );
494 for (const text of [written, ...exported]) {
495 assert.notInclude(text, "ticket-secret");
496 assert.notInclude(text, "proof-secret");
497 }
498 assert.include(written, "wsTicket=<redacted>&dpop=<redacted>&clientSurface=web");
499 assert.include(exported.join("\n"), "effect.cause");
500 }),
501 );
502​
503 it.effect("drops only the invalid trace record when serialization fails", () =>
504 Effect.gen(function* () {
505 const fileSystem = yield* FileSystem.FileSystem;
506 const path = yield* Path.Path;
507 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
508 const tracePath = path.join(tempDir, "shared.trace.ndjson");
509​
510 const sink = yield* makeTraceSink({
511 filePath: tracePath,
512 maxBytes: 1024,
513 maxFiles: 2,
514 batchWindowMs: 10_000,
515 });
516​
517 const circular: Array<unknown> = [];
518 circular.push(circular);
519​
520 sink.push(makeRecord("alpha"));
521 sink.push({
522 ...makeRecord("invalid"),
523 attributes: {
524 circular,
525 },
526 } as TraceRecord);
527 sink.push(makeRecord("beta"));
528 yield* sink.close();
529​
530 const lines = yield* readTraceRecords(tracePath);
531​
532 assert.deepStrictEqual(
533 lines.map((line) => line.name),
534 ["alpha", "beta"],
535 );
536 }),
537 );
538​
539 it.effect("writes nested spans to disk and captures log messages as span events", () =>
540 Effect.gen(function* () {
541 const fileSystem = yield* FileSystem.FileSystem;
542 const path = yield* Path.Path;
543 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
544 const tracePath = path.join(tempDir, "shared.trace.ndjson");
545​
546 yield* Effect.scoped(
547 Effect.gen(function* () {
548 const program = Effect.gen(function* () {
549 yield* Effect.annotateCurrentSpan({
550 "demo.parent": true,
551 });
552 yield* Effect.logInfo("parent event");
553 yield* Effect.gen(function* () {
554 yield* Effect.annotateCurrentSpan({
555 "demo.child": true,
556 });
557 yield* Effect.logInfo("child event");
558 }).pipe(Effect.withSpan("child-span"));
559 }).pipe(Effect.withSpan("parent-span"));
560​
561 yield* program.pipe(Effect.provide(layerTest(tracePath)));
562 }),
563 );
564​
565 const records = yield* readTraceRecords(tracePath);
566 assert.equal(records.length, 2);
567​
568 const parent = records.find((record) => record.name === "parent-span");
569 const child = records.find((record) => record.name === "child-span");
570​
571 assert.notEqual(parent, undefined);
572 assert.notEqual(child, undefined);
573 if (!parent || !child) {
574 return;
575 }
576​
577 assert.equal(child.parentSpanId, parent.spanId);
578 assert.equal(parent.attributes["demo.parent"], true);
579 assert.equal(child.attributes["demo.child"], true);
580 assert.equal(
581 parent.events.some((event) => event.name === "parent event"),
582 true,
583 );
584 assert.equal(
585 child.events.some((event) => event.name === "child event"),
586 true,
587 );
588 assert.equal(
589 child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
590 true,
591 );
592 }),
593 );
594​
595 it.effect("serializes interrupted spans with an interrupted exit status", () =>
596 Effect.gen(function* () {
597 const fileSystem = yield* FileSystem.FileSystem;
598 const path = yield* Path.Path;
599 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
600 const tracePath = path.join(tempDir, "shared.trace.ndjson");
601​
602 yield* Effect.scoped(
603 Effect.exit(
604 Effect.interrupt.pipe(
605 Effect.withSpan("interrupt-span"),
606 Effect.provide(layerTest(tracePath)),
607 ),
608 ),
609 );
610​
611 const records = yield* readTraceRecords(tracePath);
612 assert.equal(records.length, 1);
613 assert.equal(records[0]?.name, "interrupt-span");
614 assert.equal(records[0]?.exit?._tag, "Interrupted");
615 }),
616 );
617 });
618});
619​
620describe("decodeOtlpTraceRecords", () => {
621 it("decodes spans when OTLP/JSON omits unset and empty fields", () => {
622 // Protobuf JSON leaves out unset and empty fields, so this batch is valid.
623 const payload = cast<unknown, OtlpTracer.TraceData>({
624 resourceSpans: [
625 {},
626 {
627 scopeSpans: [
628 {},
629 {
630 spans: [
631 {
632 traceId: "trace-1",
633 spanId: "span-1",
634 name: "browser.request",
635 startTimeUnixNano: "1000000",
636 endTimeUnixNano: "3000000",
637 attributes: [{ key: "tags", value: { arrayValue: {} } }],
638 },
639 ],
640 },
641 ],
642 },
643 ],
644 });
645​
646 assert.deepStrictEqual(decodeOtlpTraceRecords(cast<unknown, OtlpTracer.TraceData>({})), []);
647 assert.deepStrictEqual(decodeOtlpTraceRecords(payload), [
648 {
649 type: "otlp-span",
650 name: "browser.request",
651 traceId: "trace-1",
652 spanId: "span-1",
653 sampled: true,
654 kind: "internal",
655 startTimeUnixNano: "1000000",
656 endTimeUnixNano: "3000000",
657 durationMs: 2,
658 attributes: { tags: [] },
659 resourceAttributes: {},
660 scope: { attributes: {} },
661 events: [],
662 links: [],
663 status: { code: "0" },
664 },
665 ]);
666 });
667});
668​
669describe("OtlpHeadersFromString", () => {
670 const decode = Schema.decodeUnknownSync(OtlpHeadersFromString);
671​
672 it.each([
673 {
674 name: "decodes percent-encoded values",
675 input: "authorization=Basic%20abc%3D%3D,x-tenant=t3",
676 expected: { authorization: "Basic abc==", "x-tenant": "t3" },
677 },
678 {
679 name: "ignores whitespace around separators",
680 input: "authorization=Basic%20abc%3D%3D, x-tenant = t3 ,",
681 expected: { authorization: "Basic abc==", "x-tenant": "t3" },
682 },
683 {
684 name: "keeps literal equals signs inside a value",
685 input: "authorization=Bearer abc==",
686 expected: { authorization: "Bearer abc==" },
687 },
688 {
689 name: "keeps an empty value",
690 input: "x-empty=",
691 expected: { "x-empty": "" },
692 },
693 ])("$name", ({ input, expected }) => {
694 expect(decode(input)).toEqual(expected);
695 });
696​
697 it.each([
698 { name: "rejects a pair without a separator", input: "authorization" },
699 { name: "rejects a pair without a key", input: "=value" },
700 { name: "rejects a malformed percent-encoding", input: "authorization=%E0" },
701 ])("$name", ({ input }) => {
702 expect(() => decode(input)).toThrow();
703 });
704});