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