Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from "@effect/vitest";
2import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
3import * as Effect from "effect/Effect";
4import * as Tracer from "effect/Tracer";
5
6afterEach(() => {
7 vi.unstubAllEnvs();
8 vi.unstubAllGlobals();
9});
10
11describe("web runtime relay telemetry policy", () => {
12 it.each([
13 {
14 surface: "desktop opt-out",
15 desktopBridge: { getRelayTelemetryEnabled: () => false },
16 exports: false,
17 },
18 {
19 surface: "desktop enabled",
20 desktopBridge: { getRelayTelemetryEnabled: () => true },
21 exports: true,
22 },
23 { surface: "older desktop bridge", desktopBridge: {}, exports: true },
24 {
25 surface: "ordinary browser ignores host opt-out",
26 desktopBridge: undefined,
27 exports: true,
28 },
29 ])("applies $surface before the first relay span", async ({ desktopBridge, exports }) => {
30 vi.resetModules();
31 vi.stubEnv("T3CODE_TELEMETRY_ENABLED", "false");
32 vi.stubEnv("T3CODE_OTEL_SDK_DISABLED", "true");
33 vi.stubEnv("OTEL_SDK_DISABLED", "true");
34 vi.stubEnv("VITE_RELAY_OTLP_TRACES_URL", "https://telemetry.example.test/v1/traces");
35 vi.stubEnv("VITE_RELAY_OTLP_TRACES_DATASET", "relay-test");
36 vi.stubEnv("VITE_RELAY_OTLP_TRACES_TOKEN", "test-token");
37 vi.stubGlobal("window", { desktopBridge });
38 const fetchFn = vi.fn<typeof fetch>(async () => new Response(null, { status: 202 }));
39 vi.stubGlobal("fetch", fetchFn);
40 // Re-import after setting runtime policy: static initialization creates the exporter layer.
41 const { runtime: freshRuntime } = await import("./runtime");
42 const { setDelegate } = await import("../observability/clientTracer");
43 const userSpans: Array<string> = [];
44
45 try {
46 expect(
47 await freshRuntime.runPromise(
48 Effect.succeed("relay operation completed").pipe(
49 Effect.withSpan("relay.first-operation"),
50 withRelayClientTracing,
51 ),
52 ),
53 ).toBe("relay operation completed");
54
55 setDelegate(
56 Tracer.make({
57 span(options) {
58 userSpans.push(options.name);
59 return new Tracer.NativeSpan(options);
60 },
61 }),
62 );
63 await freshRuntime.runPromise(Effect.void.pipe(Effect.withSpan("user.work")));
64 expect(userSpans).toEqual(["user.work"]);
65 } finally {
66 setDelegate(null);
67 // Closing the runtime flushes the exporter without waiting for its batch timer.
68 await freshRuntime.dispose();
69 }
70
71 if (exports) {
72 expect(fetchFn).toHaveBeenCalledOnce();
73 expect(String(fetchFn.mock.calls[0]?.[0])).toBe("https://telemetry.example.test/v1/traces");
74 const payload = new TextDecoder().decode(fetchFn.mock.calls[0]?.[1]?.body as Uint8Array);
75 expect(payload).toContain('"name":"relay.first-operation"');
76 } else {
77 expect(fetchFn).not.toHaveBeenCalled();
78 }
79 });
80});