Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

clientTracing.ts

161 lines5.6 KB

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 { HttpClient } from "effect/http";
6import { OtlpExporter, OtlpSerialization, OtlpTracer } from "effect/observability";
7​
8import { settleAsyncResult, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
9import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
10import { resolvePrimaryEnvironmentHttpUrl } from "../environments/primary";
11import { releaseChannelOf, releaseResourceAttributes } from "@t3tools/shared/releaseResource";
12import * as ClientTracer from "./clientTracer";
13import * as PrimaryEnvironmentHttpLayer from "../environments/primary/httpLayer";
14import { isElectron } from "../env";
15import { APP_VERSION } from "~/branding";
16​
17const DEFAULT_EXPORT_INTERVAL_MS = 1_000;
18interface NavigatorUserAgentData {
19 readonly platform: string;
20 readonly mobile: boolean;
21 readonly brands: ReadonlyArray<{ readonly brand: string; readonly version: string }>;
23​
24/**
25 * The `browser.*` and `user_agent.original` attributes the OpenTelemetry browser
26 * resource detector reports. `userAgentData` exists only in Chromium, which
27 * includes the desktop app.
28 */
29const browserResourceAttributes = (): Record<string, unknown> => {
30 if (typeof navigator === "undefined") return {};
31 const userAgentData = (navigator as Navigator & { userAgentData?: NavigatorUserAgentData })
32 .userAgentData;
33 return {
34 "user_agent.original": navigator.userAgent,
35 "browser.language": navigator.language,
36 ...(userAgentData && {
37 "browser.platform": userAgentData.platform,
38 "browser.mobile": userAgentData.mobile,
39 "browser.brands": userAgentData.brands.map(({ brand, version }) => `${brand} ${version}`),
40 }),
41 };
42};
43​
44// PR previews can't mark themselves in APP_VERSION without breaking the version-skew check against the server.
45const RELEASE_CHANNEL =
46 import.meta.env.DEV || import.meta.env.VITE_RELEASE_CHANNEL === "dev"
47 ? "dev"
48 : import.meta.env.VITE_RELEASE_CHANNEL === "preview"
49 ? "preview"
50 : releaseChannelOf(APP_VERSION);
51const CLIENT_TRACING_RESOURCE = {
52 serviceName: "t3code-web",
53 attributes: {
54 "service.namespace": "t3code",
55 "service.instance.id": ClientTracer.serviceInstanceId,
56 ...releaseResourceAttributes(RELEASE_CHANNEL),
57 "service.runtime": "t3-web",
58 "t3code.client.surface": isElectron ? "desktop" : "web",
59 "service.version": APP_VERSION,
60 ...browserResourceAttributes(),
61 },
62} as const;
63​
64const layerDelegateRuntime = Layer.mergeAll(
65 PrimaryEnvironmentHttpLayer.layer,
66 OtlpExporter.layerFlusher,
67 OtlpSerialization.layerJson,
68 Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
69);
70​
71let activeRuntime: ManagedRuntime.ManagedRuntime<never, never> | null = null;
72let activeScope: Scope.Closeable | null = null;
73let activeConfigKey: string | null = null;
74let configurationGeneration = 0;
75let pendingConfiguration = Promise.resolve();
76​
77export interface ClientTracingConfig {
78 readonly exportIntervalMs?: number;
80​
81export function configureClientTracing(config: ClientTracingConfig = {}): Promise<void> {
82 if (config.exportIntervalMs === undefined && activeConfigKey !== null) {
83 return pendingConfiguration;
84 }
85 pendingConfiguration = pendingConfiguration.finally(() => applyClientTracingConfig(config));
86 return pendingConfiguration;
88​
89async function applyClientTracingConfig(config: ClientTracingConfig): Promise<void> {
90 const otlpTracesUrl = resolvePrimaryEnvironmentHttpUrl("/api/observability/v1/traces");
91 const exportIntervalMs = Math.max(10, config.exportIntervalMs ?? DEFAULT_EXPORT_INTERVAL_MS);
92 const nextConfigKey = `${otlpTracesUrl}|${exportIntervalMs}`;
93​
94 if (activeConfigKey === nextConfigKey && ClientTracer.hasDelegate()) {
95 return;
96 }
97​
98 activeConfigKey = nextConfigKey;
99 const generation = ++configurationGeneration;
100​
101 const previousRuntime = activeRuntime;
102 const previousScope = activeScope;
103​
104 ClientTracer.setDelegate(null);
105 activeRuntime = null;
106 activeScope = null;
107​
108 await disposeTracerRuntime(previousRuntime, previousScope);
109​
110 const runtime = ManagedRuntime.make(layerDelegateRuntime);
111 const scope = runtime.runSync(Scope.make());
112​
113 const delegateResult = await settleAsyncResult(() =>
114 runtime.runPromiseExit(
115 Scope.provide(scope)(
116 OtlpTracer.make({
117 url: otlpTracesUrl,
118 exportInterval: `${exportIntervalMs} millis`,
119 resource: CLIENT_TRACING_RESOURCE,
120 }),
121 ),
122 ),
123 );
124 if (delegateResult._tag === "Failure") {
125 await disposeTracerRuntime(runtime, scope);
126​
127 if (generation === configurationGeneration) {
128 const error = squashAtomCommandFailure(delegateResult);
129 const tracesUrl = new URL(otlpTracesUrl);
130 console.warn("Failed to configure client tracing exporter", {
131 scheme: tracesUrl.protocol.replace(/:$/, ""),
132 host: tracesUrl.hostname,
133 port: tracesUrl.port || undefined,
134 exportIntervalMs,
135 ...safeErrorLogAttributes(error),
136 });
137 }
138 return;
139 }
140​
141 if (generation !== configurationGeneration) {
142 await disposeTracerRuntime(runtime, scope);
143 return;
144 }
145​
146 ClientTracer.setDelegate(delegateResult.value);
147 activeRuntime = runtime;
148 activeScope = scope;
150​
151async function disposeTracerRuntime(
152 runtime: ManagedRuntime.ManagedRuntime<never, never> | null,
153 scope: Scope.Closeable | null,
154): Promise<void> {
155 if (runtime === null || scope === null) {
156 return;
157 }
158​
159 await settleAsyncResult(() => runtime.runPromiseExit(Scope.close(scope, Exit.void)));
160 runtime.dispose();