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