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 { describe, expect } from "@alchemy.run/test"; |
| 4 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as FileSystem from "effect/FileSystem"; |
| 7 | import * as HttpClient from "effect/http/HttpClient"; |
| 8 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 9 | import * as Path from "effect/Path"; |
| 10 | import { MinimumLogLevel } from "effect/References"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | import * as pathe from "pathe"; |
| 13 | import { cloneFixture } from "../Utils/Fixture.ts"; |
| 14 | import { waitForWorkerToBeDeleted } from "../Utils/Worker.ts"; |
| 15 | import { prepareNextjsFixture } from "./TypeScriptCompat.ts"; |
| 16 | |
| 17 | const { test } = Test.make({ providers: Cloudflare.providers() }); |
| 18 | |
| 19 | const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info"); |
| 20 | |
| 21 | const fixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "nextjs-isr-app"); |
| 22 | const stampOf = (body: string, prefix: string): string | undefined => |
| 23 | body.match(new RegExp(`${prefix}:(?:<!-- -->)?(\\d+)`))?.[1]; |
| 24 | |
| 25 | /** GET `url` until a stamp is present and `predicate(stamp)` holds. */ |
| 26 | const pollStamp = ( |
| 27 | url: string, |
| 28 | prefix: string, |
| 29 | predicate: (stamp: string) => boolean, |
| 30 | times = 45, |
| 31 | ) => |
| 32 | Effect.gen(function* () { |
| 33 | const client = yield* HttpClient.HttpClient; |
| 34 | return yield* client.get(url).pipe( |
| 35 | Effect.flatMap((res) => |
| 36 | Effect.flatMap(res.text, (body) => { |
| 37 | const stamp = res.status === 200 ? stampOf(body, prefix) : undefined; |
| 38 | return stamp !== undefined && predicate(stamp) |
| 39 | ? Effect.succeed(stamp) |
| 40 | : Effect.fail( |
| 41 | new Error(`stamp not ready (${res.status}): ${stamp ?? body.slice(0, 200)}`), |
| 42 | ); |
| 43 | }), |
| 44 | ), |
| 45 | Effect.retry({ schedule: Schedule.spaced("2 seconds"), times }), |
| 46 | ); |
| 47 | }); |
| 48 | |
| 49 | /** |
| 50 | * Writable ISR on real Cloudflare: KV incremental cache + KV tag cache + |
| 51 | * same-worker Durable Object revalidation queue, with the |
| 52 | * `WORKER_SELF_REFERENCE` self service binding wired automatically by the |
| 53 | * Nextjs resource. Covers: |
| 54 | * |
| 55 | * 1. the ISR page caches in KV (stable stamp across hits) |
| 56 | * 2. on-demand `revalidatePath` purges the writable cache (fresh stamp) |
| 57 | * 3. time-based revalidation regenerates through the DO queue, which |
| 58 | * re-fetches the worker via the self service binding |
| 59 | * 4. a second deploy is a noop (pins the self_service + DO binding |
| 60 | * metadata hash stability) |
| 61 | */ |
| 62 | // Tests are independent (per-test scratch stacks, private fixture clones), |
| 63 | // so run them concurrently; suites are sequential by default. |
| 64 | describe.concurrent( |
| 65 | "Nextjs ISR", |
| 66 | { |
| 67 | tags: [ |
| 68 | "provider:cloudflare", |
| 69 | "provider:cloudflare:kv", |
| 70 | "provider:cloudflare:website", |
| 71 | "provider:cloudflare:worker", |
| 72 | "live", |
| 73 | ], |
| 74 | }, |
| 75 | () => { |
| 76 | test.provider( |
| 77 | "Nextjs writable ISR: KV cache + DO queue + self-reference on real Cloudflare", |
| 78 | (stack) => |
| 79 | Effect.gen(function* () { |
| 80 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 81 | |
| 82 | yield* stack.destroy(); |
| 83 | |
| 84 | const rootDir = yield* cloneFixture(fixtureDir, { |
| 85 | prefix: "alchemy-nextjs-isr-", |
| 86 | entries: ["package.json", "tsconfig.json", "next.config.mjs", "app", "public"], |
| 87 | }); |
| 88 | yield* prepareNextjsFixture(rootDir); |
| 89 | const fs = yield* FileSystem.FileSystem; |
| 90 | const path = yield* Path.Path; |
| 91 | const nextConfigPath = path.join(rootDir, "next.config.mjs"); |
| 92 | const nextConfig = yield* fs.readFileString(nextConfigPath); |
| 93 | expect(yield* fs.exists(path.join(rootDir, "open-next.config.ts"))).toBe(false); |
| 94 | |
| 95 | const deploy = () => |
| 96 | stack.deploy( |
| 97 | Effect.gen(function* () { |
| 98 | const incCache = yield* Cloudflare.KV.Namespace("NextIncCache"); |
| 99 | const tagCache = yield* Cloudflare.KV.Namespace("NextTagCache"); |
| 100 | const site = yield* Cloudflare.Website.Nextjs("NextjsIsrSite", { |
| 101 | rootDir, |
| 102 | workersDev: { enabled: true, previewsEnabled: true }, |
| 103 | memo: { |
| 104 | include: [ |
| 105 | "app/**", |
| 106 | "public/**", |
| 107 | "package.json", |
| 108 | "tsconfig.json", |
| 109 | "next.config.mjs", |
| 110 | ], |
| 111 | }, |
| 112 | isr: { incrementalCache: incCache, tagCache }, |
| 113 | }); |
| 114 | return { site }; |
| 115 | }), |
| 116 | ); |
| 117 | |
| 118 | const { site } = yield* deploy(); |
| 119 | expect(yield* fs.readFileString(nextConfigPath)).toBe(nextConfig); |
| 120 | expect(yield* fs.exists(path.join(rootDir, "open-next.config.ts"))).toBe(false); |
| 121 | expect(site.url).toBeDefined(); |
| 122 | |
| 123 | // 1. The ISR page caches in KV: the stamp stabilizes across hits. |
| 124 | // (The very first hits may race the initial cache write, so anchor |
| 125 | // on two consecutive equal reads.) |
| 126 | const client = yield* HttpClient.HttpClient; |
| 127 | // Read until two consecutive reads agree (bounded): earlier reads can |
| 128 | // each race the first cache write and render fresh. |
| 129 | let settled = yield* pollStamp(`${site.url!}/isr`, "isr-stamp", () => true); |
| 130 | for (let attempt = 0; attempt < 10; attempt++) { |
| 131 | const next = yield* pollStamp(`${site.url!}/isr`, "isr-stamp", () => true); |
| 132 | if (next === settled) break; |
| 133 | settled = next; |
| 134 | } |
| 135 | const cached = yield* pollStamp(`${site.url!}/isr`, "isr-stamp", () => true); |
| 136 | expect(cached).toBe(settled); |
| 137 | |
| 138 | // 2. On-demand revalidation: revalidatePath purges the KV entry; a |
| 139 | // subsequent render produces a NEW stamp. With a read-only cache |
| 140 | // this would never change. A single edge request can still 404 |
| 141 | // right after earlier probes succeeded (workers.dev colo |
| 142 | // inconsistency), so retry through non-200s, bounded — |
| 143 | // revalidatePath is idempotent. |
| 144 | const revalidateRes = yield* client |
| 145 | .execute(HttpClientRequest.post(`${site.url!}/api/revalidate`)) |
| 146 | .pipe( |
| 147 | Effect.flatMap((res) => |
| 148 | res.status === 200 |
| 149 | ? Effect.succeed(res) |
| 150 | : Effect.flatMap(res.text, (body) => |
| 151 | Effect.fail( |
| 152 | new Error(`revalidate not ready (${res.status}): ${body.slice(0, 200)}`), |
| 153 | ), |
| 154 | ), |
| 155 | ), |
| 156 | Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 30 }), |
| 157 | ); |
| 158 | expect(revalidateRes.status).toBe(200); |
| 159 | const fresh = yield* pollStamp(`${site.url!}/isr`, "isr-stamp", (s) => s !== cached); |
| 160 | expect(fresh).not.toBe(cached); |
| 161 | |
| 162 | // 3. Time-based revalidation: after the 2s window lapses, a stale |
| 163 | // hit enqueues regeneration through the DO queue (which re-fetches |
| 164 | // the worker via WORKER_SELF_REFERENCE) and a later hit serves the |
| 165 | // regenerated payload. |
| 166 | const fastPrimed = yield* pollStamp( |
| 167 | `${site.url!}/fast-isr`, |
| 168 | "fast-isr-stamp", |
| 169 | () => true, |
| 170 | ); |
| 171 | yield* Effect.sleep("3 seconds"); |
| 172 | const fastFresh = yield* pollStamp( |
| 173 | `${site.url!}/fast-isr`, |
| 174 | "fast-isr-stamp", |
| 175 | (s) => s !== fastPrimed, |
| 176 | 60, |
| 177 | ); |
| 178 | expect(fastFresh).not.toBe(fastPrimed); |
| 179 | |
| 180 | // 4. Second deploy: nothing changed, so the deploy is a noop — pins |
| 181 | // the metadata-hash stability of the self_service sentinel and the |
| 182 | // own-class DO binding. |
| 183 | const again = yield* deploy(); |
| 184 | expect(again.site.hash?.input).toEqual(site.hash?.input); |
| 185 | expect(again.site.url).toBe(site.url); |
| 186 | |
| 187 | yield* stack.destroy(); |
| 188 | yield* waitForWorkerToBeDeleted(site.workerName, accountId); |
| 189 | }).pipe(logLevel), |
| 190 | { timeout: 600_000 }, |
| 191 | ); |
| 192 | }, |
| 193 | ); |