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

clientTracing.ts

123 lines4.0 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/unstable/http";
6import { OtlpExporter, OtlpSerialization, OtlpTracer } from "effect/unstable/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 { 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: "t3-web",
19 attributes: {
20 "service.runtime": "t3-web",
21 "service.mode": isElectron ? "electron" : "browser",
22 "service.version": APP_VERSION,
23 },
24} as const;
25​
26const delegateRuntimeLayer = Layer.mergeAll(
27 primaryEnvironmentHttpLayer,
28 OtlpExporter.layerFlusher,
29 OtlpSerialization.layerJson,
30 Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
31);
32​
33let activeRuntime: ManagedRuntime.ManagedRuntime<never, never> | null = null;
34let activeScope: Scope.Closeable | null = null;
35let activeConfigKey: string | null = null;
36let configurationGeneration = 0;
37let pendingConfiguration = Promise.resolve();
38​
39export interface ClientTracingConfig {
40 readonly exportIntervalMs?: number;
42​
43export function configureClientTracing(config: ClientTracingConfig = {}): Promise<void> {
44 if (config.exportIntervalMs === undefined && activeConfigKey !== null) {
45 return pendingConfiguration;
46 }
47 pendingConfiguration = pendingConfiguration.finally(() => applyClientTracingConfig(config));
48 return pendingConfiguration;
50​
51async function applyClientTracingConfig(config: ClientTracingConfig): Promise<void> {
52 const otlpTracesUrl = resolvePrimaryEnvironmentHttpUrl("/api/observability/v1/traces");
53 const exportIntervalMs = Math.max(10, config.exportIntervalMs ?? DEFAULT_EXPORT_INTERVAL_MS);
54 const nextConfigKey = `${otlpTracesUrl}|${exportIntervalMs}`;
55​
56 if (activeConfigKey === nextConfigKey && ClientTracer.hasDelegate()) {
57 return;
58 }
59​
60 activeConfigKey = nextConfigKey;
61 const generation = ++configurationGeneration;
62​
63 const previousRuntime = activeRuntime;
64 const previousScope = activeScope;
65​
66 ClientTracer.setDelegate(null);
67 activeRuntime = null;
68 activeScope = null;
69​
70 await disposeTracerRuntime(previousRuntime, previousScope);
71​
72 const runtime = ManagedRuntime.make(delegateRuntimeLayer);
73 const scope = runtime.runSync(Scope.make());
74​
75 const delegateResult = await settleAsyncResult(() =>
76 runtime.runPromiseExit(
77 Scope.provide(scope)(
78 OtlpTracer.make({
79 url: otlpTracesUrl,
80 exportInterval: `${exportIntervalMs} millis`,
81 resource: CLIENT_TRACING_RESOURCE,
82 }),
83 ),
84 ),
85 );
86 if (delegateResult._tag === "Failure") {
87 await disposeTracerRuntime(runtime, scope);
88​
89 if (generation === configurationGeneration) {
90 const error = squashAtomCommandFailure(delegateResult);
91 const tracesUrl = new URL(otlpTracesUrl);
92 console.warn("Failed to configure client tracing exporter", {
93 scheme: tracesUrl.protocol.replace(/:$/, ""),
94 host: tracesUrl.hostname,
95 port: tracesUrl.port || undefined,
96 exportIntervalMs,
97 ...safeErrorLogAttributes(error),
98 });
99 }
100 return;
101 }
102​
103 if (generation !== configurationGeneration) {
104 await disposeTracerRuntime(runtime, scope);
105 return;
106 }
107​
108 ClientTracer.setDelegate(delegateResult.value);
109 activeRuntime = runtime;
110 activeScope = scope;
112​
113async function disposeTracerRuntime(
114 runtime: ManagedRuntime.ManagedRuntime<never, never> | null,
115 scope: Scope.Closeable | null,
116): Promise<void> {
117 if (runtime === null || scope === null) {
118 return;
119 }
120​
121 await settleAsyncResult(() => runtime.runPromiseExit(Scope.close(scope, Exit.void)));
122 runtime.dispose();