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 * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment"; |
| 3 | import { CloudflareApiLive } from "@alchemy.run/cloudflare/Providers"; |
| 4 | import { describe, expect } from "@alchemy.run/test"; |
| 5 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 6 | import * as durableObjects from "@distilled.cloud/cloudflare/durable-objects"; |
| 7 | import * as workers from "@distilled.cloud/cloudflare/workers"; |
| 8 | import { adopt } from "alchemy/AdoptPolicy"; |
| 9 | import * as Output from "alchemy/Output"; |
| 10 | import { State } from "alchemy/State"; |
| 11 | import * as Data from "effect/Data"; |
| 12 | import * as Effect from "effect/Effect"; |
| 13 | import * as Exit from "effect/Exit"; |
| 14 | import * as HttpClient from "effect/http/HttpClient"; |
| 15 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 16 | import { MinimumLogLevel } from "effect/References"; |
| 17 | import * as Schedule from "effect/Schedule"; |
| 18 | import * as Stream from "effect/Stream"; |
| 19 | import { testName } from "../../names.ts"; |
| 20 | import { getWorkerTags } from "../Utils/Worker.ts"; |
| 21 | import { requestWorker } from "../Utils/WorkerRequest.ts"; |
| 22 | import Stack from "./fixtures/do-rpc/stack.ts"; |
| 23 | |
| 24 | const { test, beforeAll, afterAll, deploy, destroy } = Test.make({ |
| 25 | providers: Cloudflare.providers(), |
| 26 | }); |
| 27 | |
| 28 | const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info"); |
| 29 | |
| 30 | const stack = beforeAll(deploy(Stack)); |
| 31 | afterAll.skipIf(!!process.env.NO_DESTROY)( |
| 32 | Effect.gen(function* () { |
| 33 | const deployed = yield* Effect.exit(stack); |
| 34 | yield* destroy(Stack); |
| 35 | if (Exit.isFailure(deployed)) return; |
| 36 | const scriptName = new URL(deployed.value.url).hostname.split(".")[0]!; |
| 37 | yield* Effect.gen(function* () { |
| 38 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 39 | const deleted = yield* workers.getScript({ accountId, scriptName }).pipe( |
| 40 | Effect.as(false), |
| 41 | Effect.catchTag("WorkerNotFound", () => Effect.succeed(true)), |
| 42 | Effect.repeat({ while: (gone) => !gone, schedule: Schedule.spaced("1 second"), times: 8 }), |
| 43 | Effect.timeout("15 seconds"), |
| 44 | ); |
| 45 | expect(deleted).toBe(true); |
| 46 | const namespaceDeleted = yield* durableObjects.listNamespaces.items({ accountId }).pipe( |
| 47 | Stream.runCollect, |
| 48 | Effect.map( |
| 49 | (namespaces) => !namespaces.some((namespace) => namespace.script === scriptName), |
| 50 | ), |
| 51 | Effect.repeat({ while: (gone) => !gone, schedule: Schedule.spaced("1 second"), times: 8 }), |
| 52 | Effect.timeout("15 seconds"), |
| 53 | ); |
| 54 | expect(namespaceDeleted).toBe(true); |
| 55 | }).pipe(Effect.provide(CloudflareApiLive()), Effect.scoped); |
| 56 | }), |
| 57 | { timeout: 120_000 }, |
| 58 | ); |
| 59 | |
| 60 | // Cap exponential backoff at 3s — keeps the fast-path snappy but stops |
| 61 | // the geometric blow-up (0.5 + 1 + 2 + 4 + 8 + 16 + 32 + 64s ...) that |
| 62 | // makes retries dominate test wall time when CF edge is slow. |
| 63 | const readinessSchedule = Schedule.min([ |
| 64 | Schedule.exponential("500 millis"), |
| 65 | Schedule.spaced("3 seconds"), |
| 66 | ]); |
| 67 | |
| 68 | const readinessRetries = 10; |
| 69 | |
| 70 | // The test runtime's HttpClient (FetchHttpClient/undici) keeps HTTP/1.1 |
| 71 | // connections alive and pooled. A pooled connection stays pinned to a single |
| 72 | // Cloudflare edge metal, so when that metal lags the freshly-deployed version |
| 73 | // every retry rides the same stale socket and keeps reading the old body for |
| 74 | // the life of the keep-alive — even though the new version is already live. |
| 75 | // Forcing `Connection: close` makes each readiness attempt open a fresh |
| 76 | // connection, letting it land on an edge that has the new version (this is |
| 77 | // why a brand-new `curl` sees the update immediately while a kept-alive |
| 78 | // client does not). See do-rpc DurableObject test investigation. |
| 79 | const freshConn = HttpClient.mapRequest(HttpClientRequest.setHeader("connection", "close")); |
| 80 | |
| 81 | for (const encoding of ["json", "bytes"] as const) { |
| 82 | for (const scenario of ["complete", "cancel", "empty", "head-failure", "tail-failure"] as const) { |
| 83 | test( |
| 84 | `native RPC ${encoding} stream handles ${scenario} with its source and event scopes`, |
| 85 | Effect.gen(function* () { |
| 86 | const { url } = yield* stack; |
| 87 | const client = freshConn(yield* HttpClient.HttpClient); |
| 88 | yield* client.get(`${url}/rpc-stream-ready/${encoding}-${scenario}`).pipe( |
| 89 | Effect.flatMap((response) => |
| 90 | response.text.pipe( |
| 91 | Effect.flatMap((body) => |
| 92 | response.status === 200 && body === "rpc-stream-scopes" |
| 93 | ? Effect.void |
| 94 | : Effect.fail( |
| 95 | new Error(`RPC fixture not ready: ${response.status}: ${body.slice(0, 300)}`), |
| 96 | ), |
| 97 | ), |
| 98 | ), |
| 99 | ), |
| 100 | // Namespace activation can lag the Worker route. This is bounded |
| 101 | // to ten retries and under a minute of total backoff. |
| 102 | Effect.retry({ |
| 103 | schedule: Schedule.min([ |
| 104 | Schedule.exponential("500 millis"), |
| 105 | Schedule.spaced("7 seconds"), |
| 106 | ]), |
| 107 | times: readinessRetries, |
| 108 | }), |
| 109 | ); |
| 110 | |
| 111 | // These calls cross the native DO RPC boundary; they do not use the |
| 112 | // separate Effect RPC-over-HTTP namespace protocol. |
| 113 | const response = yield* requestWorker( |
| 114 | HttpClientRequest.get(`${url}/rpc-stream/${encoding}/${scenario}`).pipe( |
| 115 | HttpClientRequest.setHeader("connection", "close"), |
| 116 | ), |
| 117 | { retryDelay: "5 seconds" }, |
| 118 | ); |
| 119 | expect(response.status).toBe(200); |
| 120 | const body = (yield* response.json) as { |
| 121 | values: Array<{ part: string; eventClosed: number; sourceClosed: number }>; |
| 122 | failed: boolean; |
| 123 | error?: { _tag: string; error?: { _tag: string; phase: string } }; |
| 124 | after: string; |
| 125 | }; |
| 126 | const parts = |
| 127 | scenario === "complete" |
| 128 | ? ["head", "tail"] |
| 129 | : scenario === "cancel" || scenario === "tail-failure" |
| 130 | ? ["head"] |
| 131 | : []; |
| 132 | expect(body.values).toEqual( |
| 133 | parts.map((part) => ({ part, eventClosed: 0, sourceClosed: 0 })), |
| 134 | ); |
| 135 | expect(body.failed).toBe(scenario === "head-failure" || scenario === "tail-failure"); |
| 136 | expect(body.after).toMatch(/^[0-9a-f]{64}$/); |
| 137 | if (scenario === "head-failure" || (scenario === "tail-failure" && encoding === "json")) { |
| 138 | expect(body.error).toMatchObject({ |
| 139 | _tag: "RpcRemoteStreamError", |
| 140 | error: { |
| 141 | _tag: "RpcStreamFixtureError", |
| 142 | phase: scenario === "head-failure" ? "head" : "tail", |
| 143 | }, |
| 144 | }); |
| 145 | } else if (scenario === "tail-failure") { |
| 146 | expect(body.error?._tag).toBe("SocketError"); |
| 147 | } |
| 148 | }).pipe(logLevel), |
| 149 | { tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"], timeout: 120_000 }, |
| 150 | ); |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | test( |
| 155 | "durable object methods can use binding clients", |
| 156 | Effect.gen(function* () { |
| 157 | const { url } = yield* stack; |
| 158 | const client = yield* HttpClient.HttpClient; |
| 159 | |
| 160 | const res = yield* client.post(`${url}/roundtrip`).pipe( |
| 161 | Effect.flatMap((res) => |
| 162 | res.status === 200 |
| 163 | ? Effect.succeed(res) |
| 164 | : Effect.fail(new Error(`Worker not ready: ${res.status}`)), |
| 165 | ), |
| 166 | Effect.retry({ schedule: readinessSchedule, times: 15 }), |
| 167 | ); |
| 168 | |
| 169 | expect(res.status).toBe(200); |
| 170 | const body = (yield* res.json) as { value: string }; |
| 171 | expect(body.value).toBe("ok"); |
| 172 | }).pipe(logLevel), |
| 173 | { |
| 174 | tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "live"], |
| 175 | timeout: 60_000, |
| 176 | }, |
| 177 | ); |
| 178 | |
| 179 | test( |
| 180 | "jurisdiction() addresses objects inside that jurisdiction", |
| 181 | Effect.gen(function* () { |
| 182 | const { url } = yield* stack; |
| 183 | const client = freshConn(yield* HttpClient.HttpClient); |
| 184 | const name = "jurisdiction-probe"; |
| 185 | |
| 186 | const res = yield* client.get(`${url}/jurisdiction?name=${name}`).pipe( |
| 187 | Effect.flatMap((res) => |
| 188 | res.status === 200 |
| 189 | ? Effect.succeed(res) |
| 190 | : Effect.fail(new Error(`Worker not ready: ${res.status}`)), |
| 191 | ), |
| 192 | Effect.retry({ schedule: readinessSchedule, times: readinessRetries }), |
| 193 | ); |
| 194 | const body = (yield* res.json) as { global: string; eu: string; euAgain: string }; |
| 195 | |
| 196 | // A jurisdiction-restricted id is a different object from the global one |
| 197 | // with the same name, and is stable across lookups. |
| 198 | expect(body.eu).toMatch(/^[0-9a-f]{64}$/); |
| 199 | expect(body.eu).not.toBe(body.global); |
| 200 | expect(body.euAgain).toBe(body.eu); |
| 201 | }).pipe(logLevel), |
| 202 | { |
| 203 | tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"], |
| 204 | timeout: 60_000, |
| 205 | }, |
| 206 | ); |
| 207 | |
| 208 | test( |
| 209 | "get, idFromName, idFromString and newUniqueId address the expected instance", |
| 210 | Effect.gen(function* () { |
| 211 | const { url } = yield* stack; |
| 212 | const client = freshConn(yield* HttpClient.HttpClient); |
| 213 | |
| 214 | const res = yield* client.get(`${url}/addressing?name=addressing-probe`).pipe( |
| 215 | Effect.flatMap((res) => |
| 216 | res.status === 200 |
| 217 | ? Effect.succeed(res) |
| 218 | : Effect.fail(new Error(`Worker not ready: ${res.status}`)), |
| 219 | ), |
| 220 | Effect.retry({ schedule: readinessSchedule, times: readinessRetries }), |
| 221 | ); |
| 222 | const body = (yield* res.json) as { |
| 223 | idFromName: string; |
| 224 | byName: string; |
| 225 | byId: string; |
| 226 | byIdString: string; |
| 227 | uniqueId: string; |
| 228 | unique: string; |
| 229 | otherUnique: string; |
| 230 | }; |
| 231 | |
| 232 | // `get(idFromName(name))` and the string round-trip reach the same |
| 233 | // instance as `getByName(name)`. |
| 234 | expect(body.byName).toMatch(/^[0-9a-f]{64}$/); |
| 235 | expect(body.idFromName).toBe(body.byName); |
| 236 | expect(body.byId).toBe(body.byName); |
| 237 | expect(body.byIdString).toBe(body.byName); |
| 238 | // `newUniqueId()` addresses a fresh instance each time. |
| 239 | expect(body.unique).toBe(body.uniqueId); |
| 240 | expect(body.unique).not.toBe(body.byName); |
| 241 | expect(body.otherUnique).not.toBe(body.unique); |
| 242 | }).pipe(logLevel), |
| 243 | { |
| 244 | tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"], |
| 245 | timeout: 60_000, |
| 246 | }, |
| 247 | ); |
| 248 | |
| 249 | test( |
| 250 | "calling an undefined durable object RPC method fails", |
| 251 | Effect.gen(function* () { |
| 252 | const { url } = yield* stack; |
| 253 | const client = freshConn(yield* HttpClient.HttpClient); |
| 254 | |
| 255 | const res = yield* client.get(`${url}/unknown-rpc`).pipe( |
| 256 | Effect.flatMap((res) => |
| 257 | res.status === 200 |
| 258 | ? Effect.succeed(res) |
| 259 | : Effect.fail(new Error(`Worker not ready: ${res.status}`)), |
| 260 | ), |
| 261 | Effect.retry({ schedule: readinessSchedule, times: readinessRetries }), |
| 262 | ); |
| 263 | const body = (yield* res.json) as { missing: string }; |
| 264 | |
| 265 | expect(body.missing).toContain('Method "missing" not found on Durable Object'); |
| 266 | }).pipe(logLevel), |
| 267 | { |
| 268 | tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"], |
| 269 | timeout: 60_000, |
| 270 | }, |
| 271 | ); |
| 272 | |
| 273 | class DurableObjectLocationNotReady extends Data.TaggedError("DurableObjectLocationNotReady")<{ |
| 274 | readonly message: string; |
| 275 | }> {} |
| 276 | |
| 277 | const locationFor = Effect.fn(function* ( |
| 278 | url: string, |
| 279 | options: { name?: string; hint?: Cloudflare.DurableObjectLocationHint } = {}, |
| 280 | ) { |
| 281 | const client = freshConn(yield* HttpClient.HttpClient); |
| 282 | const name = options.name ?? (yield* Effect.sync(() => crypto.randomUUID())); |
| 283 | const query = `name=${encodeURIComponent(name)}${options.hint ? `&hint=${options.hint}` : ""}`; |
| 284 | return yield* client.get(`${url}/colo?${query}`).pipe( |
| 285 | Effect.flatMap((res) => |
| 286 | Effect.gen(function* () { |
| 287 | if (res.status !== 200) { |
| 288 | return yield* new DurableObjectLocationNotReady({ |
| 289 | message: `Worker not ready: ${res.status}`, |
| 290 | }); |
| 291 | } |
| 292 | const body = (yield* res.json) as { id: string; colo: string; locationHintRead: boolean }; |
| 293 | if (!body.id || !body.colo || body.colo === "unknown") { |
| 294 | return yield* new DurableObjectLocationNotReady({ |
| 295 | message: `Instance not ready: ${JSON.stringify(body)}`, |
| 296 | }); |
| 297 | } |
| 298 | return body; |
| 299 | }), |
| 300 | ), |
| 301 | Effect.retry({ schedule: readinessSchedule, times: readinessRetries }), |
| 302 | ); |
| 303 | }); |
| 304 | |
| 305 | // Nearby placement is best-effort; named identity is the stable contract. |
| 306 | test( |
| 307 | "unhinted lookups preserve named instance identity", |
| 308 | Effect.gen(function* () { |
| 309 | const { url } = yield* stack; |
| 310 | const name = yield* Effect.sync(() => crypto.randomUUID()); |
| 311 | const [first, second] = yield* Effect.all( |
| 312 | [locationFor(url, { name }), locationFor(url, { name })], |
| 313 | { concurrency: 2 }, |
| 314 | ); |
| 315 | const other = yield* locationFor(url); |
| 316 | |
| 317 | expect(first.id).toMatch(/^[0-9a-f]{64}$/); |
| 318 | expect(first.id).toBe(second.id); |
| 319 | expect(first.id).not.toBe(other.id); |
| 320 | for (const result of [first, second, other]) { |
| 321 | expect(result.locationHintRead).toBe(false); |
| 322 | } |
| 323 | }).pipe(logLevel), |
| 324 | { |
| 325 | tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "live"], |
| 326 | timeout: 60_000, |
| 327 | }, |
| 328 | ); |
| 329 | |
| 330 | // The getter is read by the real native namespace only when options reach it. |
| 331 | test( |
| 332 | "locationHint reaches the native namespace for new instances", |
| 333 | Effect.gen(function* () { |
| 334 | const { url } = yield* stack; |
| 335 | const [wnam, apac] = yield* Effect.all( |
| 336 | [locationFor(url, { hint: "wnam" }), locationFor(url, { hint: "apac" })], |
| 337 | { concurrency: 2 }, |
| 338 | ); |
| 339 | |
| 340 | expect(wnam.locationHintRead).toBe(true); |
| 341 | expect(apac.locationHintRead).toBe(true); |
| 342 | expect(wnam.id).not.toBe(apac.id); |
| 343 | }).pipe(logLevel), |
| 344 | { |
| 345 | tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "live"], |
| 346 | timeout: 60_000, |
| 347 | }, |
| 348 | ); |
| 349 | |
| 350 | // Reproduces the `tick` streaming example from the Durable Objects tutorial: |
| 351 | // https://alchemy.run/cloudflare/compute/durable-objects |
| 352 | // |
| 353 | // The DO exposes `tick(n): Stream<number>` and the Worker forwards it to the |
| 354 | // HTTP response with `HttpServerResponse.stream`. The client reads the body as |
| 355 | // newline-delimited integers. With `/tick/5` we expect ["0","1","2","3","4"]. |
| 356 | // `pubsub` and `callback` push their values after the RPC method has |
| 357 | // returned; they ended after the first element while the stream's source |
| 358 | // scope closed with the call (#2273). |
| 359 | for (const source of ["tick", "pubsub", "callback"] as const) |
| 360 | test( |
| 361 | source === "tick" |
| 362 | ? "tick streams sequential values from a durable object (tutorial repro)" |
| 363 | : `${source}-backed stream delivers every value from a durable object`, |
| 364 | Effect.gen(function* () { |
| 365 | const { url } = yield* stack; |
| 366 | const client = freshConn(yield* HttpClient.HttpClient); |
| 367 | |
| 368 | const lines = yield* client.get(`${url}/${source}/5`).pipe( |
| 369 | Effect.flatMap((res) => |
| 370 | res.status === 200 |
| 371 | ? res.stream.pipe( |
| 372 | Stream.decodeText, |
| 373 | Stream.splitLines, |
| 374 | Stream.filter((line) => line.length > 0), |
| 375 | Stream.runCollect, |
| 376 | Effect.map((chunk) => [...chunk]), |
| 377 | // A cold edge can answer 200 with an empty/placeholder body |
| 378 | // (the script isn't serving yet), which collects to `[]` |
| 379 | // instead of failing — fail so the readiness retry rides it out |
| 380 | // rather than asserting against an empty stream. |
| 381 | Effect.flatMap((rows) => |
| 382 | rows.length > 0 |
| 383 | ? Effect.succeed(rows) |
| 384 | : Effect.fail(new Error("Worker not ready: empty stream")), |
| 385 | ), |
| 386 | ) |
| 387 | : Effect.fail(new Error(`Worker not ready: ${res.status}`)), |
| 388 | ), |
| 389 | Effect.retry({ schedule: readinessSchedule, times: readinessRetries }), |
| 390 | ); |
| 391 | |
| 392 | expect(lines).toEqual(["0", "1", "2", "3", "4"]); |
| 393 | }).pipe(logLevel), |
| 394 | { |
| 395 | tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "live"], |
| 396 | timeout: 60_000, |
| 397 | }, |
| 398 | ); |
| 399 | |
| 400 | // While a freshly pre-created worker is propagating, Cloudflare's edge |
| 401 | // serves Alchemy's pre-create stub, which responds 200 with this plain-text |
| 402 | // body. It is not the real script, so any poll that sees it must retry. |
| 403 | const DEPLOY_PLACEHOLDER = "Alchemy worker is being deployed..."; |
| 404 | |
| 405 | // Cloudflare's edge keeps serving the previous worker version (or the |
| 406 | // pre-create stub) for a while after a (re)deploy, so retrying on 200-only |
| 407 | // is not enough — the stale version still returns 200 with the old body. |
| 408 | // Retry until the body matches the expected version string. |
| 409 | const fetchReady = (url: string, expected: string) => |
| 410 | Effect.gen(function* () { |
| 411 | const client = freshConn(yield* HttpClient.HttpClient); |
| 412 | return yield* client.get(url).pipe( |
| 413 | Effect.flatMap((r) => |
| 414 | r.status === 200 |
| 415 | ? Effect.flatMap(r.text, (body) => |
| 416 | body === expected |
| 417 | ? Effect.succeed(body) |
| 418 | : Effect.fail(new Error(`stale: got ${body}, want ${expected}`)), |
| 419 | ) |
| 420 | : Effect.fail(new Error(`Worker not ready: ${r.status}`)), |
| 421 | ), |
| 422 | Effect.retry({ schedule: readinessSchedule, times: readinessRetries }), |
| 423 | ); |
| 424 | }); |
| 425 | |
| 426 | const fetchJsonReady = <T>(url: string) => |
| 427 | Effect.gen(function* () { |
| 428 | const client = freshConn(yield* HttpClient.HttpClient); |
| 429 | return yield* client.get(url).pipe( |
| 430 | // Parse the body INSIDE the retry: the pre-create stub answers 200 with |
| 431 | // a non-JSON placeholder, so JSON decoding must be part of the readiness |
| 432 | // check (a 200 status alone does not mean the real script is live yet). |
| 433 | Effect.flatMap((r) => |
| 434 | r.status !== 200 |
| 435 | ? Effect.flatMap(r.text, (body) => |
| 436 | Effect.fail( |
| 437 | new Error(`Worker not ready at ${url}: ${r.status} ${body.slice(0, 500)}`), |
| 438 | ), |
| 439 | ) |
| 440 | : Effect.flatMap(r.text, (body) => |
| 441 | body.includes(DEPLOY_PLACEHOLDER) |
| 442 | ? Effect.fail(new Error("stale: still deploying")) |
| 443 | : Effect.try({ |
| 444 | try: () => JSON.parse(body) as T, |
| 445 | catch: () => new Error(`non-json body: ${body}`), |
| 446 | }), |
| 447 | ), |
| 448 | ), |
| 449 | Effect.retry({ schedule: readinessSchedule, times: readinessRetries }), |
| 450 | ); |
| 451 | }); |
| 452 | |
| 453 | const hostWorkerScript = `import { DurableObject } from "cloudflare:workers"; |
| 454 | export class Counter extends DurableObject { |
| 455 | async increment() { |
| 456 | const value = (await this.ctx.storage.get("count")) ?? 0; |
| 457 | const next = value + 1; |
| 458 | await this.ctx.storage.put("count", next); |
| 459 | return next; |
| 460 | } |
| 461 | async reset() { |
| 462 | await this.ctx.storage.delete("count"); |
| 463 | } |
| 464 | async get() { |
| 465 | return (await this.ctx.storage.get("count")) ?? 0; |
| 466 | } |
| 467 | } |
| 468 | export default { |
| 469 | async fetch(request, env) { |
| 470 | const stub = env.Counter.getByName("shared"); |
| 471 | const url = new URL(request.url); |
| 472 | if (url.pathname === "/increment") { |
| 473 | return Response.json({ value: await stub.increment() }); |
| 474 | } |
| 475 | if (url.pathname === "/get") { |
| 476 | return Response.json({ value: await stub.get() }); |
| 477 | } |
| 478 | if (url.pathname === "/reset") { |
| 479 | await stub.reset(); |
| 480 | return Response.json({ ok: true }); |
| 481 | } |
| 482 | return new Response("Not Found", { status: 404 }); |
| 483 | }, |
| 484 | }; |
| 485 | `; |
| 486 | |
| 487 | const consumerWorkerScript = `export default { |
| 488 | async fetch(request, env) { |
| 489 | const stub = env.Counter.getByName("shared"); |
| 490 | const url = new URL(request.url); |
| 491 | if (url.pathname === "/increment") { |
| 492 | return Response.json({ value: await stub.increment() }); |
| 493 | } |
| 494 | if (url.pathname === "/get") { |
| 495 | return Response.json({ value: await stub.get() }); |
| 496 | } |
| 497 | if (url.pathname === "/reset") { |
| 498 | await stub.reset(); |
| 499 | return Response.json({ ok: true }); |
| 500 | } |
| 501 | return new Response("Not Found", { status: 404 }); |
| 502 | }, |
| 503 | }; |
| 504 | `; |
| 505 | |
| 506 | // Calls `get()` (RPC) or `fetch()` on a cross-script `Counter` and reports |
| 507 | // the outcome as JSON, so a failing Durable Object call is observable. |
| 508 | const placeholderProbeScript = `export default { |
| 509 | async fetch(request, env) { |
| 510 | const stub = env.Counter.getByName("placeholder-probe"); |
| 511 | const url = new URL(request.url); |
| 512 | try { |
| 513 | if (url.pathname === "/rpc") { |
| 514 | return Response.json({ ok: true, value: await stub.get() }); |
| 515 | } |
| 516 | if (url.pathname === "/fetch") { |
| 517 | const res = await stub.fetch("https://counter/"); |
| 518 | return Response.json({ ok: true, value: await res.text() }); |
| 519 | } |
| 520 | } catch (error) { |
| 521 | return Response.json({ ok: false, error: String(error?.message ?? error) }); |
| 522 | } |
| 523 | return new Response("Not Found", { status: 404 }); |
| 524 | }, |
| 525 | }; |
| 526 | `; |
| 527 | |
| 528 | interface ProbeResult { |
| 529 | ok: boolean; |
| 530 | value?: unknown; |
| 531 | error?: string; |
| 532 | } |
| 533 | |
| 534 | // Until the freshly pre-created host script reaches the consumer's edge, a |
| 535 | // cross-script call fails with "Worker not found." (fetch) or an opaque |
| 536 | // "internal error; reference = ..." (RPC) — retry past that propagation. |
| 537 | const probePlaceholder = (url: string) => |
| 538 | fetchJsonReady<ProbeResult>(url).pipe( |
| 539 | Effect.flatMap((result) => |
| 540 | result.error?.startsWith("internal error") || result.error === "Worker not found." |
| 541 | ? Effect.fail(new Error(`host not propagated yet: ${result.error}`)) |
| 542 | : Effect.succeed(result), |
| 543 | ), |
| 544 | Effect.retry({ schedule: readinessSchedule, times: readinessRetries }), |
| 545 | ); |
| 546 | |
| 547 | // Every `test.provider` test below owns an isolated scratch stack (private |
| 548 | // in-memory state, physical names derived from the unique test name), so |
| 549 | // none of them can observe another's cloud resources. Run them concurrently: |
| 550 | // each test's wall time is dominated by workers.dev edge-propagation waits, |
| 551 | // so overlapping them collapses the file from the sum of all tests (~7 min) |
| 552 | // to roughly the slowest single test. |
| 553 | describe.concurrent( |
| 554 | "scratch", |
| 555 | { tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "live"] }, |
| 556 | () => { |
| 557 | test.provider( |
| 558 | "async worker durable object binding accepts scriptName", |
| 559 | (scratch) => |
| 560 | Effect.gen(function* () { |
| 561 | yield* scratch.deploy( |
| 562 | Effect.gen(function* () { |
| 563 | return { |
| 564 | host: yield* Cloudflare.Worker("host-worker", { |
| 565 | script: hostWorkerScript, |
| 566 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 567 | }), |
| 568 | }; |
| 569 | }), |
| 570 | ); |
| 571 | |
| 572 | const deployed = yield* scratch.deploy( |
| 573 | Effect.gen(function* () { |
| 574 | const host = yield* Cloudflare.Worker("host-worker", { |
| 575 | script: hostWorkerScript, |
| 576 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 577 | }); |
| 578 | const consumer = yield* Cloudflare.Worker("consumer-worker", { |
| 579 | script: consumerWorkerScript, |
| 580 | env: { |
| 581 | Counter: Cloudflare.DurableObject("Counter", { scriptName: host.workerName }), |
| 582 | }, |
| 583 | }); |
| 584 | |
| 585 | return { consumer, host }; |
| 586 | }), |
| 587 | ); |
| 588 | |
| 589 | const reset = yield* fetchJsonReady<{ ok: boolean }>(`${deployed.host.url}/reset`); |
| 590 | expect(reset.ok).toBe(true); |
| 591 | |
| 592 | const first = yield* fetchJsonReady<{ value: number }>( |
| 593 | `${deployed.consumer.url}/increment`, |
| 594 | ); |
| 595 | expect(first.value).toBe(1); |
| 596 | |
| 597 | const second = yield* fetchJsonReady<{ value: number }>(`${deployed.host.url}/get`); |
| 598 | expect(second.value).toBe(1); |
| 599 | |
| 600 | yield* scratch.destroy(); |
| 601 | }).pipe(logLevel), |
| 602 | { timeout: 60_000 }, |
| 603 | ); |
| 604 | |
| 605 | // Walk an async worker through four redeploys against the same scratch state, |
| 606 | // each one swapping in a new script + bindings shape so we exercise the |
| 607 | // migration paths `putWorker` relies on: |
| 608 | // v1 — create with a single DO class `DO_A` |
| 609 | // v2 — rename `DO_A` → `DO_A_v2` (className change, same binding id) |
| 610 | // v3 — add a brand-new DO class `DO_B` alongside `DO_A_v2` |
| 611 | // v4 — delete `DO_A`, keep only `DO_B` |
| 612 | test.provider( |
| 613 | "durable object class migrations across redeploys", |
| 614 | (scratch) => |
| 615 | Effect.gen(function* () { |
| 616 | const v1 = yield* scratch.deploy( |
| 617 | Effect.gen(function* () { |
| 618 | return { |
| 619 | worker: yield* Cloudflare.Worker("worker", { |
| 620 | script: `import { DurableObject } from "cloudflare:workers"; |
| 621 | export class DO_A extends DurableObject {} |
| 622 | export default { async fetch() { return new Response("v1"); } }; |
| 623 | `, |
| 624 | env: { DO_A: Cloudflare.DurableObject("DO_A") }, |
| 625 | }), |
| 626 | }; |
| 627 | }), |
| 628 | ); |
| 629 | expect(yield* fetchReady(v1.worker.url!, "v1")).toBe("v1"); |
| 630 | |
| 631 | const v2 = yield* scratch.deploy( |
| 632 | Effect.gen(function* () { |
| 633 | return { |
| 634 | worker: yield* Cloudflare.Worker("worker", { |
| 635 | script: `import { DurableObject } from "cloudflare:workers"; |
| 636 | export class DO_A_v2 extends DurableObject {} |
| 637 | export default { async fetch() { return new Response("v2"); } }; |
| 638 | `, |
| 639 | env: { DO_A: Cloudflare.DurableObject("DO_A", { className: "DO_A_v2" }) }, |
| 640 | }), |
| 641 | }; |
| 642 | }), |
| 643 | ); |
| 644 | expect(yield* fetchReady(v2.worker.url!, "v2")).toBe("v2"); |
| 645 | |
| 646 | const v3 = yield* scratch.deploy( |
| 647 | Effect.gen(function* () { |
| 648 | return { |
| 649 | worker: yield* Cloudflare.Worker("worker", { |
| 650 | script: `import { DurableObject } from "cloudflare:workers"; |
| 651 | export class DO_A_v2 extends DurableObject {} |
| 652 | export class DO_B extends DurableObject {} |
| 653 | export default { async fetch() { return new Response("v3"); } }; |
| 654 | `, |
| 655 | env: { |
| 656 | DO_A: Cloudflare.DurableObject("DO_A", { className: "DO_A_v2" }), |
| 657 | DO_B: Cloudflare.DurableObject("DO_B"), |
| 658 | }, |
| 659 | }), |
| 660 | }; |
| 661 | }), |
| 662 | ); |
| 663 | expect(yield* fetchReady(v3.worker.url!, "v3")).toBe("v3"); |
| 664 | |
| 665 | const v4 = yield* scratch.deploy( |
| 666 | Effect.gen(function* () { |
| 667 | return { |
| 668 | worker: yield* Cloudflare.Worker("worker", { |
| 669 | script: `import { DurableObject } from "cloudflare:workers"; |
| 670 | export class DO_B extends DurableObject {} |
| 671 | export default { async fetch() { return new Response("v4"); } }; |
| 672 | `, |
| 673 | env: { DO_B: Cloudflare.DurableObject("DO_B") }, |
| 674 | }), |
| 675 | }; |
| 676 | }), |
| 677 | ); |
| 678 | expect(yield* fetchReady(v4.worker.url!, "v4")).toBe("v4"); |
| 679 | |
| 680 | yield* scratch.destroy(); |
| 681 | }).pipe(logLevel), |
| 682 | { timeout: 180_000 }, |
| 683 | ); |
| 684 | |
| 685 | // Reproduces #763: a Worker's precreate stub must declare Durable Object |
| 686 | // classes that exist only as env *bindings* — an async worker has no |
| 687 | // Effect-native exports, so before the fix the stub declared no DO classes at |
| 688 | // all. A resource caught in a dependency cycle with the worker resolves |
| 689 | // `worker.durableObjectNamespaces` against that stub (not the final reconcile |
| 690 | // output), so a binding-only class had no namespace id there and the deploy |
| 691 | // failed with "Worker did not expose Durable Object namespace <class>" on |
| 692 | // every fresh stage's FIRST deploy (reruns found the script already existing |
| 693 | // and passed — which is why this must run on a scratch stack, not a shared |
| 694 | // beforeAll deploy). |
| 695 | // |
| 696 | // The cycle here mirrors the worker<->container shape from the issue (a bare |
| 697 | // `Cloudflare.DurableObject` fronting a Container, where the container binds |
| 698 | // the DO's namespace id and the worker binds the container) without needing a |
| 699 | // Docker build: the consumer worker binds the host's `Counter` namespace id, |
| 700 | // and the host binds the consumer's name back. |
| 701 | test.provider( |
| 702 | "precreate stub exposes binding-only durable object namespaces to cycle peers", |
| 703 | (scratch) => |
| 704 | Effect.gen(function* () { |
| 705 | const deployed = yield* scratch.deploy( |
| 706 | Effect.gen(function* () { |
| 707 | // `Counter` lives only in the inline script + env binding — it is |
| 708 | // never an Effect-native export. |
| 709 | const host = yield* Cloudflare.Worker("host-worker", { |
| 710 | script: hostWorkerScript, |
| 711 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 712 | }); |
| 713 | |
| 714 | const consumer = yield* Cloudflare.Worker("consumer-worker", { |
| 715 | script: `export default { |
| 716 | async fetch(request, env) { |
| 717 | return Response.json({ namespaceId: env.COUNTER_NS }); |
| 718 | }, |
| 719 | }; |
| 720 | `, |
| 721 | }); |
| 722 | |
| 723 | // consumer -> host: resolve the DO namespace id, exactly how a |
| 724 | // Container application binds `durableObjects.namespaceId`. The |
| 725 | // throw fires when the precreate stub omits the class — failing the |
| 726 | // deploy the same way the container cycle in #763 did. |
| 727 | yield* consumer.bind("counter-namespace", { |
| 728 | bindings: [ |
| 729 | { |
| 730 | type: "plain_text", |
| 731 | name: "COUNTER_NS", |
| 732 | text: host.durableObjectNamespaces.pipe( |
| 733 | Output.map((namespaces) => { |
| 734 | const id = namespaces.Counter; |
| 735 | if (!id) { |
| 736 | throw new Error( |
| 737 | "Worker did not expose Durable Object namespace Counter.", |
| 738 | ); |
| 739 | } |
| 740 | return id; |
| 741 | }), |
| 742 | ), |
| 743 | }, |
| 744 | ], |
| 745 | }); |
| 746 | |
| 747 | // host -> consumer: closes the cycle so both workers are SCC |
| 748 | // members and rendezvous on each other's precreate stubs. |
| 749 | yield* host.bind("consumer-name", { |
| 750 | bindings: [ |
| 751 | { type: "plain_text", name: "CONSUMER_NAME", text: consumer.workerName }, |
| 752 | ], |
| 753 | }); |
| 754 | |
| 755 | return { host, consumer }; |
| 756 | }), |
| 757 | ); |
| 758 | |
| 759 | // The namespace id created for the precreate stub must survive into the |
| 760 | // final reconcile output... |
| 761 | const finalNamespaceId = deployed.host.durableObjectNamespaces.Counter; |
| 762 | expect(finalNamespaceId).toBeDefined(); |
| 763 | |
| 764 | // ...and be the same id the consumer resolved from the stub and |
| 765 | // deployed into its live environment. |
| 766 | const body = yield* fetchJsonReady<{ namespaceId: string }>(deployed.consumer.url!); |
| 767 | |
| 768 | expect(body.namespaceId).toBe(finalNamespaceId); |
| 769 | |
| 770 | yield* scratch.destroy(); |
| 771 | }).pipe(logLevel), |
| 772 | { timeout: 120_000 }, |
| 773 | ); |
| 774 | |
| 775 | // A Durable Object instance created on the precreate placeholder must reset |
| 776 | // itself on any call instead of serving the empty placeholder class. Before |
| 777 | // the fix, an instance that landed on the placeholder (an edge that hadn't |
| 778 | // seen the real version yet) failed every RPC call with "The RPC receiver |
| 779 | // does not implement the method" for as long as callers kept it busy. |
| 780 | // |
| 781 | // The placeholder is held live deterministically: the host's real script |
| 782 | // throws at startup, so its reconcile upload is rejected after precreate |
| 783 | // has already uploaded the placeholder, while the consumer (a cycle peer |
| 784 | // that rendezvoused on the host's precreate stub) deploys fully and |
| 785 | // reaches the placeholder's `Counter` through a cross-script binding. |
| 786 | test.provider( |
| 787 | "durable objects on the precreate placeholder reset onto the real version", |
| 788 | (scratch) => |
| 789 | Effect.gen(function* () { |
| 790 | yield* scratch.destroy(); |
| 791 | |
| 792 | const program = (hostScript: string) => |
| 793 | Effect.gen(function* () { |
| 794 | const host = yield* Cloudflare.Worker("host-worker", { |
| 795 | script: hostScript, |
| 796 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 797 | }); |
| 798 | const consumer = yield* Cloudflare.Worker("consumer-worker", { |
| 799 | script: placeholderProbeScript, |
| 800 | env: { |
| 801 | Counter: Cloudflare.DurableObject("Counter", { scriptName: host.workerName }), |
| 802 | }, |
| 803 | }); |
| 804 | // host -> consumer closes the cycle, so the host is pre-created. |
| 805 | yield* host.bind("consumer-name", { |
| 806 | bindings: [ |
| 807 | { type: "plain_text", name: "CONSUMER_NAME", text: consumer.workerName }, |
| 808 | ], |
| 809 | }); |
| 810 | return { host, consumer }; |
| 811 | }); |
| 812 | |
| 813 | const failed = yield* scratch |
| 814 | .deploy( |
| 815 | program( |
| 816 | `${hostWorkerScript}\nthrow new Error("placeholder probe: host fails at startup");\n`, |
| 817 | ), |
| 818 | ) |
| 819 | .pipe(Effect.exit); |
| 820 | expect(failed._tag).toBe("Failure"); |
| 821 | |
| 822 | // The deploy failed, so read the consumer's URL from the scratch state. |
| 823 | const consumerUrl = yield* Effect.gen(function* () { |
| 824 | const state = yield* yield* State; |
| 825 | const fqns = yield* state.list({ stack: scratch.name, stage: scratch.stage }); |
| 826 | const fqn = fqns.find((fqn) => fqn.endsWith("consumer-worker")); |
| 827 | expect(fqn).toBeDefined(); |
| 828 | const row = yield* state.get({ stack: scratch.name, stage: scratch.stage, fqn: fqn! }); |
| 829 | const attr = row && "attr" in row ? row.attr : undefined; |
| 830 | return (attr as { url?: string } | undefined)?.url; |
| 831 | }).pipe(Effect.provide(scratch.state)); |
| 832 | expect(consumerUrl).toBeDefined(); |
| 833 | |
| 834 | // Every call into the placeholder resets the object rather than |
| 835 | // reporting a missing method — RPC and fetch alike. |
| 836 | const rpc = yield* probePlaceholder(`${consumerUrl}/rpc`); |
| 837 | expect(rpc).toMatchObject({ ok: false }); |
| 838 | expect(rpc.error).toContain("Alchemy worker is being deployed"); |
| 839 | expect(rpc.error).not.toContain("does not implement the method"); |
| 840 | |
| 841 | const fetched = yield* probePlaceholder(`${consumerUrl}/fetch`); |
| 842 | expect(fetched).toMatchObject({ ok: false }); |
| 843 | expect(fetched.error).toContain("Alchemy worker is being deployed"); |
| 844 | |
| 845 | // Deploy the real host. The same named object now answers the real |
| 846 | // method — the placeholder instance reset instead of pinning it. |
| 847 | const deployed = yield* scratch.deploy(program(hostWorkerScript)); |
| 848 | expect(deployed.consumer.url).toBe(consumerUrl); |
| 849 | |
| 850 | const value = yield* fetchJsonReady<ProbeResult>(`${consumerUrl}/rpc`).pipe( |
| 851 | Effect.flatMap((result) => |
| 852 | result.ok |
| 853 | ? Effect.succeed(result.value) |
| 854 | : Effect.fail(new Error(`still on the placeholder: ${result.error}`)), |
| 855 | ), |
| 856 | Effect.retry({ schedule: readinessSchedule, times: readinessRetries }), |
| 857 | ); |
| 858 | expect(value).toBe(0); |
| 859 | |
| 860 | yield* scratch.destroy(); |
| 861 | }).pipe(logLevel), |
| 862 | { timeout: 180_000 }, |
| 863 | ); |
| 864 | |
| 865 | // Adopt a Durable Object class that already exists on a worker created |
| 866 | // *outside* Alchemy (raw Cloudflare API here, standing in for Wrangler or the |
| 867 | // dashboard). The worker carries no `alchemy:*` ownership tags and no |
| 868 | // `alchemy:do:` logical-id→class mapping, so `read` returns `Unowned` and the |
| 869 | // takeover requires `adopt(true)`. The matching `Counter` class must be reused |
| 870 | // — if `putWorker` instead asked Cloudflare to create it as a *new* class the |
| 871 | // migration would fail with "class already exists". This is the documented |
| 872 | // limitation: on the first (adopting) deploy the binding's class name must |
| 873 | // match the existing class; renames only work once Alchemy owns the worker. |
| 874 | test.provider( |
| 875 | "adopts a durable object class created outside alchemy", |
| 876 | (scratch) => |
| 877 | Effect.gen(function* () { |
| 878 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 879 | |
| 880 | // Phase 1: provision a worker + `Counter` DO class straight through the |
| 881 | // Cloudflare API — no Alchemy involvement, so none of our tags. The |
| 882 | // name is deterministic (never Date.now()/random); a crashed run can |
| 883 | // leave the worker behind, and `putScript` would then reject the |
| 884 | // `newSqliteClasses` migration ("class already exists"), so purge any |
| 885 | // leftover first. |
| 886 | const physicalName = testName("alchemy-test-do-adopt"); |
| 887 | |
| 888 | yield* workers |
| 889 | .deleteScript({ accountId, scriptName: physicalName, force: true }) |
| 890 | .pipe(Effect.catchTag("WorkerNotFound", () => Effect.void)); |
| 891 | |
| 892 | yield* workers.putScript({ |
| 893 | accountId, |
| 894 | scriptName: physicalName, |
| 895 | metadata: { |
| 896 | mainModule: "main.js", |
| 897 | bindings: [ |
| 898 | { type: "durable_object_namespace", name: "Counter", className: "Counter" }, |
| 899 | ], |
| 900 | migrations: { newSqliteClasses: ["Counter"] }, |
| 901 | // Match Alchemy's default compatibility date so adoption is a |
| 902 | // pure class-reuse with no compat-date churn. Old dates predate |
| 903 | // `DurableObjectNamespace.getByName`, which `hostWorkerScript` |
| 904 | // relies on. |
| 905 | compatibilityDate: "2026-03-17", |
| 906 | }, |
| 907 | files: [ |
| 908 | new File([hostWorkerScript], "main.js", { type: "application/javascript+module" }), |
| 909 | ], |
| 910 | }); |
| 911 | |
| 912 | // Phase 2: deploy an async Alchemy Worker (inline script) over the same |
| 913 | // physical name with a matching `Counter` binding, opting in to the |
| 914 | // takeover via `adopt(true)`. |
| 915 | const adopted = yield* scratch |
| 916 | .deploy( |
| 917 | Effect.gen(function* () { |
| 918 | return yield* Cloudflare.Worker("AdoptDO", { |
| 919 | name: physicalName, |
| 920 | script: hostWorkerScript, |
| 921 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 922 | }); |
| 923 | }), |
| 924 | ) |
| 925 | .pipe(adopt(true)); |
| 926 | |
| 927 | expect(adopted.workerName).toBe(physicalName); |
| 928 | // The existing class was adopted (and resolved to a namespace id), |
| 929 | // not recreated. |
| 930 | expect(adopted.durableObjectNamespaces.Counter).toBeDefined(); |
| 931 | |
| 932 | // The adopted DO is functional end-to-end: increment round-trips |
| 933 | // through the reused `Counter` class. |
| 934 | yield* fetchJsonReady<{ ok: boolean }>(`${adopted.url}/reset`); |
| 935 | const first = yield* fetchJsonReady<{ value: number }>(`${adopted.url}/increment`); |
| 936 | expect(first.value).toBe(1); |
| 937 | |
| 938 | yield* scratch.destroy(); |
| 939 | }).pipe(logLevel), |
| 940 | { timeout: 120_000 }, |
| 941 | ); |
| 942 | |
| 943 | // #2072: Wrangler ≥ 4.107 deploys Durable Objects with Cloudflare's |
| 944 | // declarative `exports` map, after which Cloudflare rejects every |
| 945 | // `migrations` upload ("reverting to `migrations` is not supported"). |
| 946 | // Alchemy must adopt such a Worker without touching its namespaces — |
| 947 | // including a class it never binds (reached through `ctx.exports`), which |
| 948 | // must stay declared or Cloudflare refuses the upload. |
| 949 | test.provider( |
| 950 | "adopts a worker deployed with declarative exports", |
| 951 | (scratch) => |
| 952 | Effect.gen(function* () { |
| 953 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 954 | const physicalName = `alchemy-test-do-exports-${scratch.stage |
| 955 | .toLowerCase() |
| 956 | .replace(/[^a-z0-9-]/g, "-")}`; |
| 957 | const script = `${hostWorkerScript}\nexport class Unbound extends DurableObject {}\n`; |
| 958 | |
| 959 | yield* workers |
| 960 | .deleteScript({ accountId, scriptName: physicalName, force: true }) |
| 961 | .pipe(Effect.catchTag("WorkerNotFound", () => Effect.void)); |
| 962 | |
| 963 | // Phase 1: the Wrangler-shaped deploy — declarative `exports`, no |
| 964 | // migrations, no Alchemy tags. |
| 965 | yield* workers.putScript({ |
| 966 | accountId, |
| 967 | scriptName: physicalName, |
| 968 | metadata: { |
| 969 | mainModule: "main.js", |
| 970 | bindings: [ |
| 971 | { type: "durable_object_namespace", name: "Counter", className: "Counter" }, |
| 972 | ], |
| 973 | exports: { |
| 974 | Counter: { type: "durable-object", storage: "sqlite" }, |
| 975 | Unbound: { type: "durable-object", storage: "sqlite" }, |
| 976 | }, |
| 977 | compatibilityDate: "2026-03-17", |
| 978 | }, |
| 979 | files: [new File([script], "main.js", { type: "application/javascript+module" })], |
| 980 | }); |
| 981 | const namespacesOf = Effect.gen(function* () { |
| 982 | const namespaces = yield* durableObjects.listNamespaces.items({ accountId }).pipe( |
| 983 | Stream.filter((ns) => ns.script === physicalName), |
| 984 | Stream.runCollect, |
| 985 | ); |
| 986 | return Object.fromEntries(Array.from(namespaces).map((ns) => [ns.class, ns.id])); |
| 987 | }); |
| 988 | const before = yield* namespacesOf; |
| 989 | expect(Object.keys(before).sort()).toEqual(["Counter", "Unbound"]); |
| 990 | |
| 991 | // Phase 2: adopt it. Only `Counter` is bound. |
| 992 | const deployAdopted = scratch |
| 993 | .deploy( |
| 994 | Effect.gen(function* () { |
| 995 | return yield* Cloudflare.Worker("AdoptExports", { |
| 996 | name: physicalName, |
| 997 | script, |
| 998 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 999 | }); |
| 1000 | }), |
| 1001 | ) |
| 1002 | .pipe(adopt(true)); |
| 1003 | const adopted = yield* deployAdopted; |
| 1004 | |
| 1005 | // Both namespaces survived the takeover unchanged. |
| 1006 | expect(adopted.durableObjectNamespaces.Counter).toBe(before.Counter); |
| 1007 | expect(yield* namespacesOf).toEqual(before); |
| 1008 | |
| 1009 | yield* fetchJsonReady<{ ok: boolean }>(`${adopted.url}/reset`); |
| 1010 | const written = yield* fetchJsonReady<{ value: number }>(`${adopted.url}/increment`); |
| 1011 | expect(written.value).toBe(1); |
| 1012 | |
| 1013 | // A routine redeploy keeps the data. |
| 1014 | const redeployed = yield* deployAdopted; |
| 1015 | const read = yield* fetchJsonReady<{ value: number }>(`${redeployed.url}/get`); |
| 1016 | expect(read.value).toBe(1); |
| 1017 | expect(yield* namespacesOf).toEqual(before); |
| 1018 | |
| 1019 | yield* scratch.destroy(); |
| 1020 | expect(yield* namespacesOf).toEqual({}); |
| 1021 | }).pipe(logLevel), |
| 1022 | { timeout: 180_000 }, |
| 1023 | ); |
| 1024 | |
| 1025 | // #799: moving a Durable Object class from one Worker to another is |
| 1026 | // *declared*: the new host names the former host with `transferredFrom` — |
| 1027 | // here by Worker *logical id*, resolved to the actual script via alchemy's |
| 1028 | // ownership tags (`alchemy:id:` + stack + stage) among scripts observed to |
| 1029 | // host the class. Worker-a's deploy ships Cloudflare's data-preserving |
| 1030 | // `transferred_classes` migration; worker-b's deploy converges on its own |
| 1031 | // (no `deleted_classes` for a class that moved away). |
| 1032 | // |
| 1033 | // v1 — worker-b hosts `Counter` locally; write data into the namespace |
| 1034 | // v2 — worker-a hosts `Counter` with `transferredFrom: "worker-b"`; |
| 1035 | // worker-b re-binds it cross-script. The stored data must survive |
| 1036 | // the move, reachable from both. |
| 1037 | // v3 — redeploy of the same shape is inert (no re-transfer; the |
| 1038 | // declaration stays in the code). |
| 1039 | test.provider( |
| 1040 | "durable object host move declared by worker logical id preserves data", |
| 1041 | (scratch) => |
| 1042 | Effect.gen(function* () { |
| 1043 | yield* scratch.destroy(); |
| 1044 | |
| 1045 | const v1 = yield* scratch.deploy( |
| 1046 | Effect.gen(function* () { |
| 1047 | return { |
| 1048 | b: yield* Cloudflare.Worker("worker-b", { |
| 1049 | script: hostWorkerScript, |
| 1050 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 1051 | }), |
| 1052 | }; |
| 1053 | }), |
| 1054 | ); |
| 1055 | |
| 1056 | const originalNamespaceId = v1.b.durableObjectNamespaces.Counter; |
| 1057 | expect(originalNamespaceId).toBeDefined(); |
| 1058 | |
| 1059 | // Write data while worker-b hosts the namespace. |
| 1060 | yield* fetchJsonReady<{ ok: boolean }>(`${v1.b.url}/reset`); |
| 1061 | const written = yield* fetchJsonReady<{ value: number }>(`${v1.b.url}/increment`); |
| 1062 | expect(written.value).toBe(1); |
| 1063 | |
| 1064 | const moved = Effect.gen(function* () { |
| 1065 | const a = yield* Cloudflare.Worker("worker-a", { |
| 1066 | script: hostWorkerScript, |
| 1067 | env: { |
| 1068 | Counter: Cloudflare.DurableObject("Counter", { |
| 1069 | // The former host's Worker *logical id* — resolved to its |
| 1070 | // physical script via alchemy's ownership tags. |
| 1071 | transferredFrom: "worker-b", |
| 1072 | }), |
| 1073 | }, |
| 1074 | }); |
| 1075 | const b = yield* Cloudflare.Worker("worker-b", { |
| 1076 | script: consumerWorkerScript, |
| 1077 | env: { Counter: Cloudflare.DurableObject("Counter", { scriptName: a.workerName }) }, |
| 1078 | }); |
| 1079 | return { a, b }; |
| 1080 | }); |
| 1081 | |
| 1082 | const v2 = yield* scratch.deploy(moved); |
| 1083 | expect(v2.a.durableObjectNamespaces.Counter).toBe(originalNamespaceId); |
| 1084 | expect(v2.b.durableObjectNamespaces.Counter).toBe(originalNamespaceId); |
| 1085 | |
| 1086 | // The namespace moved to worker-a with its data intact... |
| 1087 | const viaA = yield* fetchJsonReady<{ value: number }>(`${v2.a.url}/get`); |
| 1088 | expect(viaA.value).toBe(1); |
| 1089 | |
| 1090 | // ...and worker-b reaches the same objects through the cross-script |
| 1091 | // binding. |
| 1092 | const viaB = yield* fetchJsonReady<{ value: number }>(`${v2.b.url}/increment`); |
| 1093 | expect(viaB.value).toBe(2); |
| 1094 | |
| 1095 | // Redeploying the same shape is inert: the class now lives on |
| 1096 | // worker-a (tracked by its alchemy:do tag), so the standing |
| 1097 | // declaration must not re-emit a transfer migration. Data intact. |
| 1098 | const v3 = yield* scratch.deploy(moved); |
| 1099 | const afterRedeploy = yield* fetchJsonReady<{ value: number }>(`${v3.a.url}/get`); |
| 1100 | expect(afterRedeploy.value).toBe(2); |
| 1101 | |
| 1102 | // ...and once the move has landed everywhere, the declaration can be |
| 1103 | // removed entirely: the class is anchored by its alchemy:do tag, so |
| 1104 | // dropping `transferredFrom` emits no migration and touches no data. |
| 1105 | const v4 = yield* scratch.deploy( |
| 1106 | Effect.gen(function* () { |
| 1107 | const a = yield* Cloudflare.Worker("worker-a", { |
| 1108 | script: hostWorkerScript, |
| 1109 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 1110 | }); |
| 1111 | const b = yield* Cloudflare.Worker("worker-b", { |
| 1112 | script: consumerWorkerScript, |
| 1113 | env: { Counter: Cloudflare.DurableObject("Counter", { scriptName: a.workerName }) }, |
| 1114 | }); |
| 1115 | return { a, b }; |
| 1116 | }), |
| 1117 | ); |
| 1118 | const afterRemoval = yield* fetchJsonReady<{ value: number }>(`${v4.a.url}/get`); |
| 1119 | expect(afterRemoval.value).toBe(2); |
| 1120 | |
| 1121 | yield* scratch.destroy(); |
| 1122 | }).pipe(logLevel), |
| 1123 | { timeout: 240_000 }, |
| 1124 | ); |
| 1125 | |
| 1126 | // #799: `transferredFrom` also accepts the former host's *physical script |
| 1127 | // name* — the form required for cross-stack moves, where the new host |
| 1128 | // deploys from a different plan entirely (modeled here with raw-string |
| 1129 | // script names on a pre-existing worker). |
| 1130 | test.provider( |
| 1131 | "transferredFrom by physical script name transfers the namespace", |
| 1132 | (scratch) => |
| 1133 | Effect.gen(function* () { |
| 1134 | yield* scratch.destroy(); |
| 1135 | |
| 1136 | // v1: worker-b hosts the class; worker-a exists but has no DO yet — |
| 1137 | // deploying it now is what makes its physical name knowable as a raw |
| 1138 | // string in v2 (the cross-stack shape). |
| 1139 | const v1 = yield* scratch.deploy( |
| 1140 | Effect.gen(function* () { |
| 1141 | return { |
| 1142 | a: yield* Cloudflare.Worker("worker-a", { |
| 1143 | script: `export default { fetch() { return new Response("plain"); } };`, |
| 1144 | }), |
| 1145 | b: yield* Cloudflare.Worker("worker-b", { |
| 1146 | script: hostWorkerScript, |
| 1147 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 1148 | }), |
| 1149 | }; |
| 1150 | }), |
| 1151 | ); |
| 1152 | |
| 1153 | yield* fetchJsonReady<{ ok: boolean }>(`${v1.b.url}/reset`); |
| 1154 | const written = yield* fetchJsonReady<{ value: number }>(`${v1.b.url}/increment`); |
| 1155 | expect(written.value).toBe(1); |
| 1156 | |
| 1157 | const aScriptName = v1.a.workerName; |
| 1158 | const bScriptName = v1.b.workerName; |
| 1159 | |
| 1160 | const v2 = yield* scratch.deploy( |
| 1161 | Effect.gen(function* () { |
| 1162 | const a = yield* Cloudflare.Worker("worker-a", { |
| 1163 | script: hostWorkerScript, |
| 1164 | env: { |
| 1165 | Counter: Cloudflare.DurableObject("Counter", { |
| 1166 | // Thunk form — evaluated lazily at plan time and |
| 1167 | // normalized to the plain script name. |
| 1168 | transferredFrom: () => bScriptName, |
| 1169 | }), |
| 1170 | }, |
| 1171 | }); |
| 1172 | const b = yield* Cloudflare.Worker("worker-b", { |
| 1173 | script: consumerWorkerScript, |
| 1174 | env: { |
| 1175 | // Service binding orders worker-b after worker-a (the raw |
| 1176 | // string scriptName below carries no dependency edge). |
| 1177 | A: a, |
| 1178 | Counter: Cloudflare.DurableObject("Counter", { scriptName: aScriptName }), |
| 1179 | }, |
| 1180 | }); |
| 1181 | return { a, b }; |
| 1182 | }), |
| 1183 | ); |
| 1184 | |
| 1185 | const viaA = yield* fetchJsonReady<{ value: number }>(`${v2.a.url}/get`); |
| 1186 | expect(viaA.value).toBe(1); |
| 1187 | |
| 1188 | yield* scratch.destroy(); |
| 1189 | }).pipe(logLevel), |
| 1190 | { timeout: 240_000 }, |
| 1191 | ); |
| 1192 | |
| 1193 | // #799 (safety interlock): a host move WITHOUT `transferredFrom` must fail |
| 1194 | // loudly before the former host uploads anything — moves are never |
| 1195 | // inferred, the namespace (and its data) still lives on worker-b, and |
| 1196 | // deleting the class would destroy it. The error names the exact |
| 1197 | // declaration to add. |
| 1198 | test.provider( |
| 1199 | "undeclared host move fails with DurableObjectTransferRequired", |
| 1200 | (scratch) => |
| 1201 | Effect.gen(function* () { |
| 1202 | yield* scratch.destroy(); |
| 1203 | |
| 1204 | const v1 = yield* scratch.deploy( |
| 1205 | Effect.gen(function* () { |
| 1206 | return { |
| 1207 | a: yield* Cloudflare.Worker("worker-a", { |
| 1208 | script: `export default { fetch() { return new Response("plain"); } };`, |
| 1209 | }), |
| 1210 | b: yield* Cloudflare.Worker("worker-b", { |
| 1211 | script: hostWorkerScript, |
| 1212 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 1213 | }), |
| 1214 | }; |
| 1215 | }), |
| 1216 | ); |
| 1217 | |
| 1218 | // Data exists on worker-b's namespace — this is what the interlock |
| 1219 | // protects. |
| 1220 | yield* fetchJsonReady<{ ok: boolean }>(`${v1.b.url}/reset`); |
| 1221 | yield* fetchJsonReady<{ value: number }>(`${v1.b.url}/increment`); |
| 1222 | |
| 1223 | const aScriptName = v1.a.workerName; |
| 1224 | |
| 1225 | const error = yield* scratch |
| 1226 | .deploy( |
| 1227 | Effect.gen(function* () { |
| 1228 | const a = yield* Cloudflare.Worker("worker-a", { |
| 1229 | script: hostWorkerScript, |
| 1230 | env: { |
| 1231 | // Fresh, empty namespace for the same class name — the |
| 1232 | // move is not declared, so nothing transfers. |
| 1233 | Counter: Cloudflare.DurableObject("Counter"), |
| 1234 | }, |
| 1235 | }); |
| 1236 | const b = yield* Cloudflare.Worker("worker-b", { |
| 1237 | script: consumerWorkerScript, |
| 1238 | env: { |
| 1239 | Counter: Cloudflare.DurableObject("Counter", { scriptName: aScriptName }), |
| 1240 | }, |
| 1241 | }); |
| 1242 | return { a, b }; |
| 1243 | }), |
| 1244 | ) |
| 1245 | .pipe(Effect.flip); |
| 1246 | |
| 1247 | expect(error._tag).toEqual("DurableObjectTransferRequired"); |
| 1248 | expect((yield* fetchJsonReady<{ value: number }>(`${v1.b.url}/get`)).value).toBe(1); |
| 1249 | |
| 1250 | yield* scratch.destroy(); |
| 1251 | }).pipe(logLevel), |
| 1252 | { timeout: 240_000 }, |
| 1253 | ); |
| 1254 | |
| 1255 | test.provider( |
| 1256 | "a transferred namespace cannot be rebound to a different namespace", |
| 1257 | (scratch) => |
| 1258 | Effect.gen(function* () { |
| 1259 | yield* scratch.destroy(); |
| 1260 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 1261 | |
| 1262 | const v1 = yield* scratch.deploy( |
| 1263 | Effect.gen(function* () { |
| 1264 | return { |
| 1265 | a: yield* Cloudflare.Worker("worker-a", { |
| 1266 | script: hostWorkerScript, |
| 1267 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 1268 | }), |
| 1269 | }; |
| 1270 | }), |
| 1271 | ); |
| 1272 | const originalNamespaceId = v1.a.durableObjectNamespaces.Counter; |
| 1273 | expect(originalNamespaceId).toBeDefined(); |
| 1274 | yield* fetchJsonReady<{ ok: boolean }>(`${v1.a.url}/reset`); |
| 1275 | expect((yield* fetchJsonReady<{ value: number }>(`${v1.a.url}/increment`)).value).toBe(1); |
| 1276 | |
| 1277 | const transferredStack = (scriptName?: string) => |
| 1278 | Effect.gen(function* () { |
| 1279 | const a = yield* Cloudflare.Worker("worker-a", { |
| 1280 | script: scriptName === undefined ? hostWorkerScript : consumerWorkerScript, |
| 1281 | env: { |
| 1282 | Counter: |
| 1283 | scriptName === undefined |
| 1284 | ? Cloudflare.DurableObject("Counter") |
| 1285 | : Cloudflare.DurableObject("Counter", { scriptName }), |
| 1286 | }, |
| 1287 | }); |
| 1288 | const b = yield* Cloudflare.Worker("worker-b", { |
| 1289 | script: hostWorkerScript, |
| 1290 | env: { Counter: Cloudflare.DurableObject("Counter", { transferredFrom: a }) }, |
| 1291 | }); |
| 1292 | const c = yield* Cloudflare.Worker("worker-c", { |
| 1293 | script: hostWorkerScript, |
| 1294 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 1295 | }); |
| 1296 | return { a, b, c }; |
| 1297 | }); |
| 1298 | |
| 1299 | // A stays unchanged while B receives its namespace; C owns a fresh one. |
| 1300 | const v2 = yield* scratch.deploy(transferredStack()); |
| 1301 | expect(v2.b.durableObjectNamespaces.Counter).toBe(originalNamespaceId); |
| 1302 | const unrelatedNamespaceId = v2.c.durableObjectNamespaces.Counter; |
| 1303 | expect(unrelatedNamespaceId).toBeDefined(); |
| 1304 | expect(unrelatedNamespaceId).not.toBe(originalNamespaceId); |
| 1305 | |
| 1306 | const namespaces = yield* durableObjects.listNamespaces.items({ accountId }).pipe( |
| 1307 | Stream.runCollect, |
| 1308 | Effect.repeat({ |
| 1309 | schedule: Schedule.spaced("1 second"), |
| 1310 | times: 8, |
| 1311 | until: (namespaces) => |
| 1312 | namespaces.some( |
| 1313 | (ns) => ns.id === originalNamespaceId && ns.script === v2.b.workerName, |
| 1314 | ) && |
| 1315 | namespaces.some( |
| 1316 | (ns) => ns.id === unrelatedNamespaceId && ns.script === v2.c.workerName, |
| 1317 | ) && |
| 1318 | !namespaces.some((ns) => ns.script === v2.a.workerName && ns.class === "Counter"), |
| 1319 | }), |
| 1320 | ); |
| 1321 | expect(namespaces.find((ns) => ns.id === originalNamespaceId)).toMatchObject({ |
| 1322 | script: v2.b.workerName, |
| 1323 | class: "Counter", |
| 1324 | }); |
| 1325 | expect(namespaces.find((ns) => ns.id === unrelatedNamespaceId)).toMatchObject({ |
| 1326 | script: v2.c.workerName, |
| 1327 | class: "Counter", |
| 1328 | }); |
| 1329 | expect( |
| 1330 | namespaces.some((ns) => ns.script === v2.a.workerName && ns.class === "Counter"), |
| 1331 | ).toBe(false); |
| 1332 | expect((yield* fetchJsonReady<{ value: number }>(`${v2.b.url}/get`)).value).toBe(1); |
| 1333 | expect((yield* fetchJsonReady<{ value: number }>(`${v2.c.url}/get`)).value).toBe(0); |
| 1334 | |
| 1335 | const error = yield* scratch.deploy(transferredStack(v2.c.workerName)).pipe(Effect.flip); |
| 1336 | expect(error._tag).toBe("DurableObjectTransferRequired"); |
| 1337 | expect((yield* fetchJsonReady<{ value: number }>(`${v2.b.url}/get`)).value).toBe(1); |
| 1338 | expect((yield* fetchJsonReady<{ value: number }>(`${v2.c.url}/get`)).value).toBe(0); |
| 1339 | |
| 1340 | yield* scratch.destroy(); |
| 1341 | }).pipe(logLevel), |
| 1342 | { timeout: 120_000 }, |
| 1343 | ); |
| 1344 | |
| 1345 | // A former host keeps its `alchemy:dos:` tag until its next deploy, while |
| 1346 | // Cloudflare rewrites its binding to a className-less reference to the |
| 1347 | // moved namespace (dangling once the new host is deleted). Naming that |
| 1348 | // former host again — e.g. a host history `[b, a]` after b is gone — must |
| 1349 | // treat it as not hosting the class and create a fresh namespace, not fail |
| 1350 | // trying to locate a namespace that no longer exists. |
| 1351 | test.provider( |
| 1352 | "a former host with a stale class tag is not a transfer source", |
| 1353 | (scratch) => |
| 1354 | Effect.gen(function* () { |
| 1355 | yield* scratch.destroy(); |
| 1356 | |
| 1357 | const hostA = Cloudflare.Worker("worker-a", { |
| 1358 | script: hostWorkerScript, |
| 1359 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 1360 | }); |
| 1361 | |
| 1362 | // v1 — worker-b takes worker-a's namespace; worker-a is untouched. |
| 1363 | const v1 = yield* scratch.deploy( |
| 1364 | Effect.gen(function* () { |
| 1365 | const a = yield* hostA; |
| 1366 | const b = yield* Cloudflare.Worker("worker-b", { |
| 1367 | script: hostWorkerScript, |
| 1368 | env: { Counter: Cloudflare.DurableObject("Counter", { transferredFrom: a }) }, |
| 1369 | }); |
| 1370 | return { a, b }; |
| 1371 | }), |
| 1372 | ); |
| 1373 | const movedNamespaceId = v1.b.durableObjectNamespaces.Counter; |
| 1374 | expect(movedNamespaceId).toBe(v1.a.durableObjectNamespaces.Counter); |
| 1375 | |
| 1376 | // v2 — worker-b (and with it the moved namespace) is deleted. |
| 1377 | yield* scratch.deploy( |
| 1378 | Effect.gen(function* () { |
| 1379 | return { a: yield* hostA }; |
| 1380 | }), |
| 1381 | ); |
| 1382 | |
| 1383 | // v3 — worker-d names worker-a as its former host: worker-a no |
| 1384 | // longer hosts Counter, so worker-d creates a fresh namespace. |
| 1385 | const v3 = yield* scratch.deploy( |
| 1386 | Effect.gen(function* () { |
| 1387 | const a = yield* hostA; |
| 1388 | const d = yield* Cloudflare.Worker("worker-d", { |
| 1389 | script: hostWorkerScript, |
| 1390 | env: { Counter: Cloudflare.DurableObject("Counter", { transferredFrom: a }) }, |
| 1391 | }); |
| 1392 | return { a, d }; |
| 1393 | }), |
| 1394 | ); |
| 1395 | const freshNamespaceId = v3.d.durableObjectNamespaces.Counter; |
| 1396 | expect(freshNamespaceId).toBeDefined(); |
| 1397 | expect(freshNamespaceId).not.toBe(movedNamespaceId); |
| 1398 | |
| 1399 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 1400 | const namespaces = yield* durableObjects.listNamespaces |
| 1401 | .items({ accountId }) |
| 1402 | .pipe(Stream.runCollect); |
| 1403 | expect(namespaces.find((ns) => ns.id === freshNamespaceId)).toMatchObject({ |
| 1404 | script: v3.d.workerName, |
| 1405 | class: "Counter", |
| 1406 | }); |
| 1407 | expect(namespaces.some((ns) => ns.id === movedNamespaceId)).toBe(false); |
| 1408 | |
| 1409 | yield* scratch.destroy(); |
| 1410 | }).pipe(logLevel), |
| 1411 | { timeout: 120_000 }, |
| 1412 | ); |
| 1413 | |
| 1414 | // #799: the documented *pure move* — the former host drops the DO entirely, |
| 1415 | // keeping no cross-script reference — done as two deploys. Phase 1 adds the |
| 1416 | // class to worker-a, declaring the former host by **Worker resource |
| 1417 | // reference** (`transferredFrom: b`, normalized at plan time to worker-b's |
| 1418 | // logical id — no dependency edge on b); worker-b is untouched. Phase 2 |
| 1419 | // removes the DO from worker-b, whose deploy observes the class already |
| 1420 | // transferred away and skips the delete. |
| 1421 | test.provider( |
| 1422 | "two-deploy pure move with a Worker resource reference", |
| 1423 | (scratch) => |
| 1424 | Effect.gen(function* () { |
| 1425 | yield* scratch.destroy(); |
| 1426 | |
| 1427 | const v1 = yield* scratch.deploy( |
| 1428 | Effect.gen(function* () { |
| 1429 | return { |
| 1430 | b: yield* Cloudflare.Worker("worker-b", { |
| 1431 | script: hostWorkerScript, |
| 1432 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 1433 | }), |
| 1434 | }; |
| 1435 | }), |
| 1436 | ); |
| 1437 | |
| 1438 | yield* fetchJsonReady<{ ok: boolean }>(`${v1.b.url}/reset`); |
| 1439 | const written = yield* fetchJsonReady<{ value: number }>(`${v1.b.url}/increment`); |
| 1440 | expect(written.value).toBe(1); |
| 1441 | |
| 1442 | // Phase 1: worker-a takes the class, naming the former host by |
| 1443 | // resource reference. worker-b's declaration is unchanged (noop). |
| 1444 | const v2 = yield* scratch.deploy( |
| 1445 | Effect.gen(function* () { |
| 1446 | const b = yield* Cloudflare.Worker("worker-b", { |
| 1447 | script: hostWorkerScript, |
| 1448 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 1449 | }); |
| 1450 | const a = yield* Cloudflare.Worker("worker-a", { |
| 1451 | script: hostWorkerScript, |
| 1452 | env: { Counter: Cloudflare.DurableObject("Counter", { transferredFrom: b }) }, |
| 1453 | }); |
| 1454 | return { a, b }; |
| 1455 | }), |
| 1456 | ); |
| 1457 | |
| 1458 | // The namespace moved to worker-a with its data intact. |
| 1459 | const viaA = yield* fetchJsonReady<{ value: number }>(`${v2.a.url}/get`); |
| 1460 | expect(viaA.value).toBe(1); |
| 1461 | |
| 1462 | // Phase 2: worker-b drops the DO entirely. Its deploy observes the |
| 1463 | // class already lives on worker-a and emits no delete migration. |
| 1464 | const v3 = yield* scratch.deploy( |
| 1465 | Effect.gen(function* () { |
| 1466 | const b = yield* Cloudflare.Worker("worker-b", { |
| 1467 | script: `export default { fetch() { return new Response("plain"); } };`, |
| 1468 | }); |
| 1469 | const a = yield* Cloudflare.Worker("worker-a", { |
| 1470 | script: hostWorkerScript, |
| 1471 | env: { Counter: Cloudflare.DurableObject("Counter", { transferredFrom: b }) }, |
| 1472 | }); |
| 1473 | return { a, b }; |
| 1474 | }), |
| 1475 | ); |
| 1476 | |
| 1477 | const afterRemoval = yield* fetchJsonReady<{ value: number }>(`${v3.a.url}/increment`); |
| 1478 | expect(afterRemoval.value).toBe(2); |
| 1479 | |
| 1480 | yield* scratch.destroy(); |
| 1481 | }).pipe(logLevel), |
| 1482 | { timeout: 240_000 }, |
| 1483 | ); |
| 1484 | |
| 1485 | // Reproduces #811: one script tag per DO binding blew Cloudflare's 10-tag |
| 1486 | // limit at 7+ Durable Objects (3 ownership tags + 1 migration tag + N DO |
| 1487 | // tags). The logical-id→class mapping is now packed into `alchemy:dos:` |
| 1488 | // tags, so a worker with 20 DOs — double the count that used to consume the |
| 1489 | // entire tag budget — deploys fine and the whole tag set stays within the |
| 1490 | // limit. The second deploy renames a class and drops another to prove |
| 1491 | // migrations are still driven by the packed mapping. |
| 1492 | test.provider( |
| 1493 | "worker with 20 durable objects deploys within the 10-tag limit", |
| 1494 | (scratch) => |
| 1495 | Effect.gen(function* () { |
| 1496 | yield* scratch.destroy(); |
| 1497 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 1498 | const ids = Array.from({ length: 20 }, (_, i) => `DO_${i}`); |
| 1499 | const makeScript = (classes: string[], version: string) => |
| 1500 | `import { DurableObject } from "cloudflare:workers"; |
| 1501 | ${classes.map((c) => `export class ${c} extends DurableObject {}`).join("\n")} |
| 1502 | export default { async fetch() { return new Response("${version}"); } }; |
| 1503 | `; |
| 1504 | |
| 1505 | const v1 = yield* scratch.deploy( |
| 1506 | Effect.gen(function* () { |
| 1507 | return { |
| 1508 | worker: yield* Cloudflare.Worker("worker", { |
| 1509 | script: makeScript( |
| 1510 | ids.map((_, i) => `Class${i}`), |
| 1511 | "v1", |
| 1512 | ), |
| 1513 | env: Object.fromEntries( |
| 1514 | ids.map((id, i) => [ |
| 1515 | id, |
| 1516 | Cloudflare.DurableObject(id, { className: `Class${i}` }), |
| 1517 | ]), |
| 1518 | ), |
| 1519 | }), |
| 1520 | }; |
| 1521 | }), |
| 1522 | ); |
| 1523 | expect(yield* fetchReady(v1.worker.url!, "v1")).toBe("v1"); |
| 1524 | |
| 1525 | const tags = yield* getWorkerTags(v1.worker.workerName, accountId); |
| 1526 | expect(tags.length).toBeLessThanOrEqual(10); |
| 1527 | expect(tags.filter((t) => t.startsWith("alchemy:dos:"))).toHaveLength(1); |
| 1528 | expect(tags.filter((t) => t.startsWith("alchemy:do:"))).toHaveLength(0); |
| 1529 | |
| 1530 | expect(Object.keys(v1.worker.durableObjectNamespaces).sort()).toEqual( |
| 1531 | ids.map((_, i) => `Class${i}`).sort(), |
| 1532 | ); |
| 1533 | |
| 1534 | // Rename Class0 → Class0V2 (same binding id) and delete DO_19 — both |
| 1535 | // migrations resolve their previous class through the packed tag. |
| 1536 | const v2 = yield* scratch.deploy( |
| 1537 | Effect.gen(function* () { |
| 1538 | return { |
| 1539 | worker: yield* Cloudflare.Worker("worker", { |
| 1540 | script: makeScript( |
| 1541 | ["Class0V2", ...ids.slice(1, 19).map((_, i) => `Class${i + 1}`)], |
| 1542 | "v2", |
| 1543 | ), |
| 1544 | env: Object.fromEntries( |
| 1545 | ids.slice(0, 19).map((id, i) => [ |
| 1546 | id, |
| 1547 | Cloudflare.DurableObject(id, { |
| 1548 | className: i === 0 ? "Class0V2" : `Class${i}`, |
| 1549 | }), |
| 1550 | ]), |
| 1551 | ), |
| 1552 | }), |
| 1553 | }; |
| 1554 | }), |
| 1555 | ); |
| 1556 | expect(yield* fetchReady(v2.worker.url!, "v2")).toBe("v2"); |
| 1557 | expect(Object.keys(v2.worker.durableObjectNamespaces).sort()).toEqual( |
| 1558 | ["Class0V2", ...ids.slice(1, 19).map((_, i) => `Class${i + 1}`)].sort(), |
| 1559 | ); |
| 1560 | expect(v2.worker.durableObjectNamespaces.Class0V2).toBe( |
| 1561 | v1.worker.durableObjectNamespaces.Class0, |
| 1562 | ); |
| 1563 | expect(v2.worker.durableObjectNamespaces.Class19).toBeUndefined(); |
| 1564 | for (let i = 1; i < 19; i++) { |
| 1565 | expect(v2.worker.durableObjectNamespaces[`Class${i}`]).toBe( |
| 1566 | v1.worker.durableObjectNamespaces[`Class${i}`], |
| 1567 | ); |
| 1568 | } |
| 1569 | |
| 1570 | const namespaces = yield* durableObjects.listNamespaces.items({ accountId }).pipe( |
| 1571 | Stream.runCollect, |
| 1572 | Effect.map((namespaces) => |
| 1573 | namespaces.filter((ns) => ns.script === v2.worker.workerName), |
| 1574 | ), |
| 1575 | Effect.repeat({ |
| 1576 | schedule: Schedule.spaced("2 seconds"), |
| 1577 | until: (namespaces) => |
| 1578 | namespaces.length === 19 && |
| 1579 | new Set(namespaces.map((ns) => ns.id)).size === 19 && |
| 1580 | namespaces.every( |
| 1581 | (ns) => |
| 1582 | ns.class !== undefined && |
| 1583 | ns.class !== null && |
| 1584 | v2.worker.durableObjectNamespaces[ns.class] === ns.id, |
| 1585 | ), |
| 1586 | times: 8, |
| 1587 | }), |
| 1588 | ); |
| 1589 | expect(namespaces).toHaveLength(19); |
| 1590 | expect(namespaces.map((ns) => ns.id).sort()).toEqual( |
| 1591 | Object.values(v2.worker.durableObjectNamespaces).sort(), |
| 1592 | ); |
| 1593 | expect(namespaces.some((ns) => ns.id === v1.worker.durableObjectNamespaces.Class19)).toBe( |
| 1594 | false, |
| 1595 | ); |
| 1596 | |
| 1597 | yield* scratch.destroy(); |
| 1598 | }).pipe(logLevel), |
| 1599 | { timeout: 120_000 }, |
| 1600 | ); |
| 1601 | |
| 1602 | // Roll-forward from the legacy tag format: a worker last deployed by an |
| 1603 | // older alchemy carries one `alchemy:do:{logicalId}:{className}` tag per DO. |
| 1604 | // Simulate that by rewriting the live script tags to the legacy format |
| 1605 | // out-of-band, then redeploy with a class rename — reconcile must parse the |
| 1606 | // legacy tags to resolve the previous class, and the deploy rewrites the |
| 1607 | // mapping in the packed format. |
| 1608 | test.provider( |
| 1609 | "rolls forward from legacy per-DO alchemy:do: tags", |
| 1610 | (scratch) => |
| 1611 | Effect.gen(function* () { |
| 1612 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 1613 | |
| 1614 | const v1 = yield* scratch.deploy( |
| 1615 | Effect.gen(function* () { |
| 1616 | return { |
| 1617 | worker: yield* Cloudflare.Worker("worker", { |
| 1618 | script: `import { DurableObject } from "cloudflare:workers"; |
| 1619 | export class CounterClass extends DurableObject {} |
| 1620 | export class MeterClass extends DurableObject {} |
| 1621 | export default { async fetch() { return new Response("v1"); } }; |
| 1622 | `, |
| 1623 | env: { |
| 1624 | Counter: Cloudflare.DurableObject("Counter", { className: "CounterClass" }), |
| 1625 | Meter: Cloudflare.DurableObject("Meter", { className: "MeterClass" }), |
| 1626 | }, |
| 1627 | }), |
| 1628 | }; |
| 1629 | }), |
| 1630 | ); |
| 1631 | expect(yield* fetchReady(v1.worker.url!, "v1")).toBe("v1"); |
| 1632 | const scriptName = v1.worker.workerName; |
| 1633 | |
| 1634 | // Rewrite the tags the way alchemy <= beta.62 wrote them: one |
| 1635 | // `alchemy:do:` tag per binding, no packed tag. The Worker deploys |
| 1636 | // with declarative `exports`, and Cloudflare reconciles every |
| 1637 | // settings patch against the `exports` it carries, so the live |
| 1638 | // classes are re-declared alongside the tags. |
| 1639 | const deployedTags = yield* getWorkerTags(scriptName, accountId); |
| 1640 | yield* workers.patchScriptScriptAndVersionSetting({ |
| 1641 | accountId, |
| 1642 | scriptName, |
| 1643 | settings: { |
| 1644 | exports: { |
| 1645 | CounterClass: { type: "durable-object", storage: "sqlite" }, |
| 1646 | MeterClass: { type: "durable-object", storage: "sqlite" }, |
| 1647 | }, |
| 1648 | tags: [ |
| 1649 | ...deployedTags.filter((t) => !t.startsWith("alchemy:dos:")), |
| 1650 | "alchemy:do:Counter:CounterClass", |
| 1651 | "alchemy:do:Meter:MeterClass", |
| 1652 | ], |
| 1653 | }, |
| 1654 | }); |
| 1655 | |
| 1656 | // Redeploy with a rename; the previous class must be resolved from the |
| 1657 | // legacy tags for the migration to succeed. |
| 1658 | const v2 = yield* scratch.deploy( |
| 1659 | Effect.gen(function* () { |
| 1660 | return { |
| 1661 | worker: yield* Cloudflare.Worker("worker", { |
| 1662 | script: `import { DurableObject } from "cloudflare:workers"; |
| 1663 | export class CounterClassV2 extends DurableObject {} |
| 1664 | export class MeterClass extends DurableObject {} |
| 1665 | export default { async fetch() { return new Response("v2"); } }; |
| 1666 | `, |
| 1667 | env: { |
| 1668 | Counter: Cloudflare.DurableObject("Counter", { className: "CounterClassV2" }), |
| 1669 | Meter: Cloudflare.DurableObject("Meter", { className: "MeterClass" }), |
| 1670 | }, |
| 1671 | }), |
| 1672 | }; |
| 1673 | }), |
| 1674 | ); |
| 1675 | expect(yield* fetchReady(v2.worker.url!, "v2")).toBe("v2"); |
| 1676 | |
| 1677 | // The deploy rewrote the mapping in the packed format. |
| 1678 | const rolledForward = yield* getWorkerTags(scriptName, accountId); |
| 1679 | expect(rolledForward.filter((t) => t.startsWith("alchemy:dos:"))).toHaveLength(1); |
| 1680 | expect(rolledForward.filter((t) => t.startsWith("alchemy:do:"))).toHaveLength(0); |
| 1681 | |
| 1682 | yield* scratch.destroy(); |
| 1683 | }).pipe(logLevel), |
| 1684 | { timeout: 180_000 }, |
| 1685 | ); |
| 1686 | |
| 1687 | // #799 (idempotence): a standing `transferredFrom` declaration must never do |
| 1688 | // anything destructive after its job is done. |
| 1689 | // |
| 1690 | // v1 — a FRESH stage deployed directly in the final topology, declaration |
| 1691 | // present: no listed source hosts the class, so worker-a creates a |
| 1692 | // fresh namespace. Same-class namespaces owned by other stacks and |
| 1693 | // stages on the account must not match the declaration. |
| 1694 | // v2 — worker-b later hosts its OWN Durable Object under the same name and |
| 1695 | // class (the isolated-twins pattern): a fresh, separate namespace. |
| 1696 | // v3 — worker-a redeploys (forced update) with the now-stale declaration |
| 1697 | // while that same-name namespace exists on worker-b: the class is |
| 1698 | // already anchored to worker-a by its DO tag, so the stale |
| 1699 | // declaration must not steal worker-b's namespace or emit any |
| 1700 | // migration. Distinct counter values prove both namespaces survive |
| 1701 | // untouched. |
| 1702 | test.provider( |
| 1703 | "standing transferredFrom is inert on fresh stages and never steals a same-name namespace", |
| 1704 | (scratch) => |
| 1705 | Effect.gen(function* () { |
| 1706 | yield* scratch.destroy(); |
| 1707 | |
| 1708 | // Fresh stage, final topology, declaration present from day one. |
| 1709 | const v1 = yield* scratch.deploy( |
| 1710 | Effect.gen(function* () { |
| 1711 | const a = yield* Cloudflare.Worker("worker-a", { |
| 1712 | script: hostWorkerScript, |
| 1713 | env: { |
| 1714 | Counter: Cloudflare.DurableObject("Counter", { transferredFrom: "worker-b" }), |
| 1715 | }, |
| 1716 | }); |
| 1717 | const b = yield* Cloudflare.Worker("worker-b", { |
| 1718 | script: consumerWorkerScript, |
| 1719 | env: { Counter: Cloudflare.DurableObject("Counter", { scriptName: a.workerName }) }, |
| 1720 | }); |
| 1721 | return { a, b }; |
| 1722 | }), |
| 1723 | ); |
| 1724 | |
| 1725 | // Fresh namespace on worker-a; give it a distinctly non-zero count. |
| 1726 | // (`/increment` is not idempotent and readiness retries can re-run |
| 1727 | // it, so assertions use the idempotent `/get` instead of increment |
| 1728 | // return values.) |
| 1729 | yield* fetchJsonReady<{ ok: boolean }>(`${v1.a.url}/reset`); |
| 1730 | yield* fetchJsonReady<{ value: number }>(`${v1.a.url}/increment`); |
| 1731 | yield* fetchJsonReady<{ value: number }>(`${v1.a.url}/increment`); |
| 1732 | const aBefore = (yield* fetchJsonReady<{ value: number }>(`${v1.a.url}/get`)).value; |
| 1733 | expect(aBefore).toBeGreaterThanOrEqual(2); |
| 1734 | |
| 1735 | // worker-b now hosts its OWN same-name Counter — an isolated twin. |
| 1736 | const v2 = yield* scratch.deploy( |
| 1737 | Effect.gen(function* () { |
| 1738 | const a = yield* Cloudflare.Worker("worker-a", { |
| 1739 | script: hostWorkerScript, |
| 1740 | env: { |
| 1741 | Counter: Cloudflare.DurableObject("Counter", { transferredFrom: "worker-b" }), |
| 1742 | }, |
| 1743 | }); |
| 1744 | const b = yield* Cloudflare.Worker("worker-b", { |
| 1745 | script: hostWorkerScript, |
| 1746 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 1747 | }); |
| 1748 | return { a, b }; |
| 1749 | }), |
| 1750 | ); |
| 1751 | |
| 1752 | // The twin starts empty — its own namespace, not worker-a's. b's |
| 1753 | // edge may briefly serve the previous (cross-script) version, whose |
| 1754 | // /get reads worker-a's non-zero count, so poll until the fresh |
| 1755 | // version answers with the twin's empty count. |
| 1756 | yield* fetchJsonReady<{ value: number }>(`${v2.b.url}/get`).pipe( |
| 1757 | Effect.flatMap((r) => |
| 1758 | r.value === 0 ? Effect.void : Effect.fail(new Error(`stale: twin sees ${r.value}`)), |
| 1759 | ), |
| 1760 | Effect.retry({ schedule: readinessSchedule, times: readinessRetries }), |
| 1761 | ); |
| 1762 | |
| 1763 | // Force a real reconcile of worker-a with the stale declaration while |
| 1764 | // the twin exists. The class is tag-anchored to worker-a, so no |
| 1765 | // migration may be emitted and neither namespace may change. |
| 1766 | const v3 = yield* scratch.deploy( |
| 1767 | Effect.gen(function* () { |
| 1768 | const a = yield* Cloudflare.Worker("worker-a", { |
| 1769 | script: hostWorkerScript, |
| 1770 | env: { |
| 1771 | FORCE_UPDATE: "1", |
| 1772 | Counter: Cloudflare.DurableObject("Counter", { transferredFrom: "worker-b" }), |
| 1773 | }, |
| 1774 | }); |
| 1775 | const b = yield* Cloudflare.Worker("worker-b", { |
| 1776 | script: hostWorkerScript, |
| 1777 | env: { Counter: Cloudflare.DurableObject("Counter") }, |
| 1778 | }); |
| 1779 | return { a, b }; |
| 1780 | }), |
| 1781 | ); |
| 1782 | |
| 1783 | const aAfter = yield* fetchJsonReady<{ value: number }>(`${v3.a.url}/get`); |
| 1784 | expect(aAfter.value).toBe(aBefore); |
| 1785 | // worker-b was a noop in v3, but its v2 upload was only moments ago — |
| 1786 | // an edge metal can still serve the v1 (cross-script) version, whose |
| 1787 | // /get reads worker-a's non-zero counter. Poll until the twin's own |
| 1788 | // empty namespace answers: a genuinely stolen/deleted namespace never |
| 1789 | // reads 0, so the bounded retry still fails in the regression case. |
| 1790 | const twinAfter = yield* fetchJsonReady<{ value: number }>(`${v3.b.url}/get`).pipe( |
| 1791 | Effect.flatMap((r) => |
| 1792 | r.value === 0 |
| 1793 | ? Effect.succeed(r) |
| 1794 | : Effect.fail(new Error(`stale: twin sees ${r.value}`)), |
| 1795 | ), |
| 1796 | Effect.retry({ schedule: readinessSchedule, times: readinessRetries }), |
| 1797 | ); |
| 1798 | expect(twinAfter.value).toBe(0); |
| 1799 | |
| 1800 | yield* scratch.destroy(); |
| 1801 | }).pipe(logLevel), |
| 1802 | { timeout: 240_000 }, |
| 1803 | ); |
| 1804 | }, |
| 1805 | ); |