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

main
ts 189 lines 7.09 KB
Raw
1 import type * as Output from "alchemy/Output";
2 import { defaultProviderMode, remote, type ProviderMode } from "alchemy/ProviderMode";
3 import { Random } from "alchemy/Random";
4 /**
5 * Dev-mode remote-producer shim for `Alchemy.remote()` queues.
6 *
7 * Cloudflare's preview/remote-binding sessions reject queue bindings
8 * outright (a preview worker carrying one serves 503 for every request;
9 * wrangler has the same gap — cloudflare/workers-sdk#9929), so a locally
10 * running worker cannot produce to a live queue through the usual
11 * remote-binding proxy. Instead, alchemy deploys a REAL shim worker that
12 * holds the actual queue binding:
13 *
14 * local worker ── env.QUEUE.send() ──▶ forwarder service (local workerd)
15 * POST /message | /batch + Authorization: Bearer <token>
16 * │
17 * ▼
18 * deployed shim worker (workers.dev)
19 * │ env.QUEUE.send(body, { contentType })
20 * ▼
21 * real Cloudflare Queue
22 *
23 * The shim and its bearer token are ordinary engine-managed resources
24 * ({@link Worker} + {@link Random}), conditionally instantiated at eval
25 * time when a LOCAL worker binds a LIVE queue — the same idiom as
26 * `AccountApiToken` (capability layers minting token resources) and
27 * event-source mappings. The engine gives the full lifecycle for free:
28 * Output-based ordering (shim deploys before the local worker serves),
29 * stable-name updates, deletion on destroy, and orphan GC on promotion
30 * (`alchemy deploy` no longer registers the shim, so it is cleaned up).
31 *
32 * NOT exported from `index.ts` — binding-internal scaffolding.
33 */
34 import * as Effect from "effect/Effect";
35 import type * as Redacted from "effect/Redacted";
36 import { Worker } from "../Workers/Worker.ts";
37 import type { Queue } from "./Queue.ts";
38
39 /**
40 * The deployed shim's script: decodes workerd's queue wire protocol
41 * (`POST /message` with raw bytes + `X-Msg-Fmt`, `POST /batch` with base64
42 * payloads) back into `send()`/`sendBatch()` calls on its real queue
43 * binding, gated by a bearer token.
44 *
45 * `v8`-serialized messages cannot cross the boundary — deserializing V8
46 * payloads in userland is not possible — so they are rejected with a clear
47 * error telling the caller to pass an explicit contentType.
48 */
49 const QUEUE_SHIM_SCRIPT = `class HttpError extends Error {
50 constructor(status, message) {
51 super(message);
52 this.status = status;
53 }
54 }
55
56 function decodeBody(contentType, bytes) {
57 switch (contentType) {
58 case "text":
59 return { contentType, body: new TextDecoder().decode(bytes) };
60 case "json":
61 return { contentType, body: JSON.parse(new TextDecoder().decode(bytes)) };
62 case "bytes":
63 return { contentType, body: bytes.slice().buffer };
64 case "v8":
65 throw new HttpError(
66 422,
67 'v8-serialized queue messages cannot be produced to a live queue from local dev; pass an explicit contentType of "json", "text", or "bytes" to send()/sendBatch()',
68 );
69 default:
70 throw new HttpError(400, "message content type " + contentType + " is invalid");
71 }
72 }
73
74 function base64ToBytes(b64) {
75 const binary = atob(b64);
76 const bytes = new Uint8Array(binary.length);
77 for (let i = 0; i < binary.length; i++) {
78 bytes[i] = binary.charCodeAt(i);
79 }
80 return bytes;
81 }
82
83 function getDelay(value) {
84 if (!value) return undefined;
85 const delay = Number(value);
86 if (!Number.isInteger(delay) || delay < 0) {
87 throw new HttpError(400, "message delay " + value + " is invalid");
88 }
89 return delay;
90 }
91
92 // workerd's queue client requires this response shape (SendMetadata);
93 // the metrics are informational and synthesized as zeros here.
94 const sendResponse = () =>
95 Response.json({
96 metadata: {
97 metrics: { backlogCount: 0, backlogBytes: 0, oldestMessageTimestamp: 0 },
98 },
99 });
100
101 export default {
102 async fetch(request, env) {
103 try {
104 const auth = request.headers.get("authorization");
105 if (auth !== "Bearer " + env.SHIM_TOKEN) {
106 throw new HttpError(401, "unauthorized");
107 }
108 if (request.method !== "POST") {
109 throw new HttpError(405, "method " + request.method + " not allowed");
110 }
111 const url = new URL(request.url);
112 switch (url.pathname) {
113 case "/message": {
114 // workerd's absent-header default is "v8" — mirrored here so an
115 // unmarked payload is rejected rather than misparsed.
116 const contentType = request.headers.get("X-Msg-Fmt") ?? "v8";
117 const delaySeconds = getDelay(request.headers.get("X-Msg-Delay-Secs"));
118 const bytes = new Uint8Array(await request.arrayBuffer());
119 const decoded = decodeBody(contentType, bytes);
120 await env.QUEUE.send(decoded.body, {
121 contentType: decoded.contentType,
122 ...(delaySeconds !== undefined && { delaySeconds }),
123 });
124 return sendResponse();
125 }
126 case "/batch": {
127 const delaySeconds = getDelay(request.headers.get("X-Msg-Delay-Secs"));
128 const body = await request.json();
129 const messages = body.messages.map((message) => {
130 const decoded = decodeBody(message.contentType, base64ToBytes(message.body));
131 const delay = message.delaySecs ?? delaySeconds;
132 return {
133 body: decoded.body,
134 contentType: decoded.contentType,
135 ...(delay !== undefined && { delaySeconds: delay }),
136 };
137 });
138 await env.QUEUE.sendBatch(messages);
139 return sendResponse();
140 }
141 default:
142 throw new HttpError(404, "not found");
143 }
144 } catch (e) {
145 if (e instanceof HttpError) {
146 return new Response(e.message, { status: e.status });
147 }
148 const message = e instanceof Error ? e.message : String(e);
149 return new Response("queue shim failed: " + message, { status: 500 });
150 }
151 },
152 };`;
153
154 export interface QueueShimBinding {
155 url: Output.Output<string | undefined>;
156 token: Output.Output<Redacted.Redacted<string>>;
157 }
158
159 /**
160 * Conditionally instantiate the queue shim for a producer binding: when a
161 * LOCAL host worker binds a LIVE queue (dev run + `Alchemy.remote()` on the
162 * queue), register the shim worker + its token and return their outputs
163 * for the binding data. Any other mode combination returns `undefined` —
164 * including the shim worker's own eval of its queue binding (the shim is
165 * pinned live, so no recursion).
166 */
167 export const maybeQueueShim = Effect.fn(function* (
168 queue: Queue,
169 host: { Mode?: ProviderMode | undefined },
170 ) {
171 const runDefault = yield* defaultProviderMode;
172 const hostMode = host.Mode ?? runDefault;
173 const queueMode = queue.Mode ?? runDefault;
174 if (hostMode !== "local" || queueMode !== "live") {
175 return undefined;
176 }
177 const token = yield* Random(`${queue.LogicalId}ShimToken`);
178 const shim = yield* Worker(`${queue.LogicalId}Shim`, {
179 script: QUEUE_SHIM_SCRIPT,
180 env: {
181 QUEUE: queue,
182 SHIM_TOKEN: token.text,
183 },
184 }).pipe(remote());
185 return {
186 url: shim.url,
187 token: token.text,
188 } satisfies QueueShimBinding;
189 });