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

main
ts 162 lines 5.97 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import * as Alchemy from "alchemy";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import * as HttpServerRequest from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Redacted from "effect/Redacted";
8 import { Logs, Metrics, Traces } from "./Datasets.ts";
9 import { IngestToken } from "./IngestToken.ts";
10
11 class UpstreamFetchError extends Data.TaggedError("UpstreamFetchError")<{
12 message: string;
13 cause: unknown;
14 }> {}
15
16 const upstreamFetchError = (cause: unknown) =>
17 new UpstreamFetchError({
18 message: cause instanceof Error ? cause.message : String(cause),
19 cause,
20 });
21
22 /**
23 * Public ingest relay used by both:
24 *
25 * 1. The alchemy CLI / services posting OTLP/JSON to `/v1/{traces,logs,metrics}`,
26 * which we forward to Axiom with the ingest bearer token attached server-side.
27 * 2. The website's PostHog browser SDK, which posts to anything else
28 * (`/e`, `/s`, `/flags`, `/decide`, `/static/*`, ...). PostHog ingest needs
29 * no server secret, so we just reverse-proxy to PostHog Cloud (US region).
30 *
31 * Bound to two custom domains in prod:
32 * - `otel.alchemy.run` — primary OTLP entrypoint
33 * - `analytics.alchemy.run` — first-party PostHog ingest (defeats ad-blockers)
34 *
35 * Environment (set by `stacks/src/otel.ts`):
36 * - `AXIOM_TRACES_ENDPOINT` — full Axiom OTLP traces URL
37 * - `AXIOM_LOGS_ENDPOINT` — full Axiom OTLP logs URL
38 * - `AXIOM_METRICS_ENDPOINT` — full Axiom OTLP metrics URL
39 * - `AXIOM_INGEST_TOKEN` — Bearer token (Redacted)
40 */
41 export default class Ingester extends Cloudflare.Worker<Ingester>()(
42 "OtelWorker",
43 Alchemy.Stack.useSync(({ stage }) => ({
44 main: import.meta.url,
45 observability: { enabled: true },
46 domain:
47 stage === "prod"
48 ? { name: "otel.alchemy.run", aliases: ["analytics.alchemy.run"] }
49 : undefined,
50 })),
51 Effect.gen(function* () {
52 const tokenValue = yield* (yield* IngestToken).token;
53 const traces = yield* Traces;
54 const logs = yield* Logs;
55 const metrics = yield* Metrics;
56 const tracesEndpoint = yield* traces.otelTracesEndpoint;
57 const logsEndpoint = yield* logs.otelLogsEndpoint;
58 const metricsEndpoint = yield* metrics.otelMetricsEndpoint;
59 const tracesDataset = yield* traces.name;
60 const logsDataset = yield* logs.name;
61 const metricsDataset = yield* metrics.name;
62
63 return {
64 fetch: Effect.gen(function* () {
65 const request = yield* HttpServerRequest.HttpServerRequest;
66 const url = new URL(request.url, "http://x");
67 const path = url.pathname;
68
69 // 1. OTLP → Axiom (POST /v1/{traces,logs,metrics})
70 const otlp =
71 request.method === "POST"
72 ? path === "/v1/traces"
73 ? {
74 endpoint: yield* tracesEndpoint,
75 dataset: yield* tracesDataset,
76 }
77 : path === "/v1/logs"
78 ? { endpoint: yield* logsEndpoint, dataset: yield* logsDataset }
79 : path === "/v1/metrics"
80 ? {
81 endpoint: yield* metricsEndpoint,
82 dataset: yield* metricsDataset,
83 }
84 : undefined
85 : undefined;
86
87 if (otlp) {
88 const tokenRaw = yield* tokenValue.pipe(Effect.map(Redacted.value));
89 const token = Redacted.isRedacted(tokenRaw)
90 ? String(Redacted.value(tokenRaw))
91 : (tokenRaw as string);
92
93 const body = yield* request.arrayBuffer;
94
95 const response = yield* Effect.tryPromise({
96 try: () =>
97 fetch(otlp.endpoint, {
98 method: "POST",
99 headers: {
100 "content-type": request.headers["content-type"] ?? "application/json",
101 authorization: `Bearer ${token}`,
102 "x-axiom-dataset": otlp.dataset,
103 },
104 body,
105 }),
106 catch: upstreamFetchError,
107 });
108
109 return HttpServerResponse.fromWeb(response);
110 }
111
112 // 2. Everything else → PostHog Cloud (US region)
113 // /static/* and /array/* live on the assets host; everything else on the
114 // ingest host. Static assets are cacheable at the edge.
115 const isAsset = path.startsWith("/static/") || path.startsWith("/array/");
116 const upstreamHost = isAsset
117 ? "https://us-assets.i.posthog.com"
118 : "https://us.i.posthog.com";
119 const target = `${upstreamHost}${path}${url.search}`;
120
121 const raw = yield* HttpServerRequest.toWeb(request);
122
123 // Drop hop-by-hop / Cloudflare-internal headers; preserve everything
124 // else (content-type, accept, user-agent, x-forwarded-for, etc.).
125 const headers = new Headers(raw.headers);
126 headers.delete("host");
127 headers.delete("cookie");
128 for (const key of headers.keys()) {
129 if (key.startsWith("cf-")) headers.delete(key);
130 }
131 const cfIp =
132 raw.headers.get("cf-connecting-ip") ?? raw.headers.get("x-real-ip") ?? undefined;
133 if (cfIp) headers.set("x-forwarded-for", cfIp);
134
135 const upstream = yield* Effect.tryPromise({
136 try: () =>
137 fetch(target, {
138 method: raw.method,
139 headers,
140 body: raw.method === "GET" || raw.method === "HEAD" ? null : raw.body,
141 redirect: "manual",
142 ...(isAsset
143 ? // Cache the SDK loader / array bundles at the edge for an hour.
144 ({ cf: { cacheTtl: 3600, cacheEverything: true } } as any)
145 : {}),
146 }),
147 catch: upstreamFetchError,
148 });
149
150 return HttpServerResponse.fromWeb(upstream);
151 }).pipe(
152 Effect.catch((err) =>
153 Effect.succeed(
154 HttpServerResponse.text(`Relay error: ${err.message}`, {
155 status: 502,
156 }),
157 ),
158 ),
159 ),
160 };
161 }),
162 ) {}