The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment"; |
| 3 | import { CloudflareApiLive } from "@alchemy.run/cloudflare/Providers"; |
| 4 | import { expect } from "@alchemy.run/test"; |
| 5 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 6 | import * as workers from "@distilled.cloud/cloudflare/workers"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Exit from "effect/Exit"; |
| 9 | import * as HttpClient from "effect/http/HttpClient"; |
| 10 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 11 | import { MinimumLogLevel } from "effect/References"; |
| 12 | import * as Schedule from "effect/Schedule"; |
| 13 | import { requestWorker } from "../Utils/WorkerRequest.ts"; |
| 14 | import { A as AsyncCycleA, B as AsyncCycleB } from "./fixtures/async-circular-bindings/stack.ts"; |
| 15 | import Stack from "./fixtures/worker-worker-binding/stack.ts"; |
| 16 | |
| 17 | const { test, beforeAll, afterAll, deploy, destroy } = Test.make({ |
| 18 | providers: Cloudflare.providers(), |
| 19 | }); |
| 20 | |
| 21 | const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info"); |
| 22 | |
| 23 | const stack = beforeAll(deploy(Stack)); |
| 24 | afterAll.skipIf(!!process.env.NO_DESTROY)( |
| 25 | Effect.gen(function* () { |
| 26 | const deployed = yield* Effect.exit(stack); |
| 27 | yield* destroy(Stack); |
| 28 | if (Exit.isFailure(deployed)) return; |
| 29 | const urls = [ |
| 30 | deployed.value.targetUrl, |
| 31 | deployed.value.asyncCallerUrl, |
| 32 | deployed.value.effectCallerUrl, |
| 33 | deployed.value.selfWorkerUrl, |
| 34 | ]; |
| 35 | yield* Effect.gen(function* () { |
| 36 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 37 | for (const url of urls) { |
| 38 | const deleted = yield* workers |
| 39 | .getScript({ |
| 40 | accountId, |
| 41 | scriptName: new URL(url).hostname.split(".")[0]!, |
| 42 | }) |
| 43 | .pipe( |
| 44 | Effect.as(false), |
| 45 | Effect.catchTag("WorkerNotFound", () => Effect.succeed(true)), |
| 46 | Effect.repeat({ |
| 47 | while: (gone) => !gone, |
| 48 | schedule: Schedule.spaced("1 second"), |
| 49 | times: 8, |
| 50 | }), |
| 51 | Effect.timeout("15 seconds"), |
| 52 | ); |
| 53 | expect(deleted).toBe(true); |
| 54 | } |
| 55 | }).pipe(Effect.provide(CloudflareApiLive()), Effect.scoped); |
| 56 | }), |
| 57 | { timeout: 120_000 }, |
| 58 | ); |
| 59 | |
| 60 | // Cold-start retry — fresh `workers.dev` URLs take a few seconds to start |
| 61 | // answering 200, so the very first request rides this schedule. Cap the |
| 62 | // exponential at 5s: uncapped, the doubling sleeps blow through the test |
| 63 | // timeout in a single wait after ~7 misses, even though the edge would |
| 64 | // have propagated moments later. |
| 65 | const coldStartRetry = Effect.retry({ |
| 66 | schedule: Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("5 seconds")]), |
| 67 | times: 10, |
| 68 | }); |
| 69 | |
| 70 | for (const encoding of ["json", "bytes"] as const) { |
| 71 | for (const scenario of ["complete", "cancel", "empty", "head-failure", "tail-failure"] as const) { |
| 72 | test( |
| 73 | `native RPC ${encoding} stream handles ${scenario} with its source and event scopes`, |
| 74 | Effect.gen(function* () { |
| 75 | const { effectCallerUrl } = yield* stack; |
| 76 | const client = HttpClient.filterStatusOk(yield* HttpClient.HttpClient).pipe( |
| 77 | HttpClient.mapRequest(HttpClientRequest.setHeader("connection", "close")), |
| 78 | ); |
| 79 | yield* client.get(`${effectCallerUrl}/rpc-stream-ready`).pipe( |
| 80 | Effect.flatMap((response) => response.text), |
| 81 | Effect.flatMap((body) => |
| 82 | body === "rpc-stream-scopes" |
| 83 | ? Effect.void |
| 84 | : Effect.fail(new Error(`Worker not ready: ${body}`)), |
| 85 | ), |
| 86 | coldStartRetry, |
| 87 | ); |
| 88 | |
| 89 | // A later request can reach an edge that has not received the route. |
| 90 | // Only Cloudflare's pre-invocation placeholder is safe to retry. |
| 91 | const response = yield* requestWorker( |
| 92 | HttpClientRequest.get(`${effectCallerUrl}/rpc-stream/${encoding}/${scenario}`).pipe( |
| 93 | HttpClientRequest.setHeader("connection", "close"), |
| 94 | ), |
| 95 | { retryDelay: "5 seconds" }, |
| 96 | ); |
| 97 | expect(response.status).toBe(200); |
| 98 | const body = (yield* response.json) as { |
| 99 | values: Array<{ part: string; eventClosed: number; sourceClosed: number }>; |
| 100 | failed: boolean; |
| 101 | error?: { _tag: string; error?: { _tag: string; phase: string } }; |
| 102 | after: string; |
| 103 | }; |
| 104 | const parts = |
| 105 | scenario === "complete" |
| 106 | ? ["head", "tail"] |
| 107 | : scenario === "cancel" || scenario === "tail-failure" |
| 108 | ? ["head"] |
| 109 | : []; |
| 110 | expect(body.values).toEqual( |
| 111 | parts.map((part) => ({ part, eventClosed: 0, sourceClosed: 0 })), |
| 112 | ); |
| 113 | expect(body.failed).toBe(scenario === "head-failure" || scenario === "tail-failure"); |
| 114 | expect(body.after).toBe("hello after stream"); |
| 115 | if (scenario === "head-failure" || (scenario === "tail-failure" && encoding === "json")) { |
| 116 | expect(body.error).toMatchObject({ |
| 117 | _tag: "RpcRemoteStreamError", |
| 118 | error: { |
| 119 | _tag: "RpcStreamFixtureError", |
| 120 | phase: scenario === "head-failure" ? "head" : "tail", |
| 121 | }, |
| 122 | }); |
| 123 | } else if (scenario === "tail-failure") { |
| 124 | expect(body.error?._tag).toBe("SocketError"); |
| 125 | } |
| 126 | }).pipe(logLevel), |
| 127 | { tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"], timeout: 90_000 }, |
| 128 | ); |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | test( |
| 133 | "target worker's own fetch handler responds", |
| 134 | Effect.gen(function* () { |
| 135 | const { targetUrl } = yield* stack; |
| 136 | const client = HttpClient.filterStatusOk(yield* HttpClient.HttpClient); |
| 137 | |
| 138 | const res = yield* client.get(targetUrl).pipe(coldStartRetry); |
| 139 | expect(res.status).toBe(200); |
| 140 | expect(yield* res.text).toBe("hello from BindingTargetWorker"); |
| 141 | }).pipe(logLevel), |
| 142 | { |
| 143 | tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"], |
| 144 | timeout: 120_000, |
| 145 | }, |
| 146 | ); |
| 147 | |
| 148 | test( |
| 149 | "async caller can call target's RPC method via service binding", |
| 150 | Effect.gen(function* () { |
| 151 | const { asyncCallerUrl } = yield* stack; |
| 152 | const client = HttpClient.filterStatusOk(yield* HttpClient.HttpClient); |
| 153 | |
| 154 | const res = yield* client.get(`${asyncCallerUrl}/?name=alice`).pipe(coldStartRetry); |
| 155 | expect(res.status).toBe(200); |
| 156 | expect(yield* res.text).toBe("hello alice"); |
| 157 | }).pipe(logLevel), |
| 158 | { |
| 159 | tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"], |
| 160 | timeout: 120_000, |
| 161 | }, |
| 162 | ); |
| 163 | |
| 164 | test( |
| 165 | "async caller can await a toRpcAsync view and call through it", |
| 166 | Effect.gen(function* () { |
| 167 | const { asyncCallerUrl } = yield* stack; |
| 168 | const client = yield* HttpClient.HttpClient; |
| 169 | |
| 170 | // Warm the binding on the plain route so cold starts don't mask the |
| 171 | // result; the `/rpc-async` call itself is not retried, so a view that |
| 172 | // is mistaken for a thenable surfaces as the fixture's timeout 500. |
| 173 | yield* HttpClient.filterStatusOk(client) |
| 174 | .get(`${asyncCallerUrl}/?name=warmup`) |
| 175 | .pipe(coldStartRetry); |
| 176 | |
| 177 | const res = yield* client.get(`${asyncCallerUrl}/rpc-async?name=carol`); |
| 178 | expect(yield* res.text).toBe("hello carol"); |
| 179 | expect(res.status).toBe(200); |
| 180 | }).pipe(logLevel), |
| 181 | { |
| 182 | tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"], |
| 183 | timeout: 120_000, |
| 184 | }, |
| 185 | ); |
| 186 | |
| 187 | test( |
| 188 | "effect caller can call target's RPC method via bindWorker", |
| 189 | Effect.gen(function* () { |
| 190 | const { effectCallerUrl } = yield* stack; |
| 191 | const client = HttpClient.filterStatusOk(yield* HttpClient.HttpClient); |
| 192 | |
| 193 | const res = yield* client.get(`${effectCallerUrl}/?name=bob`).pipe(coldStartRetry); |
| 194 | expect(res.status).toBe(200); |
| 195 | expect(yield* res.text).toBe("hello bob"); |
| 196 | }).pipe(logLevel), |
| 197 | { |
| 198 | tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"], |
| 199 | timeout: 120_000, |
| 200 | }, |
| 201 | ); |
| 202 | |
| 203 | test( |
| 204 | "effect worker calls its own RPC method via bindWorker(Self)", |
| 205 | Effect.gen(function* () { |
| 206 | const { selfWorkerUrl } = yield* stack; |
| 207 | const client = HttpClient.filterStatusOk(yield* HttpClient.HttpClient); |
| 208 | |
| 209 | const res = yield* client.get(`${selfWorkerUrl}/?name=carol`).pipe(coldStartRetry); |
| 210 | expect(yield* res.text).toBe("hello carol from self"); |
| 211 | }).pipe(logLevel), |
| 212 | { |
| 213 | tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"], |
| 214 | timeout: 120_000, |
| 215 | }, |
| 216 | ); |
| 217 | |
| 218 | test.provider( |
| 219 | "an effect worker's self binding is not deployed as a service binding", |
| 220 | () => |
| 221 | Effect.gen(function* () { |
| 222 | const { selfWorkerName } = yield* stack; |
| 223 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 224 | |
| 225 | // `bindWorker(Self)` resolves through workerd's `ctx.exports.default` |
| 226 | // loopback, so the upload carries no service binding naming the |
| 227 | // Worker's own script. |
| 228 | const settings = yield* workers.getScriptScriptAndVersionSetting({ |
| 229 | accountId, |
| 230 | scriptName: selfWorkerName, |
| 231 | }); |
| 232 | const selfServiceBindings = (settings.bindings ?? []).filter( |
| 233 | (binding) => binding.type === "service" && binding.service === selfWorkerName, |
| 234 | ); |
| 235 | expect(selfServiceBindings).toEqual([]); |
| 236 | }).pipe(logLevel), |
| 237 | { |
| 238 | tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"], |
| 239 | timeout: 120_000, |
| 240 | }, |
| 241 | ); |
| 242 | |
| 243 | test( |
| 244 | "async worker re-enters its default export through Workers.Self", |
| 245 | Effect.gen(function* () { |
| 246 | const { asyncCallerUrl } = yield* stack; |
| 247 | const client = HttpClient.filterStatusOk(yield* HttpClient.HttpClient); |
| 248 | |
| 249 | const res = yield* client.get(`${asyncCallerUrl}/self?name=dave`).pipe(coldStartRetry); |
| 250 | expect(yield* res.text).toBe("via self: inner dave"); |
| 251 | }).pipe(logLevel), |
| 252 | { |
| 253 | tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"], |
| 254 | timeout: 120_000, |
| 255 | }, |
| 256 | ); |
| 257 | |
| 258 | /** |
| 259 | * Two plain async Workers bind each other: A binds B's default entrypoint |
| 260 | * and B binds A's named `Callbacks` entrypoint. Declaring the stack used to |
| 261 | * recurse between the two `env` declarations until the heap ran out (#2672). |
| 262 | */ |
| 263 | test.provider( |
| 264 | "async workers in a cycle deploy and call each other", |
| 265 | (stack) => |
| 266 | Effect.gen(function* () { |
| 267 | yield* stack.destroy(); |
| 268 | |
| 269 | const deployed = yield* stack.deploy( |
| 270 | Effect.gen(function* () { |
| 271 | const a = yield* AsyncCycleA; |
| 272 | const b = yield* AsyncCycleB; |
| 273 | return { |
| 274 | urlA: a.url.as<string>(), |
| 275 | workerNames: [a.workerName, b.workerName], |
| 276 | }; |
| 277 | }), |
| 278 | ); |
| 279 | |
| 280 | // A → B.start → A's Callbacks.done: both edges of the cycle. |
| 281 | const client = HttpClient.filterStatusOk(yield* HttpClient.HttpClient); |
| 282 | const res = yield* client.get(`${deployed.urlA}/?id=7`).pipe(coldStartRetry); |
| 283 | expect(yield* res.text).toBe("a got 7"); |
| 284 | |
| 285 | yield* stack.destroy(); |
| 286 | |
| 287 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 288 | for (const scriptName of deployed.workerNames) { |
| 289 | const gone = yield* workers.getScript({ accountId, scriptName }).pipe( |
| 290 | Effect.as(false), |
| 291 | Effect.catchTag("WorkerNotFound", () => Effect.succeed(true)), |
| 292 | Effect.repeat({ |
| 293 | while: (gone) => !gone, |
| 294 | schedule: Schedule.spaced("1 second"), |
| 295 | times: 8, |
| 296 | }), |
| 297 | ); |
| 298 | expect(gone).toBe(true); |
| 299 | } |
| 300 | }).pipe(logLevel), |
| 301 | { |
| 302 | tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"], |
| 303 | timeout: 180_000, |
| 304 | }, |
| 305 | ); |