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

observability.test.ts

316 lines9.6 KB

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