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 { WorkerDomainConfigError } from "@alchemy.run/cloudflare/Workers/WorkerProvider"; |
| 4 | import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup"; |
| 5 | import { describe, expect } from "@alchemy.run/test"; |
| 6 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 7 | import * as rulesets from "@distilled.cloud/cloudflare/rulesets"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import { MinimumLogLevel } from "effect/References"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | import { stageSuffix } from "../../names.ts"; |
| 13 | import { expectUrlContains, waitForDns } from "../Utils/Http.ts"; |
| 14 | import { waitForWorkerToBeDeleted } from "../Utils/Worker.ts"; |
| 15 | |
| 16 | const { test } = Test.make({ providers: Cloudflare.providers() }); |
| 17 | |
| 18 | const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info"); |
| 19 | |
| 20 | const script = (marker: string) => |
| 21 | `export default { fetch() { return new Response("${marker}"); } };`; |
| 22 | |
| 23 | class RedirectNotReady extends Data.TaggedError("RedirectNotReady")<{ |
| 24 | url: string; |
| 25 | detail: string; |
| 26 | }> {} |
| 27 | |
| 28 | /** |
| 29 | * Fetch `from` without following redirects and assert a 301 whose |
| 30 | * `location` matches `expectedLocation` exactly (path + query preserved). |
| 31 | * Retried through DNS/certificate propagation on a freshly attached |
| 32 | * custom domain. |
| 33 | */ |
| 34 | const expectRedirect = Effect.fn(function* (from: string, expectedLocation: string) { |
| 35 | const location = yield* Effect.tryPromise({ |
| 36 | try: async (signal) => { |
| 37 | const res = await fetch(from, { redirect: "manual", signal }); |
| 38 | if (res.status !== 301) { |
| 39 | throw new Error(`expected 301, got ${res.status}`); |
| 40 | } |
| 41 | return res.headers.get("location") ?? ""; |
| 42 | }, |
| 43 | catch: (cause) => new RedirectNotReady({ url: from, detail: String(cause) }), |
| 44 | }).pipe( |
| 45 | Effect.flatMap((location) => |
| 46 | location === expectedLocation |
| 47 | ? Effect.succeed(location) |
| 48 | : Effect.fail( |
| 49 | new RedirectNotReady({ |
| 50 | url: from, |
| 51 | detail: `location was '${location}', expected '${expectedLocation}'`, |
| 52 | }), |
| 53 | ), |
| 54 | ), |
| 55 | Effect.retry({ |
| 56 | while: (e) => e._tag === "RedirectNotReady", |
| 57 | schedule: Schedule.spaced("5 seconds"), |
| 58 | times: 48, |
| 59 | }), |
| 60 | ); |
| 61 | expect(location).toEqual(expectedLocation); |
| 62 | }); |
| 63 | |
| 64 | /** Our redirect rules in the zone's dynamic-redirect phase entrypoint. */ |
| 65 | const listWorkerRedirectRules = Effect.fn(function* (zoneId: string, scriptName: string) { |
| 66 | const entrypoint = yield* rulesets |
| 67 | .getPhasForZone({ zoneId, rulesetPhase: "http_request_dynamic_redirect" }) |
| 68 | .pipe(Effect.catchTag("RulesetNotFound", () => Effect.succeed(undefined))); |
| 69 | return (entrypoint?.rules ?? []).flatMap((rule) => |
| 70 | (rule.description ?? "").startsWith(`alchemy:worker:${scriptName}:redirect:`) |
| 71 | ? [rule.description as string] |
| 72 | : [], |
| 73 | ); |
| 74 | }); |
| 75 | |
| 76 | describe.concurrent( |
| 77 | "Cloudflare.Worker urls & domain", |
| 78 | { tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"] }, |
| 79 | () => { |
| 80 | test.provider( |
| 81 | "rejects a hostname playing more than one role", |
| 82 | (stack) => |
| 83 | Effect.gen(function* () { |
| 84 | yield* stack.destroy(); |
| 85 | |
| 86 | const error = yield* stack |
| 87 | .deploy( |
| 88 | Effect.gen(function* () { |
| 89 | return yield* Cloudflare.Worker("OverlapWorker", { |
| 90 | script: script("overlap"), |
| 91 | domain: { name: "app.example.com", aliases: ["app.example.com"] }, |
| 92 | }); |
| 93 | }), |
| 94 | ) |
| 95 | .pipe(Effect.flip); |
| 96 | |
| 97 | expect(error).toBeInstanceOf(WorkerDomainConfigError); |
| 98 | expect(String(error)).toContain("one role"); |
| 99 | |
| 100 | yield* stack.destroy(); |
| 101 | }).pipe(logLevel), |
| 102 | { timeout: 120_000 }, |
| 103 | ); |
| 104 | |
| 105 | const customDomainZone = |
| 106 | process.env.CLOUDFLARE_TEST_WORKER_DOMAIN_ZONE_NAME ?? "alchemy-test-2.us"; |
| 107 | test.provider( |
| 108 | "redirect hostnames 301 to the canonical name and stay out of urls", |
| 109 | (stack) => |
| 110 | Effect.gen(function* () { |
| 111 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 112 | const suffix = stageSuffix(); |
| 113 | const mainHost = `alchemy-rdr-a-${suffix}.${customDomainZone}`; |
| 114 | const oldHost = `alchemy-rdr-b-${suffix}.${customDomainZone}`; |
| 115 | const aliasHost = `alchemy-rdr-c-${suffix}.${customDomainZone}`; |
| 116 | |
| 117 | yield* stack.destroy(); |
| 118 | |
| 119 | const deploy = (domain: { name: string; aliases?: string[]; redirects?: string[] }) => |
| 120 | stack.deploy( |
| 121 | Effect.gen(function* () { |
| 122 | return yield* Cloudflare.Worker("RedirectWorker", { |
| 123 | script: script("redirect-target"), |
| 124 | domain, |
| 125 | }); |
| 126 | }), |
| 127 | ); |
| 128 | |
| 129 | const worker = yield* deploy({ |
| 130 | name: mainHost, |
| 131 | aliases: [aliasHost], |
| 132 | redirects: [oldHost], |
| 133 | }); |
| 134 | |
| 135 | // All three roles resolve into the domain output; the redirect |
| 136 | // hostname serves nothing, so it must not appear in `urls`. |
| 137 | expect(worker.domain).toEqual({ |
| 138 | name: mainHost, |
| 139 | aliases: [aliasHost], |
| 140 | redirects: [oldHost], |
| 141 | }); |
| 142 | expect(worker.url).toEqual(`https://${mainHost}`); |
| 143 | expect(worker.urls.slice(0, 2)).toEqual([`https://${mainHost}`, `https://${aliasHost}`]); |
| 144 | expect(worker.urls.some((u) => u.includes(oldHost))).toBe(false); |
| 145 | // workers.dev stays on by default and ranks after the domain. |
| 146 | expect(worker.urls[worker.urls.length - 1]).toMatch(/\.workers\.dev$/); |
| 147 | |
| 148 | // Our tagged rule exists in the zone's shared entrypoint — one for |
| 149 | // the redirect host, none for the alias (aliases serve, not 301). |
| 150 | const zone = yield* findZoneByName({ accountId, name: customDomainZone! }); |
| 151 | expect(zone).toBeDefined(); |
| 152 | expect(yield* listWorkerRedirectRules(zone!.id, worker.workerName)).toEqual([ |
| 153 | `alchemy:worker:${worker.workerName}:redirect:${oldHost}`, |
| 154 | ]); |
| 155 | |
| 156 | // The canonical domain AND the alias serve the Worker; the |
| 157 | // redirect host 301s with path and query preserved — and never |
| 158 | // invokes the Worker. Confirm DNS on the authoritative nameservers |
| 159 | // before the first fetch (see waitForDns in ../Utils/Http.ts). |
| 160 | yield* waitForDns(mainHost); |
| 161 | yield* waitForDns(aliasHost); |
| 162 | yield* waitForDns(oldHost); |
| 163 | yield* expectUrlContains(worker.url!, "redirect-target", { |
| 164 | label: "canonical domain serves the worker", |
| 165 | timeout: "120 seconds", |
| 166 | }); |
| 167 | yield* expectUrlContains(`https://${aliasHost}`, "redirect-target", { |
| 168 | label: "alias serves the worker", |
| 169 | timeout: "120 seconds", |
| 170 | }); |
| 171 | yield* expectRedirect(`https://${oldHost}/hello?x=1`, `https://${mainHost}/hello?x=1`); |
| 172 | |
| 173 | // Removing the redirect cleans our rule and detaches nothing else. |
| 174 | const updated = yield* deploy({ name: mainHost }); |
| 175 | expect(updated.domain).toEqual({ name: mainHost, aliases: [], redirects: [] }); |
| 176 | expect(yield* listWorkerRedirectRules(zone!.id, updated.workerName)).toEqual([]); |
| 177 | |
| 178 | // Re-add, then destroy — teardown must remove the rule too. |
| 179 | const readded = yield* deploy({ name: mainHost, redirects: [oldHost] }); |
| 180 | expect(yield* listWorkerRedirectRules(zone!.id, readded.workerName)).toHaveLength(1); |
| 181 | yield* stack.destroy(); |
| 182 | expect(yield* listWorkerRedirectRules(zone!.id, readded.workerName)).toEqual([]); |
| 183 | yield* waitForWorkerToBeDeleted(readded.workerName, accountId); |
| 184 | }).pipe(logLevel), |
| 185 | { tags: ["provider:cloudflare:ruleset", "provider:cloudflare:zone"], timeout: 540_000 }, |
| 186 | ); |
| 187 | |
| 188 | test.provider( |
| 189 | "domain string shorthand resolves to { name }", |
| 190 | (stack) => |
| 191 | Effect.gen(function* () { |
| 192 | const suffix = stageSuffix(); |
| 193 | const host = `alchemy-shorthand-${suffix}.${customDomainZone}`; |
| 194 | |
| 195 | yield* stack.destroy(); |
| 196 | |
| 197 | const worker = yield* stack.deploy( |
| 198 | Effect.gen(function* () { |
| 199 | return yield* Cloudflare.Worker("ShorthandWorker", { |
| 200 | script: script("shorthand"), |
| 201 | domain: host, |
| 202 | workersDev: false, |
| 203 | }); |
| 204 | }), |
| 205 | ); |
| 206 | |
| 207 | expect(worker.domain).toEqual({ name: host, aliases: [], redirects: [] }); |
| 208 | expect(worker.url).toEqual(`https://${host}`); |
| 209 | expect(worker.urls).toEqual([`https://${host}`]); |
| 210 | |
| 211 | yield* stack.destroy(); |
| 212 | }).pipe(logLevel), |
| 213 | { timeout: 240_000 }, |
| 214 | ); |
| 215 | }, |
| 216 | ); |