@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 262 lines 10.5 KB
Raw
1 import type * as cf from "@cloudflare/workers-types";
2 import * as Cause from "effect/Cause";
3 import * as Effect from "effect/Effect";
4 import { pipe } from "effect/Function";
5 import * as HttpBody from "effect/http/HttpBody";
6 import * as HttpClient from "effect/http/HttpClient";
7 import { HttpClientError, TransportError } from "effect/http/HttpClientError";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import * as HttpClientResponse from "effect/http/HttpClientResponse";
10 import type { HttpServerError } from "effect/http/HttpServerError";
11 import * as HttpServerRequest from "effect/http/HttpServerRequest";
12 import * as HttpServerResponse from "effect/http/HttpServerResponse";
13 import * as Schedule from "effect/Schedule";
14 import * as Socket from "effect/socket/Socket";
15
16 export type SocketAddress = cf.SocketAddress;
17
18 export type SocketOptions = cf.SocketOptions;
19
20 /**
21 * Whether a native Web `Headers` and an Effect headers record carry the
22 * same entries. Lets {@link makeFetcher} keep forwarding the platform's
23 * own request object when `request.modify` left the headers unchanged,
24 * and rebuild only when they genuinely differ. Effect header keys are
25 * already lowercased and `Headers.get` is case-insensitive, so the
26 * comparison needs no normalization.
27 */
28 const sameHeaders = (web: Headers, eff: Readonly<Record<string, string>>): boolean => {
29 const keys = Object.keys(eff);
30 let webCount = 0;
31 for (const _ of web.keys()) {
32 webCount++;
33 if (webCount > keys.length) return false;
34 }
35 if (webCount !== keys.length) return false;
36 for (const key of keys) {
37 if (web.get(key) !== eff[key]) return false;
38 }
39 return true;
40 };
41
42 export interface Fetcher {
43 raw: cf.Fetcher;
44 fetch(
45 request: HttpClientRequest.HttpClientRequest,
46 ): Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError>;
47 fetch(
48 request: HttpServerRequest.HttpServerRequest,
49 ): Effect.Effect<HttpServerResponse.HttpServerResponse, HttpServerError>;
50
51 connect(address: SocketAddress | string, options?: SocketOptions): Socket.Socket;
52 }
53
54 export const toCloudflareFetcher = Effect.fn(function* (fetcher: Fetcher) {
55 const context = yield* Effect.context();
56 return {
57 fetch: (input, init) =>
58 fetcher
59 .fetch(HttpServerRequest.fromWeb(new Request(input as any, init as any) as any as Request))
60 .pipe(
61 Effect.map(
62 (response) => HttpServerResponse.toWeb(response, { context }) as any as cf.Response,
63 ),
64 Effect.provideContext(context),
65 Effect.runPromise,
66 ),
67 connect() {
68 // TODO
69 throw new Error("toCloudflareFetcher does not support connect()");
70 },
71 } satisfies cf.Fetcher;
72 });
73
74 export const fromCloudflareFetcher = (fetcher: cf.Fetcher | globalThis.Fetcher): Fetcher => {
75 const fetch = (request: Request) =>
76 Effect.suspend(() => {
77 // Clone per attempt, keeping `request` pristine: the HandlerNotReady
78 // retry below re-runs this suspend, and replaying a Request whose body
79 // the failed attempt already consumed makes workerd reject with
80 // "TypeError: Cannot reconstruct a Request with a used body".
81 const attempt = request.clone() as Request;
82 return Effect.promise((signal) =>
83 (fetcher as globalThis.Fetcher).fetch(attempt, { signal: signal }),
84 );
85 }).pipe(
86 // The "Handler does not export a fetch()" window is a property of
87 // invoking a freshly-deployed Cloudflare binding, so it is ridden out
88 // HERE — the one adapter every binding flows through — rather than in any
89 // single higher-level wrapper (`toHttpClient`, the client/server
90 // overloads, the RPC DO transport all go through this). `Effect.promise`
91 // surfaces the rejection as a defect; lift it to a typed retryable error
92 // and back off until the new version propagates. The request never
93 // reached a handler, so nothing committed — safe to retry. This wraps
94 // only the promise, leaving the response (and its streaming body)
95 // untouched, so RPC/stream decoding is unaffected. After the budget is
96 // exhausted, re-raise the original defect unchanged.
97 Effect.catchCause((cause) => {
98 const squashed = Cause.squash(cause);
99 return isHandlerNotReady(squashed)
100 ? Effect.fail(new HandlerNotReady(squashed))
101 : Effect.failCause(cause);
102 }),
103 Effect.retry({
104 while: (error) => error instanceof HandlerNotReady,
105 schedule: Schedule.exponential("100 millis"),
106 times: 8,
107 }),
108 Effect.catch((error) =>
109 error instanceof HandlerNotReady
110 ? Effect.die(error.cause)
111 : Effect.failCause(Cause.fail(error)),
112 ),
113 );
114
115 return {
116 raw: fetcher as cf.Fetcher,
117 connect: (address, options) => fromCloudflareSocket(fetcher.connect(address, options)),
118 fetch: (
119 request: HttpClientRequest.HttpClientRequest | HttpServerRequest.HttpServerRequest,
120 ): any =>
121 HttpClientRequest.isHttpClientRequest(request)
122 ? request.pipe(
123 HttpServerRequest.fromClientRequest,
124 HttpServerRequest.toWeb,
125 Effect.flatMap(fetch),
126 Effect.map((response) =>
127 HttpClientResponse.fromWeb(request, response as any as Response),
128 ),
129 Effect.catch((error) =>
130 Effect.succeed(
131 HttpClientResponse.fromWeb(
132 request,
133 new Response(error.message, {
134 status:
135 error._tag === "InternalError"
136 ? 500
137 : error._tag === "RequestParseError"
138 ? 400
139 : 404,
140 }),
141 ),
142 ),
143 ),
144 )
145 : pipe(
146 HttpServerRequest.toWeb(request),
147 // `toWeb` hands back the raw native request untouched whenever
148 // there is one (always, on workerd) — the fast path we WANT:
149 // it forwards the platform's own edge request instead of
150 // cloning it. The catch is that it also ignores header
151 // overrides from `request.modify({ headers })`, so a caller
152 // that strips or mints an internal header before forwarding
153 // (e.g. a Worker sanitizing a trust header for its Durable
154 // Object) would be silently dropped. Rebuild ONLY when the
155 // effect request's headers actually differ from the native
156 // request's; an unmodified forward (or a modify that was a
157 // no-op) stays on the metal. `new Request(req, init)`
158 // preserves the method and un-consumed streaming body.
159 Effect.map((webRequest) =>
160 sameHeaders(webRequest.headers, request.headers)
161 ? webRequest
162 : new Request(webRequest, { headers: request.headers as Record<string, string> }),
163 ),
164 Effect.flatMap(fetch),
165 Effect.map((response) => {
166 if ((response as any).status === 101) {
167 return HttpServerResponse.setBody(
168 HttpServerResponse.empty({ status: 101 }),
169 HttpBody.raw(response),
170 );
171 }
172 return HttpServerResponse.fromWeb(response as any as Response);
173 }),
174 ),
175 };
176 };
177
178 /**
179 * A freshly-deployed Durable Object / service script is eventually consistent:
180 * for a short window after deploy, workerd can route a `.fetch()` to a stale
181 * script version whose class has no fetch handler yet, surfacing as
182 * "Handler does not export a fetch() function." It clears within seconds once
183 * the new version propagates, so it is safe to retry.
184 */
185 const isHandlerNotReady = (error: unknown): boolean => {
186 const message =
187 error instanceof Error
188 ? error.message
189 : typeof error === "string"
190 ? error
191 : typeof (error as { message?: unknown } | null)?.message === "string"
192 ? ((error as { message: string }).message as string)
193 : "";
194 return message.includes("does not export a fetch");
195 };
196
197 /**
198 * Adapt anything that exposes a server-shaped `fetch` (e.g. a Durable Object
199 * stub, a Worker service binding) into an Effect `HttpClient`. Lets HttpApi
200 * clients address bindings without a base URL via `transformClient`.
201 */
202 class HandlerNotReady {
203 readonly _tag = "HandlerNotReady";
204 constructor(readonly cause: unknown) {}
205 }
206
207 export const toHttpClient = (fetcher: {
208 fetch: (
209 request: HttpServerRequest.HttpServerRequest,
210 ) => Effect.Effect<HttpServerResponse.HttpServerResponse, HttpServerError>;
211 }) =>
212 HttpClient.make((request) =>
213 Effect.suspend(() =>
214 // Rebuild the server request on every attempt so a retry re-serializes
215 // the body instead of replaying a consumed one.
216 fetcher
217 .fetch(HttpServerRequest.fromClientRequest(request))
218 .pipe(
219 Effect.map((response) =>
220 HttpClientResponse.fromWeb(request, HttpServerResponse.toWeb(response)),
221 ),
222 ),
223 ).pipe(
224 // The handler-not-ready window is already ridden out at the lowest level
225 // (the `fromCloudflareFetcher` promise retries `HandlerNotReady` before
226 // it ever reaches here). A `HandlerNotReady` still surfacing means the
227 // budget was exhausted — it arrives as a defect (re-raised rejected
228 // promise), so convert it (and any other failure cause) into a typed
229 // transport error rather than retrying again.
230 Effect.catchCause((cause) => {
231 const squashed = Cause.squash(cause);
232 return Effect.fail(
233 new HttpClientError({
234 reason: new TransportError({
235 request,
236 cause: isHandlerNotReady(squashed) ? (squashed as { message?: unknown }) : squashed,
237 description: "Fetcher-backed HttpClient request failed",
238 }),
239 }),
240 );
241 }),
242 ),
243 );
244
245 export const fromCloudflareSocket = (cfSocket: globalThis.Socket | cf.Socket): Socket.Socket =>
246 // `fromTransformStream` snapshots fiber context, then waits to acquire
247 // the streams until a consumer opens the reader. `runSync` is only that
248 // snapshot — connection still happens on first `socket.reader`.
249 Effect.tryPromise({
250 try: () =>
251 Promise.resolve(cfSocket.opened).then(
252 () =>
253 ({
254 readable: cfSocket.readable,
255 writable: cfSocket.writable,
256 }) as Socket.InputTransformStream,
257 ),
258 catch: (cause) =>
259 Socket.SocketError.make({
260 reason: Socket.SocketOpenError.make({ kind: "Unknown", cause }),
261 }),
262 }).pipe(Socket.fromTransformStream, Effect.runSync);