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

clientTracing.ts

133 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 * as Tracer from "effect/Tracer";
6import { HttpClient } from "effect/unstable/http";
7import { OtlpExporter, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
8​
9import { settleAsyncResult, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
10import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
11import { resolvePrimaryEnvironmentHttpUrl } from "../environments/primary";
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 activeDelegate: Tracer.Tracer | null = null;
34let activeRuntime: ManagedRuntime.ManagedRuntime<never, never> | null = null;
35let activeScope: Scope.Closeable | null = null;
36let activeConfigKey: string | null = null;
37let configurationGeneration = 0;
38let pendingConfiguration = Promise.resolve();
39​
40export interface ClientTracingConfig {
41 readonly exportIntervalMs?: number;
43​
44export const ClientTracingLive = Layer.succeed(
45 Tracer.Tracer,
46 Tracer.make({
47 span(options) {
48 return activeDelegate?.span(options) ?? new Tracer.NativeSpan(options);
49 },
50 }),
51);
52​
53export function configureClientTracing(config: ClientTracingConfig = {}): Promise<void> {
54 if (config.exportIntervalMs === undefined && activeConfigKey !== null) {
55 return pendingConfiguration;
56 }
57 pendingConfiguration = pendingConfiguration.finally(() => applyClientTracingConfig(config));
58 return pendingConfiguration;
60​
61async function applyClientTracingConfig(config: ClientTracingConfig): Promise<void> {
62 const otlpTracesUrl = resolvePrimaryEnvironmentHttpUrl("/api/observability/v1/traces");
63 const exportIntervalMs = Math.max(10, config.exportIntervalMs ?? DEFAULT_EXPORT_INTERVAL_MS);
64 const nextConfigKey = `${otlpTracesUrl}|${exportIntervalMs}`;
65​
66 if (activeConfigKey === nextConfigKey && activeDelegate !== null) {
67 return;
68 }
69​
70 activeConfigKey = nextConfigKey;
71 const generation = ++configurationGeneration;
72​
73 const previousRuntime = activeRuntime;
74 const previousScope = activeScope;
75​
76 activeDelegate = null;
77 activeRuntime = null;
78 activeScope = null;
79​
80 await disposeTracerRuntime(previousRuntime, previousScope);
81​
82 const runtime = ManagedRuntime.make(delegateRuntimeLayer);
83 const scope = runtime.runSync(Scope.make());
84​
85 const delegateResult = await settleAsyncResult(() =>
86 runtime.runPromiseExit(
87 Scope.provide(scope)(
88 OtlpTracer.make({
89 url: otlpTracesUrl,
90 exportInterval: `${exportIntervalMs} millis`,
91 resource: CLIENT_TRACING_RESOURCE,
92 }),
93 ),
94 ),
95 );
96 if (delegateResult._tag === "Failure") {
97 await disposeTracerRuntime(runtime, scope);
98​
99 if (generation === configurationGeneration) {
100 const error = squashAtomCommandFailure(delegateResult);
101 const tracesUrl = new URL(otlpTracesUrl);
102 console.warn("Failed to configure client tracing exporter", {
103 scheme: tracesUrl.protocol.replace(/:$/, ""),
104 host: tracesUrl.hostname,
105 port: tracesUrl.port || undefined,
106 exportIntervalMs,
107 ...safeErrorLogAttributes(error),
108 });
109 }
110 return;
111 }
112​
113 if (generation !== configurationGeneration) {
114 await disposeTracerRuntime(runtime, scope);
115 return;
116 }
117​
118 activeDelegate = delegateResult.value;
119 activeRuntime = runtime;
120 activeScope = scope;
122​
123async function disposeTracerRuntime(
124 runtime: ManagedRuntime.ManagedRuntime<never, never> | null,
125 scope: Scope.Closeable | null,
126): Promise<void> {
127 if (runtime === null || scope === null) {
128 return;
129 }
130​
131 await settleAsyncResult(() => runtime.runPromiseExit(Scope.close(scope, Exit.void)));
132 runtime.dispose();