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