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

clientTracing.ts

146 lines4.5 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 { 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 OtlpSerialization.layerJson,
29 Layer.succeed(HttpClient.TracerDisabledWhen, () => true),
30);
31​
32let activeDelegate: Tracer.Tracer | null = null;
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 const ClientTracingLive = Layer.succeed(
44 Tracer.Tracer,
45 Tracer.make({
46 span(options) {
47 return activeDelegate?.span(options) ?? new Tracer.NativeSpan(options);
48 },
49 }),
50);
51​
52export function configureClientTracing(config: ClientTracingConfig = {}): Promise<void> {
53 if (config.exportIntervalMs === undefined && activeConfigKey !== null) {
54 return pendingConfiguration;
55 }
56 pendingConfiguration = pendingConfiguration.finally(() => applyClientTracingConfig(config));
57 return pendingConfiguration;
59​
60async function applyClientTracingConfig(config: ClientTracingConfig): Promise<void> {
61 const otlpTracesUrl = resolvePrimaryEnvironmentHttpUrl("/api/observability/v1/traces");
62 const exportIntervalMs = Math.max(10, config.exportIntervalMs ?? DEFAULT_EXPORT_INTERVAL_MS);
63 const nextConfigKey = `${otlpTracesUrl}|${exportIntervalMs}`;
64​
65 if (activeConfigKey === nextConfigKey && activeDelegate !== null) {
66 return;
67 }
68​
69 activeConfigKey = nextConfigKey;
70 const generation = ++configurationGeneration;
71​
72 const previousRuntime = activeRuntime;
73 const previousScope = activeScope;
74​
75 activeDelegate = null;
76 activeRuntime = null;
77 activeScope = null;
78​
79 await disposeTracerRuntime(previousRuntime, previousScope);
80​
81 const runtime = ManagedRuntime.make(delegateRuntimeLayer);
82 const scope = runtime.runSync(Scope.make());
83​
84 const delegateResult = await settleAsyncResult(() =>
85 runtime.runPromiseExit(
86 Scope.provide(scope)(
87 OtlpTracer.make({
88 url: otlpTracesUrl,
89 exportInterval: `${exportIntervalMs} millis`,
90 resource: CLIENT_TRACING_RESOURCE,
91 }),
92 ),
93 ),
94 );
95 if (delegateResult._tag === "Failure") {
96 await disposeTracerRuntime(runtime, scope);
97​
98 if (generation === configurationGeneration) {
99 const error = squashAtomCommandFailure(delegateResult);
100 const tracesUrl = new URL(otlpTracesUrl);
101 console.warn("Failed to configure client tracing exporter", {
102 scheme: tracesUrl.protocol.replace(/:$/, ""),
103 host: tracesUrl.hostname,
104 port: tracesUrl.port || undefined,
105 exportIntervalMs,
106 ...safeErrorLogAttributes(error),
107 });
108 }
109 return;
110 }
111​
112 if (generation !== configurationGeneration) {
113 await disposeTracerRuntime(runtime, scope);
114 return;
115 }
116​
117 activeDelegate = delegateResult.value;
118 activeRuntime = runtime;
119 activeScope = scope;
121​
122async function disposeTracerRuntime(
123 runtime: ManagedRuntime.ManagedRuntime<never, never> | null,
124 scope: Scope.Closeable | null,
125): Promise<void> {
126 if (runtime === null || scope === null) {
127 return;
128 }
129​
130 await settleAsyncResult(() => runtime.runPromiseExit(Scope.close(scope, Exit.void)));
131 runtime.dispose();
133​
134export async function __resetClientTracingForTests() {
135 configurationGeneration++;
136 activeConfigKey = null;
137 activeDelegate = null;
138 pendingConfiguration = Promise.resolve();
139​
140 const runtime = activeRuntime;
141 const scope = activeScope;
142 activeRuntime = null;
143 activeScope = null;
144​
145 await disposeTracerRuntime(runtime, scope);