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

main
ts 269 lines 10.7 KB
Raw
1 import type * as cf from "@cloudflare/workers-types";
2 import { RuntimeContext } from "alchemy/RuntimeContext";
3 import { buildEventTelemetry } from "alchemy/TelemetryRuntime";
4 import type { DurableObject as DurableObjectClass } from "cloudflare:workers";
5 import * as Cause from "effect/Cause";
6 import * as Context from "effect/Context";
7 import * as Effect from "effect/Effect";
8 import * as Exit from "effect/Exit";
9 import { HttpServerResponse } from "effect/http";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
12 import * as Scope from "effect/Scope";
13 import * as Stream from "effect/Stream";
14 import {
15 dispatchAlarmCallbacks,
16 initializeAlarmCallbacks,
17 makeDurableObjectCallbackFactory,
18 } from "./AlarmCallback.ts";
19 import type { DurableObjectExport, DurableObjectShape } from "./DurableObject.ts";
20 import {
21 BackgroundWork,
22 DurableObjectState,
23 fromDurableObjectState,
24 } from "./DurableObjectState.ts";
25 import { isScopeEjected, makeRequestEffect } from "./HttpServer.ts";
26 import { takeRpcTraceContext } from "./internal/RpcTraceContext.ts";
27 import { fromWebSocket } from "./WebSocket.ts";
28 import { getWorkerExport, handleRpcExit } from "./WorkerBridge.ts";
29
30 /**
31 * Create a DurableObjectBridge class that proxies RPC method calls through
32 * the Effect runtime, encoding success/fail/stream results as RPC envelopes.
33 *
34 * Accepts the `DurableObject` base class and a `getExport` resolver so the
35 * implementation lives in real TypeScript instead of a generated string template.
36 */
37 export const makeDurableObjectBridge =
38 (
39 DurableObject: typeof DurableObjectClass,
40 {
41 entrypoint,
42 stack,
43 }: {
44 entrypoint: Effect.Effect<Record<string, any>>;
45 stack: {
46 name: string;
47 stage: string;
48 };
49 },
50 ) =>
51 (className: string) => {
52 // One isolate-lifetime layer build shared by every activation of this DO
53 // class: `build` memoizes the built context, so re-activations (including
54 // hibernatable WebSocket wakes, which re-run the constructor) reuse it
55 // instead of rebuilding the layer stack.
56 const { build } = getWorkerExport<DurableObjectExport>({
57 entrypoint,
58 stack,
59 exportName: className,
60 });
61
62 return class DurableObjectBridge extends DurableObject {
63 #state;
64 #instance;
65 constructor(state: cf.DurableObjectState, env: any) {
66 super(state as any, env);
67 this.#state = state;
68
69 this.#instance = state.blockConcurrencyWhile(() =>
70 build((promise) => void (state as any).waitUntil?.(promise)).then(
71 ({ context, runtimeContext, export: exported, telemetry }) => {
72 const { constructor, services } = exported;
73 const instanceRuntimeContext = {
74 ...runtimeContext,
75 makeCallback: makeDurableObjectCallbackFactory(this.#state),
76 };
77 const doContext = Layer.succeed(
78 DurableObjectState,
79 fromDurableObjectState(this.#state),
80 ).pipe(
81 Layer.provideMerge(Layer.succeedContext(services)),
82 Layer.provideMerge(Layer.succeedContext(context)),
83 );
84 return constructor.pipe(
85 Effect.provide(doContext),
86 Effect.flatMap((instance) =>
87 Effect.suspend(() => {
88 const seal = initializeAlarmCallbacks(this.#state);
89 const instanceContext = Layer.succeed(
90 RuntimeContext,
91 instanceRuntimeContext,
92 ).pipe(Layer.provideMerge(doContext));
93 return instance.pipe(
94 Effect.provide(instanceContext),
95 Effect.ensuring(Effect.sync(seal)),
96 );
97 }),
98 ),
99 Effect.map((instance) => ({
100 instance,
101 services: Context.add(services, RuntimeContext, instanceRuntimeContext),
102 context,
103 telemetry,
104 })),
105 Effect.runPromise,
106 );
107 },
108 ),
109 );
110
111 return new Proxy(this, {
112 get: (target, prop) => {
113 const bind = (f: any) => (typeof f === "function" ? f.bind(target) : f);
114 if (typeof prop !== "string") return bind((target as any)[prop]);
115 if (prop in target) return bind((target as any)[prop]);
116 return (...callArgs: unknown[]) => {
117 // A stub appends the caller's trace context; one from an older
118 // deploy doesn't, and its call starts a trace of its own.
119 const [args, parent] = takeRpcTraceContext(callArgs);
120 return this.#execute(
121 (instance) =>
122 Effect.suspend(() => {
123 if (!Object.hasOwn(instance, prop)) {
124 return Effect.die(new Error(`Method "${prop}" not found on Durable Object`));
125 }
126 const member = instance[prop as keyof DurableObjectShape];
127 const result =
128 typeof member === "function"
129 ? (member as (...args: unknown[]) => unknown)(...args)
130 : member;
131 // Effects (including nested-RPC values built by
132 // `asEffectOrStream`, which are Effects branded as Streams)
133 // run as effects; a genuine Stream is lifted into the
134 // success channel for `handleRpcExit` to encode. The RPC
135 // Shape constraint rejects any other member at
136 // declaration, so anything else got past it with a cast.
137 if (Effect.isEffect(result)) return result;
138 if (Stream.isStream(result)) return Effect.succeed(result);
139 return Effect.die(
140 new Error(
141 `Durable Object RPC member "${prop}" must return an Effect or a Stream`,
142 ),
143 );
144 }).pipe((effect) =>
145 Option.isSome(parent) ? Effect.withParentSpan(effect, parent.value) : effect,
146 ),
147 handleRpcExit,
148 );
149 };
150 },
151 });
152 }
153
154 async #execute(
155 fn: (instance: DurableObjectShape) => Effect.Effect<any, any, any>,
156 onExit?: (exit: Exit.Exit<any, any>, scope: Scope.Closeable) => Promise<any>,
157 ) {
158 const scope = Scope.makeUnsafe();
159 // Work this call hands to `waitUntil` runs after it returns, in its
160 // context, so it records into this call's telemetry. The exporters get
161 // a scope of their own, flushed once that work (and any it starts)
162 // settles; the call's scope closes as soon as the call does.
163 const telemetryScope = Scope.makeUnsafe();
164 const background: Array<Promise<unknown>> = [];
165 const settled = async () => {
166 for (let seen = 0; seen < background.length;) {
167 const batch = background.slice(seen);
168 seen = background.length;
169 await Promise.allSettled(batch);
170 }
171 };
172 // However the call's scope closes (here, or later by whoever ejected
173 // it), flush telemetry once the background work has settled, without
174 // holding up the close.
175 Effect.runSync(
176 Scope.addFinalizer(
177 scope,
178 Effect.sync(() =>
179 this.ctx.waitUntil(
180 settled().then(() => Effect.runPromise(Scope.close(telemetryScope, Exit.void))),
181 ),
182 ),
183 ),
184 );
185
186 const { instance, services, context, telemetry } = await this.#instance;
187
188 return fn(instance)
189 .pipe(
190 Effect.provide(
191 Layer.mergeAll(
192 Layer.succeed(DurableObjectState, fromDurableObjectState(this.#state)),
193 Layer.succeed(BackgroundWork, (promise) => void background.push(promise)),
194 Layer.succeed(Scope.Scope, scope),
195 // The configured telemetry exporters, on their own scope:
196 // flushed into `waitUntil` once the call's scope has closed and
197 // its background work has settled (the isolate scope never
198 // finalizes on workerd).
199 Layer.effectContext(buildEventTelemetry(context, telemetryScope, telemetry())),
200 ).pipe(
201 Layer.provideMerge(Layer.succeedContext(services)),
202 Layer.provideMerge(Layer.succeedContext(context)),
203 ),
204 ),
205 Effect.runPromiseExit,
206 )
207 .then((exit) =>
208 onExit
209 ? onExit(exit, scope)
210 : exit._tag === "Success"
211 ? Promise.resolve(exit.value)
212 : Promise.reject(Cause.squash(exit.cause)),
213 )
214 .finally(() =>
215 isScopeEjected(scope)
216 ? undefined
217 : this.ctx.waitUntil(
218 // Match WorkerBridge: yield one macrotask so the
219 // HttpMiddleware tracer's late span-end reaches the
220 // telemetry exporter before the scope's flush finalizer.
221 new Promise((resolve) => setTimeout(resolve, 0)).then(() =>
222 Effect.runPromise(Scope.close(scope, Exit.void)),
223 ),
224 ),
225 );
226 }
227
228 async fetch(request: Request): Promise<any> {
229 return this.#execute((instance) =>
230 instance.fetch
231 ? makeRequestEffect(request as any, instance.fetch)
232 : Effect.succeed(
233 HttpServerResponse.text("Not implemented", {
234 status: 404,
235 }),
236 ),
237 );
238 }
239
240 async alarm(alarmInfo?: cf.AlarmInvocationInfo) {
241 return this.#execute((instance) =>
242 dispatchAlarmCallbacks(this.#state, instance.alarm !== undefined).pipe(
243 Effect.andThen(() => instance.alarm?.(alarmInfo) ?? Effect.void),
244 ),
245 );
246 }
247
248 async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) {
249 return this.#execute(
250 (instance) =>
251 instance.webSocketMessage?.(fromWebSocket(ws as any), message) ?? Effect.void,
252 );
253 }
254
255 async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean) {
256 return this.#execute(
257 (instance) =>
258 instance.webSocketClose?.(fromWebSocket(ws as any), code, reason, wasClean) ??
259 Effect.void,
260 );
261 }
262
263 async webSocketError(ws: WebSocket, error: unknown) {
264 return this.#execute(
265 (instance) => instance.webSocketError?.(fromWebSocket(ws as any), error) ?? Effect.void,
266 );
267 }
268 } as any;
269 };