The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Os from "node:os"; |
| 2 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 3 | import { expect } from "@alchemy.run/test"; |
| 4 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 5 | import * as Alchemy from "alchemy"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Fiber from "effect/Fiber"; |
| 8 | import * as FileSystem from "effect/FileSystem"; |
| 9 | import * as HttpClient from "effect/http/HttpClient"; |
| 10 | import * as Path from "effect/Path"; |
| 11 | import { MinimumLogLevel } from "effect/References"; |
| 12 | import * as Schedule from "effect/Schedule"; |
| 13 | import HandoffWorkerLive, { HandoffWorker, setDeployN } from "./fixtures/handoff-worker.ts"; |
| 14 | |
| 15 | /** |
| 16 | * `dev: true` runs the local providers in a persistent, file-scoped RPC |
| 17 | * sidecar by default, exactly like `alchemy dev` (see MakeOptions.sidecar in |
| 18 | * Test/Core.ts). This test DEPENDS on that topology: in-process (`sidecar: |
| 19 | * false`), each `deploy(Stack)` builds a fresh provider (fresh in-memory |
| 20 | * instance maps), so the second deploy never takes the "Changes detected, |
| 21 | * interrupting existing instance" replacement path this test exists to |
| 22 | * cover. The proxy caches its sidecar session per entry URL, so both |
| 23 | * deploys talk to the same provider process. |
| 24 | */ |
| 25 | const { test, deploy, destroy } = Test.make({ |
| 26 | providers: Cloudflare.providers(), |
| 27 | state: Alchemy.localState(), |
| 28 | dev: true, |
| 29 | }); |
| 30 | |
| 31 | const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info"); |
| 32 | |
| 33 | const Stack = Alchemy.Stack( |
| 34 | "LocalWorkerHandoffStack", |
| 35 | { providers: Cloudflare.providers(), state: Alchemy.localState() }, |
| 36 | Effect.gen(function* () { |
| 37 | const worker = yield* HandoffWorker; |
| 38 | return { |
| 39 | url: worker.url.as<string>(), |
| 40 | workerName: worker.workerName.as<string>(), |
| 41 | }; |
| 42 | }).pipe(Effect.provide(HandoffWorkerLive)), |
| 43 | ); |
| 44 | |
| 45 | const fetchDeploy = (url: string) => |
| 46 | Effect.gen(function* () { |
| 47 | const client = yield* HttpClient.HttpClient; |
| 48 | const res = yield* client.get(url); |
| 49 | if (res.status !== 200) { |
| 50 | const text = yield* res.text; |
| 51 | return yield* Effect.fail(new Error(`status ${res.status}: ${text.slice(0, 500)}`)); |
| 52 | } |
| 53 | const body = (yield* res.json) as { deploy: string; pong: string }; |
| 54 | expect(body.pong).toBe("pong"); |
| 55 | return body.deploy; |
| 56 | }).pipe(Effect.timeout("10 seconds")); |
| 57 | |
| 58 | const registryEntryPath = (workerName: string) => |
| 59 | Effect.gen(function* () { |
| 60 | const path = yield* Path.Path; |
| 61 | const stateHome = process.env.XDG_STATE_HOME ?? path.join(Os.homedir(), ".local", "state"); |
| 62 | return path.join(stateHome, "alchemy", "registry", `${encodeURIComponent(workerName)}.json`); |
| 63 | }); |
| 64 | |
| 65 | const registryEntryExists = (workerName: string) => |
| 66 | Effect.gen(function* () { |
| 67 | const fs = yield* FileSystem.FileSystem; |
| 68 | return yield* fs.exists(yield* registryEntryPath(workerName)); |
| 69 | }); |
| 70 | |
| 71 | /** |
| 72 | * Poll the registry entry's existence in a tight loop, counting every probe |
| 73 | * that finds it missing. A make-before-break handoff only ever overwrites |
| 74 | * `{scriptName}.json` (an atomic temp-file + rename, so the path always |
| 75 | * resolves; the owner-aware unregister of the old instance no-ops). The |
| 76 | * broken path unlinks the entry when the old instance is torn down and |
| 77 | * recreates it when the replacement finally serves — a dark window the |
| 78 | * millisecond poller catches even when it is too short to observe with a |
| 79 | * request. (The inode is NOT a usable signal: every atomic rename publishes |
| 80 | * a fresh inode.) |
| 81 | */ |
| 82 | const watchRegistryEntryMisses = (workerName: string) => |
| 83 | Effect.gen(function* () { |
| 84 | let probes = 0; |
| 85 | let misses = 0; |
| 86 | const fiber = yield* registryEntryExists(workerName).pipe( |
| 87 | Effect.tap((exists) => |
| 88 | Effect.sync(() => { |
| 89 | probes++; |
| 90 | if (!exists) misses++; |
| 91 | }), |
| 92 | ), |
| 93 | Effect.repeat(Schedule.spaced("2 millis")), |
| 94 | Effect.forkChild, |
| 95 | ); |
| 96 | return Fiber.interrupt(fiber).pipe(Effect.map(() => ({ probes, misses }))); |
| 97 | }); |
| 98 | |
| 99 | /** |
| 100 | * Regression test for alchemy-run/alchemy#859: replacing a local dev Worker |
| 101 | * instance (a reconcile with a changed structural signature logs "Changes |
| 102 | * detected, interrupting existing instance") must not tear down the running |
| 103 | * workerd before the replacement has started. The last good instance keeps |
| 104 | * serving — and keeps its dev-registry entry, which cross-script DO bindings |
| 105 | * resolve through — until the replacement's first serve completes. |
| 106 | */ |
| 107 | test( |
| 108 | "previous instance keeps serving and stays registered during redeploy", |
| 109 | Effect.gen(function* () { |
| 110 | // Clear any state a previous interrupted run left behind. |
| 111 | yield* destroy(Stack); |
| 112 | |
| 113 | setDeployN("1"); |
| 114 | const first = yield* deploy(Stack); |
| 115 | |
| 116 | // The local provider serves from the dev proxy — proof no cloud call ran. |
| 117 | expect(first.url).toMatch(/^http:\/\/localhost:\d+$/); |
| 118 | |
| 119 | // Wait for the first instance to actually serve (fresh workerd + DO). |
| 120 | const initial = yield* fetchDeploy(first.url).pipe( |
| 121 | Effect.retry({ |
| 122 | schedule: Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]), |
| 123 | times: 20, |
| 124 | }), |
| 125 | ); |
| 126 | expect(initial).toBe("1"); |
| 127 | expect(yield* registryEntryExists(first.workerName)).toBe(true); |
| 128 | const stopWatching = yield* watchRegistryEntryMisses(first.workerName); |
| 129 | |
| 130 | // Redeploy with a changed env var: the Worker's structural signature |
| 131 | // changes, so the provider replaces the instance. The deploy returns as |
| 132 | // soon as reconcile completes — before the replacement workerd has |
| 133 | // started serving. |
| 134 | setDeployN("2"); |
| 135 | const second = yield* deploy(Stack); |
| 136 | |
| 137 | // The previous instance must still be serving (make-before-break): a |
| 138 | // single un-retried request must succeed, whether it is answered by the |
| 139 | // old instance ("1") or an already-cut-over replacement ("2"). |
| 140 | const during = yield* fetchDeploy(second.url); |
| 141 | expect(["1", "2"]).toContain(during); |
| 142 | |
| 143 | // ...and its dev-registry entry must still exist, so cross-script DO |
| 144 | // bindings from other workers keep resolving throughout the handoff. |
| 145 | expect(yield* registryEntryExists(second.workerName)).toBe(true); |
| 146 | |
| 147 | // The replacement eventually takes over. |
| 148 | const final = yield* fetchDeploy(second.url).pipe( |
| 149 | Effect.flatMap((deploy) => |
| 150 | deploy === "2" |
| 151 | ? Effect.succeed(deploy) |
| 152 | : Effect.fail(new Error(`still serving deploy ${deploy}`)), |
| 153 | ), |
| 154 | Effect.retry({ schedule: Schedule.spaced("1 second"), times: 90 }), |
| 155 | ); |
| 156 | expect(final).toBe("2"); |
| 157 | expect(yield* registryEntryExists(second.workerName)).toBe(true); |
| 158 | // The entry was overwritten by the replacement, never deleted — |
| 159 | // cross-script DO bindings resolving through it never saw it vanish. |
| 160 | const { probes, misses } = yield* stopWatching; |
| 161 | expect(probes).toBeGreaterThan(0); |
| 162 | expect(misses).toBe(0); |
| 163 | |
| 164 | yield* destroy(Stack); |
| 165 | }).pipe(logLevel), |
| 166 | { |
| 167 | tags: ["provider:cloudflare", "provider:cloudflare:worker", "local"], |
| 168 | timeout: 240_000, |
| 169 | }, |
| 170 | ); |