The best way to control Claude Code, Codex and more from any computer or phone

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