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