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

main
ts 282 lines 11.1 KB
Raw
1 import {
2 Runtime,
3 type RuntimeError,
4 type RuntimeServices,
5 } from "@alchemy.run/cloudflare-runtime/core";
6 import { Service } from "@alchemy.run/cloudflare-runtime/core/bindings";
7 import { DEFAULT_COMPATIBILITY_DATE } from "@alchemy.run/cloudflare-runtime/core/internal/constants";
8 import * as WorkerProxy from "@alchemy.run/cloudflare-runtime/core/proxy/WorkerProxy";
9 import * as Context from "effect/Context";
10 import * as Effect from "effect/Effect";
11 import * as Exit from "effect/Exit";
12 import * as Layer from "effect/Layer";
13 import * as Scope from "effect/Scope";
14 import * as Semaphore from "effect/Semaphore";
15 import { routeMatcherSource, routePatternHost, routePatternMatchesHost } from "./RoutePattern.ts";
16
17 /**
18 * A zone route as the local edge sees it: a Cloudflare route pattern and
19 * the script it runs, or `undefined` for an opt-out route (Workers
20 * disabled for matching requests).
21 */
22 export interface LocalEdgeRoute {
23 readonly pattern: string;
24 readonly script: string | undefined;
25 }
26
27 /** A custom-domain Worker, served on its own stable dev proxy. */
28 export interface LocalEdgeDomain {
29 readonly script: string;
30 readonly proxy: WorkerProxy.WorkerProxyInstance;
31 /** The Worker's current workerd address. */
32 readonly upstream: URL;
33 }
34
35 /**
36 * Local emulation of Cloudflare's zone routing — the control-plane rules
37 * that send `api.example.com/users/*` to one Worker and
38 * `api.example.com/orders/*` to another with no gateway Worker in the
39 * request path.
40 *
41 * Every route registered by a local `Worker` (`routes` prop) or
42 * `Workers.Route` resource is matched by one router workerd, which forwards
43 * the request over a service binding to the matched script — the target
44 * sees the original `request.url`, like on Cloudflare. Hostnames map to
45 * local listeners by port:
46 *
47 * - Each literal hostname named by a route pattern gets its own listener
48 * on a free port, logged as `[edge] <host> → <url>`.
49 * - A Worker whose custom `domain` is a routed hostname serves it on its
50 * own dev URL too: its proxy points at the router, with the Worker as the
51 * fallback for unmatched paths (routes take precedence over custom
52 * domains on Cloudflare). Without matching routes the proxy points
53 * straight at the Worker, with no extra hop.
54 */
55 export class LocalEdge extends Context.Service<
56 LocalEdge,
57 {
58 /** Replace the routes owned by `owner` (a Worker or Route identity). */
59 readonly setRoutes: (
60 owner: string,
61 routes: ReadonlyArray<LocalEdgeRoute>,
62 ) => Effect.Effect<void, RuntimeError>;
63 readonly removeRoutes: (owner: string) => Effect.Effect<void, RuntimeError>;
64 /**
65 * Expose a custom-domain Worker. Replaces the Worker's own
66 * `proxy.set(upstream)`: the edge points the proxy at the Worker or at
67 * the router.
68 */
69 readonly serveDomain: (
70 host: string,
71 domain: LocalEdgeDomain,
72 ) => Effect.Effect<void, RuntimeError>;
73 readonly removeDomain: (host: string, script: string) => Effect.Effect<void, RuntimeError>;
74 /** The edge listener serving a routed hostname, if any. */
75 readonly url: (host: string) => Effect.Effect<URL | undefined>;
76 }
77 >()("alchemy/cloudflare/LocalEdge") {}
78
79 interface RouterConfig {
80 /** Listener port → the hostname it serves. */
81 readonly ports: Record<string, string>;
82 readonly routes: ReadonlyArray<{ pattern: string; binding: string | null }>;
83 /** Hostname → the binding of its custom-domain Worker. */
84 readonly domains: Record<string, string>;
85 }
86
87 /**
88 * How long a routed request waits for its target Worker to register with
89 * the dev registry — the same budget a Worker's own dev proxy parks
90 * requests for while it starts.
91 */
92 const TARGET_WAIT_MS = 120_000;
93
94 const routerScript = (config: RouterConfig) => `
95 const CONFIG = ${JSON.stringify(config)};
96 const HOSTS = Object.values(CONFIG.ports);
97 ${routeMatcherSource()}
98 // The registry proxy answers 503 with this message while the target
99 // script has not registered yet (it is still starting). Wait for it, like
100 // a request to the Worker's own dev URL does.
101 const NOT_REGISTERED = /^Worker ".*" not found. Make sure the worker is running locally.$/;
102 async function forward(target, request) {
103 const deadline = Date.now() + ${TARGET_WAIT_MS};
104 for (let delay = 50; ; delay = Math.min(delay * 2, 1000)) {
105 const response = await target.fetch(request.clone());
106 if (
107 response.status !== 503 ||
108 Date.now() > deadline ||
109 !NOT_REGISTERED.test(await response.clone().text())
110 ) {
111 return response;
112 }
113 await new Promise((resolve) => setTimeout(resolve, delay));
114 }
115 }
116 export default {
117 async fetch(request, env) {
118 const url = new URL(request.url);
119 const host = CONFIG.ports[url.port] ?? (HOSTS.length === 1 ? HOSTS[0] : url.hostname);
120 const route = matchRoute(CONFIG.routes, host, url.pathname);
121 const binding = route?.binding ?? CONFIG.domains[host];
122 if (binding) return forward(env[binding], request);
123 const message = route
124 ? "Workers are disabled for " + host + url.pathname + " by route '" + route.pattern + "', and alchemy dev has no origin to fall back to."
125 : "No Worker route matches " + host + url.pathname + ". Routes: " + CONFIG.routes.map((r) => r.pattern).join(", ");
126 return new Response(message, { status: 404, headers: { "content-type": "text/plain" } });
127 },
128 };
129 `;
130
131 export const LocalEdgeLive = Layer.effect(
132 LocalEdge,
133 Effect.gen(function* () {
134 const runtime = yield* Runtime;
135 const workerProxy = yield* WorkerProxy.WorkerProxy;
136 const context = yield* Effect.context<RuntimeServices>();
137 const rootScope = yield* Effect.scope;
138 const lock = yield* Semaphore.make(1);
139 // Unique per edge: the router registers in the machine-wide dev registry.
140 const routerName = `alchemy-edge-${crypto.randomUUID().slice(0, 8)}`;
141
142 const routes = new Map<string, ReadonlyArray<LocalEdgeRoute>>();
143 const domains = new Map<string, LocalEdgeDomain>();
144 const listeners = new Map<
145 string,
146 { instance: WorkerProxy.WorkerProxyInstance; scope: Scope.Closeable }
147 >();
148 let router: { url: URL; scope: Scope.Closeable; key: string } | undefined;
149 // Where each domain proxy currently points, so a rebuild only touches
150 // proxies whose target moved.
151 const domainTargets = new Map<string, string>();
152
153 const syncListeners = Effect.fnUntraced(function* (hosts: ReadonlySet<string>) {
154 for (const [host, listener] of listeners) {
155 if (!hosts.has(host)) {
156 listeners.delete(host);
157 yield* Scope.close(listener.scope, Exit.void);
158 }
159 }
160 for (const host of hosts) {
161 if (listeners.has(host)) continue;
162 const scope = yield* Scope.fork(rootScope);
163 const instance = yield* workerProxy.serve().pipe(Scope.provide(scope));
164 listeners.set(host, { instance, scope });
165 yield* Effect.log(`[edge] ${host} → ${instance.url.origin}`);
166 }
167 });
168
169 const startRouter = Effect.fnUntraced(function* (scripts: string[], config: RouterConfig) {
170 const scope = yield* Scope.fork(rootScope);
171 const url = yield* runtime
172 .start({
173 name: routerName,
174 compatibilityDate: DEFAULT_COMPATIBILITY_DATE,
175 compatibilityFlags: [],
176 bindings: scripts.map((scriptName, index) =>
177 Service.local({ binding: `WORKER_${index}`, scriptName }),
178 ),
179 modules: [{ name: "router.js", type: "ESModule", content: routerScript(config) }],
180 })
181 .pipe(
182 Scope.provide(scope),
183 Effect.provideContext(context),
184 Effect.onExit((exit) =>
185 exit._tag === "Failure" ? Scope.close(scope, exit) : Effect.void,
186 ),
187 );
188 return { url, scope };
189 });
190
191 const rebuild = Effect.gen(function* () {
192 const patterns = [...routes.values()].flat();
193 yield* syncListeners(
194 new Set(patterns.flatMap((route) => routePatternHost(route.pattern) ?? [])),
195 );
196 // Domains with at least one matching route sit behind the router.
197 const routedDomains = [...domains].filter(([host]) =>
198 patterns.some((route) => routePatternMatchesHost(route.pattern, host)),
199 );
200
201 const previous = router;
202 if (patterns.length === 0) {
203 router = undefined;
204 } else {
205 const scripts = [
206 ...new Set([
207 ...patterns.flatMap((route) => route.script ?? []),
208 ...routedDomains.map(([, domain]) => domain.script),
209 ]),
210 ].sort();
211 const binding = (script: string) => `WORKER_${scripts.indexOf(script)}`;
212 const config: RouterConfig = {
213 ports: Object.fromEntries([
214 ...[...listeners].map(([host, l]) => [l.instance.url.port, host]),
215 ...routedDomains.map(([host, d]) => [d.proxy.url.port, host]),
216 ]),
217 routes: patterns.map((route) => ({
218 pattern: route.pattern,
219 binding: route.script ? binding(route.script) : null,
220 })),
221 domains: Object.fromEntries(routedDomains.map(([host, d]) => [host, binding(d.script)])),
222 };
223 const key = JSON.stringify(config);
224 if (previous?.key !== key) {
225 router = { ...(yield* startRouter(scripts, config)), key };
226 }
227 }
228
229 // Make-before-break: point everything at the new router before the
230 // previous one closes.
231 if (router) {
232 const url = router.url;
233 yield* Effect.forEach(listeners.values(), (l) => l.instance.set(url), { discard: true });
234 }
235 for (const [host, domain] of domains) {
236 const routed = router && routedDomains.some(([routedHost]) => routedHost === host);
237 const target = routed ? router!.url : domain.upstream;
238 if (domainTargets.get(host) !== target.href) {
239 domainTargets.set(host, target.href);
240 yield* domain.proxy.set(target);
241 }
242 }
243 if (previous && previous !== router) {
244 yield* Scope.close(previous.scope, Exit.void);
245 }
246 });
247
248 const update = (mutate: () => void) =>
249 Effect.sync(mutate).pipe(Effect.andThen(rebuild), lock.withPermits(1));
250
251 return LocalEdge.of({
252 setRoutes: (owner, next) =>
253 Effect.suspend(() =>
254 JSON.stringify(routes.get(owner) ?? []) === JSON.stringify(next)
255 ? Effect.void
256 : update(() => (next.length ? routes.set(owner, next) : routes.delete(owner))),
257 ),
258 removeRoutes: (owner) =>
259 Effect.suspend(() =>
260 routes.has(owner) ? update(() => routes.delete(owner)) : Effect.void,
261 ),
262 serveDomain: (host, domain) =>
263 update(() => {
264 const key = host.toLowerCase();
265 domains.set(key, domain);
266 // The Worker just (re)served: always re-point its proxy.
267 domainTargets.delete(key);
268 }),
269 removeDomain: (host, script) =>
270 Effect.suspend(() => {
271 const key = host.toLowerCase();
272 return domains.get(key)?.script === script
273 ? update(() => {
274 domains.delete(key);
275 domainTargets.delete(key);
276 })
277 : Effect.void;
278 }),
279 url: (host) => Effect.sync(() => listeners.get(host.toLowerCase())?.instance.url),
280 });
281 }),
282 );