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