Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Tracer from "effect/Tracer";
8import type { HttpClient } from "effect/http";
9import { OtlpSerialization, OtlpTracer } from "effect/observability";
10
11export interface RelayClientTracingConfig {
12 readonly tracesUrl: string;
13 readonly tracesDataset: string;
14 readonly tracesToken: string;
15}
16
17export interface RelayClientTracingResource {
18 readonly serviceName: string;
19 readonly serviceVersion?: string;
20 readonly runtime: string;
21 readonly client: string;
22 readonly component?: string;
23}
24
25export class RelayClientTracer extends Context.Reference(
26 "@t3tools/shared/relayTracing/RelayClientTracer",
27 {
28 defaultValue: () => Option.none<Tracer.Tracer>(),
29 },
30) {}
31
32class LocalTracer extends Context.Reference("@t3tools/shared/relayTracing/LocalTracer", {
33 defaultValue: () => Option.none<Tracer.Tracer>(),
34}) {}
35
36/**
37 * Exports every span `effect` creates through the product tracer. Use it only
38 * around T3 Connect work; wrap local work inside it with
39 * {@link withLocalTracing} so it stays off the product tracer.
40 */
41export const withRelayClientTracing = <A, E, R>(
42 effect: Effect.Effect<A, E, R>,
43): Effect.Effect<A, E, R> =>
44 RelayClientTracer.pipe(
45 Effect.flatMap(
46 Option.match({
47 onNone: () => effect,
48 onSome: (tracer) =>
49 Tracer.Tracer.pipe(
50 Effect.flatMap((local) =>
51 effect.pipe(
52 Effect.provideService(Tracer.Tracer, tracer),
53 Effect.provideService(LocalTracer, Option.some(local)),
54 ),
55 ),
56 ),
57 }),
58 ),
59 );
60
61/**
62 * Its spans stay in the local trace and are never exported, so a relay span can
63 * time the work without shipping what the user's machine did to answer it.
64 */
65export const withLocalTracing = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
66 LocalTracer.pipe(
67 Effect.flatMap(
68 Option.match({
69 onNone: () => effect,
70 onSome: (local) => effect.pipe(Effect.provideService(Tracer.Tracer, local)),
71 }),
72 ),
73 );
74
75function cleanTraceStack(error: Error): string {
76 const stack = error.stack ?? `${error.name}: ${error.message}`;
77 const lines = stack.split("\n");
78 const effectFrameIndex = lines.findIndex(
79 (line, index) => index > 0 && /(?:Generator\.next|~effect\/Effect)/.test(line),
80 );
81 return effectFrameIndex < 0 ? stack : lines.slice(0, effectFrameIndex).join("\n");
82}
83
84function traceSafeError(value: unknown, seen = new WeakSet<object>()): Error {
85 const message =
86 value instanceof Error
87 ? value.message
88 : typeof value === "object" &&
89 value !== null &&
90 "message" in value &&
91 typeof value.message === "string"
92 ? value.message
93 : String(value);
94
95 let cause: Error | undefined;
96 if (typeof value === "object" && value !== null && !seen.has(value)) {
97 seen.add(value);
98 if ("cause" in value && value.cause !== undefined) {
99 cause = traceSafeError(value.cause, seen);
100 }
101 }
102
103 const error = new Error(message, cause ? { cause } : undefined);
104 if (value instanceof Error) {
105 error.name = value.name;
106 error.stack = cleanTraceStack(value);
107 } else if (
108 typeof value === "object" &&
109 value !== null &&
110 "name" in value &&
111 typeof value.name === "string"
112 ) {
113 error.name = value.name;
114 }
115 if (cause) {
116 error.stack = `${error.stack ?? `${error.name}: ${error.message}`}\nCaused by: ${cause.stack ?? `${cause.name}: ${cause.message}`}`;
117 }
118 return error;
119}
120
121function traceSafeExit(exit: Exit.Exit<unknown, unknown>): Exit.Exit<unknown, unknown> {
122 if (Exit.isSuccess(exit)) {
123 return exit;
124 }
125 return Exit.failCause(
126 Cause.fromReasons(
127 exit.cause.reasons.map((reason) => {
128 if (Cause.isFailReason(reason)) {
129 return Cause.makeFailReason(traceSafeError(reason.error));
130 }
131 if (Cause.isDieReason(reason)) {
132 return Cause.makeDieReason(traceSafeError(reason.defect));
133 }
134 return reason;
135 }),
136 ),
137 );
138}
139
140function nonInterferingTracer(delegate: Tracer.Tracer): Tracer.Tracer {
141 return Tracer.make({
142 span(options) {
143 const span = delegate.span(options);
144 const end = span.end.bind(span);
145 span.end = (endTime, exit) => {
146 try {
147 end(endTime, traceSafeExit(exit));
148 } catch {}
149 };
150 return span;
151 },
152 ...(delegate.context ? { context: delegate.context } : {}),
153 });
154}
155
156export function layer(
157 config: RelayClientTracingConfig | null,
158 resource: RelayClientTracingResource,
159): Layer.Layer<never, never, HttpClient.HttpClient> {
160 if (config === null) {
161 return Layer.succeed(RelayClientTracer, Option.none());
162 }
163
164 const layerTracer = OtlpTracer.layer({
165 url: config.tracesUrl,
166 headers: {
167 Authorization: `Bearer ${config.tracesToken}`,
168 "X-Axiom-Dataset": config.tracesDataset,
169 },
170 resource: {
171 serviceName: resource.serviceName,
172 serviceVersion: resource.serviceVersion,
173 attributes: {
174 "service.namespace": "t3code",
175 "service.runtime": resource.runtime,
176 "service.component": resource.component ?? "relay-client",
177 "t3.client.surface": resource.client,
178 },
179 },
180 }).pipe(Layer.provide(OtlpSerialization.layerJson));
181
182 return Layer.effect(
183 RelayClientTracer,
184 Tracer.Tracer.pipe(Effect.map(nonInterferingTracer), Effect.asSome),
185 ).pipe(Layer.provide(layerTracer));
186}