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