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

main
ts 332 lines 13.6 KB
Raw
1 import { spawn } from "node:child_process";
2 /**
3 * Cross-version upgrade tests for moving AWS framework sites onto Lambda Web
4 * Functions.
5 *
6 * A temp project deploys a site with the PUBLISHED alchemy and
7 * frontend-frameworks 2.0.0-beta.81 (SSR on a Lambda Function URL), then the
8 * CURRENT workspace version re-deploys over the same local state. The site
9 * must move onto Web Functions and keep its CloudFront distribution, and
10 * the old functions must be deleted.
11 */
12 import * as AWS from "@alchemy.run/aws";
13 import { AWSEnvironment } from "@alchemy.run/aws/Environment";
14 import { expect } from "@alchemy.run/test";
15 import * as Test from "@alchemy.run/test/Alchemy";
16 import * as cloudfront from "@distilled.cloud/aws/cloudfront";
17 import * as Effect from "effect/Effect";
18 import * as FileSystem from "effect/FileSystem";
19 import * as Path from "effect/Path";
20 import * as Redacted from "effect/Redacted";
21 import * as Schedule from "effect/Schedule";
22 import * as pathe from "pathe";
23 import { cloneFixture } from "../../Cloudflare/Utils/Fixture.ts";
24 import { expectUrlContains } from "../../Cloudflare/Utils/Http.ts";
25
26 const { test } = Test.make({ providers: AWS.providers() });
27
28 const PUBLISHED = "2.0.0-beta.81";
29 const STACK = "WebFunctionUpgradeTest";
30 const STAGE = "wfupgrade";
31
32 const repoRoot = pathe.resolve(import.meta.dirname, "../../../../..");
33 const workspaceCli = pathe.join(repoRoot, "packages/alchemy/bin/alchemy.js");
34 const fixtures = pathe.resolve(import.meta.dirname, "fixtures");
35
36 /**
37 * The Effect release that was current when the published alchemy came out
38 * (2026-10-05). Its peers accept `^4.0.0`, but later releases break it: 4.0.7
39 * rejects a schema it builds (`Schema.optional` on an index signature) and 4.1
40 * removed `effect/Crypto`, which it imports. Platform peers match: a platform
41 * package from another release calls Effect APIs (e.g. `Path.make`) that the
42 * other `effect` does not export.
43 */
44 const PUBLISHED_EFFECT = "4.0.1";
45 const publishedPeers = {
46 effect: PUBLISHED_EFFECT,
47 "@effect/platform-node": PUBLISHED_EFFECT,
48 "@effect/platform-bun": PUBLISHED_EFFECT,
49 "@effect/platform-node-shared": PUBLISHED_EFFECT,
50 };
51
52 /**
53 * Run a command to completion without blocking the runner's event loop.
54 * Fails with the combined output on a non-zero exit.
55 */
56 const run = (options: { cmd: string; args: string[]; cwd: string; env: Record<string, string> }) =>
57 Effect.callback<string, Error>((resume) => {
58 const child = spawn(options.cmd, options.args, {
59 cwd: options.cwd,
60 // `CI=1` keeps both CLIs non-interactive.
61 env: { ...process.env, ...options.env, NO_COLOR: "1", CI: "1" },
62 stdio: ["ignore", "pipe", "pipe"],
63 });
64 let output = "";
65 child.stdout.on("data", (chunk) => (output += chunk));
66 child.stderr.on("data", (chunk) => (output += chunk));
67 child.once("error", (error) => resume(Effect.fail(error)));
68 child.once("close", (code) =>
69 resume(
70 code === 0
71 ? Effect.succeed(output)
72 : Effect.fail(
73 new Error(`${options.cmd} ${options.args.join(" ")} exited ${code}:\n${output}`),
74 ),
75 ),
76 );
77 return Effect.sync(() => child.kill("SIGKILL"));
78 });
79
80 interface UpgradeCase {
81 readonly framework: "Nuxt" | "Nextjs";
82 readonly fixture: string;
83 readonly entries: string[];
84 /**
85 * Where the temp project lives. Nuxt clones under the alchemy package so
86 * `nuxt` resolves from the workspace; Next.js clones outside the repo
87 * (OpenNext traces a monorepo's symlink store wrong) and installs its own
88 * dependencies.
89 */
90 readonly tempRoot: string | undefined;
91 readonly install: string[];
92 /**
93 * Peers the published alchemy needs, pinned to the Effect it was built for.
94 */
95 readonly peers?: Record<string, string>;
96 readonly marker: string;
97 /** State rows of the old Lambda Functions and their Web Function successors. */
98 readonly moved: ReadonlyArray<{ readonly from: string; readonly to: string }>;
99 /** State rows the upgrade removes without a successor. */
100 readonly removed?: ReadonlyArray<string>;
101 }
102
103 const cases: UpgradeCase[] = [
104 {
105 framework: "Nuxt",
106 fixture: "nuxt-app",
107 entries: [".gitignore", "nuxt.config.ts", "app", "server", "public"],
108 tempRoot: pathe.resolve(import.meta.dirname, "../../../.tmp"),
109 // Peers (nuxt, astro, ...) resolve from the workspace above.
110 install: ["install", "--omit", "peer"],
111 peers: publishedPeers,
112 marker: "NUXT_AWS_PAGE_MARKER",
113 moved: [{ from: "Site__Server", to: "Site__WebServer" }],
114 },
115 {
116 framework: "Nextjs",
117 fixture: "nextjs-app",
118 entries: [".gitignore", "package.json", "next.config.ts", "tsconfig.json", "app", "public"],
119 tempRoot: undefined,
120 install: ["install", "--linker=hoisted", "--omit", "peer"],
121 peers: publishedPeers,
122 marker: "NEXTJS_AWS_PAGE_MARKER",
123 moved: [{ from: "Site__Server", to: "Site__WebServer" }],
124 // Next's standalone server optimizes images and revalidates in-process.
125 removed: [
126 "Site__ImageOptimization",
127 "Site__Revalidation",
128 "Site__RevalidationQueue",
129 "Site__TagCache",
130 ],
131 },
132 ];
133
134 /** The stack program, valid for both versions. */
135 const stackProgram = (framework: string, alchemyImport: string, awsImport: string) =>
136 [
137 `import * as Alchemy from "${alchemyImport}";`,
138 `import * as AWS from "${awsImport}";`,
139 "",
140 "export default Alchemy.Stack(",
141 ` "${STACK}",`,
142 " { providers: AWS.providers(), state: Alchemy.localState() },",
143 ` AWS.Website.${framework}("Site", {`,
144 " forceDestroy: true,",
145 ' invalidation: { paths: "all", wait: true },',
146 " }),",
147 ");",
148 "",
149 ].join("\n");
150
151 for (const upgrade of cases) {
152 test.provider.skipIf(!!process.env.FAST)(
153 `a ${upgrade.framework} site deployed by ${PUBLISHED} moves onto Web Functions and keeps its distribution`,
154 () =>
155 Effect.gen(function* () {
156 const fs = yield* FileSystem.FileSystem;
157 const path = yield* Path.Path;
158
159 // Both CLIs read AWS credentials from the environment; under `CI=1`
160 // the published one does not fall back to an SSO profile.
161 const aws = yield* AWSEnvironment.current;
162 const credentials = yield* aws.credentials;
163 const awsEnv: Record<string, string> = {
164 AWS_ACCESS_KEY_ID: Redacted.value(credentials.accessKeyId),
165 AWS_SECRET_ACCESS_KEY: Redacted.value(credentials.secretAccessKey),
166 ...(credentials.sessionToken
167 ? { AWS_SESSION_TOKEN: Redacted.value(credentials.sessionToken) }
168 : {}),
169 AWS_REGION: aws.region,
170 };
171
172 const dir = yield* cloneFixture(path.join(fixtures, upgrade.fixture), {
173 prefix: `alchemy-wf-upgrade-${upgrade.fixture}-`,
174 tempRoot: upgrade.tempRoot,
175 entries: upgrade.entries,
176 });
177 const stateFile = (fqn: string) =>
178 // LocalState layout: .alchemy/state/<stack>/<stage>/<encodeFqn>.json
179 path.join(dir, ".alchemy", "state", STACK, STAGE, `${fqn}.json`);
180 const readRow = (fqn: string) =>
181 fs.readFileString(stateFile(fqn)).pipe(Effect.map((raw) => JSON.parse(raw)));
182
183 // Destroy whatever this attempt deployed even when a step fails. The
184 // published CLI is the fallback for a state the current version
185 // cannot load.
186 const destroy = run({
187 cmd: "bun",
188 args: [workspaceCli, "destroy", "./alchemy.current.run.ts", "--stage", STAGE, "--yes"],
189 cwd: dir,
190 env: awsEnv,
191 }).pipe(
192 Effect.catch(() =>
193 run({
194 cmd: "bun",
195 args: ["node_modules/alchemy/bin/cli.js", "destroy", "--stage", STAGE, "--yes"],
196 cwd: dir,
197 env: awsEnv,
198 }),
199 ),
200 );
201 const cleanup = destroy.pipe(
202 Effect.ignore,
203 Effect.andThen(fs.remove(dir, { recursive: true }).pipe(Effect.ignore)),
204 );
205
206 yield* Effect.gen(function* () {
207 // ── Fixture ───────────────────────────────────────────────────────
208 // The fixture's own dependencies (if any) plus the published pair.
209 const fixturePackage = yield* fs.readFileString(path.join(dir, "package.json")).pipe(
210 Effect.map((raw) => JSON.parse(raw) as { dependencies?: Record<string, string> }),
211 Effect.orElseSucceed(() => ({}) as { dependencies?: Record<string, string> }),
212 );
213 yield* fs.writeFileString(
214 path.join(dir, "package.json"),
215 JSON.stringify(
216 {
217 ...fixturePackage,
218 name: "web-function-upgrade-fixture",
219 private: true,
220 type: "module",
221 dependencies: {
222 ...fixturePackage.dependencies,
223 ...upgrade.peers,
224 alchemy: PUBLISHED,
225 "@alchemy.run/frontend-frameworks": PUBLISHED,
226 },
227 // Transitive platform packages must not float past them either.
228 ...(upgrade.peers ? { overrides: upgrade.peers } : {}),
229 },
230 null,
231 2,
232 ),
233 );
234 yield* fs.writeFileString(
235 path.join(dir, "alchemy.run.ts"),
236 stackProgram(upgrade.framework, "alchemy", "alchemy/AWS"),
237 );
238 // Current-version entry: the WORKSPACE sources by absolute path.
239 yield* fs.writeFileString(
240 path.join(dir, "alchemy.current.run.ts"),
241 stackProgram(
242 upgrade.framework,
243 pathe.join(repoRoot, "packages/alchemy/src/index.ts"),
244 pathe.join(repoRoot, "packages/aws/src/index.ts"),
245 ),
246 );
247
248 // Keep the stack entries out of the app's type-check: the current
249 // one imports the whole workspace source.
250 const tsconfigPath = path.join(dir, "tsconfig.json");
251 if (yield* fs.exists(tsconfigPath)) {
252 const tsconfig = JSON.parse(yield* fs.readFileString(tsconfigPath));
253 yield* fs.writeFileString(
254 tsconfigPath,
255 JSON.stringify({
256 ...tsconfig,
257 exclude: [...(tsconfig.exclude ?? []), "alchemy.run.ts", "alchemy.current.run.ts"],
258 }),
259 );
260 }
261
262 // ── Phase 1: deploy with the published version ────────────────────
263 yield* run({ cmd: "bun", args: upgrade.install, cwd: dir, env: awsEnv });
264 yield* run({
265 cmd: "bun",
266 args: ["node_modules/alchemy/bin/cli.js", "deploy", "--stage", STAGE, "--yes"],
267 cwd: dir,
268 env: awsEnv,
269 });
270
271 for (const { from } of upgrade.moved) {
272 expect((yield* readRow(from)).attr.functionUrl).toContain(".lambda-url.");
273 }
274 for (const row of upgrade.removed ?? []) {
275 expect(yield* fs.exists(stateFile(row))).toBe(true);
276 }
277 const before = yield* readRow("Site__Distribution");
278 const distributionId: string = before.attr.distributionId;
279 const siteUrl = `https://${before.attr.domainName}`;
280 yield* expectUrlContains(`${siteUrl}/`, upgrade.marker, {
281 timeout: "180 seconds",
282 label: "SSR page from the published version",
283 });
284
285 // ── Phase 2: re-deploy with the CURRENT workspace version ─────────
286 // The upgrade a user runs bumps both packages together.
287 const linked = path.join(dir, "node_modules", "@alchemy.run", "frontend-frameworks");
288 yield* fs.remove(linked, { recursive: true });
289 yield* fs.symlink(path.join(repoRoot, "packages/frontend-frameworks"), linked);
290 yield* run({
291 cmd: "bun",
292 args: [workspaceCli, "deploy", "./alchemy.current.run.ts", "--stage", STAGE, "--yes"],
293 cwd: dir,
294 env: awsEnv,
295 });
296
297 // Each server moved onto a Web Function and the old function is gone.
298 for (const { from, to } of upgrade.moved) {
299 expect((yield* readRow(to)).attr.domainName).toContain(".lambda-web.");
300 expect(yield* fs.exists(stateFile(from))).toBe(false);
301 }
302 for (const row of upgrade.removed ?? []) {
303 expect(yield* fs.exists(stateFile(row))).toBe(false);
304 }
305
306 // THE assertion: same distribution, same URL, still serving.
307 const after = yield* readRow("Site__Distribution");
308 expect(after.attr.distributionId).toEqual(distributionId);
309 yield* expectUrlContains(`${siteUrl}/`, upgrade.marker, {
310 timeout: "180 seconds",
311 label: "SSR page after the upgrade",
312 });
313
314 // ── Cleanup ───────────────────────────────────────────────────────
315 yield* destroy;
316 yield* cloudfront.getDistribution({ Id: distributionId }).pipe(
317 Effect.flatMap(() => Effect.fail(new Error("DistributionStillExists"))),
318 Effect.catchTag("NoSuchDistribution", () => Effect.void),
319 Effect.retry({
320 while: (error) =>
321 error instanceof Error && error.message === "DistributionStillExists",
322 schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(60)]),
323 }),
324 );
325 }).pipe(Effect.ensuring(cleanup));
326 }),
327 {
328 tags: ["provider:aws", "provider:aws:cloudfront", "provider:aws:website", "live"],
329 timeout: 2_400_000,
330 },
331 );
332 }