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

observability.test.ts

528 lines17.8 KB

1import { assert, describe, expect, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Cause from "effect/Cause";
4import * as Effect from "effect/Effect";
5import * as Deferred from "effect/Deferred";
6import * as Fiber from "effect/Fiber";
7import * as Exit from "effect/Exit";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Logger from "effect/Logger";
11import * as Path from "effect/Path";
12import * as Ref from "effect/Ref";
13import * as References from "effect/References";
14import * as Schema from "effect/Schema";
15import * as Tracer from "effect/Tracer";
16​
17import {
18 causeErrorTag,
19 compactTraceAttributes,
20 errorTag,
21 makeLocalFileTracer,
22 makeTraceSink,
23 type EffectTraceRecord,
24 type TraceRecord,
25 OtlpHeadersFromString,
26 truncateTraceAttributes,
27 processServiceInstanceId,
28} from "./observability.ts";
29​
30describe("processServiceInstanceId", () => {
31 it("stays the same for the process unless the operator set one", () => {
32 expect(processServiceInstanceId()).toBe(processServiceInstanceId({}));
33 expect(processServiceInstanceId({ "service.instance.id": "pod-7" })).toBe("pod-7");
34 });
35});
36​
37describe("errorTag", () => {
38 it("reports structural tags without retaining arbitrary values", () => {
39 assert.equal(errorTag({ _tag: "AcpRequestError" }), "AcpRequestError");
40 assert.equal(errorTag(new TypeError("secret-token-value")), "TypeError");
41 assert.equal(errorTag({ _tag: "secret token value" }), "TaggedError");
42 });
43});
44​
45describe("causeErrorTag", () => {
46 it("reports the tagged failure value instead of the Cause reason wrapper", () => {
47 assert.equal(
48 causeErrorTag(Cause.fail({ _tag: "ServerAuthInvalidCredentialError" })),
49 "ServerAuthInvalidCredentialError",
50 );
51 });
52});
53​
54const TraceRecordLine = Schema.Struct({
55 name: Schema.String,
56 spanId: Schema.String,
57 parentSpanId: Schema.optional(Schema.String),
58 attributes: Schema.Record(Schema.String, Schema.Unknown),
59 events: Schema.Array(
60 Schema.Struct({
61 name: Schema.String,
62 attributes: Schema.Record(Schema.String, Schema.Unknown),
63 }),
64 ),
65 exit: Schema.optional(
66 Schema.Struct({
67 _tag: Schema.String,
68 }),
69 ),
70});
71​
72const decodeTraceRecordLine = Schema.decodeUnknownSync(Schema.fromJsonString(TraceRecordLine));
73​
74const makeRecord = (name: string, suffix = ""): TraceRecord => ({
75 type: "effect-span",
76 name,
77 traceId: `trace-${name}-${suffix}`,
78 spanId: `span-${name}-${suffix}`,
79 sampled: true,
80 kind: "internal",
81 startTimeUnixNano: "1",
82 endTimeUnixNano: "2",
83 durationMs: 1,
84 attributes: {
85 payload: suffix,
86 },
87 events: [],
88 links: [],
89 exit: {
90 _tag: "Success",
91 },
92});
93​
94const readTraceRecords = Effect.fn("readTraceRecords")(function* (tracePath: string) {
95 const fileSystem = yield* FileSystem.FileSystem;
96 return (yield* fileSystem.readFileString(tracePath))
97 .trim()
98 .split("\n")
99 .filter((line) => line.length > 0)
100 .map((line) => decodeTraceRecordLine(line));
101});
102​
103const layerTest = (tracePath: string) =>
104 Layer.mergeAll(
105 Layer.effect(
106 Tracer.Tracer,
107 makeLocalFileTracer({
108 filePath: tracePath,
109 maxBytes: 1024 * 1024,
110 maxFiles: 2,
111 batchWindowMs: 10_000,
112 }),
113 ),
114 Logger.layer([Logger.tracerLogger], { mergeWithExisting: false }),
115 Layer.succeed(References.MinimumLogLevel, "Info"),
116 );
117​
118const nodeServicesIt = it.layer(NodeServices.layer);
119​
120describe("truncateTraceAttributes", () => {
121 it("clamps oversized strings at any depth without mutating the input", () => {
122 const stack = "s".repeat(2_000);
123 const attributes = {
124 "db.query.text": "q".repeat(2_000),
125 short: "ok",
126 error: { name: "Error", stack, nested: ["a".repeat(2_000)] },
127 };
128 const truncated = truncateTraceAttributes(attributes);
129​
130 assert.equal((truncated["db.query.text"] as string).length, 200 + "…[truncated]".length);
131 assert.equal(truncated["short"], "ok");
132 const error = truncated["error"] as { stack: string; nested: Array<string> };
133 assert.equal(error.stack.length, 500 + "…[truncated]".length);
134 assert.equal(error.nested[0]?.length, 500 + "…[truncated]".length);
135 assert.equal(attributes.error.stack, stack);
136 });
137});
138​
139describe("observability", () => {
140 it.effect(
141 "preserves successful results without retaining them in sampled or unsampled spans",
142 () =>
143 Effect.gen(function* () {
144 for (const sampled of [true, false]) {
145 const delegates: Array<Tracer.Span> = [];
146 const records: Array<EffectTraceRecord> = [];
147 const tracer = yield* makeLocalFileTracer({
148 filePath: "unused",
149 maxBytes: 1024,
150 maxFiles: 1,
151 batchWindowMs: 10_000,
152 sink: {
153 filePath: "unused",
154 push: (record) => {
155 if (record.type === "effect-span") records.push(record);
156 },
157 flush: Effect.void,
158 close: () => Effect.void,
159 },
160 delegate: Tracer.make({
161 span: (options) => {
162 const span = new Tracer.NativeSpan({ ...options, sampled });
163 delegates.push(span);
164 return span;
165 },
166 }),
167 });
168 const payload = { turnItems: [{ output: [{ text: "synthetic-result" }] }] };
169 let span: Tracer.Span | undefined;
170 const result = yield* Effect.gen(function* () {
171 span = yield* Effect.currentSpan;
172 return payload;
173 }).pipe(
174 Effect.withSpan("read-thread-projection"),
175 Effect.provideService(Tracer.Tracer, tracer),
176 );
177 assert.strictEqual(result, payload);
178 assert.isDefined(span);
179 for (const completed of [span!, ...delegates]) {
180 assert.equal(completed.status._tag, "Ended");
181 if (completed.status._tag === "Ended") {
182 assert.deepStrictEqual(completed.status.exit, Exit.void);
183 }
184 }
185 assert.deepStrictEqual(
186 records.map((record) => record.exit),
187 sampled ? [{ _tag: "Success" }] : [],
188 );
189 }
190 }).pipe(Effect.provide(NodeServices.layer)),
191 );
192​
193 it("normalizes circular arrays, maps, and sets without recursing forever", () => {
194 const array: Array<unknown> = ["alpha"];
195 array.push(array);
196​
197 const map = new Map<string, unknown>();
198 map.set("self", map);
199​
200 const set = new Set<unknown>();
201 set.add(set);
202​
203 assert.deepStrictEqual(
204 compactTraceAttributes({
205 array,
206 map,
207 set,
208 }),
209 {
210 array: ["alpha", "[Circular]"],
211 map: { self: "[Circular]" },
212 set: ["[Circular]"],
213 },
214 );
215 });
216​
217 it("keeps an object that appears twice without marking it circular", () => {
218 const shared = { cwd: "/repo" };
219 const sharedMap = new Map([["cwd", "/repo"]]);
220 const sharedSet = new Set(["/repo"]);
221​
222 assert.deepStrictEqual(
223 compactTraceAttributes({
224 ctx: { first: shared, second: shared },
225 list: [shared, shared],
226 maps: [sharedMap, sharedMap],
227 sets: [sharedSet, sharedSet],
228 }),
229 {
230 ctx: { first: { cwd: "/repo" }, second: { cwd: "/repo" } },
231 list: [{ cwd: "/repo" }, { cwd: "/repo" }],
232 maps: [{ cwd: "/repo" }, { cwd: "/repo" }],
233 sets: [["/repo"], ["/repo"]],
234 },
235 );
236 });
237​
238 it("caps shared references that would expand exponentially", () => {
239 let graph: Record<string, unknown> = { cwd: "/repo" };
240 for (let depth = 0; depth < 20; depth++) {
241 graph = { left: graph, right: graph };
242 }
243​
244 const serialized = JSON.stringify(compactTraceAttributes({ graph }));
245​
246 assert.include(serialized, '"[Truncated]"');
247 assert.isBelow(serialized.length, 1_000_000);
248 });
249​
250 nodeServicesIt("node services", (it) => {
251 it.effect(
252 "keeps trace producers responsive during a slow write, bounds the backlog, and drains on close",
253 () =>
254 Effect.scoped(
255 Effect.gen(function* () {
256 const fs = yield* FileSystem.FileSystem;
257 const path = yield* Path.Path;
258 const directory = yield* fs.makeTempDirectoryScoped({
259 prefix: "t3-trace-backpressure-",
260 });
261 const tracePath = path.join(directory, "trace.ndjson");
262 const started = yield* Deferred.make<void>();
263 const release = yield* Deferred.make<void>();
264 const closed = yield* Ref.make(false);
265 const sink = yield* makeTraceSink({
266 filePath: tracePath,
267 maxBytes: 5_000_000,
268 maxFiles: 2,
269 batchWindowMs: 10_000,
270 }).pipe(
271 Effect.provideService(FileSystem.FileSystem, {
272 ...fs,
273 writeFile: (file, data, options) =>
274 Effect.gen(function* () {
275 yield* Deferred.succeed(started, undefined);
276 yield* Deferred.await(release);
277 yield* fs.writeFile(file, data, options);
278 }),
279 }),
280 );
281 sink.push(makeRecord("first"));
282 const flushing = yield* Effect.forkChild(sink.flush);
283 yield* Deferred.await(started);
284 for (let index = 0; index < 2_000; index++)
285 sink.push(makeRecord("small", String(index)));
286 for (let index = 0; index < 3; index++)
287 sink.push({ ...makeRecord("large"), attributes: { payload: "x".repeat(2_000_000) } });
288 const closing = yield* Effect.forkChild(
289 sink.close().pipe(Effect.tap(() => Ref.set(closed, true))),
290 );
291 yield* Effect.yieldNow;
292 assert.isFalse(yield* Ref.get(closed));
293 yield* Deferred.succeed(release, undefined);
294 yield* Fiber.join(flushing);
295 yield* Fiber.join(closing);
296 const records = yield* readTraceRecords(tracePath);
297 assert.deepStrictEqual(
298 records.map((record) => record.name),
299 ["first", ...Array.from({ length: 2_000 }, () => "small"), "large", "large"],
300 );
301 assert.isTrue(yield* Ref.get(closed));
302 }),
303 ),
304 );
305​
306 it.effect("keeps every trace file within the configured limit for threshold flushes", () =>
307 Effect.scoped(
308 Effect.gen(function* () {
309 const fileSystem = yield* FileSystem.FileSystem;
310 const path = yield* Path.Path;
311 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
312 const tracePath = path.join(tempDir, "shared.trace.ndjson");
313 const maxBytes = 1_024;
314​
315 const sink = yield* makeTraceSink({
316 filePath: tracePath,
317 maxBytes,
318 maxFiles: 2,
319 batchWindowMs: 10_000,
320 });
321​
322 for (let index = 0; index < 256; index += 1) {
323 sink.push(makeRecord("threshold", `${index}-${"x".repeat(48)}`));
324 }
325 yield* sink.close();
326​
327 const matchingFiles = (yield* fileSystem.readDirectory(tempDir)).filter(
328 (entry) => entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
329 );
330 assert.include(matchingFiles, "shared.trace.ndjson.1");
331 for (const entry of matchingFiles) {
332 const stat = yield* fileSystem.stat(path.join(tempDir, entry));
333 assert.isAtMost(Number(stat.size), maxBytes, entry);
334 }
335 }),
336 ),
337 );
338​
339 it.effect("drops a single trace record that cannot fit within the configured limit", () =>
340 Effect.scoped(
341 Effect.gen(function* () {
342 const fileSystem = yield* FileSystem.FileSystem;
343 const path = yield* Path.Path;
344 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
345 const tracePath = path.join(tempDir, "shared.trace.ndjson");
346 const maxBytes = 1_024;
347​
348 const sink = yield* makeTraceSink({
349 filePath: tracePath,
350 maxBytes,
351 maxFiles: 2,
352 batchWindowMs: 10_000,
353 });
354​
355 sink.push(makeRecord("oversized", "x".repeat(maxBytes * 2)));
356 sink.push(makeRecord("retained"));
357 yield* sink.close();
358​
359 const records = yield* readTraceRecords(tracePath);
360 const stat = yield* fileSystem.stat(tracePath);
361 assert.deepEqual(
362 records.map((record) => record.name),
363 ["retained"],
364 );
365 assert.isAtMost(Number(stat.size), maxBytes);
366 }),
367 ),
368 );
369​
370 it.effect("drops only the invalid trace record when serialization fails", () =>
371 Effect.scoped(
372 Effect.gen(function* () {
373 const fileSystem = yield* FileSystem.FileSystem;
374 const path = yield* Path.Path;
375 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
376 const tracePath = path.join(tempDir, "shared.trace.ndjson");
377​
378 const sink = yield* makeTraceSink({
379 filePath: tracePath,
380 maxBytes: 1024,
381 maxFiles: 2,
382 batchWindowMs: 10_000,
383 });
384​
385 const circular: Array<unknown> = [];
386 circular.push(circular);
387​
388 sink.push(makeRecord("alpha"));
389 sink.push({
390 ...makeRecord("invalid"),
391 attributes: {
392 circular,
393 },
394 } as TraceRecord);
395 sink.push(makeRecord("beta"));
396 yield* sink.close();
397​
398 const lines = yield* readTraceRecords(tracePath);
399​
400 assert.deepStrictEqual(
401 lines.map((line) => line.name),
402 ["alpha", "beta"],
403 );
404 }),
405 ),
406 );
407​
408 it.effect("writes nested spans to disk and captures log messages as span events", () =>
409 Effect.scoped(
410 Effect.gen(function* () {
411 const fileSystem = yield* FileSystem.FileSystem;
412 const path = yield* Path.Path;
413 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
414 const tracePath = path.join(tempDir, "shared.trace.ndjson");
415​
416 yield* Effect.scoped(
417 Effect.gen(function* () {
418 const program = Effect.gen(function* () {
419 yield* Effect.annotateCurrentSpan({
420 "demo.parent": true,
421 });
422 yield* Effect.logInfo("parent event");
423 yield* Effect.gen(function* () {
424 yield* Effect.annotateCurrentSpan({
425 "demo.child": true,
426 });
427 yield* Effect.logInfo("child event");
428 }).pipe(Effect.withSpan("child-span"));
429 }).pipe(Effect.withSpan("parent-span"));
430​
431 yield* program.pipe(Effect.provide(layerTest(tracePath)));
432 }),
433 );
434​
435 const records = yield* readTraceRecords(tracePath);
436 assert.equal(records.length, 2);
437​
438 const parent = records.find((record) => record.name === "parent-span");
439 const child = records.find((record) => record.name === "child-span");
440​
441 assert.notEqual(parent, undefined);
442 assert.notEqual(child, undefined);
443 if (!parent || !child) {
444 return;
445 }
446​
447 assert.equal(child.parentSpanId, parent.spanId);
448 assert.equal(parent.attributes["demo.parent"], true);
449 assert.equal(child.attributes["demo.child"], true);
450 assert.equal(
451 parent.events.some((event) => event.name === "parent event"),
452 true,
453 );
454 assert.equal(
455 child.events.some((event) => event.name === "child event"),
456 true,
457 );
458 assert.equal(
459 child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
460 true,
461 );
462 }),
463 ),
464 );
465​
466 it.effect("serializes interrupted spans with an interrupted exit status", () =>
467 Effect.scoped(
468 Effect.gen(function* () {
469 const fileSystem = yield* FileSystem.FileSystem;
470 const path = yield* Path.Path;
471 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
472 const tracePath = path.join(tempDir, "shared.trace.ndjson");
473​
474 yield* Effect.scoped(
475 Effect.exit(
476 Effect.interrupt.pipe(
477 Effect.withSpan("interrupt-span"),
478 Effect.provide(layerTest(tracePath)),
479 ),
480 ),
481 );
482​
483 const records = yield* readTraceRecords(tracePath);
484 assert.equal(records.length, 1);
485 assert.equal(records[0]?.name, "interrupt-span");
486 assert.equal(records[0]?.exit?._tag, "Interrupted");
487 }),
488 ),
489 );
490 });
491});
492​
493describe("OtlpHeadersFromString", () => {
494 const decode = Schema.decodeUnknownSync(OtlpHeadersFromString);
495​
496 it.each([
497 {
498 name: "decodes percent-encoded values",
499 input: "authorization=Basic%20abc%3D%3D,x-tenant=t3",
500 expected: { authorization: "Basic abc==", "x-tenant": "t3" },
501 },
502 {
503 name: "ignores whitespace around separators",
504 input: "authorization=Basic%20abc%3D%3D, x-tenant = t3 ,",
505 expected: { authorization: "Basic abc==", "x-tenant": "t3" },
506 },
507 {
508 name: "keeps literal equals signs inside a value",
509 input: "authorization=Bearer abc==",
510 expected: { authorization: "Bearer abc==" },
511 },
512 {
513 name: "keeps an empty value",
514 input: "x-empty=",
515 expected: { "x-empty": "" },
516 },
517 ])("$name", ({ input, expected }) => {
518 expect(decode(input)).toEqual(expected);
519 });
520​
521 it.each([
522 { name: "rejects a pair without a separator", input: "authorization" },
523 { name: "rejects a pair without a key", input: "=value" },
524 { name: "rejects a malformed percent-encoding", input: "authorization=%E0" },
525 ])("$name", ({ input }) => {
526 expect(() => decode(input)).toThrow();
527 });
528});