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