Open History to see the last commit
1import { Exit, Layer, ManagedRuntime, Scope, Tracer } from "effect";
2import { FetchHttpClient, HttpClient } from "effect/unstable/http";
3import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
4
5import { resolvePrimaryEnvironmentHttpUrl } from "../environments/primary";
6import { isElectron } from "../env";
7import { APP_VERSION } from "~/branding";
8
9const DEFAULT_EXPORT_INTERVAL_MS = 1_000;
10const CLIENT_TRACING_RESOURCE = {
11 serviceName: "t3-web",
12 attributes: {
13 "service.runtime": "t3-web",
14 "service.mode": isElectron ? "electron" : "browser",
15 "service.version": APP_VERSION,
16 },
17} as const;
18
19const delegateRuntimeLayer = Layer.mergeAll(
20 FetchHttpClient.layer,
21 OtlpSerialization.layerJson,
22 Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
23);
24
25let activeDelegate: Tracer.Tracer | null = null;
26let activeRuntime: ManagedRuntime.ManagedRuntime<never, never> | null = null;
27let activeScope: Scope.Closeable | null = null;
28let activeConfigKey: string | null = null;
29let configurationGeneration = 0;
30let pendingConfiguration = Promise.resolve();
31
32export interface ClientTracingConfig {
33 readonly exportIntervalMs?: number;
34}
35
36export const ClientTracingLive = Layer.succeed(
37 Tracer.Tracer,
38 Tracer.make({
39 span(options) {
40 return activeDelegate?.span(options) ?? new Tracer.NativeSpan(options);
41 },
42 }),
43);
44
45export function configureClientTracing(config: ClientTracingConfig = {}): Promise<void> {
46 if (config.exportIntervalMs === undefined && activeConfigKey !== null) {
47 return pendingConfiguration;
48 }
49 pendingConfiguration = pendingConfiguration.finally(() => applyClientTracingConfig(config));
50 return pendingConfiguration;
51}
52
53async function applyClientTracingConfig(config: ClientTracingConfig): Promise<void> {
54 const otlpTracesUrl = resolvePrimaryEnvironmentHttpUrl("/api/observability/v1/traces");
55 const exportIntervalMs = Math.max(10, config.exportIntervalMs ?? DEFAULT_EXPORT_INTERVAL_MS);
56 const nextConfigKey = `${otlpTracesUrl}|${exportIntervalMs}`;
57
58 if (activeConfigKey === nextConfigKey && activeDelegate !== null) {
59 return;
60 }
61
62 activeConfigKey = nextConfigKey;
63 const generation = ++configurationGeneration;
64
65 const previousRuntime = activeRuntime;
66 const previousScope = activeScope;
67
68 activeDelegate = null;
69 activeRuntime = null;
70 activeScope = null;
71
72 await disposeTracerRuntime(previousRuntime, previousScope);
73
74 const runtime = ManagedRuntime.make(delegateRuntimeLayer);
75 const scope = runtime.runSync(Scope.make());
76
77 try {
78 const delegate = await runtime.runPromise(
79 Scope.provide(scope)(
80 OtlpTracer.make({
81 url: otlpTracesUrl,
82 exportInterval: `${exportIntervalMs} millis`,
83 resource: CLIENT_TRACING_RESOURCE,
84 }),
85 ),
86 );
87
88 if (generation !== configurationGeneration) {
89 await disposeTracerRuntime(runtime, scope);
90 return;
91 }
92
93 activeDelegate = delegate;
94 activeRuntime = runtime;
95 activeScope = scope;
96 } catch (error) {
97 await disposeTracerRuntime(runtime, scope);
98
99 if (generation === configurationGeneration) {
100 console.warn("Failed to configure client tracing exporter", {
101 error: formatError(error),
102 otlpTracesUrl,
103 });
104 }
105 }
106}
107
108async function disposeTracerRuntime(
109 runtime: ManagedRuntime.ManagedRuntime<never, never> | null,
110 scope: Scope.Closeable | null,
111): Promise<void> {
112 if (runtime === null || scope === null) {
113 return;
114 }
115
116 await runtime
117 .runPromise(Scope.close(scope, Exit.void))
118 .catch(() => undefined)
119 .finally(() => {
120 runtime.dispose();
121 });
122}
123
124function formatError(error: unknown): string {
125 if (error instanceof Error && error.message.trim().length > 0) {
126 return error.message;
127 }
128
129 return String(error);
130}
131
132export async function __resetClientTracingForTests() {
133 configurationGeneration++;
134 activeConfigKey = null;
135 activeDelegate = null;
136 pendingConfiguration = Promise.resolve();
137
138 const runtime = activeRuntime;
139 const scope = activeScope;
140 activeRuntime = null;
141 activeScope = null;
142
143 await disposeTracerRuntime(runtime, scope);
144}