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 References from "effect/References";
12import * as Schema from "effect/Schema";
13import * as Tracer from "effect/Tracer";
14
15import {
16 causeErrorTag,
17 compactTraceAttributes,
18 errorTag,
19 makeLocalFileTracer,
20 makeTraceSink,
21 type TraceRecord,
22} from "./observability.ts";
23
24describe("errorTag", () => {
25 it("reports structural tags without retaining arbitrary values", () => {
26 assert.equal(errorTag({ _tag: "AcpRequestError" }), "AcpRequestError");
27 assert.equal(errorTag(new TypeError("secret-token-value")), "TypeError");
28 assert.equal(errorTag({ _tag: "secret token value" }), "TaggedError");
29 });
30});
31
32describe("causeErrorTag", () => {
33 it("reports the tagged failure value instead of the Cause reason wrapper", () => {
34 assert.equal(
35 causeErrorTag(Cause.fail({ _tag: "ServerAuthInvalidCredentialError" })),
36 "ServerAuthInvalidCredentialError",
37 );
38 });
39
40 it("reports structural cause kinds when no typed failure exists", () => {
41 assert.equal(causeErrorTag(Cause.die(new Error("unexpected"))), "Die");
42 assert.equal(causeErrorTag(Cause.interrupt()), "Interrupt");
43 });
44});
45
46const TraceRecordLine = Schema.Struct({
47 name: Schema.String,
48 spanId: Schema.String,
49 parentSpanId: Schema.optional(Schema.String),
50 attributes: Schema.Record(Schema.String, Schema.Unknown),
51 events: Schema.Array(
52 Schema.Struct({
53 name: Schema.String,
54 attributes: Schema.Record(Schema.String, Schema.Unknown),
55 }),
56 ),
57 exit: Schema.optional(
58 Schema.Struct({
59 _tag: Schema.String,
60 }),
61 ),
62});
63
64const decodeTraceRecordLine = Schema.decodeUnknownSync(Schema.fromJsonString(TraceRecordLine));
65
66const makeRecord = (name: string, suffix = ""): TraceRecord => ({
67 type: "effect-span",
68 name,
69 traceId: `trace-${name}-${suffix}`,
70 spanId: `span-${name}-${suffix}`,
71 sampled: true,
72 kind: "internal",
73 startTimeUnixNano: "1",
74 endTimeUnixNano: "2",
75 durationMs: 1,
76 attributes: {
77 payload: suffix,
78 },
79 events: [],
80 links: [],
81 exit: {
82 _tag: "Success",
83 },
84});
85
86const readTraceRecords = Effect.fn("readTraceRecords")(function* (tracePath: string) {
87 const fileSystem = yield* FileSystem.FileSystem;
88 return (yield* fileSystem.readFileString(tracePath))
89 .trim()
90 .split("\n")
91 .filter((line) => line.length > 0)
92 .map((line) => decodeTraceRecordLine(line));
93});
94
95const makeTestLayer = (tracePath: string) =>
96 Layer.mergeAll(
97 Layer.effect(
98 Tracer.Tracer,
99 makeLocalFileTracer({
100 filePath: tracePath,
101 maxBytes: 1024 * 1024,
102 maxFiles: 2,
103 batchWindowMs: 10_000,
104 }),
105 ),
106 Logger.layer([Logger.tracerLogger], { mergeWithExisting: false }),
107 Layer.succeed(References.MinimumLogLevel, "Info"),
108 );
109
110const nodeServicesIt = it.layer(NodeServices.layer);
111
112describe("observability", () => {
113 it("normalizes circular arrays, maps, and sets without recursing forever", () => {
114 const array: Array<unknown> = ["alpha"];
115 array.push(array);
116
117 const map = new Map<string, unknown>();
118 map.set("self", map);
119
120 const set = new Set<unknown>();
121 set.add(set);
122
123 assert.deepStrictEqual(
124 compactTraceAttributes({
125 array,
126 map,
127 set,
128 }),
129 {
130 array: ["alpha", "[Circular]"],
131 map: { self: "[Circular]" },
132 set: ["[Circular]"],
133 },
134 );
135 });
136
137 it("normalizes invalid dates without throwing", () => {
138 // @effect-diagnostics-next-line globalDate:off
139 const invalidDate = new Date("not-a-real-date");
140 assert.deepStrictEqual(
141 compactTraceAttributes({
142 invalidDate,
143 }),
144 {
145 invalidDate: "Invalid Date",
146 },
147 );
148 });
149
150 nodeServicesIt("node services", (it) => {
151 it.effect("flushes buffered trace records on close", () =>
152 Effect.scoped(
153 Effect.gen(function* () {
154 const fileSystem = yield* FileSystem.FileSystem;
155 const path = yield* Path.Path;
156 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
157 const tracePath = path.join(tempDir, "shared.trace.ndjson");
158
159 const sink = yield* makeTraceSink({
160 filePath: tracePath,
161 maxBytes: 1024,
162 maxFiles: 2,
163 batchWindowMs: 10_000,
164 });
165
166 sink.push(makeRecord("alpha"));
167 sink.push(makeRecord("beta"));
168 yield* sink.close();
169
170 const lines = yield* readTraceRecords(tracePath);
171
172 assert.equal(lines.length, 2);
173 assert.equal(lines[0]?.name, "alpha");
174 assert.equal(lines[1]?.name, "beta");
175 }),
176 ),
177 );
178
179 it.effect("rotates the trace file when the configured max size is exceeded", () =>
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: 180,
190 maxFiles: 2,
191 batchWindowMs: 10_000,
192 });
193
194 for (let index = 0; index < 8; index += 1) {
195 sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`));
196 yield* sink.flush;
197 }
198 yield* sink.close();
199
200 const matchingFiles = Arr.sort(
201 (yield* fileSystem.readDirectory(tempDir)).filter(
202 (entry) =>
203 entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
204 ),
205 Order.String,
206 );
207
208 assert.equal(
209 matchingFiles.some((entry) => entry === "shared.trace.ndjson.1"),
210 true,
211 );
212 assert.equal(
213 matchingFiles.some((entry) => entry === "shared.trace.ndjson.3"),
214 false,
215 );
216 }),
217 ),
218 );
219
220 it.effect("drops only the invalid trace record when serialization fails", () =>
221 Effect.scoped(
222 Effect.gen(function* () {
223 const fileSystem = yield* FileSystem.FileSystem;
224 const path = yield* Path.Path;
225 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
226 const tracePath = path.join(tempDir, "shared.trace.ndjson");
227
228 const sink = yield* makeTraceSink({
229 filePath: tracePath,
230 maxBytes: 1024,
231 maxFiles: 2,
232 batchWindowMs: 10_000,
233 });
234
235 const circular: Array<unknown> = [];
236 circular.push(circular);
237
238 sink.push(makeRecord("alpha"));
239 sink.push({
240 ...makeRecord("invalid"),
241 attributes: {
242 circular,
243 },
244 } as TraceRecord);
245 sink.push(makeRecord("beta"));
246 yield* sink.close();
247
248 const lines = yield* readTraceRecords(tracePath);
249
250 assert.deepStrictEqual(
251 lines.map((line) => line.name),
252 ["alpha", "beta"],
253 );
254 }),
255 ),
256 );
257
258 it.effect("writes nested spans to disk and captures log messages as span events", () =>
259 Effect.scoped(
260 Effect.gen(function* () {
261 const fileSystem = yield* FileSystem.FileSystem;
262 const path = yield* Path.Path;
263 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
264 const tracePath = path.join(tempDir, "shared.trace.ndjson");
265
266 yield* Effect.scoped(
267 Effect.gen(function* () {
268 const program = Effect.gen(function* () {
269 yield* Effect.annotateCurrentSpan({
270 "demo.parent": true,
271 });
272 yield* Effect.logInfo("parent event");
273 yield* Effect.gen(function* () {
274 yield* Effect.annotateCurrentSpan({
275 "demo.child": true,
276 });
277 yield* Effect.logInfo("child event");
278 }).pipe(Effect.withSpan("child-span"));
279 }).pipe(Effect.withSpan("parent-span"));
280
281 yield* program.pipe(Effect.provide(makeTestLayer(tracePath)));
282 }),
283 );
284
285 const records = yield* readTraceRecords(tracePath);
286 assert.equal(records.length, 2);
287
288 const parent = records.find((record) => record.name === "parent-span");
289 const child = records.find((record) => record.name === "child-span");
290
291 assert.notEqual(parent, undefined);
292 assert.notEqual(child, undefined);
293 if (!parent || !child) {
294 return;
295 }
296
297 assert.equal(child.parentSpanId, parent.spanId);
298 assert.equal(parent.attributes["demo.parent"], true);
299 assert.equal(child.attributes["demo.child"], true);
300 assert.equal(
301 parent.events.some((event) => event.name === "parent event"),
302 true,
303 );
304 assert.equal(
305 child.events.some((event) => event.name === "child event"),
306 true,
307 );
308 assert.equal(
309 child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
310 true,
311 );
312 }),
313 ),
314 );
315
316 it.effect("serializes interrupted spans with an interrupted exit status", () =>
317 Effect.scoped(
318 Effect.gen(function* () {
319 const fileSystem = yield* FileSystem.FileSystem;
320 const path = yield* Path.Path;
321 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
322 const tracePath = path.join(tempDir, "shared.trace.ndjson");
323
324 yield* Effect.scoped(
325 Effect.exit(
326 Effect.interrupt.pipe(
327 Effect.withSpan("interrupt-span"),
328 Effect.provide(makeTestLayer(tracePath)),
329 ),
330 ),
331 );
332
333 const records = yield* readTraceRecords(tracePath);
334 assert.equal(records.length, 1);
335 assert.equal(records[0]?.name, "interrupt-span");
336 assert.equal(records[0]?.exit?._tag, "Interrupted");
337 }),
338 ),
339 );
340 });
341});