Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

observability.test.ts

313 lines9.5 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Logger from "effect/Logger";
7import * as Path from "effect/Path";
8import * as References from "effect/References";
9import * as Schema from "effect/Schema";
10import * as Tracer from "effect/Tracer";
11​
12import {
13 compactTraceAttributes,
14 makeLocalFileTracer,
15 makeTraceSink,
16 type TraceRecord,
17} from "./observability.ts";
18​
19const TraceRecordLine = Schema.Struct({
20 name: Schema.String,
21 spanId: Schema.String,
22 parentSpanId: Schema.optional(Schema.String),
23 attributes: Schema.Record(Schema.String, Schema.Unknown),
24 events: Schema.Array(
25 Schema.Struct({
26 name: Schema.String,
27 attributes: Schema.Record(Schema.String, Schema.Unknown),
28 }),
29 ),
30 exit: Schema.optional(
31 Schema.Struct({
32 _tag: Schema.String,
33 }),
34 ),
35});
36​
37const decodeTraceRecordLine = Schema.decodeUnknownSync(Schema.fromJsonString(TraceRecordLine));
38​
39const makeRecord = (name: string, suffix = ""): TraceRecord => ({
40 type: "effect-span",
41 name,
42 traceId: `trace-${name}-${suffix}`,
43 spanId: `span-${name}-${suffix}`,
44 sampled: true,
45 kind: "internal",
46 startTimeUnixNano: "1",
47 endTimeUnixNano: "2",
48 durationMs: 1,
49 attributes: {
50 payload: suffix,
51 },
52 events: [],
53 links: [],
54 exit: {
55 _tag: "Success",
56 },
57});
58​
59const readTraceRecords = Effect.fn("readTraceRecords")(function* (tracePath: string) {
60 const fileSystem = yield* FileSystem.FileSystem;
61 return (yield* fileSystem.readFileString(tracePath))
62 .trim()
63 .split("\n")
64 .filter((line) => line.length > 0)
65 .map((line) => decodeTraceRecordLine(line));
66});
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​
83const nodeServicesIt = it.layer(NodeServices.layer);
84​
85describe("observability", () => {
86 it("normalizes circular arrays, maps, and sets without recursing forever", () => {
87 const array: Array<unknown> = ["alpha"];
88 array.push(array);
89​
90 const map = new Map<string, unknown>();
91 map.set("self", map);
92​
93 const set = new Set<unknown>();
94 set.add(set);
95​
96 assert.deepStrictEqual(
97 compactTraceAttributes({
98 array,
99 map,
100 set,
101 }),
102 {
103 array: ["alpha", "[Circular]"],
104 map: { self: "[Circular]" },
105 set: ["[Circular]"],
106 },
107 );
108 });
109​
110 it("normalizes invalid dates without throwing", () => {
111 // @effect-diagnostics-next-line globalDate:off
112 const invalidDate = new Date("not-a-real-date");
113 assert.deepStrictEqual(
114 compactTraceAttributes({
115 invalidDate,
116 }),
117 {
118 invalidDate: "Invalid Date",
119 },
120 );
121 });
122​
123 nodeServicesIt("node services", (it) => {
124 it.effect("flushes buffered trace records on close", () =>
125 Effect.scoped(
126 Effect.gen(function* () {
127 const fileSystem = yield* FileSystem.FileSystem;
128 const path = yield* Path.Path;
129 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
130 const tracePath = path.join(tempDir, "shared.trace.ndjson");
131​
132 const sink = yield* makeTraceSink({
133 filePath: tracePath,
134 maxBytes: 1024,
135 maxFiles: 2,
136 batchWindowMs: 10_000,
137 });
138​
139 sink.push(makeRecord("alpha"));
140 sink.push(makeRecord("beta"));
141 yield* sink.close();
142​
143 const lines = yield* readTraceRecords(tracePath);
144​
145 assert.equal(lines.length, 2);
146 assert.equal(lines[0]?.name, "alpha");
147 assert.equal(lines[1]?.name, "beta");
148 }),
149 ),
150 );
151​
152 it.effect("rotates the trace file when the configured max size is exceeded", () =>
153 Effect.scoped(
154 Effect.gen(function* () {
155 const fileSystem = yield* FileSystem.FileSystem;
156 const path = yield* Path.Path;
157 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
158 const tracePath = path.join(tempDir, "shared.trace.ndjson");
159​
160 const sink = yield* makeTraceSink({
161 filePath: tracePath,
162 maxBytes: 180,
163 maxFiles: 2,
164 batchWindowMs: 10_000,
165 });
166​
167 for (let index = 0; index < 8; index += 1) {
168 sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`));
169 yield* sink.flush;
170 }
171 yield* sink.close();
172​
173 const matchingFiles = (yield* fileSystem.readDirectory(tempDir))
174 .filter(
175 (entry) =>
176 entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
177 )
178 .toSorted();
179​
180 assert.equal(
181 matchingFiles.some((entry) => entry === "shared.trace.ndjson.1"),
182 true,
183 );
184 assert.equal(
185 matchingFiles.some((entry) => entry === "shared.trace.ndjson.3"),
186 false,
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 fileSystem = yield* FileSystem.FileSystem;
196 const path = yield* Path.Path;
197 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
198 const tracePath = path.join(tempDir, "shared.trace.ndjson");
199​
200 const sink = yield* makeTraceSink({
201 filePath: tracePath,
202 maxBytes: 1024,
203 maxFiles: 2,
204 batchWindowMs: 10_000,
205 });
206​
207 const circular: Array<unknown> = [];
208 circular.push(circular);
209​
210 sink.push(makeRecord("alpha"));
211 sink.push({
212 ...makeRecord("invalid"),
213 attributes: {
214 circular,
215 },
216 } as TraceRecord);
217 sink.push(makeRecord("beta"));
218 yield* sink.close();
219​
220 const lines = yield* readTraceRecords(tracePath);
221​
222 assert.deepStrictEqual(
223 lines.map((line) => line.name),
224 ["alpha", "beta"],
225 );
226 }),
227 ),
228 );
229​
230 it.effect("writes nested spans to disk and captures log messages as span events", () =>
231 Effect.scoped(
232 Effect.gen(function* () {
233 const fileSystem = yield* FileSystem.FileSystem;
234 const path = yield* Path.Path;
235 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
236 const tracePath = path.join(tempDir, "shared.trace.ndjson");
237​
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 = yield* 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 }),
285 ),
286 );
287​
288 it.effect("serializes interrupted spans with an interrupted exit status", () =>
289 Effect.scoped(
290 Effect.gen(function* () {
291 const fileSystem = yield* FileSystem.FileSystem;
292 const path = yield* Path.Path;
293 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
294 const tracePath = path.join(tempDir, "shared.trace.ndjson");
295​
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 = yield* 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 }),
310 ),
311 );
312 });
313});