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