@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 152 lines 5.92 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as FetchHttpClient from "effect/http/FetchHttpClient";
3 import * as HttpClient from "effect/http/HttpClient";
4 import * as HttpClientRequest from "effect/http/HttpClientRequest";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Option from "effect/Option";
8 import { configuredDestinations, type ResolvedSignal } from "./TelemetryRuntime.ts";
9
10 /** An OpenTelemetry signal the relay forwards. */
11 export type Signal = "traces" | "logs" | "metrics";
12
13 /** Where the relay forwards one batch: an OTLP/HTTP endpoint and the headers to send it. */
14 export interface Destination {
15 readonly url: string;
16 readonly headers?: Readonly<Record<string, string>>;
17 }
18
19 /** Options for {@link relay}. */
20 export interface RelayOptions<R = never> {
21 /**
22 * The signals the relay accepts. A post for any other gets a 404.
23 * @default ["traces", "logs", "metrics"]
24 */
25 readonly signals?: ReadonlyArray<Signal>;
26 /**
27 * The largest body accepted, in bytes. Larger posts get a 413.
28 * @default 1048576
29 */
30 readonly maxBytes?: number;
31 /**
32 * Decide whether to accept a post, e.g. only from signed-in users. A post
33 * it refuses gets a 403. The relay is a public endpoint, so gate it when
34 * you can.
35 * @default every post is accepted
36 */
37 readonly authorize?: Effect.Effect<boolean, never, R | HttpServerRequest>;
38 /**
39 * Choose where a batch goes. It receives the destinations this runtime
40 * exports its own telemetry to, and returns the ones to forward to: all
41 * of them, some, or others entirely.
42 * @default the runtime's own destinations for that signal
43 */
44 readonly route?: (
45 signal: Signal,
46 configured: ReadonlyArray<Destination>,
47 ) => Effect.Effect<ReadonlyArray<Destination>, never, R | HttpServerRequest>;
48 }
49
50 const SIGNALS: ReadonlyArray<Signal> = ["traces", "logs", "metrics"];
51
52 const json = (status: number, body: unknown) => HttpServerResponse.jsonUnsafe(body, { status });
53
54 /**
55 * Collect OpenTelemetry from browsers and other clients through your own
56 * Worker or Function, and forward it to where your backend's telemetry
57 * goes, with the backend's own credentials. Clients post OTLP/HTTP to a
58 * path ending in `/v1/traces`, `/v1/logs` or `/v1/metrics`; each body is
59 * forwarded unchanged, JSON or protobuf.
60 *
61 * No ingest token ever reaches the client, the client posts to its own
62 * origin, and `route` decides where each batch goes.
63 *
64 * ### Collecting browser traces
65 * **Example:** Relay the app's spans through the backend Worker
66 * ```typescript
67 * import * as Telemetry from "alchemy/Telemetry";
68 *
69 * const telemetry = Telemetry.relay({ signals: ["traces"] });
70 *
71 * // in the Worker's fetch handler
72 * if (path.startsWith("/api/telemetry/")) return yield* telemetry;
73 * ```
74 *
75 * **Example:** The browser exports to it
76 * ```typescript
77 * import * as OtlpTracer from "effect/observability/OtlpTracer";
78 *
79 * OtlpTracer.layer({
80 * url: `${location.origin}/api/telemetry/v1/traces`,
81 * resource: { serviceName: "bank-web" },
82 * });
83 * ```
84 *
85 * ### Routing batches
86 * **Example:** Send browser traces to their own dataset
87 * ```typescript
88 * Telemetry.relay({
89 * route: (signal, configured) =>
90 * Effect.succeed(
91 * signal === "traces"
92 * ? configured.map((d) => ({ ...d, headers: { ...d.headers, "x-axiom-dataset": "browser" } }))
93 * : configured,
94 * ),
95 * });
96 * ```
97 *
98 * @primitive
99 */
100 export const relay = <R = never>(
101 options: RelayOptions<R> = {},
102 ): Effect.Effect<HttpServerResponse.HttpServerResponse, never, R | HttpServerRequest> =>
103 Effect.gen(function* () {
104 const request = yield* HttpServerRequest;
105 if (request.method !== "POST") return json(405, { error: "OTLP is posted" });
106 const signal = SIGNALS.find((s) =>
107 new URL(request.url, "http://relay").pathname.endsWith(`/v1/${s}`),
108 );
109 if (!signal || !(options.signals ?? SIGNALS).includes(signal)) {
110 return json(404, { error: "Unknown signal" });
111 }
112 const maxBytes = options.maxBytes ?? 1_048_576;
113 const declared = Number(request.headers["content-length"] ?? "0");
114 if (declared > maxBytes) return json(413, { error: "Too large" });
115 if (options.authorize && !(yield* options.authorize)) return json(403, { error: "Forbidden" });
116
117 const body = yield* request.arrayBuffer.pipe(Effect.option);
118 if (Option.isNone(body)) return json(400, { error: "Unreadable body" });
119 if (body.value.byteLength > maxBytes) return json(413, { error: "Too large" });
120
121 const configured = (yield* configuredDestinations).flatMap(
122 (destination): ReadonlyArray<ResolvedSignal> => {
123 const target = destination[signal];
124 return target ? [target] : [];
125 },
126 );
127 const targets = options.route ? yield* options.route(signal, configured) : configured;
128 // Nowhere to send it is not the client's problem: accept and drop.
129 if (targets.length === 0) return json(200, {});
130
131 const client = Option.getOrElse(
132 yield* Effect.serviceOption(HttpClient.HttpClient),
133 () => undefined,
134 );
135 const contentType = request.headers["content-type"] ?? "application/json";
136 const forward = (target: Destination) =>
137 Effect.gen(function* () {
138 const http =
139 client ?? (yield* HttpClient.HttpClient.pipe(Effect.provide(FetchHttpClient.layer)));
140 const response = yield* http.execute(
141 HttpClientRequest.post(target.url).pipe(
142 HttpClientRequest.bodyUint8Array(new Uint8Array(body.value), contentType),
143 HttpClientRequest.setHeaders(target.headers ?? {}),
144 ),
145 );
146 return response.status >= 200 && response.status < 300;
147 }).pipe(Effect.orElseSucceed(() => false));
148 const delivered = yield* Effect.forEach(targets, forward, { concurrency: "unbounded" });
149 return delivered.some(Boolean)
150 ? json(200, {})
151 : json(502, { error: "No destination accepted the batch" });
152 });