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

main
ts 174 lines 6.15 KB
Raw
1 import type * as cf from "@cloudflare/workers-types";
2 import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import * as HttpBody from "effect/http/HttpBody";
5 import * as HttpServerResponse from "effect/http/HttpServerResponse";
6 import * as Schema from "effect/Schema";
7 import { DurableObjectState } from "./DurableObjectState.ts";
8
9 export type RawWebSocket = cf.WebSocket;
10
11 /**
12 * An application attachment could not be encoded, decoded, read, or written.
13 * Catch this tag to choose whether to fail, ignore the attachment, or close the
14 * connection. Codec failures and native exceptions are preserved in `cause`.
15 */
16 export class WebSocketAttachmentError extends Data.TaggedError("WebSocketAttachmentError")<{
17 /** The failed attachment operation, or `missing` for a nullish attachment. */
18 readonly reason: "encode" | "decode" | "missing" | "read" | "write";
19 /** A description of the failed operation. */
20 readonly message: string;
21 /** The original schema error or native exception, when present. */
22 readonly cause?: unknown;
23 }> {}
24
25 export interface WebSocket {
26 readonly ws: RawWebSocket;
27 send(data: string | Uint8Array): Effect.Effect<void>;
28 close(code: number, reason: string): Effect.Effect<void>;
29 /**
30 * Encode an application value and persist the encoded representation alongside
31 * this socket. The native structured-clone and serialized-size limits apply;
32 * schema validation does not guarantee that the encoded value is cloneable.
33 * Requires only the codec's encoding services. Does not close the socket.
34 *
35 * @example
36 * ```ts
37 * yield* socket.setAttachment(Schema.NumberFromString, 42);
38 * // The unchecked deserializeAttachment() now returns "42".
39 * ```
40 */
41 setAttachment<S extends Schema.Constraint>(
42 schema: S,
43 value: NoInfer<S["Type"]>,
44 ): Effect.Effect<void, WebSocketAttachmentError, S["EncodingServices"]>;
45 /**
46 * Read and decode an application attachment, including after hibernation.
47 * A nullish native value fails with reason `missing`; other values are decoded
48 * from the codec's encoded side. Requires only its decoding services.
49 * No envelope or schema version is added, so unchecked attachments interoperate
50 * and applications own migrations and invalid-attachment policy.
51 *
52 * @example
53 * ```ts
54 * const count = yield* socket.getAttachment(Schema.NumberFromString);
55 * // count is a number, not the stored string.
56 * ```
57 */
58 getAttachment<S extends Schema.Constraint>(
59 schema: S,
60 ): Effect.Effect<S["Type"], WebSocketAttachmentError, S["DecodingServices"]>;
61 serializeAttachment<T>(value: T): void;
62 deserializeAttachment<T>(): T | null;
63 }
64
65 export const fromWebSocket = (ws: RawWebSocket): WebSocket => ({
66 ws,
67 send: (data) => Effect.sync(() => ws.send(data as any)),
68 close: (code, reason) => Effect.sync(() => ws.close(code, reason)),
69 setAttachment: (schema, value) =>
70 Schema.encodeEffect(schema)(value).pipe(
71 Effect.mapError(
72 (cause) =>
73 new WebSocketAttachmentError({
74 reason: "encode",
75 message: "Could not encode WebSocket attachment",
76 cause,
77 }),
78 ),
79 Effect.flatMap((encoded) =>
80 Effect.try({
81 try: () => ws.serializeAttachment(encoded),
82 catch: (cause) =>
83 new WebSocketAttachmentError({
84 reason: "write",
85 message: "Could not write WebSocket attachment",
86 cause,
87 }),
88 }),
89 ),
90 ),
91 getAttachment: (schema) =>
92 Effect.try({
93 try: () => ws.deserializeAttachment(),
94 catch: (cause) =>
95 new WebSocketAttachmentError({
96 reason: "read",
97 message: "Could not read WebSocket attachment",
98 cause,
99 }),
100 }).pipe(
101 Effect.flatMap((encoded) =>
102 encoded === null || encoded === undefined
103 ? Effect.fail(
104 new WebSocketAttachmentError({
105 reason: "missing",
106 message: "WebSocket attachment is missing",
107 }),
108 )
109 : Schema.decodeUnknownEffect(schema)(encoded).pipe(
110 Effect.mapError(
111 (cause) =>
112 new WebSocketAttachmentError({
113 reason: "decode",
114 message: "Could not decode WebSocket attachment",
115 cause,
116 }),
117 ),
118 ),
119 ),
120 ),
121 serializeAttachment: (value) => ws.serializeAttachment(value),
122 deserializeAttachment: () => ws.deserializeAttachment() as any,
123 });
124
125 // declare global {
126 // const WebSocketPair: new () => [cf.WebSocket, cf.WebSocket];
127 // }
128
129 export interface UpgradeOptions {
130 /**
131 * Hibernation tags for the accepted socket. Look up every socket with a tag
132 * via `state.getWebSockets(tag)` and read a socket's tags with
133 * `state.getTags(socket.ws)`; both work after the Durable Object wakes from
134 * hibernation, so group membership needs no in-memory state.
135 *
136 * Cloudflare allows at most 10 tags per WebSocket, each at most 256
137 * characters.
138 */
139 readonly tags?: ReadonlyArray<string>;
140 }
141
142 /**
143 * Accept a hibernatable WebSocket in a Durable Object's `fetch` handler.
144 * Returns the `101 Switching Protocols` response to return from `fetch`, and
145 * the server-side socket.
146 *
147 * @example
148 * ```ts
149 * const [response, socket] = yield* Cloudflare.upgrade({
150 * tags: [`user:${userId}`, "role:admin"],
151 * });
152 * // Later, even after hibernation:
153 * for (const peer of yield* state.getWebSockets("role:admin")) {
154 * yield* peer.send("hello admins");
155 * }
156 * ```
157 */
158 export const upgrade = Effect.fn(function* (options?: UpgradeOptions) {
159 const _Response = Response as any as typeof cf.Response;
160 const ctx = yield* DurableObjectState;
161 // @ts-expect-error
162 const [client, server] = new WebSocketPair();
163 const serverSocket = fromWebSocket(server);
164 yield* ctx.acceptWebSocket(serverSocket, options?.tags ? [...options.tags] : undefined);
165 const rawResponse = new _Response(null, {
166 status: 101,
167 webSocket: client,
168 });
169 const effectResponse = HttpServerResponse.setBody(
170 HttpServerResponse.empty({ status: 101 }),
171 HttpBody.raw(rawResponse),
172 );
173 return [effectResponse, serverSocket] as const;
174 });