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

observability.test.ts

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