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

clientTracing.ts

125 lines4.2 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 * as ClientTracer from "./clientTracer";
12import * as PrimaryEnvironmentHttpLayer from "../environments/primary/httpLayer";
13import { isElectron } from "../env";
14import { APP_VERSION } from "~/branding";
15​
16const DEFAULT_EXPORT_INTERVAL_MS = 1_000;
17const CLIENT_TRACING_RESOURCE = {
18 serviceName: "t3code-web",
19 attributes: {
20 "service.namespace": "t3code",
21 "deployment.environment.name": import.meta.env.DEV ? "development" : "production",
22 "service.runtime": "t3-web",
23 "t3code.client.surface": isElectron ? "desktop" : "web",
24 "service.version": APP_VERSION,
25 },
26} as const;
27​
28const layerDelegateRuntime = Layer.mergeAll(
29 PrimaryEnvironmentHttpLayer.layer,
30 OtlpExporter.layerFlusher,
31 OtlpSerialization.layerJson,
32 Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
33);
34​
35let activeRuntime: ManagedRuntime.ManagedRuntime<never, never> | null = null;
36let activeScope: Scope.Closeable | null = null;
37let activeConfigKey: string | null = null;
38let configurationGeneration = 0;
39let pendingConfiguration = Promise.resolve();
40​
41export interface ClientTracingConfig {
42 readonly exportIntervalMs?: number;
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;
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 && ClientTracer.hasDelegate()) {
59 return;
60 }
61​
62 activeConfigKey = nextConfigKey;
63 const generation = ++configurationGeneration;
64​
65 const previousRuntime = activeRuntime;
66 const previousScope = activeScope;
67​
68 ClientTracer.setDelegate(null);
69 activeRuntime = null;
70 activeScope = null;
71​
72 await disposeTracerRuntime(previousRuntime, previousScope);
73​
74 const runtime = ManagedRuntime.make(layerDelegateRuntime);
75 const scope = runtime.runSync(Scope.make());
76​
77 const delegateResult = await settleAsyncResult(() =>
78 runtime.runPromiseExit(
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 (delegateResult._tag === "Failure") {
89 await disposeTracerRuntime(runtime, scope);
90​
91 if (generation === configurationGeneration) {
92 const error = squashAtomCommandFailure(delegateResult);
93 const tracesUrl = new URL(otlpTracesUrl);
94 console.warn("Failed to configure client tracing exporter", {
95 scheme: tracesUrl.protocol.replace(/:$/, ""),
96 host: tracesUrl.hostname,
97 port: tracesUrl.port || undefined,
98 exportIntervalMs,
99 ...safeErrorLogAttributes(error),
100 });
101 }
102 return;
103 }
104​
105 if (generation !== configurationGeneration) {
106 await disposeTracerRuntime(runtime, scope);
107 return;
108 }
109​
110 ClientTracer.setDelegate(delegateResult.value);
111 activeRuntime = runtime;
112 activeScope = scope;
114​
115async function disposeTracerRuntime(
116 runtime: ManagedRuntime.ManagedRuntime<never, never> | null,
117 scope: Scope.Closeable | null,
118): Promise<void> {
119 if (runtime === null || scope === null) {
120 return;
121 }
122​
123 await settleAsyncResult(() => runtime.runPromiseExit(Scope.close(scope, Exit.void)));
124 runtime.dispose();