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 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("keeps WebSocket credentials out of trace files and exported spans", () =>
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 const sink = yield* makeTraceSink({
378 filePath: tracePath,
379 maxBytes: 1024 * 1024,
380 maxFiles: 2,
381 batchWindowMs: 10_000,
382 });
383 const delegates: Array<Tracer.NativeSpan> = [];
384 const tracer = yield* makeLocalFileTracer({
385 filePath: tracePath,
386 maxBytes: 1024 * 1024,
387 maxFiles: 2,
388 batchWindowMs: 10_000,
389 sink,
390 delegate: Tracer.make({
391 span: (options) => {
392 const span = new Tracer.NativeSpan(options);
393 delegates.push(span);
394 return span;
395 },
396 }),
397 });
398 const url = "/ws?wsTicket=ticket-secret&dpop=proof-secret&clientSurface=web";
399
400 yield* Effect.annotateCurrentSpan({
401 "url.full": `http://127.0.0.1:3773${url}`,
402 "url.query": url.slice(4),
403 }).pipe(
404 Effect.withSpan("GET", { kind: "server" }),
405 Effect.provideService(Tracer.Tracer, tracer),
406 );
407 yield* Effect.die(new Error(`RequestParseError (GET ${url})`)).pipe(
408 Effect.tapCause((cause) => Effect.logError(cause)),
409 Effect.withSpan("DeviceHubProxy.proxyWebSocket"),
410 Effect.provideService(Tracer.Tracer, tracer),
411 Effect.provide(Logger.layer([Logger.tracerLogger], { mergeWithExisting: false })),
412 Effect.exit,
413 );
414 yield* sink.close();
415
416 const written = yield* fileSystem.readFileString(tracePath);
417 const exported = delegates.map((span) =>
418 JSON.stringify({
419 attributes: Object.fromEntries(span.attributes),
420 events: span.events.map(([, , attributes]) => attributes),
421 exit:
422 span.status._tag === "Ended" && Exit.isFailure(span.status.exit)
423 ? Cause.pretty(span.status.exit.cause)
424 : "",
425 }),
426 );
427 for (const text of [written, ...exported]) {
428 assert.notInclude(text, "ticket-secret");
429 assert.notInclude(text, "proof-secret");
430 }
431 assert.include(written, "wsTicket=<redacted>&dpop=<redacted>&clientSurface=web");
432 assert.include(exported.join("\n"), "effect.cause");
433 }),
434 ),
435 );
436
437 it.effect("drops only the invalid trace record when serialization fails", () =>
438 Effect.scoped(
439 Effect.gen(function* () {
440 const fileSystem = yield* FileSystem.FileSystem;
441 const path = yield* Path.Path;
442 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" });
443 const tracePath = path.join(tempDir, "shared.trace.ndjson");
444
445 const sink = yield* makeTraceSink({
446 filePath: tracePath,
447 maxBytes: 1024,
448 maxFiles: 2,
449 batchWindowMs: 10_000,
450 });
451
452 const circular: Array<unknown> = [];
453 circular.push(circular);
454
455 sink.push(makeRecord("alpha"));
456 sink.push({
457 ...makeRecord("invalid"),
458 attributes: {
459 circular,
460 },
461 } as TraceRecord);
462 sink.push(makeRecord("beta"));
463 yield* sink.close();
464
465 const lines = yield* readTraceRecords(tracePath);
466
467 assert.deepStrictEqual(
468 lines.map((line) => line.name),
469 ["alpha", "beta"],
470 );
471 }),
472 ),
473 );
474
475 it.effect("writes nested spans to disk and captures log messages as span events", () =>
476 Effect.scoped(
477 Effect.gen(function* () {
478 const fileSystem = yield* FileSystem.FileSystem;
479 const path = yield* Path.Path;
480 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
481 const tracePath = path.join(tempDir, "shared.trace.ndjson");
482
483 yield* Effect.scoped(
484 Effect.gen(function* () {
485 const program = Effect.gen(function* () {
486 yield* Effect.annotateCurrentSpan({
487 "demo.parent": true,
488 });
489 yield* Effect.logInfo("parent event");
490 yield* Effect.gen(function* () {
491 yield* Effect.annotateCurrentSpan({
492 "demo.child": true,
493 });
494 yield* Effect.logInfo("child event");
495 }).pipe(Effect.withSpan("child-span"));
496 }).pipe(Effect.withSpan("parent-span"));
497
498 yield* program.pipe(Effect.provide(layerTest(tracePath)));
499 }),
500 );
501
502 const records = yield* readTraceRecords(tracePath);
503 assert.equal(records.length, 2);
504
505 const parent = records.find((record) => record.name === "parent-span");
506 const child = records.find((record) => record.name === "child-span");
507
508 assert.notEqual(parent, undefined);
509 assert.notEqual(child, undefined);
510 if (!parent || !child) {
511 return;
512 }
513
514 assert.equal(child.parentSpanId, parent.spanId);
515 assert.equal(parent.attributes["demo.parent"], true);
516 assert.equal(child.attributes["demo.child"], true);
517 assert.equal(
518 parent.events.some((event) => event.name === "parent event"),
519 true,
520 );
521 assert.equal(
522 child.events.some((event) => event.name === "child event"),
523 true,
524 );
525 assert.equal(
526 child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
527 true,
528 );
529 }),
530 ),
531 );
532
533 it.effect("serializes interrupted spans with an interrupted exit status", () =>
534 Effect.scoped(
535 Effect.gen(function* () {
536 const fileSystem = yield* FileSystem.FileSystem;
537 const path = yield* Path.Path;
538 const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-local-tracer-" });
539 const tracePath = path.join(tempDir, "shared.trace.ndjson");
540
541 yield* Effect.scoped(
542 Effect.exit(
543 Effect.interrupt.pipe(
544 Effect.withSpan("interrupt-span"),
545 Effect.provide(layerTest(tracePath)),
546 ),
547 ),
548 );
549
550 const records = yield* readTraceRecords(tracePath);
551 assert.equal(records.length, 1);
552 assert.equal(records[0]?.name, "interrupt-span");
553 assert.equal(records[0]?.exit?._tag, "Interrupted");
554 }),
555 ),
556 );
557 });
558});
559
560describe("OtlpHeadersFromString", () => {
561 const decode = Schema.decodeUnknownSync(OtlpHeadersFromString);
562
563 it.each([
564 {
565 name: "decodes percent-encoded values",
566 input: "authorization=Basic%20abc%3D%3D,x-tenant=t3",
567 expected: { authorization: "Basic abc==", "x-tenant": "t3" },
568 },
569 {
570 name: "ignores whitespace around separators",
571 input: "authorization=Basic%20abc%3D%3D, x-tenant = t3 ,",
572 expected: { authorization: "Basic abc==", "x-tenant": "t3" },
573 },
574 {
575 name: "keeps literal equals signs inside a value",
576 input: "authorization=Bearer abc==",
577 expected: { authorization: "Bearer abc==" },
578 },
579 {
580 name: "keeps an empty value",
581 input: "x-empty=",
582 expected: { "x-empty": "" },
583 },
584 ])("$name", ({ input, expected }) => {
585 expect(decode(input)).toEqual(expected);
586 });
587
588 it.each([
589 { name: "rejects a pair without a separator", input: "authorization" },
590 { name: "rejects a pair without a key", input: "=value" },
591 { name: "rejects a malformed percent-encoding", input: "authorization=%E0" },
592 ])("$name", ({ input }) => {
593 expect(() => decode(input)).toThrow();
594 });
595});