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

main
ts 153 lines 6.69 KB
Raw
1 import type * as cf from "@cloudflare/workers-types";
2 import type { RuntimeContext } from "alchemy/RuntimeContext";
3 import * as Context from "effect/Context";
4 import * as Effect from "effect/Effect";
5 import * as Option from "effect/Option";
6 import { fromDurableObjectStorage, type DurableObjectStorage } from "./DurableObjectStorage.ts";
7 import { fromWebSocket, type WebSocket } from "./WebSocket.ts";
8 import {
9 getLoopbackEntrypoint,
10 makeEntrypointExports,
11 type EntrypointExports,
12 } from "./WorkerRuntime.ts";
13
14 /**
15 * Options for {@link DurableObjectState.abort}.
16 *
17 * `retryAlarm` defaults to `true`: an alarm interrupted by `abort` is
18 * retried after the isolate resets. Set it to `false` to cancel that
19 * alarm instead.
20 */
21 export type DurableObjectAbortOptions = cf.DurableObjectAbortOptions;
22
23 export class DurableObjectState extends Context.Service<
24 DurableObjectState,
25 {
26 readonly id: cf.DurableObjectId;
27 readonly storage: DurableObjectStorage;
28 container?: cf.Container;
29 /**
30 * Run an Effect in the background without blocking the current event,
31 * keeping the Durable Object alive until it settles. The Effect runs with
32 * the caller's full context (services, tracing), and the resulting
33 * promise is registered with workerd's `state.waitUntil`.
34 */
35 waitUntil<A, E, R>(
36 effect: Effect.Effect<A, E, R>,
37 ): Effect.Effect<void, never, R | RuntimeContext>;
38 /**
39 * The entrypoints of the Worker hosting this Durable Object (workerd's
40 * `ctx.exports`): `yield* ctx.exports.default({ props })` mints a stub to
41 * the host Worker's own Effect handlers that delivers `props` as the
42 * target's `ctx.props`. The `Cloudflare.Fetcher` can be passed to APIs that
43 * route traffic to a Worker entrypoint, such as this object's container
44 * `interceptOutboundHttps`; its `raw` is the native `Fetcher`.
45 */
46 readonly exports: EntrypointExports;
47 /**
48 * The raw workerd DurableObjectState, for interop with async APIs.
49 */
50 readonly raw: cf.DurableObjectState;
51 /**
52 * Run `callback` while workerd holds every other event on this object.
53 * The callback runs with the caller's full context (services, tracing),
54 * as `waitUntil` does, so a service provided to the calling fiber is
55 * visible inside the gate. A defect in the callback rejects the gate
56 * and workerd resets the object, which is the platform's contract.
57 */
58 blockConcurrencyWhile<T, R = never>(
59 callback: () => Effect.Effect<T, never, R>,
60 ): Effect.Effect<T, never, R | RuntimeContext>;
61 acceptWebSocket(ws: WebSocket, tags?: string[]): Effect.Effect<void, never, RuntimeContext>;
62 getWebSockets(tag?: string): Effect.Effect<WebSocket[], never, RuntimeContext>;
63 setWebSocketAutoResponse(
64 maybeReqResp?: cf.WebSocketRequestResponsePair,
65 ): Effect.Effect<void, never, RuntimeContext>;
66 getWebSocketAutoResponse(): Effect.Effect<
67 cf.WebSocketRequestResponsePair | null,
68 never,
69 RuntimeContext
70 >;
71 getWebSocketAutoResponseTimestamp(
72 ws: cf.WebSocket,
73 ): Effect.Effect<Date | null, never, RuntimeContext>;
74 setHibernatableWebSocketEventTimeout(
75 timeoutMs?: number,
76 ): Effect.Effect<void, never, RuntimeContext>;
77 getHibernatableWebSocketEventTimeout(): Effect.Effect<number | null, never, RuntimeContext>;
78 getTags(ws: cf.WebSocket): Effect.Effect<string[], never, RuntimeContext>;
79 /**
80 * Forcibly reset this Durable Object. A JavaScript `Error` with the
81 * given message is logged and cannot be caught in application code.
82 *
83 * By default an in-progress alarm retries after the reset. Pass
84 * `{ retryAlarm: false }` to stop it instead — for example an `alarm`
85 * handler that deletes storage so the constructor does not recreate it.
86 */
87 abort(
88 reason?: string,
89 options?: DurableObjectAbortOptions,
90 ): Effect.Effect<void, never, RuntimeContext>;
91 }
92 >()("Cloudflare.DurableObjectState") {}
93
94 /**
95 * Told of every promise the current event hands to `waitUntil`, so the event
96 * keeps its telemetry open until that work settles. Provided per event by
97 * the bridge, and read from the calling fiber, so it works for state
98 * captured when the object was constructed too.
99 *
100 * @internal
101 */
102 export class BackgroundWork extends Context.Service<
103 BackgroundWork,
104 (promise: Promise<unknown>) => void
105 >()("Cloudflare.DurableObjectState/BackgroundWork") {}
106
107 export const fromDurableObjectState = (
108 state: cf.DurableObjectState,
109 ): DurableObjectState["Service"] => ({
110 id: state.id,
111 container: state.container,
112 storage: fromDurableObjectStorage(state.storage),
113 raw: state,
114 exports: makeEntrypointExports((name, options) =>
115 getLoopbackEntrypoint(state.exports, name, options),
116 ),
117 waitUntil: <A, E, R>(effect: Effect.Effect<A, E, R>) =>
118 Effect.gen(function* () {
119 const context = yield* Effect.context<R>();
120 // Register the promise with workerd un-awaited — waitUntil extends the
121 // event's lifetime without blocking the caller.
122 const track = yield* Effect.serviceOption(BackgroundWork);
123 yield* Effect.sync(() => {
124 const promise = Effect.runPromiseWith(context)(effect);
125 if (Option.isSome(track)) track.value(promise);
126 state.waitUntil(promise);
127 });
128 }),
129 blockConcurrencyWhile: <T, R = never>(callback: () => Effect.Effect<T, never, R>) =>
130 Effect.gen(function* () {
131 const context = yield* Effect.context<R>();
132 // The failure is typed away as before: a rejected gate is the
133 // platform resetting the object, not a value a caller handles.
134 return yield* Effect.promise(() =>
135 state.blockConcurrencyWhile(() => Effect.runPromiseWith(context)(callback())),
136 );
137 }),
138 acceptWebSocket: (ws: WebSocket, tags?: string[]) =>
139 Effect.sync(() => state.acceptWebSocket(ws.ws, tags)),
140 getWebSockets: (tag?: string) => Effect.sync(() => state.getWebSockets(tag).map(fromWebSocket)),
141 setWebSocketAutoResponse: (maybeReqResp?: cf.WebSocketRequestResponsePair) =>
142 Effect.sync(() => state.setWebSocketAutoResponse(maybeReqResp)),
143 getWebSocketAutoResponse: () => Effect.sync(() => state.getWebSocketAutoResponse()),
144 getWebSocketAutoResponseTimestamp: (ws: cf.WebSocket) =>
145 Effect.sync(() => state.getWebSocketAutoResponseTimestamp(ws)),
146 setHibernatableWebSocketEventTimeout: (timeoutMs?: number) =>
147 Effect.sync(() => state.setHibernatableWebSocketEventTimeout(timeoutMs)),
148 getHibernatableWebSocketEventTimeout: () =>
149 Effect.sync(() => state.getHibernatableWebSocketEventTimeout()),
150 getTags: (ws: cf.WebSocket) => Effect.sync(() => state.getTags(ws)),
151 abort: (reason?: string, options?: DurableObjectAbortOptions) =>
152 Effect.sync(() => state.abort(reason, options)),
153 });