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

main
ts 249 lines 10.1 KB
Raw
1 import { spawn } from "node:child_process";
2 import * as Cloudflare from "@alchemy.run/cloudflare";
3 /**
4 * Cross-version FQN-migration regression test for the beta.68 StaticSite
5 * incident (#1053 / #1108).
6 *
7 * A temp project deploys a StaticSite with the PUBLISHED alchemy@2.0.0-beta.67
8 * (whose StaticSite persists its Worker at the `<id>/Worker` FQN), then the
9 * CURRENT workspace version re-deploys over the same local state. The
10 * `renamedFrom(`${id}/Worker`)` migration must move the state row to `<id>`
11 * and re-brand the worker in place — the worker must NOT be deleted or
12 * recreated.
13 */
14 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
15 import { Credentials } from "@alchemy.run/cloudflare/Credentials";
16 import { expect } from "@alchemy.run/test";
17 import * as Test from "@alchemy.run/test/Alchemy";
18 import * as Effect from "effect/Effect";
19 import * as FileSystem from "effect/FileSystem";
20 import * as Path from "effect/Path";
21 import * as Redacted from "effect/Redacted";
22 import * as pathe from "pathe";
23 import { expectWorkerExists, waitForWorkerToBeDeleted } from "../Utils/Worker.ts";
24
25 const { test } = Test.make({ providers: Cloudflare.providers() });
26
27 const repoRoot = pathe.resolve(import.meta.dirname, "../../../../..");
28 const workspaceCli = pathe.join(repoRoot, "packages/alchemy/bin/alchemy.js");
29
30 const STACK = "B67MigrationTest";
31 const STAGE = "b67mig";
32
33 /**
34 * Run a command to completion without blocking the runner's event loop
35 * (the suite shares one bun process; a sync spawn would stall every
36 * concurrently running test). Fails with the combined output on a
37 * non-zero exit.
38 */
39 const run = (options: {
40 cmd: string;
41 args: string[];
42 cwd: string;
43 env?: Record<string, string>;
44 }): Effect.Effect<string, Error> =>
45 Effect.callback<string, Error>((resume) => {
46 const child = spawn(options.cmd, options.args, {
47 cwd: options.cwd,
48 env: { ...process.env, NO_COLOR: "1", ...options.env },
49 stdio: ["ignore", "pipe", "pipe"],
50 });
51 let output = "";
52 child.stdout.on("data", (chunk) => (output += chunk));
53 child.stderr.on("data", (chunk) => (output += chunk));
54 child.once("error", (error) => resume(Effect.fail(error)));
55 child.once("close", (code) =>
56 resume(
57 code === 0
58 ? Effect.succeed(output)
59 : Effect.fail(
60 new Error(`${options.cmd} ${options.args.join(" ")} exited ${code}:\n${output}`),
61 ),
62 ),
63 );
64 return Effect.sync(() => child.kill("SIGKILL"));
65 });
66
67 /** The stack program, valid for both beta.67 and the current version. */
68 const stackProgram = (alchemyImport: string, cloudflareImport: string) =>
69 [
70 `import * as Alchemy from "${alchemyImport}";`,
71 `import * as Cloudflare from "${cloudflareImport}";`,
72 "",
73 "export default Alchemy.Stack(",
74 ` "${STACK}",`,
75 " { providers: Cloudflare.providers(), state: Alchemy.localState() },",
76 // A pure-static site: no `main`, no bundling — the smallest surface
77 // that exists identically in both versions.
78 ' Cloudflare.Website.StaticSite("Site", {',
79 ' command: "bash build.sh",',
80 ' outdir: "dist",',
81 " }),",
82 ");",
83 "",
84 ].join("\n");
85
86 test.provider.skipIf(!!process.env.FAST)(
87 "a beta.67 StaticSite migrates to the current version without recreating the worker",
88 () =>
89 Effect.gen(function* () {
90 const fs = yield* FileSystem.FileSystem;
91 const path = yield* Path.Path;
92 const { accountId } = yield* yield* CloudflareEnvironment;
93
94 // The published beta.67 predates the per-provider profile store, so
95 // it cannot read the credentials this process resolved from the
96 // profile. Environment credentials are the contract that is stable
97 // across versions: hand it the resolved credentials under `CI=1`.
98 const credentials = yield* yield* Credentials;
99 const legacyCliEnv: Record<string, string> = {
100 CI: "1",
101 CLOUDFLARE_ACCOUNT_ID: accountId,
102 ...(credentials.type === "apiKey"
103 ? {
104 CLOUDFLARE_API_KEY: Redacted.value(credentials.apiKey),
105 CLOUDFLARE_EMAIL: credentials.email,
106 }
107 : {
108 // An OAuth access token is a bearer token like an API token.
109 CLOUDFLARE_API_TOKEN: Redacted.value(
110 credentials.type === "apiToken" ? credentials.apiToken : credentials.accessToken,
111 ),
112 }),
113 };
114
115 const dir = yield* fs.makeTempDirectory({ prefix: "alchemy-b67-mig-" });
116 const stateFile = (fqn: string) =>
117 // LocalState layout: .alchemy/state/<stack>/<stage>/<encodeFqn>.json
118 path.join(dir, ".alchemy", "state", STACK, STAGE, `${fqn}.json`);
119 const readRow = (fqn: string) =>
120 fs.readFileString(stateFile(fqn)).pipe(Effect.map((raw) => JSON.parse(raw)));
121
122 // Destroy whatever this attempt deployed even when an assertion (or a
123 // CLI step) fails: the state lives in this attempt's temp dir, so a
124 // runner retry starts from a fresh state and could never clean it up.
125 // The current CLI destroys rows at either FQN; beta.67 is the fallback
126 // for a phase-1-only state the current version cannot load.
127 const destroy = run({
128 cmd: "bun",
129 args: [workspaceCli, "destroy", "./alchemy.current.run.ts", "--stage", STAGE, "--yes"],
130 cwd: dir,
131 }).pipe(
132 Effect.catch(() =>
133 run({
134 cmd: "bun",
135 args: ["node_modules/alchemy/bin/cli.js", "destroy", "--stage", STAGE, "--yes"],
136 cwd: dir,
137 env: legacyCliEnv,
138 }),
139 ),
140 );
141 const cleanup = destroy.pipe(
142 Effect.ignore,
143 Effect.andThen(fs.remove(dir, { recursive: true }).pipe(Effect.ignore)),
144 );
145
146 yield* Effect.gen(function* () {
147 // ── Fixture ─────────────────────────────────────────────────────────
148 yield* fs.writeFileString(
149 path.join(dir, "package.json"),
150 JSON.stringify(
151 {
152 name: "b67-migration-fixture",
153 private: true,
154 dependencies: {
155 alchemy: "2.0.0-beta.67",
156 // Match the beta.67 release lockfile, independently of the
157 // current workspace's Effect version.
158 effect: "4.0.0-beta.100",
159 "@effect/platform-node": "4.0.0-beta.100",
160 "@effect/platform-bun": "4.0.0-beta.100",
161 },
162 // Prerelease ranges otherwise pull newer adapters that import
163 // APIs absent from the legacy Effect runtime (e.g. ByteSize).
164 overrides: {
165 effect: "4.0.0-beta.100",
166 "@effect/platform-node": "4.0.0-beta.100",
167 "@effect/platform-bun": "4.0.0-beta.100",
168 "@effect/platform-node-shared": "4.0.0-beta.100",
169 "@effect/sql-d1": "4.0.0-beta.100",
170 "@effect/vitest": "4.0.0-beta.100",
171 },
172 },
173 null,
174 2,
175 ),
176 );
177 yield* fs.writeFileString(path.join(dir, "index.html"), "<h1>b67-migration</h1>");
178 yield* fs.writeFileString(
179 path.join(dir, "build.sh"),
180 "mkdir -p dist && cp index.html dist/index.html",
181 );
182 // beta.67 entry: resolves `alchemy` from the temp node_modules.
183 yield* fs.writeFileString(
184 path.join(dir, "alchemy.run.ts"),
185 stackProgram("alchemy", "alchemy/Cloudflare"),
186 );
187 // Current-version entry: resolves the WORKSPACE sources directly, so
188 // no linking dance is needed and `effect` is the workspace instance.
189 yield* fs.writeFileString(
190 path.join(dir, "alchemy.current.run.ts"),
191 stackProgram(
192 pathe.join(repoRoot, "packages/alchemy/src/index.ts"),
193 pathe.join(repoRoot, "packages/cloudflare/src/index.ts"),
194 ),
195 );
196
197 // ── Phase 1: deploy with the published beta.67 ──────────────────────
198 yield* run({ cmd: "bun", args: ["install"], cwd: dir });
199 yield* run({
200 cmd: "bun",
201 args: ["node_modules/alchemy/bin/cli.js", "deploy", "--stage", STAGE, "--yes"],
202 cwd: dir,
203 env: legacyCliEnv,
204 });
205
206 // beta.67 persisted the Worker at the legacy `Site/Worker` FQN.
207 const before = yield* readRow("Site__Worker");
208 const workerName: string = before.attr.workerName;
209 expect(before.fqn).toEqual("Site/Worker");
210 expect(workerName).toBeDefined();
211 yield* expectWorkerExists(workerName, accountId);
212
213 // ── Phase 2: re-deploy with the CURRENT workspace version ───────────
214 const output = yield* run({
215 cmd: "bun",
216 args: [workspaceCli, "deploy", "./alchemy.current.run.ts", "--stage", STAGE, "--yes"],
217 cwd: dir,
218 });
219
220 // The plan surfaced the migration and never planned a create/delete.
221 expect(output).toContain("renamed from Site/Worker");
222 expect(output).not.toContain("to create");
223 expect(output).not.toContain("to delete");
224
225 // The row moved: same instanceId, same physical worker, new FQN.
226 const after = yield* readRow("Site");
227 expect(after.instanceId).toEqual(before.instanceId);
228 expect(after.attr.workerName).toEqual(workerName);
229 expect(after.logicalId).toEqual("Site");
230 expect(yield* fs.exists(stateFile("Site__Worker"))).toBe(false);
231
232 // THE assertion: the worker survived the upgrade.
233 yield* expectWorkerExists(workerName, accountId);
234
235 // ── Cleanup ─────────────────────────────────────────────────────────
236 yield* destroy;
237 yield* waitForWorkerToBeDeleted(workerName, accountId);
238 }).pipe(Effect.ensuring(cleanup));
239 }),
240 {
241 tags: [
242 "provider:cloudflare",
243 "provider:cloudflare:website",
244 "provider:cloudflare:worker",
245 "live",
246 ],
247 timeout: 600_000,
248 },
249 );