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

relayTracing.ts

179 lines5.4 KB

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;
16​
17export interface RelayClientTracingResource {
18 readonly serviceName: string;
19 readonly serviceVersion?: string;
20 readonly runtime: string;
21 readonly client: string;
22 readonly component?: string;
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/** Export only T3 Connect spans; wrap local work with {@link withLocalTracing}. */
37export const withRelayClientTracing = <A, E, R>(
38 effect: Effect.Effect<A, E, R>,
39): Effect.Effect<A, E, R> =>
40 RelayClientTracer.pipe(
41 Effect.flatMap(
42 Option.match({
43 onNone: () => effect,
44 onSome: (tracer) =>
45 Tracer.Tracer.pipe(
46 Effect.flatMap((local) =>
47 effect.pipe(
48 Effect.provideService(Tracer.Tracer, tracer),
49 Effect.provideService(LocalTracer, Option.some(local)),
50 ),
51 ),
52 ),
53 }),
54 ),
55 );
56​
57/** Keep local work in the local trace without exporting machine details through relay spans. */
58export const withLocalTracing = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
59 LocalTracer.pipe(
60 Effect.flatMap(
61 Option.match({
62 onNone: () => effect,
63 onSome: (local) => effect.pipe(Effect.provideService(Tracer.Tracer, local)),
64 }),
65 ),
66 );
67​
68function cleanTraceStack(error: Error): string {
69 const stack = error.stack ?? `${error.name}: ${error.message}`;
70 const lines = stack.split("\n");
71 const effectFrameIndex = lines.findIndex(
72 (line, index) => index > 0 && /(?:Generator\.next|~effect\/Effect)/.test(line),
73 );
74 return effectFrameIndex < 0 ? stack : lines.slice(0, effectFrameIndex).join("\n");
76​
77function traceSafeError(value: unknown, seen = new WeakSet<object>()): Error {
78 const message =
79 value instanceof Error
80 ? value.message
81 : typeof value === "object" &&
82 value !== null &&
83 "message" in value &&
84 typeof value.message === "string"
85 ? value.message
86 : String(value);
87​
88 let cause: Error | undefined;
89 if (typeof value === "object" && value !== null && !seen.has(value)) {
90 seen.add(value);
91 if ("cause" in value && value.cause !== undefined) {
92 cause = traceSafeError(value.cause, seen);
93 }
94 }
95​
96 const error = new Error(message, cause ? { cause } : undefined);
97 if (value instanceof Error) {
98 error.name = value.name;
99 error.stack = cleanTraceStack(value);
100 } else if (
101 typeof value === "object" &&
102 value !== null &&
103 "name" in value &&
104 typeof value.name === "string"
105 ) {
106 error.name = value.name;
107 }
108 if (cause) {
109 error.stack = `${error.stack ?? `${error.name}: ${error.message}`}\nCaused by: ${cause.stack ?? `${cause.name}: ${cause.message}`}`;
110 }
111 return error;
113​
114function traceSafeExit(exit: Exit.Exit<unknown, unknown>): Exit.Exit<unknown, unknown> {
115 if (Exit.isSuccess(exit)) {
116 return exit;
117 }
118 return Exit.failCause(
119 Cause.fromReasons(
120 exit.cause.reasons.map((reason) => {
121 if (Cause.isFailReason(reason)) {
122 return Cause.makeFailReason(traceSafeError(reason.error));
123 }
124 if (Cause.isDieReason(reason)) {
125 return Cause.makeDieReason(traceSafeError(reason.defect));
126 }
127 return reason;
128 }),
129 ),
130 );
132​
133function nonInterferingTracer(delegate: Tracer.Tracer): Tracer.Tracer {
134 return Tracer.make({
135 span(options) {
136 const span = delegate.span(options);
137 const end = span.end.bind(span);
138 span.end = (endTime, exit) => {
139 try {
140 end(endTime, traceSafeExit(exit));
141 } catch {}
142 };
143 return span;
144 },
145 ...(delegate.context ? { context: delegate.context } : {}),
146 });
148​
149export function layer(
150 config: RelayClientTracingConfig | null,
151 resource: RelayClientTracingResource,
152): Layer.Layer<never, never, HttpClient.HttpClient> {
153 if (config === null) {
154 return Layer.succeed(RelayClientTracer, Option.none());
155 }
156​
157 const layerTracer = OtlpTracer.layer({
158 url: config.tracesUrl,
159 headers: {
160 Authorization: `Bearer ${config.tracesToken}`,
161 "X-Axiom-Dataset": config.tracesDataset,
162 },
163 resource: {
164 serviceName: resource.serviceName,
165 serviceVersion: resource.serviceVersion,
166 attributes: {
167 "service.namespace": "t3code",
168 "service.runtime": resource.runtime,
169 "t3code.component": resource.component ?? "relay-client",
170 "t3code.client.surface": resource.client,
171 },
172 },
173 }).pipe(Layer.provide(OtlpSerialization.layerJson));
174​
175 return Layer.effect(
176 RelayClientTracer,
177 Tracer.Tracer.pipe(Effect.map(nonInterferingTracer), Effect.asSome),
178 ).pipe(Layer.provide(layerTracer));