@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, 04:45 UTC

main
ts 201 lines 7.78 KB
Raw
1 import * as Data from "effect/Data";
2 import * as Effect from "effect/Effect";
3 import * as FetchHttpClient from "effect/http/FetchHttpClient";
4 import * as HttpClient from "effect/http/HttpClient";
5 import { DecodeError, HttpClientError } from "effect/http/HttpClientError";
6 import * as HttpClientRequest from "effect/http/HttpClientRequest";
7 import type { HttpClientResponse } from "effect/http/HttpClientResponse";
8 import * as Layer from "effect/Layer";
9 import * as RpcClient from "effect/rpc/RpcClient";
10 import * as RpcSerialization from "effect/rpc/RpcSerialization";
11 import * as Schedule from "effect/Schedule";
12
13 /**
14 * A freshly-deployed Cloudflare Worker is not instantly reachable over HTTP.
15 * Its `workers.dev` route, the script, and each binding (R2 / D1 / DO / Secrets
16 * Store) propagate to the edge independently and asynchronously, so the first
17 * requests to a new URL can transiently return:
18 *
19 * - `404` while the `workers.dev` subdomain / route is still propagating
20 * (Cloudflare serves its "There is nothing here yet" placeholder), or
21 * - `5xx` while the script is up but a binding it depends on isn't ready yet.
22 *
23 * This is ordinary eventual consistency that belongs at the call site, not in
24 * the resource provider — the provider returning before every edge PoP has
25 * converged is correct. Consumers ride out the window by retrying the request.
26 */
27 export class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{ status: number }> {}
28
29 /**
30 * Status codes that indicate the edge hasn't finished converging on a fresh
31 * deploy. Deliberate client errors (`401`, `403`, `400`, …) are NOT in this
32 * set, so assertions on those statuses still observe them immediately rather
33 * than being retried away.
34 */
35 const isColdStartStatus = (status: number): boolean => status === 404 || status >= 500;
36
37 export interface WhenReadyOptions {
38 /** Max retry attempts before surfacing {@link WorkerNotReady}. Default `20`. */
39 times?: number;
40 }
41
42 /**
43 * Execute an arbitrary {@link HttpClientRequest.HttpClientRequest}, retrying
44 * through the Cloudflare cold-start window ({@link isColdStartStatus}) until the
45 * Worker serves a non-transient response. The returned response can carry any
46 * non-cold-start status (e.g. `200`, `202`, `401`) for the caller to assert on.
47 */
48 export const executeWhenReady = (
49 request: HttpClientRequest.HttpClientRequest,
50 options?: WhenReadyOptions,
51 ): Effect.Effect<HttpClientResponse, unknown, HttpClient.HttpClient> =>
52 Effect.gen(function* () {
53 const client = yield* HttpClient.HttpClient;
54 return yield* client.execute(request).pipe(
55 Effect.flatMap((response) =>
56 isColdStartStatus(response.status)
57 ? Effect.fail(new WorkerNotReady({ status: response.status }))
58 : Effect.succeed(response),
59 ),
60 Effect.retry({
61 while: (error) => error instanceof WorkerNotReady,
62 schedule: Schedule.max([
63 Schedule.exponential("500 millis"),
64 Schedule.recurs(options?.times ?? 20),
65 ]),
66 }),
67 );
68 });
69
70 /**
71 * Convenience wrapper over {@link executeWhenReady} for a plain `GET`.
72 */
73 export const getWhenReady = (
74 url: string,
75 options?: WhenReadyOptions,
76 ): Effect.Effect<HttpClientResponse, unknown, HttpClient.HttpClient> =>
77 executeWhenReady(HttpClientRequest.get(url), options);
78
79 /**
80 * Options for the edge-transient response guard applied by
81 * {@link guardContentType} / {@link rpcClientLayer}. Pass per suite via
82 * `Test.make({ http: { ... } })` or per call site.
83 */
84 export interface EdgeGuardOptions {
85 /**
86 * Retry schedule for edge-transient responses (and transport errors).
87 * Default: exponential from 500ms capped at 3s.
88 */
89 schedule?: Schedule.Schedule<unknown, unknown>;
90 /** Max transport-level retry attempts. Default `5`. */
91 times?: number;
92 }
93
94 const defaultGuardSchedule = Schedule.min([
95 Schedule.exponential("500 millis"),
96 Schedule.spaced("3 seconds"),
97 ]);
98
99 /**
100 * Guard an `HttpClient` against edge-generated bodies on a freshly deployed
101 * Worker URL.
102 *
103 * Protocol clients like effect RPC's `layerProtocolHttp` never inspect the
104 * response status or content-type — they pipe the raw body straight into the
105 * serialization parser, so every edge-generated HTML page (the workers.dev
106 * placeholder, which serves with HTTP **200**; 1101/1102 error pages;
107 * 429/1015 rate limits) surfaces as an opaque decode defect (e.g.
108 * `RpcClientDefect: Error decoding HTTP response`).
109 *
110 * This transform rejects any response whose `content-type` doesn't match the
111 * expected one as a typed `HttpClientError` that records the status + a body
112 * snippet — so a failure names its cause — and retries the request through a
113 * bounded schedule so callers ride out the cold-start window
114 * ({@link WorkerNotReady} documents why this belongs at the call site).
115 */
116 export const guardContentType =
117 (contentType: string, options?: EdgeGuardOptions) =>
118 (client: HttpClient.HttpClient): HttpClient.HttpClient =>
119 client.pipe(
120 HttpClient.transform((effect, request) =>
121 Effect.flatMap(effect, (response) => {
122 const observed = response.headers["content-type"] ?? "";
123 if (observed.includes(contentType)) {
124 return Effect.succeed(response);
125 }
126 return response.text.pipe(
127 Effect.orElseSucceed(() => "<unreadable body>"),
128 Effect.flatMap((body) =>
129 Effect.fail(
130 new HttpClientError({
131 reason: new DecodeError({
132 request,
133 response,
134 description: `expected "${contentType}", got "${observed}" (status ${response.status}): ${body.slice(0, 200)}`,
135 }),
136 }),
137 ),
138 ),
139 );
140 }),
141 ),
142 HttpClient.retry({
143 schedule: options?.schedule ?? defaultGuardSchedule,
144 times: options?.times ?? 5,
145 }),
146 );
147
148 /**
149 * A fetch-backed `HttpClient` layer wrapped with {@link guardContentType}.
150 *
151 * Deliberately a standalone layer rather than a transform of the ambient
152 * test `HttpClient`: the ambient client also serves the engine's own cloud
153 * API calls during `deploy`/`destroy` and distilled SDK calls in
154 * `test.provider` bodies, which must NOT be subjected to this guard.
155 */
156 export const guardedFetchLayer = (
157 contentType: string,
158 options?: EdgeGuardOptions,
159 ): Layer.Layer<HttpClient.HttpClient> =>
160 Layer.effect(HttpClient.HttpClient)(
161 Effect.gen(function* () {
162 const client = yield* HttpClient.HttpClient;
163 return guardContentType(contentType, options)(client);
164 }),
165 ).pipe(Layer.provide(FetchHttpClient.layer));
166
167 /**
168 * Complete RPC-over-HTTP client transport for driving a deployed Worker:
169 * `RpcClient.layerProtocolHttp` + the given serialization (ndjson by
170 * default) + a {@link guardedFetchLayer} expecting that serialization's
171 * content-type.
172 *
173 * ```ts
174 * const client = yield* RpcClient.make(WorkerRpcs);
175 * // ...
176 * }).pipe(Effect.scoped, Effect.provide(Test.Http.rpcClientLayer(url)));
177 * ```
178 */
179 export const rpcClientLayer = (
180 url: string,
181 options?: EdgeGuardOptions & {
182 /** RPC wire serialization. Default {@link RpcSerialization.ndjson}. */
183 serialization?: RpcSerialization.RpcSerialization["Service"];
184 /**
185 * Set `false` to skip the edge guard entirely and use a plain fetch
186 * transport — e.g. for a test that asserts on the raw edge behavior
187 * itself. Default `true`.
188 */
189 guard?: boolean;
190 },
191 ): Layer.Layer<RpcClient.Protocol> => {
192 const serialization = options?.serialization ?? RpcSerialization.ndjson;
193 return RpcClient.layerProtocolHttp({ url }).pipe(
194 Layer.provide(
195 options?.guard === false
196 ? FetchHttpClient.layer
197 : guardedFetchLayer(serialization.contentType, options),
198 ),
199 Layer.provide(Layer.succeed(RpcSerialization.RpcSerialization, serialization)),
200 );
201 };