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