Open History to see the last commit
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 nodeServicesIt("node services", (it) => {
218 it.effect(
219 "keeps trace producers responsive during a slow write, bounds the backlog, and drains on close",
220 () =>
221 Effect.scoped(
222 Effect.gen(function* () {
223 const fs = yield* FileSystem.FileSystem;
224 const path = yield* Path.Path;
225 const directory = yield* fs.makeTempDirectoryScoped({
226 prefix: "t3-trace-backpressure-",
227 });
228 const tracePath = path.join(directory, "trace.ndjson");
229 const started = yield* Deferred.make<void>();
230 const release = yield* Deferred.make<void>();
231 const closed = yield* Ref.make(false);
232 const sink = yield* makeTraceSink({
233 filePath: tracePath,
234 maxBytes: 5_000_000,
235 maxFiles: 2,
236 batchWindowMs: 10_000,
237 }).pipe(
238 Effect.provideService(FileSystem.FileSystem, {
239 ...fs,
240 writeFile: (file, data, options) =>
241 Effect.gen(function* () {
242 yield* Deferred.succeed(started, undefined);
243 yield* Deferred.await(release);
244 yield* fs.writeFile(file, data, options);
245 }),
246 }),
247 );
248 sink.push(makeRecord("first"));
249 const flushing = yield* Effect.forkChild(sink.flush);
250 yield* Deferred.await(started);
251 for (let index = 0; index < 2_000; index++)
252 sink.push(makeRecord("small", String(index)));
253 for (let index = 0; index < 3; index++)
254 sink.push({ ...makeRecord("large"), attributes: { payload: "x".repeat(2_000_000) } });
255 const closing = yield* Effect.forkChild(
256 sink.close().pipe(Effect.tap(() => Ref.set(closed, true))),
257 );
258 yield* Effect.yieldNow;
259 assert.isFalse(yield* Ref.get(closed));
260 yield* Deferred.succeed(release, undefined);
261 yield* Fiber.join(flushing);
262 yield* Fiber.join(closing);
263 const records = yield* readTraceRecords(tracePath);
264 assert.deepStrictEqual(
265 records.map((record) => record.name),
266 ["first", ...Array.from({ length: 2_000 }, () => "small"), "large", "large"],
267 );
268 assert.isTrue(yield* Ref.get(closed));
269 }),
270 ),
271 );
272
273 it.effect("keeps every trace file within the configured limit for threshold flushes", () =>
274 Effect.scoped(
275 Effect.gen(function* () {
276 const fileSystem = yield* FileSystem.FileSystem;
277 const path = yield* Path.Path;
278 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
279 const tracePath = path.join(tempDir, "shared.trace.ndjson");
280 const maxBytes = 1_024;
281
282 const sink = yield* makeTraceSink({
283 filePath: tracePath,
284 maxBytes,
285 maxFiles: 2,
286 batchWindowMs: 10_000,
287 });
288
289 for (let index = 0; index < 256; index += 1) {
290 sink.push(makeRecord("threshold", `${index}-${"x".repeat(48)}`));
291 }
292 yield* sink.close();
293
294 const matchingFiles = (yield* fileSystem.readDirectory(tempDir)).filter(
295 (entry) => entry === "shared.trace.ndjson" || entry.startsWith("shared.trace.ndjson."),
296 );
297 assert.include(matchingFiles, "shared.trace.ndjson.1");
298 for (const entry of matchingFiles) {
299 const stat = yield* fileSystem.stat(path.join(tempDir, entry));
300 assert.isAtMost(Number(stat.size), maxBytes, entry);
301 }
302 }),
303 ),
304 );
305
306 it.effect("drops a single trace record that cannot fit within the configured limit", () =>
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 sink.push(makeRecord("oversized", "x".repeat(maxBytes * 2)));
323 sink.push(makeRecord("retained"));
324 yield* sink.close();
325
326 const records = yield* readTraceRecords(tracePath);
327 const stat = yield* fileSystem.stat(tracePath);
328 assert.deepEqual(
329 records.map((record) => record.name),
330 ["retained"],
331 );
332 assert.isAtMost(Number(stat.size), maxBytes);
333 }),
334 ),
335 );
336
337 it.effect("drops only the invalid trace record when serialization fails", () =>
338 Effect.scoped(
339 Effect.gen(function* () {
340 const fileSystem = yield* FileSystem.FileSystem;
341 const path = yield* Path.Path;
342 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
343 const tracePath = path.join(tempDir, "shared.trace.ndjson");
344
345 const sink = yield* makeTraceSink({
346 filePath: tracePath,
347 maxBytes: 1024,
348 maxFiles: 2,
349 batchWindowMs: 10_000,
350 });
351
352 const circular: Array<unknown> = [];
353 circular.push(circular);
354
355 sink.push(makeRecord("alpha"));
356 sink.push({
357 ...makeRecord("invalid"),
358 attributes: {
359 circular,
360 },
361 } as TraceRecord);
362 sink.push(makeRecord("beta"));
363 yield* sink.close();
364
365 const lines = yield* readTraceRecords(tracePath);
366
367 assert.deepStrictEqual(
368 lines.map((line) => line.name),
369 ["alpha", "beta"],
370 );
371 }),
372 ),
373 );
374
375 it.effect("writes nested spans to disk and captures log messages as span events", () =>
376 Effect.scoped(
377 Effect.gen(function* () {
378 const fileSystem = yield* FileSystem.FileSystem;
379 const path = yield* Path.Path;
380 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
381 const tracePath = path.join(tempDir, "shared.trace.ndjson");
382
383 yield* Effect.scoped(
384 Effect.gen(function* () {
385 const program = Effect.gen(function* () {
386 yield* Effect.annotateCurrentSpan({
387 "demo.parent": true,
388 });
389 yield* Effect.logInfo("parent event");
390 yield* Effect.gen(function* () {
391 yield* Effect.annotateCurrentSpan({
392 "demo.child": true,
393 });
394 yield* Effect.logInfo("child event");
395 }).pipe(Effect.withSpan("child-span"));
396 }).pipe(Effect.withSpan("parent-span"));
397
398 yield* program.pipe(Effect.provide(layerTest(tracePath)));
399 }),
400 );
401
402 const records = yield* readTraceRecords(tracePath);
403 assert.equal(records.length, 2);
404
405 const parent = records.find((record) => record.name === "parent-span");
406 const child = records.find((record) => record.name === "child-span");
407
408 assert.notEqual(parent, undefined);
409 assert.notEqual(child, undefined);
410 if (!parent || !child) {
411 return;
412 }
413
414 assert.equal(child.parentSpanId, parent.spanId);
415 assert.equal(parent.attributes["demo.parent"], true);
416 assert.equal(child.attributes["demo.child"], true);
417 assert.equal(
418 parent.events.some((event) => event.name === "parent event"),
419 true,
420 );
421 assert.equal(
422 child.events.some((event) => event.name === "child event"),
423 true,
424 );
425 assert.equal(
426 child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
427 true,
428 );
429 }),
430 ),
431 );
432
433 it.effect("serializes interrupted spans with an interrupted exit status", () =>
434 Effect.scoped(
435 Effect.gen(function* () {
436 const fileSystem = yield* FileSystem.FileSystem;
437 const path = yield* Path.Path;
438 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
439 const tracePath = path.join(tempDir, "shared.trace.ndjson");
440
441 yield* Effect.scoped(
442 Effect.exit(
443 Effect.interrupt.pipe(
444 Effect.withSpan("interrupt-span"),
445 Effect.provide(layerTest(tracePath)),
446 ),
447 ),
448 );
449
450 const records = yield* readTraceRecords(tracePath);
451 assert.equal(records.length, 1);
452 assert.equal(records[0]?.name, "interrupt-span");
453 assert.equal(records[0]?.exit?._tag, "Interrupted");
454 }),
455 ),
456 );
457 });
458});
459
460describe("OtlpHeadersFromString", () => {
461 const decode = Schema.decodeUnknownSync(OtlpHeadersFromString);
462
463 it.each([
464 {
465 name: "decodes percent-encoded values",
466 input: "authorization=Basic%20abc%3D%3D,x-tenant=t3",
467 expected: { authorization: "Basic abc==", "x-tenant": "t3" },
468 },
469 {
470 name: "ignores whitespace around separators",
471 input: "authorization=Basic%20abc%3D%3D, x-tenant = t3 ,",
472 expected: { authorization: "Basic abc==", "x-tenant": "t3" },
473 },
474 {
475 name: "keeps literal equals signs inside a value",
476 input: "authorization=Bearer abc==",
477 expected: { authorization: "Bearer abc==" },
478 },
479 {
480 name: "keeps an empty value",
481 input: "x-empty=",
482 expected: { "x-empty": "" },
483 },
484 ])("$name", ({ input, expected }) => {
485 expect(decode(input)).toEqual(expected);
486 });
487
488 it.each([
489 { name: "rejects a pair without a separator", input: "authorization" },
490 { name: "rejects a pair without a key", input: "=value" },
491 { name: "rejects a malformed percent-encoding", input: "authorization=%E0" },
492 ])("$name", ({ input }) => {
493 expect(() => decode(input)).toThrow();
494 });
495});