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