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