The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
| 1 | import { spawn } from "node:child_process"; |
| 2 | import * as AWS from "@alchemy.run/aws"; |
| 3 | import { describe, expect } from "@alchemy.run/test"; |
| 4 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 5 | import * as cloudfront from "@distilled.cloud/aws/cloudfront"; |
| 6 | import * as S3 from "@distilled.cloud/aws/s3"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as HttpClient from "effect/http/HttpClient"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import * as pathe from "pathe"; |
| 11 | import { cloneFixture } from "../../Cloudflare/Utils/Fixture.ts"; |
| 12 | import { expectUrlContains } from "../../Cloudflare/Utils/Http.ts"; |
| 13 | |
| 14 | const { test } = Test.make({ providers: AWS.providers() }); |
| 15 | |
| 16 | // Gated with the rest of the AWS.Website suites: the OpenNext build plus the |
| 17 | // CloudFront lifecycle dominate the runtime (create ~10-20 min, destroy |
| 18 | // ~5-15 min). |
| 19 | const runLive = !process.env.FAST; |
| 20 | |
| 21 | const fixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "nextjs-app"); |
| 22 | |
| 23 | const fixtureEntries = [ |
| 24 | ".gitignore", |
| 25 | "package.json", |
| 26 | "next.config.ts", |
| 27 | "tsconfig.json", |
| 28 | "app", |
| 29 | "public", |
| 30 | ]; |
| 31 | |
| 32 | /** |
| 33 | * Run a command to completion in a child process (Effect-wrapped spawn — |
| 34 | * the suite shares one bun process, so a sync spawn would stall every |
| 35 | * concurrently running test). Fails with the combined output on a |
| 36 | * non-zero exit. |
| 37 | */ |
| 38 | const run = (options: { cmd: string; args: string[]; cwd: string }): Effect.Effect<string, Error> => |
| 39 | Effect.callback<string, Error>((resume) => { |
| 40 | const child = spawn(options.cmd, options.args, { |
| 41 | cwd: options.cwd, |
| 42 | env: { ...process.env, NO_COLOR: "1" }, |
| 43 | stdio: ["ignore", "pipe", "pipe"], |
| 44 | }); |
| 45 | let output = ""; |
| 46 | child.stdout.on("data", (chunk) => (output += chunk)); |
| 47 | child.stderr.on("data", (chunk) => (output += chunk)); |
| 48 | child.once("error", (error) => resume(Effect.fail(error))); |
| 49 | child.once("close", (code) => |
| 50 | resume( |
| 51 | code === 0 |
| 52 | ? Effect.succeed(output) |
| 53 | : Effect.fail( |
| 54 | new Error(`${options.cmd} ${options.args.join(" ")} exited ${code}:\n${output}`), |
| 55 | ), |
| 56 | ), |
| 57 | ); |
| 58 | return Effect.sync(() => child.kill("SIGKILL")); |
| 59 | }); |
| 60 | |
| 61 | // Skipped under the floci runner: in dev the composite deploys only the |
| 62 | // framework dev server (no Lambda/S3/CloudFront), so this test's live |
| 63 | // topology assertions are meaningless there. Dev behavior is covered by |
| 64 | // the co-located Nextjs.local.test.ts suite. |
| 65 | const runEmulated = process.env.ALCHEMY_TEST_DEV === "1"; |
| 66 | |
| 67 | describe.skipIf(!runLive || runEmulated)( |
| 68 | "AWS.Website.Nextjs", |
| 69 | { tags: ["provider:aws", "provider:aws:cloudfront", "provider:aws:website", "live"] }, |
| 70 | () => { |
| 71 | // The default runs the server and image optimizer on Web Functions; |
| 72 | // `server: "function"` keeps them on Lambda Function URLs. |
| 73 | for (const server of ["web-function", "function"] as const) { |
| 74 | test.provider( |
| 75 | `server: "${server}" deploys Next.js: SSR, S3 assets, image optimization, ISR`, |
| 76 | (stack) => |
| 77 | Effect.gen(function* () { |
| 78 | yield* stack.destroy(); |
| 79 | |
| 80 | // Clone OUTSIDE the repo (OS temp dir): an in-workspace clone makes |
| 81 | // OpenNext detect the workspace as a monorepo and trace the server |
| 82 | // bundle against bun's isolated-install symlink store, which drops |
| 83 | // transitive deps (e.g. @swc/helpers) from the shipped node_modules. |
| 84 | const rootDir = yield* cloneFixture(fixtureDir, { |
| 85 | prefix: `alchemy-nextjs-aws-${server}-`, |
| 86 | entries: fixtureEntries, |
| 87 | }); |
| 88 | // Hoisted install in the clone so output tracing sees a plain |
| 89 | // node_modules tree — the representative user-project shape. |
| 90 | yield* run({ cmd: "bun", args: ["install", "--linker=hoisted"], cwd: rootDir }); |
| 91 | |
| 92 | const deployed = yield* stack.deploy( |
| 93 | Effect.gen(function* () { |
| 94 | const site = yield* AWS.Website.Nextjs("NextjsSite", { |
| 95 | rootDir, |
| 96 | server, |
| 97 | forceDestroy: true, |
| 98 | invalidation: { paths: "all", wait: true }, |
| 99 | }); |
| 100 | // A second endpoint scales on its own environments: a second |
| 101 | // server process sharing the site's cache. |
| 102 | const other = |
| 103 | server === "web-function" |
| 104 | ? yield* AWS.Lambda.WebFunctionEndpoint("OtherEndpoint", { |
| 105 | function: site.server as AWS.Lambda.WebFunction, |
| 106 | authType: "ApplicationManaged", |
| 107 | }) |
| 108 | : undefined; |
| 109 | return { site, other }; |
| 110 | }), |
| 111 | ); |
| 112 | |
| 113 | const url = deployed.site.url! as string; |
| 114 | expect(url).toMatch(/^https:\/\//); |
| 115 | expect(deployed.site.serverUrl).toBeDefined(); |
| 116 | if (server === "web-function") { |
| 117 | // Next's standalone server does it all: no image function, no |
| 118 | // revalidation queue or tag table. |
| 119 | expect(deployed.site.serverUrl).toContain(".lambda-web."); |
| 120 | expect(deployed.site.imageFunction).toBeUndefined(); |
| 121 | expect(deployed.site.revalidationQueue).toBeUndefined(); |
| 122 | expect(deployed.site.tagCacheTable).toBeUndefined(); |
| 123 | } else { |
| 124 | expect(deployed.site.serverUrl).toContain(".lambda-url."); |
| 125 | expect(deployed.site.imageUrl).toContain(".lambda-url."); |
| 126 | expect(deployed.site.revalidationQueue).toBeDefined(); |
| 127 | expect(deployed.site.tagCacheTable).toBeDefined(); |
| 128 | } |
| 129 | yield* Effect.log(`site url: ${url} | server url: ${deployed.site.serverUrl}`); |
| 130 | |
| 131 | // The Lambda Function URL serves the SSR page directly — isolates |
| 132 | // server-function health from the CloudFront edge routing. |
| 133 | yield* expectUrlContains(`${deployed.site.serverUrl!}`, "NEXTJS_AWS_PAGE_MARKER", { |
| 134 | timeout: "120 seconds", |
| 135 | label: "SSR direct from Lambda URL", |
| 136 | }); |
| 137 | |
| 138 | // SSR page rendered by the Lambda through CloudFront. |
| 139 | yield* expectUrlContains(`${url}/`, "NEXTJS_AWS_PAGE_MARKER", { |
| 140 | timeout: "180 seconds", |
| 141 | label: "SSR home page", |
| 142 | }); |
| 143 | // App Router API route through the streaming Function URL origin. |
| 144 | yield* expectUrlContains(`${url}/api/hello?echo=roundtrip`, "NEXTJS_AWS_API_MARKER", { |
| 145 | label: "API route", |
| 146 | }); |
| 147 | yield* expectUrlContains(`${url}/api/hello?echo=roundtrip`, "roundtrip", { |
| 148 | label: "API route query echo", |
| 149 | }); |
| 150 | // Statically-rendered page: prerendered into the ISR cache at build |
| 151 | // time, served by the server function through the S3 incremental |
| 152 | // cache — proves the cache seed upload and the cache-bucket IAM. |
| 153 | yield* expectUrlContains(`${url}/static`, "NEXTJS_AWS_STATIC_MARKER", { |
| 154 | label: "static (prerendered) page", |
| 155 | }); |
| 156 | // Public file served from S3 via the KV file manifest. |
| 157 | yield* expectUrlContains(`${url}/robots.txt`, "nextjs-aws-robots-marker", { |
| 158 | label: "public asset from S3", |
| 159 | }); |
| 160 | // Client asset (hashed chunk) served from S3: the SSR page links |
| 161 | // /_next/static/* files uploaded by the asset deployment. |
| 162 | expect(deployed.site.files?.files).toBeDefined(); |
| 163 | |
| 164 | // Image optimization: /_next/image is routed by the edge function |
| 165 | // to the dedicated optimizer Lambda, which loads the original from |
| 166 | // the asset bucket and returns an optimized image. |
| 167 | const client = yield* HttpClient.HttpClient; |
| 168 | const imageUrl = `${url}/_next/image?url=%2Fpixel.png&w=64&q=75`; |
| 169 | const imageResponse = yield* client.get(imageUrl).pipe( |
| 170 | Effect.filterOrFail( |
| 171 | (response): boolean => response.status === 200, |
| 172 | (response) => new Error(`/_next/image returned status ${response.status}`), |
| 173 | ), |
| 174 | Effect.retry({ schedule: Schedule.exponential("2 seconds"), times: 8 }), |
| 175 | ); |
| 176 | expect(imageResponse.status).toBe(200); |
| 177 | expect(imageResponse.headers["content-type"] ?? "").toMatch(/^image\//); |
| 178 | |
| 179 | if (server === "web-function") { |
| 180 | // ISR through the S3 cache handler, across two environments. |
| 181 | // Straight to the servers: CloudFront may hold the page for its |
| 182 | // s-maxage. |
| 183 | const a = deployed.site.serverUrl as string; |
| 184 | const b = deployed.other!.url; |
| 185 | const get = (url: string) => |
| 186 | HttpClient.get(url).pipe( |
| 187 | Effect.flatMap((response) => |
| 188 | response.status === 200 |
| 189 | ? response.text |
| 190 | : Effect.fail(new Error(`${url} returned ${response.status}`)), |
| 191 | ), |
| 192 | Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 30 }), |
| 193 | ); |
| 194 | const instance = (base: string) => |
| 195 | get(`${base}/api/instance`).pipe( |
| 196 | Effect.map((body) => (JSON.parse(body) as { instance: string }).instance), |
| 197 | ); |
| 198 | const generated = (base: string) => |
| 199 | get(`${base}/isr`).pipe( |
| 200 | Effect.map((body) => /generated:(\d+):/.exec(body)?.[1]), |
| 201 | Effect.filterOrFail( |
| 202 | (stamp): stamp is string => stamp !== undefined, |
| 203 | () => new Error("no ISR timestamp"), |
| 204 | ), |
| 205 | ); |
| 206 | |
| 207 | // The two endpoints really are two server processes. |
| 208 | expect(yield* instance(a)).not.toBe(yield* instance(b)); |
| 209 | |
| 210 | // Both serve the same cached render, and it stays cached. |
| 211 | const first = yield* generated(a); |
| 212 | expect(yield* generated(b)).toBe(first); |
| 213 | expect(yield* generated(a)).toBe(first); |
| 214 | |
| 215 | // Revalidating in one environment reaches the other. |
| 216 | const revalidated = yield* HttpClient.post(`${a}/api/revalidate`).pipe( |
| 217 | Effect.flatMap((response) => response.json), |
| 218 | ); |
| 219 | expect(revalidated).toEqual({ revalidated: true }); |
| 220 | const second = yield* generated(b).pipe( |
| 221 | Effect.repeat({ |
| 222 | schedule: Schedule.spaced("2 seconds"), |
| 223 | until: (stamp) => stamp !== first, |
| 224 | times: 15, |
| 225 | }), |
| 226 | ); |
| 227 | expect(second).not.toBe(first); |
| 228 | // ...and the new render is the one both now serve. |
| 229 | expect(yield* generated(a)).toBe(second); |
| 230 | expect(yield* generated(b)).toBe(second); |
| 231 | |
| 232 | // Out-of-band: the entries and the tag manifest are in S3. |
| 233 | const objects = yield* S3.listObjectsV2({ |
| 234 | Bucket: deployed.site.cacheBucket!.bucketName, |
| 235 | Prefix: "_cache/", |
| 236 | }); |
| 237 | const keys = (objects.Contents ?? []).map((object) => object.Key ?? ""); |
| 238 | expect(keys).toContain("_cache/tags.json"); |
| 239 | expect(keys.some((key) => key.startsWith("_cache/entries/"))).toBe(true); |
| 240 | } |
| 241 | |
| 242 | const distributionId = deployed.site.distribution!.distributionId; |
| 243 | |
| 244 | if (!process.env.NO_DESTROY) { |
| 245 | yield* stack.destroy(); |
| 246 | yield* assertDistributionDeleted(distributionId); |
| 247 | } |
| 248 | }), |
| 249 | { timeout: 2_400_000 }, |
| 250 | ); |
| 251 | } |
| 252 | }, |
| 253 | ); |
| 254 | |
| 255 | const assertDistributionDeleted = (distributionId: string) => |
| 256 | cloudfront.getDistribution({ Id: distributionId }).pipe( |
| 257 | Effect.flatMap(() => Effect.fail(new Error("DistributionStillExists"))), |
| 258 | Effect.catchTag("NoSuchDistribution", () => Effect.void), |
| 259 | Effect.retry({ |
| 260 | while: (error): boolean => |
| 261 | error instanceof Error && error.message === "DistributionStillExists", |
| 262 | schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(60)]), |
| 263 | }), |
| 264 | ); |