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 Deferred from "effect/Deferred";
7import * as Fiber from "effect/Fiber";
8import * as Exit from "effect/Exit";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Logger from "effect/Logger";
12import * as Order from "effect/Order";
13import * as Path from "effect/Path";
14import * as Ref from "effect/Ref";
15import * as References from "effect/References";
16import * as Schema from "effect/Schema";
17import * as Tracer from "effect/Tracer";
18import * as TestClock from "effect/testing/TestClock";
19import { vi } from "vite-plus/test";
20
21import {
22 causeErrorTag,
23 compactTraceAttributes,
24 decodeOtlpTraceRecords,
25 errorTag,
26 makeLocalFileTracer,
27 makeTraceSink,
28 type EffectTraceRecord,
29 type TraceRecord,
30 type TraceSinkFlushStats,
31 OtlpHeadersFromString,
32 truncateTraceAttributes,
33} from "./observability.ts";
34
35describe("errorTag", () => {
36 it("reports structural tags without retaining arbitrary values", () => {
37 assert.equal(errorTag({ _tag: "AcpRequestError" }), "AcpRequestError");
38 assert.equal(errorTag(new TypeError("secret-token-value")), "TypeError");
39 assert.equal(errorTag({ _tag: "secret token value" }), "TaggedError");
40 });
41});
42
43describe("causeErrorTag", () => {
44 it("reports the tagged failure value instead of the Cause reason wrapper", () => {
45 assert.equal(
46 causeErrorTag(Cause.fail({ _tag: "ServerAuthInvalidCredentialError" })),
47 "ServerAuthInvalidCredentialError",
48 );
49 });
50
51 it("reports structural cause kinds when no typed failure exists", () => {
52 assert.equal(causeErrorTag(Cause.die(new Error("unexpected"))), "Die");
53 assert.equal(causeErrorTag(Cause.interrupt()), "Interrupt");
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("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 }).pipe(Effect.provide(NodeServices.layer)),
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 }).pipe(Effect.provide(NodeServices.layer)),
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(
335 "keeps trace producers responsive during a slow write, bounds the backlog, and drains on close",
336 () =>
337 Effect.scoped(
338 Effect.gen(function* () {
339 const fs = yield* FileSystem.FileSystem;
340 const path = yield* Path.Path;
341 const directory = yield* fs.makeTempDirectoryScoped({
342 prefix: "t3-trace-backpressure-",
343 });
344 const tracePath = path.join(directory, "trace.ndjson");
345 const started = yield* Deferred.make<void>();
346 const release = yield* Deferred.make<void>();
347 const closed = yield* Ref.make(false);
348 const sink = yield* makeTraceSink({
349 filePath: tracePath,
350 maxBytes: 5_000_000,
351 maxFiles: 2,
352 batchWindowMs: 10_000,
353 }).pipe(
354 Effect.provideService(FileSystem.FileSystem, {
355 ...fs,
356 writeFile: (file, data, options) =>
357 Effect.gen(function* () {
358 yield* Deferred.succeed(started, undefined);
359 yield* Deferred.await(release);
360 yield* fs.writeFile(file, data, options);
361 }),
362 }),
363 );
364 sink.push(makeRecord("first"));
365 const flushing = yield* Effect.forkChild(sink.flush);
366 yield* Deferred.await(started);
367 for (let index = 0; index < 2_000; index++)
368 sink.push(makeRecord("small", String(index)));
369 for (let index = 0; index < 3; index++)
370 sink.push({ ...makeRecord("large"), attributes: { payload: "x".repeat(2_000_000) } });
371 const closing = yield* Effect.forkChild(
372 sink.close().pipe(Effect.tap(() => Ref.set(closed, true))),
373 );
374 yield* Effect.yieldNow;
375 assert.isFalse(yield* Ref.get(closed));
376 yield* Deferred.succeed(release, undefined);
377 yield* Fiber.join(flushing);
378 yield* Fiber.join(closing);
379 const records = yield* readTraceRecords(tracePath);
380 assert.deepStrictEqual(
381 records.map((record) => record.name),
382 ["first", ...Array.from({ length: 2_000 }, () => "small"), "large", "large"],
383 );
384 assert.isTrue(yield* Ref.get(closed));
385 }),
386 ),
387 );
388
389 it.effect("flushes buffered trace records on close", () =>
390 Effect.scoped(
391 Effect.gen(function* () {
392 const fileSystem = yield* FileSystem.FileSystem;
393 const path = yield* Path.Path;
394 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
395 const tracePath = path.join(tempDir, "shared.trace.ndjson");
396
397 const sink = yield* makeTraceSink({
398 filePath: tracePath,
399 maxBytes: 1024,
400 maxFiles: 2,
401 batchWindowMs: 10_000,
402 });
403
404 sink.push(makeRecord("alpha"));
405 sink.push(makeRecord("beta"));
406 yield* sink.close();
407
408 const lines = yield* readTraceRecords(tracePath);
409
410 assert.equal(lines.length, 2);
411 assert.equal(lines[0]?.name, "alpha");
412 assert.equal(lines[1]?.name, "beta");
413 }),
414 ),
415 );
416
417 it.effect("reports successful logical trace writes", () =>
418 Effect.scoped(
419 Effect.gen(function* () {
420 const fileSystem = yield* FileSystem.FileSystem;
421 const path = yield* Path.Path;
422 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
423 const tracePath = path.join(tempDir, "shared.trace.ndjson");
424 const reported = yield* Ref.make<ReadonlyArray<TraceSinkFlushStats>>([]);
425
426 const sink = yield* makeTraceSink({
427 filePath: tracePath,
428 maxBytes: 1024,
429 maxFiles: 2,
430 batchWindowMs: 10_000,
431 onFlush: (stats) => Ref.update(reported, (current) => [...current, stats]),
432 });
433
434 sink.push(makeRecord("attributed"));
435 yield* sink.flush;
436
437 const stats = yield* Ref.get(reported);
438 assert.equal(stats.length, 1);
439 assert.equal(stats[0]?.count, 1);
440 assert.isAbove(stats[0]?.logicalWriteBytes ?? 0, 0);
441 }),
442 ),
443 );
444
445 it.effect("rotates the trace file when the configured max size is exceeded", () =>
446 Effect.scoped(
447 Effect.gen(function* () {
448 const fileSystem = yield* FileSystem.FileSystem;
449 const path = yield* Path.Path;
450 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
451 const tracePath = path.join(tempDir, "shared.trace.ndjson");
452
453 const sink = yield* makeTraceSink({
454 filePath: tracePath,
455 maxBytes: 500,
456 maxFiles: 2,
457 batchWindowMs: 10_000,
458 });
459
460 for (let index = 0; index < 8; index += 1) {
461 sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`));
462 yield* sink.flush;
463 }
464 yield* sink.close();
465
466 const matchingFiles = Arr.sort(
467 (yield* fileSystem.readDirectory(tempDir)).filter(
468 (entry) =>
469 entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
470 ),
471 Order.String,
472 );
473
474 assert.equal(
475 matchingFiles.some((entry) => entry === "shared.trace.ndjson.1"),
476 true,
477 );
478 assert.equal(
479 matchingFiles.some((entry) => entry === "shared.trace.ndjson.3"),
480 false,
481 );
482 }),
483 ),
484 );
485
486 it.effect("keeps every trace file within the configured limit for threshold flushes", () =>
487 Effect.scoped(
488 Effect.gen(function* () {
489 const fileSystem = yield* FileSystem.FileSystem;
490 const path = yield* Path.Path;
491 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
492 const tracePath = path.join(tempDir, "shared.trace.ndjson");
493 const maxBytes = 1_024;
494
495 const sink = yield* makeTraceSink({
496 filePath: tracePath,
497 maxBytes,
498 maxFiles: 2,
499 batchWindowMs: 10_000,
500 });
501
502 for (let index = 0; index < 256; index += 1) {
503 sink.push(makeRecord("threshold", `${index}-${"x".repeat(48)}`));
504 }
505 yield* sink.close();
506
507 const matchingFiles = (yield* fileSystem.readDirectory(tempDir)).filter(
508 (entry) => entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
509 );
510 assert.include(matchingFiles, "shared.trace.ndjson.1");
511 for (const entry of matchingFiles) {
512 const stat = yield* fileSystem.stat(path.join(tempDir, entry));
513 assert.isAtMost(Number(stat.size), maxBytes, entry);
514 }
515 }),
516 ),
517 );
518
519 it.effect("drops a single trace record that cannot fit within the configured limit", () =>
520 Effect.scoped(
521 Effect.gen(function* () {
522 const fileSystem = yield* FileSystem.FileSystem;
523 const path = yield* Path.Path;
524 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
525 const tracePath = path.join(tempDir, "shared.trace.ndjson");
526 const maxBytes = 1_024;
527
528 const sink = yield* makeTraceSink({
529 filePath: tracePath,
530 maxBytes,
531 maxFiles: 2,
532 batchWindowMs: 10_000,
533 });
534
535 sink.push(makeRecord("oversized", "x".repeat(maxBytes * 2)));
536 sink.push(makeRecord("retained"));
537 yield* sink.close();
538
539 const records = yield* readTraceRecords(tracePath);
540 const stat = yield* fileSystem.stat(tracePath);
541 assert.deepEqual(
542 records.map((record) => record.name),
543 ["retained"],
544 );
545 assert.isAtMost(Number(stat.size), maxBytes);
546 }),
547 ),
548 );
549
550 it.effect("drops only the invalid trace record when serialization fails", () =>
551 Effect.scoped(
552 Effect.gen(function* () {
553 const fileSystem = yield* FileSystem.FileSystem;
554 const path = yield* Path.Path;
555 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
556 const tracePath = path.join(tempDir, "shared.trace.ndjson");
557
558 const sink = yield* makeTraceSink({
559 filePath: tracePath,
560 maxBytes: 1024,
561 maxFiles: 2,
562 batchWindowMs: 10_000,
563 });
564
565 const circular: Array<unknown> = [];
566 circular.push(circular);
567
568 sink.push(makeRecord("alpha"));
569 sink.push({
570 ...makeRecord("invalid"),
571 attributes: {
572 circular,
573 },
574 } as TraceRecord);
575 sink.push(makeRecord("beta"));
576 yield* sink.close();
577
578 const lines = yield* readTraceRecords(tracePath);
579
580 assert.deepStrictEqual(
581 lines.map((line) => line.name),
582 ["alpha", "beta"],
583 );
584 }),
585 ),
586 );
587
588 it.effect("drops records after a failed write and logs once per failure episode", () => {
589 const logs: Array<{ readonly logLevel: string; readonly message: unknown }> = [];
590 const captureLogs = Logger.make(({ logLevel, message }) => {
591 logs.push({ logLevel, message });
592 });
593 const spans: Array<Tracer.NativeSpan> = [];
594 const recordingTracer = Tracer.make({
595 span: (options) => {
596 const span = new Tracer.NativeSpan(options);
597 spans.push(span);
598 return span;
599 },
600 });
601
602 return Effect.gen(function* () {
603 const fileSystem = yield* FileSystem.FileSystem;
604 const path = yield* Path.Path;
605 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
606 const tracePath = path.join(tempDir, "shared.trace.ndjson");
607 yield* fileSystem.makeDirectory(tracePath);
608 const write = vi.spyOn(fileSystem, "writeFile");
609 yield* Effect.addFinalizer(() => Effect.sync(() => write.mockRestore()));
610
611 const sink = yield* makeTraceSink({
612 filePath: tracePath,
613 maxBytes: 1024 * 1024,
614 maxFiles: 2,
615 batchWindowMs: 1_000,
616 }).pipe(Effect.withTracer(recordingTracer));
617
618 for (let index = 0; index < 1_024; index += 1) {
619 sink.push(makeRecord("lost", String(index)));
620 }
621 yield* sink.flush;
622 for (let index = 0; index < 5; index += 1) {
623 sink.push(makeRecord("lost"));
624 yield* TestClock.adjust("1 second");
625 yield* sink.flush;
626 }
627
628 assert.deepStrictEqual(
629 write.mock.calls.map(([, chunk]) => Buffer.from(chunk).toString().split("\n").length - 1),
630 [1024, 1, 1, 1, 1, 1],
631 );
632 expect(logs).toEqual([
633 { logLevel: "Warn", message: [expect.any(String), { filePath: tracePath }] },
634 ]);
635
636 yield* fileSystem.remove(tracePath, { recursive: true });
637 sink.push(makeRecord("recovered"));
638 yield* TestClock.adjust("1 second");
639 yield* sink.flush;
640
641 const records = yield* readTraceRecords(tracePath);
642 assert.deepStrictEqual(
643 records.map((record) => record.name),
644 ["recovered"],
645 );
646 expect(logs[1]).toEqual({
647 logLevel: "Info",
648 message: [expect.any(String), { filePath: tracePath, droppedCount: 1_029 }],
649 });
650
651 sink.push(makeRecord("healthy"));
652 yield* TestClock.adjust("1 second");
653 yield* sink.flush;
654 expect(logs).toHaveLength(2);
655
656 yield* fileSystem.remove(tracePath);
657 yield* fileSystem.makeDirectory(tracePath);
658 sink.push(makeRecord("lost-again"));
659 yield* TestClock.adjust("1 second");
660 yield* sink.flush;
661 assert.deepStrictEqual(
662 logs.map((log) => log.logLevel),
663 ["Warn", "Info", "Warn"],
664 );
665
666 assert.deepStrictEqual(
667 spans.map((span) => [span.name, span.events.length]),
668 [["makeTraceSink", 0]],
669 );
670 }).pipe(
671 Effect.scoped,
672 Effect.provide(
673 Logger.layer([captureLogs, Logger.tracerLogger], { mergeWithExisting: false }),
674 ),
675 );
676 });
677
678 it.effect("writes nested spans to disk and captures log messages as span events", () =>
679 Effect.scoped(
680 Effect.gen(function* () {
681 const fileSystem = yield* FileSystem.FileSystem;
682 const path = yield* Path.Path;
683 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
684 const tracePath = path.join(tempDir, "shared.trace.ndjson");
685
686 yield* Effect.scoped(
687 Effect.gen(function* () {
688 const program = Effect.gen(function* () {
689 yield* Effect.annotateCurrentSpan({
690 "demo.parent": true,
691 });
692 yield* Effect.logInfo("parent event");
693 yield* Effect.gen(function* () {
694 yield* Effect.annotateCurrentSpan({
695 "demo.child": true,
696 });
697 yield* Effect.logInfo("child event");
698 }).pipe(Effect.withSpan("child-span"));
699 }).pipe(Effect.withSpan("parent-span"));
700
701 yield* program.pipe(Effect.provide(layerTest(tracePath)));
702 }),
703 );
704
705 const records = yield* readTraceRecords(tracePath);
706 assert.equal(records.length, 2);
707
708 const parent = records.find((record) => record.name === "parent-span");
709 const child = records.find((record) => record.name === "child-span");
710
711 assert.notEqual(parent, undefined);
712 assert.notEqual(child, undefined);
713 if (!parent || !child) {
714 return;
715 }
716
717 assert.equal(child.parentSpanId, parent.spanId);
718 assert.equal(parent.attributes["demo.parent"], true);
719 assert.equal(child.attributes["demo.child"], true);
720 assert.equal(
721 parent.events.some((event) => event.name === "parent event"),
722 true,
723 );
724 assert.equal(
725 child.events.some((event) => event.name === "child event"),
726 true,
727 );
728 assert.equal(
729 child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
730 true,
731 );
732 }),
733 ),
734 );
735
736 it.effect("serializes interrupted spans with an interrupted exit status", () =>
737 Effect.scoped(
738 Effect.gen(function* () {
739 const fileSystem = yield* FileSystem.FileSystem;
740 const path = yield* Path.Path;
741 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
742 const tracePath = path.join(tempDir, "shared.trace.ndjson");
743
744 yield* Effect.scoped(
745 Effect.exit(
746 Effect.interrupt.pipe(
747 Effect.withSpan("interrupt-span"),
748 Effect.provide(layerTest(tracePath)),
749 ),
750 ),
751 );
752
753 const records = yield* readTraceRecords(tracePath);
754 assert.equal(records.length, 1);
755 assert.equal(records[0]?.name, "interrupt-span");
756 assert.equal(records[0]?.exit?._tag, "Interrupted");
757 }),
758 ),
759 );
760 });
761});
762
763describe("OtlpHeadersFromString", () => {
764 const decode = Schema.decodeUnknownSync(OtlpHeadersFromString);
765
766 it.each([
767 {
768 name: "decodes percent-encoded values",
769 input: "authorization=Basic%20abc%3D%3D,x-tenant=t3",
770 expected: { authorization: "Basic abc==", "x-tenant": "t3" },
771 },
772 {
773 name: "ignores whitespace around separators",
774 input: "authorization=Basic%20abc%3D%3D, x-tenant = t3 ,",
775 expected: { authorization: "Basic abc==", "x-tenant": "t3" },
776 },
777 {
778 name: "keeps literal equals signs inside a value",
779 input: "authorization=Bearer abc==",
780 expected: { authorization: "Bearer abc==" },
781 },
782 {
783 name: "keeps an empty value",
784 input: "x-empty=",
785 expected: { "x-empty": "" },
786 },
787 ])("$name", ({ input, expected }) => {
788 expect(decode(input)).toEqual(expected);
789 });
790
791 it.each([
792 { name: "rejects a pair without a separator", input: "authorization" },
793 { name: "rejects a pair without a key", input: "=value" },
794 { name: "rejects a malformed percent-encoding", input: "authorization=%E0" },
795 ])("$name", ({ input }) => {
796 expect(() => decode(input)).toThrow();
797 });
798});