import * as Cloudflare from "@alchemy.run/cloudflare";
import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
import { CloudflareApiLive } from "@alchemy.run/cloudflare/Providers";
import { describe, expect } from "@alchemy.run/test";
import * as Test from "@alchemy.run/test/Alchemy";
import * as durableObjects from "@distilled.cloud/cloudflare/durable-objects";
import * as workers from "@distilled.cloud/cloudflare/workers";
import { adopt } from "alchemy/AdoptPolicy";
import * as Output from "alchemy/Output";
import { State } from "alchemy/State";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as HttpClient from "effect/http/HttpClient";
import * as HttpClientRequest from "effect/http/HttpClientRequest";
import { MinimumLogLevel } from "effect/References";
import * as Schedule from "effect/Schedule";
import * as Stream from "effect/Stream";
import { testName } from "../../names.ts";
import { getWorkerTags } from "../Utils/Worker.ts";
import { requestWorker } from "../Utils/WorkerRequest.ts";
import Stack from "./fixtures/do-rpc/stack.ts";
const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
providers: Cloudflare.providers(),
});
const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
const stack = beforeAll(deploy(Stack));
afterAll.skipIf(!!process.env.NO_DESTROY)(
Effect.gen(function* () {
const deployed = yield* Effect.exit(stack);
yield* destroy(Stack);
if (Exit.isFailure(deployed)) return;
const scriptName = new URL(deployed.value.url).hostname.split(".")[0]!;
yield* Effect.gen(function* () {
const { accountId } = yield* yield* CloudflareEnvironment;
const deleted = yield* workers.getScript({ accountId, scriptName }).pipe(
Effect.as(false),
Effect.catchTag("WorkerNotFound", () => Effect.succeed(true)),
Effect.repeat({ while: (gone) => !gone, schedule: Schedule.spaced("1 second"), times: 8 }),
Effect.timeout("15 seconds"),
);
expect(deleted).toBe(true);
const namespaceDeleted = yield* durableObjects.listNamespaces.items({ accountId }).pipe(
Stream.runCollect,
Effect.map(
(namespaces) => !namespaces.some((namespace) => namespace.script === scriptName),
),
Effect.repeat({ while: (gone) => !gone, schedule: Schedule.spaced("1 second"), times: 8 }),
Effect.timeout("15 seconds"),
);
expect(namespaceDeleted).toBe(true);
}).pipe(Effect.provide(CloudflareApiLive()), Effect.scoped);
}),
{ timeout: 120_000 },
);
// Cap exponential backoff at 3s — keeps the fast-path snappy but stops
// the geometric blow-up (0.5 + 1 + 2 + 4 + 8 + 16 + 32 + 64s ...) that
// makes retries dominate test wall time when CF edge is slow.
const readinessSchedule = Schedule.min([
Schedule.exponential("500 millis"),
Schedule.spaced("3 seconds"),
]);
const readinessRetries = 10;
// The test runtime's HttpClient (FetchHttpClient/undici) keeps HTTP/1.1
// connections alive and pooled. A pooled connection stays pinned to a single
// Cloudflare edge metal, so when that metal lags the freshly-deployed version
// every retry rides the same stale socket and keeps reading the old body for
// the life of the keep-alive — even though the new version is already live.
// Forcing `Connection: close` makes each readiness attempt open a fresh
// connection, letting it land on an edge that has the new version (this is
// why a brand-new `curl` sees the update immediately while a kept-alive
// client does not). See do-rpc DurableObject test investigation.
const freshConn = HttpClient.mapRequest(HttpClientRequest.setHeader("connection", "close"));
for (const encoding of ["json", "bytes"] as const) {
for (const scenario of ["complete", "cancel", "empty", "head-failure", "tail-failure"] as const) {
test(
`native RPC ${encoding} stream handles ${scenario} with its source and event scopes`,
Effect.gen(function* () {
const { url } = yield* stack;
const client = freshConn(yield* HttpClient.HttpClient);
yield* client.get(`${url}/rpc-stream-ready/${encoding}-${scenario}`).pipe(
Effect.flatMap((response) =>
response.text.pipe(
Effect.flatMap((body) =>
response.status === 200 && body === "rpc-stream-scopes"
? Effect.void
: Effect.fail(
new Error(`RPC fixture not ready: ${response.status}: ${body.slice(0, 300)}`),
),
),
),
),
// Namespace activation can lag the Worker route. This is bounded
// to ten retries and under a minute of total backoff.
Effect.retry({
schedule: Schedule.min([
Schedule.exponential("500 millis"),
Schedule.spaced("7 seconds"),
]),
times: readinessRetries,
}),
);
// These calls cross the native DO RPC boundary; they do not use the
// separate Effect RPC-over-HTTP namespace protocol.
const response = yield* requestWorker(
HttpClientRequest.get(`${url}/rpc-stream/${encoding}/${scenario}`).pipe(
HttpClientRequest.setHeader("connection", "close"),
),
{ retryDelay: "5 seconds" },
);
expect(response.status).toBe(200);
const body = (yield* response.json) as {
values: Array<{ part: string; eventClosed: number; sourceClosed: number }>;
failed: boolean;
error?: { _tag: string; error?: { _tag: string; phase: string } };
after: string;
};
const parts =
scenario === "complete"
? ["head", "tail"]
: scenario === "cancel" || scenario === "tail-failure"
? ["head"]
: [];
expect(body.values).toEqual(
parts.map((part) => ({ part, eventClosed: 0, sourceClosed: 0 })),
);
expect(body.failed).toBe(scenario === "head-failure" || scenario === "tail-failure");
expect(body.after).toMatch(/^[0-9a-f]{64}$/);
if (scenario === "head-failure" || (scenario === "tail-failure" && encoding === "json")) {
expect(body.error).toMatchObject({
_tag: "RpcRemoteStreamError",
error: {
_tag: "RpcStreamFixtureError",
phase: scenario === "head-failure" ? "head" : "tail",
},
});
} else if (scenario === "tail-failure") {
expect(body.error?._tag).toBe("SocketError");
}
}).pipe(logLevel),
{ tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"], timeout: 120_000 },
);
}
}
test(
"durable object methods can use binding clients",
Effect.gen(function* () {
const { url } = yield* stack;
const client = yield* HttpClient.HttpClient;
const res = yield* client.post(`${url}/roundtrip`).pipe(
Effect.flatMap((res) =>
res.status === 200
? Effect.succeed(res)
: Effect.fail(new Error(`Worker not ready: ${res.status}`)),
),
Effect.retry({ schedule: readinessSchedule, times: 15 }),
);
expect(res.status).toBe(200);
const body = (yield* res.json) as { value: string };
expect(body.value).toBe("ok");
}).pipe(logLevel),
{
tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "live"],
timeout: 60_000,
},
);
test(
"jurisdiction() addresses objects inside that jurisdiction",
Effect.gen(function* () {
const { url } = yield* stack;
const client = freshConn(yield* HttpClient.HttpClient);
const name = "jurisdiction-probe";
const res = yield* client.get(`${url}/jurisdiction?name=${name}`).pipe(
Effect.flatMap((res) =>
res.status === 200
? Effect.succeed(res)
: Effect.fail(new Error(`Worker not ready: ${res.status}`)),
),
Effect.retry({ schedule: readinessSchedule, times: readinessRetries }),
);
const body = (yield* res.json) as { global: string; eu: string; euAgain: string };
// A jurisdiction-restricted id is a different object from the global one
// with the same name, and is stable across lookups.
expect(body.eu).toMatch(/^[0-9a-f]{64}$/);
expect(body.eu).not.toBe(body.global);
expect(body.euAgain).toBe(body.eu);
}).pipe(logLevel),
{
tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"],
timeout: 60_000,
},
);
test(
"get, idFromName, idFromString and newUniqueId address the expected instance",
Effect.gen(function* () {
const { url } = yield* stack;
const client = freshConn(yield* HttpClient.HttpClient);
const res = yield* client.get(`${url}/addressing?name=addressing-probe`).pipe(
Effect.flatMap((res) =>
res.status === 200
? Effect.succeed(res)
: Effect.fail(new Error(`Worker not ready: ${res.status}`)),
),
Effect.retry({ schedule: readinessSchedule, times: readinessRetries }),
);
const body = (yield* res.json) as {
idFromName: string;
byName: string;
byId: string;
byIdString: string;
uniqueId: string;
unique: string;
otherUnique: string;
};
// `get(idFromName(name))` and the string round-trip reach the same
// instance as `getByName(name)`.
expect(body.byName).toMatch(/^[0-9a-f]{64}$/);
expect(body.idFromName).toBe(body.byName);
expect(body.byId).toBe(body.byName);
expect(body.byIdString).toBe(body.byName);
// `newUniqueId()` addresses a fresh instance each time.
expect(body.unique).toBe(body.uniqueId);
expect(body.unique).not.toBe(body.byName);
expect(body.otherUnique).not.toBe(body.unique);
}).pipe(logLevel),
{
tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"],
timeout: 60_000,
},
);
test(
"calling an undefined durable object RPC method fails",
Effect.gen(function* () {
const { url } = yield* stack;
const client = freshConn(yield* HttpClient.HttpClient);
const res = yield* client.get(`${url}/unknown-rpc`).pipe(
Effect.flatMap((res) =>
res.status === 200
? Effect.succeed(res)
: Effect.fail(new Error(`Worker not ready: ${res.status}`)),
),
Effect.retry({ schedule: readinessSchedule, times: readinessRetries }),
);
const body = (yield* res.json) as { missing: string };
expect(body.missing).toContain('Method "missing" not found on Durable Object');
}).pipe(logLevel),
{
tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"],
timeout: 60_000,
},
);
class DurableObjectLocationNotReady extends Data.TaggedError("DurableObjectLocationNotReady")<{
readonly message: string;
}> {}
const locationFor = Effect.fn(function* (
url: string,
options: { name?: string; hint?: Cloudflare.DurableObjectLocationHint } = {},
) {
const client = freshConn(yield* HttpClient.HttpClient);
const name = options.name ?? (yield* Effect.sync(() => crypto.randomUUID()));
const query = `name=${encodeURIComponent(name)}${options.hint ? `&hint=${options.hint}` : ""}`;
return yield* client.get(`${url}/colo?${query}`).pipe(
Effect.flatMap((res) =>
Effect.gen(function* () {
if (res.status !== 200) {
return yield* new DurableObjectLocationNotReady({
message: `Worker not ready: ${res.status}`,
});
}
const body = (yield* res.json) as { id: string; colo: string; locationHintRead: boolean };
if (!body.id || !body.colo || body.colo === "unknown") {
return yield* new DurableObjectLocationNotReady({
message: `Instance not ready: ${JSON.stringify(body)}`,
});
}
return body;
}),
),
Effect.retry({ schedule: readinessSchedule, times: readinessRetries }),
);
});
// Nearby placement is best-effort; named identity is the stable contract.
test(
"unhinted lookups preserve named instance identity",
Effect.gen(function* () {
const { url } = yield* stack;
const name = yield* Effect.sync(() => crypto.randomUUID());
const [first, second] = yield* Effect.all(
[locationFor(url, { name }), locationFor(url, { name })],
{ concurrency: 2 },
);
const other = yield* locationFor(url);
expect(first.id).toMatch(/^[0-9a-f]{64}$/);
expect(first.id).toBe(second.id);
expect(first.id).not.toBe(other.id);
for (const result of [first, second, other]) {
expect(result.locationHintRead).toBe(false);
}
}).pipe(logLevel),
{
tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "live"],
timeout: 60_000,
},
);
// The getter is read by the real native namespace only when options reach it.
test(
"locationHint reaches the native namespace for new instances",
Effect.gen(function* () {
const { url } = yield* stack;
const [wnam, apac] = yield* Effect.all(
[locationFor(url, { hint: "wnam" }), locationFor(url, { hint: "apac" })],
{ concurrency: 2 },
);
expect(wnam.locationHintRead).toBe(true);
expect(apac.locationHintRead).toBe(true);
expect(wnam.id).not.toBe(apac.id);
}).pipe(logLevel),
{
tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "live"],
timeout: 60_000,
},
);
// Reproduces the `tick` streaming example from the Durable Objects tutorial:
// https://alchemy.run/cloudflare/compute/durable-objects
//
// The DO exposes `tick(n): Stream<number>` and the Worker forwards it to the
// HTTP response with `HttpServerResponse.stream`. The client reads the body as
// newline-delimited integers. With `/tick/5` we expect ["0","1","2","3","4"].
// `pubsub` and `callback` push their values after the RPC method has
// returned; they ended after the first element while the stream's source
// scope closed with the call (#2273).
for (const source of ["tick", "pubsub", "callback"] as const)
test(
source === "tick"
? "tick streams sequential values from a durable object (tutorial repro)"
: `${source}-backed stream delivers every value from a durable object`,
Effect.gen(function* () {
const { url } = yield* stack;
const client = freshConn(yield* HttpClient.HttpClient);
const lines = yield* client.get(`${url}/${source}/5`).pipe(
Effect.flatMap((res) =>
res.status === 200
? res.stream.pipe(
Stream.decodeText,
Stream.splitLines,
Stream.filter((line) => line.length > 0),
Stream.runCollect,
Effect.map((chunk) => [...chunk]),
// A cold edge can answer 200 with an empty/placeholder body
// (the script isn't serving yet), which collects to `[]`
// instead of failing — fail so the readiness retry rides it out
// rather than asserting against an empty stream.
Effect.flatMap((rows) =>
rows.length > 0
? Effect.succeed(rows)
: Effect.fail(new Error("Worker not ready: empty stream")),
),
)
: Effect.fail(new Error(`Worker not ready: ${res.status}`)),
),
Effect.retry({ schedule: readinessSchedule, times: readinessRetries }),
);
expect(lines).toEqual(["0", "1", "2", "3", "4"]);
}).pipe(logLevel),
{
tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "live"],
timeout: 60_000,
},
);
// While a freshly pre-created worker is propagating, Cloudflare's edge
// serves Alchemy's pre-create stub, which responds 200 with this plain-text
// body. It is not the real script, so any poll that sees it must retry.
const DEPLOY_PLACEHOLDER = "Alchemy worker is being deployed...";
// Cloudflare's edge keeps serving the previous worker version (or the
// pre-create stub) for a while after a (re)deploy, so retrying on 200-only
// is not enough — the stale version still returns 200 with the old body.
// Retry until the body matches the expected version string.
const fetchReady = (url: string, expected: string) =>
Effect.gen(function* () {
const client = freshConn(yield* HttpClient.HttpClient);
return yield* client.get(url).pipe(
Effect.flatMap((r) =>
r.status === 200
? Effect.flatMap(r.text, (body) =>
body === expected
? Effect.succeed(body)
: Effect.fail(new Error(`stale: got ${body}, want ${expected}`)),
)
: Effect.fail(new Error(`Worker not ready: ${r.status}`)),
),
Effect.retry({ schedule: readinessSchedule, times: readinessRetries }),
);
});
const fetchJsonReady = <T>(url: string) =>
Effect.gen(function* () {
const client = freshConn(yield* HttpClient.HttpClient);
return yield* client.get(url).pipe(
// Parse the body INSIDE the retry: the pre-create stub answers 200 with
// a non-JSON placeholder, so JSON decoding must be part of the readiness
// check (a 200 status alone does not mean the real script is live yet).
Effect.flatMap((r) =>
r.status !== 200
? Effect.flatMap(r.text, (body) =>
Effect.fail(
new Error(`Worker not ready at ${url}: ${r.status} ${body.slice(0, 500)}`),
),
)
: Effect.flatMap(r.text, (body) =>
body.includes(DEPLOY_PLACEHOLDER)
? Effect.fail(new Error("stale: still deploying"))
: Effect.try({
try: () => JSON.parse(body) as T,
catch: () => new Error(`non-json body: ${body}`),
}),
),
),
Effect.retry({ schedule: readinessSchedule, times: readinessRetries }),
);
});
const hostWorkerScript = `import { DurableObject } from "cloudflare:workers";
export class Counter extends DurableObject {
async increment() {
const value = (await this.ctx.storage.get("count")) ?? 0;
const next = value + 1;
await this.ctx.storage.put("count", next);
return next;
}
async reset() {
await this.ctx.storage.delete("count");
}
async get() {
return (await this.ctx.storage.get("count")) ?? 0;
}
}
export default {
async fetch(request, env) {
const stub = env.Counter.getByName("shared");
const url = new URL(request.url);
if (url.pathname === "/increment") {
return Response.json({ value: await stub.increment() });
}
if (url.pathname === "/get") {
return Response.json({ value: await stub.get() });
}
if (url.pathname === "/reset") {
await stub.reset();
return Response.json({ ok: true });
}
return new Response("Not Found", { status: 404 });
},
};
`;
const consumerWorkerScript = `export default {
async fetch(request, env) {
const stub = env.Counter.getByName("shared");
const url = new URL(request.url);
if (url.pathname === "/increment") {
return Response.json({ value: await stub.increment() });
}
if (url.pathname === "/get") {
return Response.json({ value: await stub.get() });
}
if (url.pathname === "/reset") {
await stub.reset();
return Response.json({ ok: true });
}
return new Response("Not Found", { status: 404 });
},
};
`;
// Calls `get()` (RPC) or `fetch()` on a cross-script `Counter` and reports
// the outcome as JSON, so a failing Durable Object call is observable.
const placeholderProbeScript = `export default {
async fetch(request, env) {
const stub = env.Counter.getByName("placeholder-probe");
const url = new URL(request.url);
try {
if (url.pathname === "/rpc") {
return Response.json({ ok: true, value: await stub.get() });
}
if (url.pathname === "/fetch") {
const res = await stub.fetch("https://counter/");
return Response.json({ ok: true, value: await res.text() });
}
} catch (error) {
return Response.json({ ok: false, error: String(error?.message ?? error) });
}
return new Response("Not Found", { status: 404 });
},
};
`;
interface ProbeResult {
ok: boolean;
value?: unknown;
error?: string;
}
// Until the freshly pre-created host script reaches the consumer's edge, a
// cross-script call fails with "Worker not found." (fetch) or an opaque
// "internal error; reference = ..." (RPC) — retry past that propagation.
const probePlaceholder = (url: string) =>
fetchJsonReady<ProbeResult>(url).pipe(
Effect.flatMap((result) =>
result.error?.startsWith("internal error") || result.error === "Worker not found."
? Effect.fail(new Error(`host not propagated yet: ${result.error}`))
: Effect.succeed(result),
),
Effect.retry({ schedule: readinessSchedule, times: readinessRetries }),
);
// Every `test.provider` test below owns an isolated scratch stack (private
// in-memory state, physical names derived from the unique test name), so
// none of them can observe another's cloud resources. Run them concurrently:
// each test's wall time is dominated by workers.dev edge-propagation waits,
// so overlapping them collapses the file from the sum of all tests (~7 min)
// to roughly the slowest single test.
describe.concurrent(
"scratch",
{ tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:worker", "live"] },
() => {
test.provider(
"async worker durable object binding accepts scriptName",
(scratch) =>
Effect.gen(function* () {
yield* scratch.deploy(
Effect.gen(function* () {
return {
host: yield* Cloudflare.Worker("host-worker", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter") },
}),
};
}),
);
const deployed = yield* scratch.deploy(
Effect.gen(function* () {
const host = yield* Cloudflare.Worker("host-worker", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter") },
});
const consumer = yield* Cloudflare.Worker("consumer-worker", {
script: consumerWorkerScript,
env: {
Counter: Cloudflare.DurableObject("Counter", { scriptName: host.workerName }),
},
});
return { consumer, host };
}),
);
const reset = yield* fetchJsonReady<{ ok: boolean }>(`${deployed.host.url}/reset`);
expect(reset.ok).toBe(true);
const first = yield* fetchJsonReady<{ value: number }>(
`${deployed.consumer.url}/increment`,
);
expect(first.value).toBe(1);
const second = yield* fetchJsonReady<{ value: number }>(`${deployed.host.url}/get`);
expect(second.value).toBe(1);
yield* scratch.destroy();
}).pipe(logLevel),
{ timeout: 60_000 },
);
// Walk an async worker through four redeploys against the same scratch state,
// each one swapping in a new script + bindings shape so we exercise the
// migration paths `putWorker` relies on:
// v1 — create with a single DO class `DO_A`
// v2 — rename `DO_A` → `DO_A_v2` (className change, same binding id)
// v3 — add a brand-new DO class `DO_B` alongside `DO_A_v2`
// v4 — delete `DO_A`, keep only `DO_B`
test.provider(
"durable object class migrations across redeploys",
(scratch) =>
Effect.gen(function* () {
const v1 = yield* scratch.deploy(
Effect.gen(function* () {
return {
worker: yield* Cloudflare.Worker("worker", {
script: `import { DurableObject } from "cloudflare:workers";
export class DO_A extends DurableObject {}
export default { async fetch() { return new Response("v1"); } };
`,
env: { DO_A: Cloudflare.DurableObject("DO_A") },
}),
};
}),
);
expect(yield* fetchReady(v1.worker.url!, "v1")).toBe("v1");
const v2 = yield* scratch.deploy(
Effect.gen(function* () {
return {
worker: yield* Cloudflare.Worker("worker", {
script: `import { DurableObject } from "cloudflare:workers";
export class DO_A_v2 extends DurableObject {}
export default { async fetch() { return new Response("v2"); } };
`,
env: { DO_A: Cloudflare.DurableObject("DO_A", { className: "DO_A_v2" }) },
}),
};
}),
);
expect(yield* fetchReady(v2.worker.url!, "v2")).toBe("v2");
const v3 = yield* scratch.deploy(
Effect.gen(function* () {
return {
worker: yield* Cloudflare.Worker("worker", {
script: `import { DurableObject } from "cloudflare:workers";
export class DO_A_v2 extends DurableObject {}
export class DO_B extends DurableObject {}
export default { async fetch() { return new Response("v3"); } };
`,
env: {
DO_A: Cloudflare.DurableObject("DO_A", { className: "DO_A_v2" }),
DO_B: Cloudflare.DurableObject("DO_B"),
},
}),
};
}),
);
expect(yield* fetchReady(v3.worker.url!, "v3")).toBe("v3");
const v4 = yield* scratch.deploy(
Effect.gen(function* () {
return {
worker: yield* Cloudflare.Worker("worker", {
script: `import { DurableObject } from "cloudflare:workers";
export class DO_B extends DurableObject {}
export default { async fetch() { return new Response("v4"); } };
`,
env: { DO_B: Cloudflare.DurableObject("DO_B") },
}),
};
}),
);
expect(yield* fetchReady(v4.worker.url!, "v4")).toBe("v4");
yield* scratch.destroy();
}).pipe(logLevel),
{ timeout: 180_000 },
);
// Reproduces #763: a Worker's precreate stub must declare Durable Object
// classes that exist only as env *bindings* — an async worker has no
// Effect-native exports, so before the fix the stub declared no DO classes at
// all. A resource caught in a dependency cycle with the worker resolves
// `worker.durableObjectNamespaces` against that stub (not the final reconcile
// output), so a binding-only class had no namespace id there and the deploy
// failed with "Worker did not expose Durable Object namespace <class>" on
// every fresh stage's FIRST deploy (reruns found the script already existing
// and passed — which is why this must run on a scratch stack, not a shared
// beforeAll deploy).
//
// The cycle here mirrors the worker<->container shape from the issue (a bare
// `Cloudflare.DurableObject` fronting a Container, where the container binds
// the DO's namespace id and the worker binds the container) without needing a
// Docker build: the consumer worker binds the host's `Counter` namespace id,
// and the host binds the consumer's name back.
test.provider(
"precreate stub exposes binding-only durable object namespaces to cycle peers",
(scratch) =>
Effect.gen(function* () {
const deployed = yield* scratch.deploy(
Effect.gen(function* () {
// `Counter` lives only in the inline script + env binding — it is
// never an Effect-native export.
const host = yield* Cloudflare.Worker("host-worker", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter") },
});
const consumer = yield* Cloudflare.Worker("consumer-worker", {
script: `export default {
async fetch(request, env) {
return Response.json({ namespaceId: env.COUNTER_NS });
},
};
`,
});
// consumer -> host: resolve the DO namespace id, exactly how a
// Container application binds `durableObjects.namespaceId`. The
// throw fires when the precreate stub omits the class — failing the
// deploy the same way the container cycle in #763 did.
yield* consumer.bind("counter-namespace", {
bindings: [
{
type: "plain_text",
name: "COUNTER_NS",
text: host.durableObjectNamespaces.pipe(
Output.map((namespaces) => {
const id = namespaces.Counter;
if (!id) {
throw new Error(
"Worker did not expose Durable Object namespace Counter.",
);
}
return id;
}),
),
},
],
});
// host -> consumer: closes the cycle so both workers are SCC
// members and rendezvous on each other's precreate stubs.
yield* host.bind("consumer-name", {
bindings: [
{ type: "plain_text", name: "CONSUMER_NAME", text: consumer.workerName },
],
});
return { host, consumer };
}),
);
// The namespace id created for the precreate stub must survive into the
// final reconcile output...
const finalNamespaceId = deployed.host.durableObjectNamespaces.Counter;
expect(finalNamespaceId).toBeDefined();
// ...and be the same id the consumer resolved from the stub and
// deployed into its live environment.
const body = yield* fetchJsonReady<{ namespaceId: string }>(deployed.consumer.url!);
expect(body.namespaceId).toBe(finalNamespaceId);
yield* scratch.destroy();
}).pipe(logLevel),
{ timeout: 120_000 },
);
// A Durable Object instance created on the precreate placeholder must reset
// itself on any call instead of serving the empty placeholder class. Before
// the fix, an instance that landed on the placeholder (an edge that hadn't
// seen the real version yet) failed every RPC call with "The RPC receiver
// does not implement the method" for as long as callers kept it busy.
//
// The placeholder is held live deterministically: the host's real script
// throws at startup, so its reconcile upload is rejected after precreate
// has already uploaded the placeholder, while the consumer (a cycle peer
// that rendezvoused on the host's precreate stub) deploys fully and
// reaches the placeholder's `Counter` through a cross-script binding.
test.provider(
"durable objects on the precreate placeholder reset onto the real version",
(scratch) =>
Effect.gen(function* () {
yield* scratch.destroy();
const program = (hostScript: string) =>
Effect.gen(function* () {
const host = yield* Cloudflare.Worker("host-worker", {
script: hostScript,
env: { Counter: Cloudflare.DurableObject("Counter") },
});
const consumer = yield* Cloudflare.Worker("consumer-worker", {
script: placeholderProbeScript,
env: {
Counter: Cloudflare.DurableObject("Counter", { scriptName: host.workerName }),
},
});
// host -> consumer closes the cycle, so the host is pre-created.
yield* host.bind("consumer-name", {
bindings: [
{ type: "plain_text", name: "CONSUMER_NAME", text: consumer.workerName },
],
});
return { host, consumer };
});
const failed = yield* scratch
.deploy(
program(
`${hostWorkerScript}\nthrow new Error("placeholder probe: host fails at startup");\n`,
),
)
.pipe(Effect.exit);
expect(failed._tag).toBe("Failure");
// The deploy failed, so read the consumer's URL from the scratch state.
const consumerUrl = yield* Effect.gen(function* () {
const state = yield* yield* State;
const fqns = yield* state.list({ stack: scratch.name, stage: scratch.stage });
const fqn = fqns.find((fqn) => fqn.endsWith("consumer-worker"));
expect(fqn).toBeDefined();
const row = yield* state.get({ stack: scratch.name, stage: scratch.stage, fqn: fqn! });
const attr = row && "attr" in row ? row.attr : undefined;
return (attr as { url?: string } | undefined)?.url;
}).pipe(Effect.provide(scratch.state));
expect(consumerUrl).toBeDefined();
// Every call into the placeholder resets the object rather than
// reporting a missing method — RPC and fetch alike.
const rpc = yield* probePlaceholder(`${consumerUrl}/rpc`);
expect(rpc).toMatchObject({ ok: false });
expect(rpc.error).toContain("Alchemy worker is being deployed");
expect(rpc.error).not.toContain("does not implement the method");
const fetched = yield* probePlaceholder(`${consumerUrl}/fetch`);
expect(fetched).toMatchObject({ ok: false });
expect(fetched.error).toContain("Alchemy worker is being deployed");
// Deploy the real host. The same named object now answers the real
// method — the placeholder instance reset instead of pinning it.
const deployed = yield* scratch.deploy(program(hostWorkerScript));
expect(deployed.consumer.url).toBe(consumerUrl);
const value = yield* fetchJsonReady<ProbeResult>(`${consumerUrl}/rpc`).pipe(
Effect.flatMap((result) =>
result.ok
? Effect.succeed(result.value)
: Effect.fail(new Error(`still on the placeholder: ${result.error}`)),
),
Effect.retry({ schedule: readinessSchedule, times: readinessRetries }),
);
expect(value).toBe(0);
yield* scratch.destroy();
}).pipe(logLevel),
{ timeout: 180_000 },
);
// Adopt a Durable Object class that already exists on a worker created
// *outside* Alchemy (raw Cloudflare API here, standing in for Wrangler or the
// dashboard). The worker carries no `alchemy:*` ownership tags and no
// `alchemy:do:` logical-id→class mapping, so `read` returns `Unowned` and the
// takeover requires `adopt(true)`. The matching `Counter` class must be reused
// — if `putWorker` instead asked Cloudflare to create it as a *new* class the
// migration would fail with "class already exists". This is the documented
// limitation: on the first (adopting) deploy the binding's class name must
// match the existing class; renames only work once Alchemy owns the worker.
test.provider(
"adopts a durable object class created outside alchemy",
(scratch) =>
Effect.gen(function* () {
const { accountId } = yield* yield* CloudflareEnvironment;
// Phase 1: provision a worker + `Counter` DO class straight through the
// Cloudflare API — no Alchemy involvement, so none of our tags. The
// name is deterministic (never Date.now()/random); a crashed run can
// leave the worker behind, and `putScript` would then reject the
// `newSqliteClasses` migration ("class already exists"), so purge any
// leftover first.
const physicalName = testName("alchemy-test-do-adopt");
yield* workers
.deleteScript({ accountId, scriptName: physicalName, force: true })
.pipe(Effect.catchTag("WorkerNotFound", () => Effect.void));
yield* workers.putScript({
accountId,
scriptName: physicalName,
metadata: {
mainModule: "main.js",
bindings: [
{ type: "durable_object_namespace", name: "Counter", className: "Counter" },
],
migrations: { newSqliteClasses: ["Counter"] },
// Match Alchemy's default compatibility date so adoption is a
// pure class-reuse with no compat-date churn. Old dates predate
// `DurableObjectNamespace.getByName`, which `hostWorkerScript`
// relies on.
compatibilityDate: "2026-03-17",
},
files: [
new File([hostWorkerScript], "main.js", { type: "application/javascript+module" }),
],
});
// Phase 2: deploy an async Alchemy Worker (inline script) over the same
// physical name with a matching `Counter` binding, opting in to the
// takeover via `adopt(true)`.
const adopted = yield* scratch
.deploy(
Effect.gen(function* () {
return yield* Cloudflare.Worker("AdoptDO", {
name: physicalName,
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter") },
});
}),
)
.pipe(adopt(true));
expect(adopted.workerName).toBe(physicalName);
// The existing class was adopted (and resolved to a namespace id),
// not recreated.
expect(adopted.durableObjectNamespaces.Counter).toBeDefined();
// The adopted DO is functional end-to-end: increment round-trips
// through the reused `Counter` class.
yield* fetchJsonReady<{ ok: boolean }>(`${adopted.url}/reset`);
const first = yield* fetchJsonReady<{ value: number }>(`${adopted.url}/increment`);
expect(first.value).toBe(1);
yield* scratch.destroy();
}).pipe(logLevel),
{ timeout: 120_000 },
);
// #2072: Wrangler ≥ 4.107 deploys Durable Objects with Cloudflare's
// declarative `exports` map, after which Cloudflare rejects every
// `migrations` upload ("reverting to `migrations` is not supported").
// Alchemy must adopt such a Worker without touching its namespaces —
// including a class it never binds (reached through `ctx.exports`), which
// must stay declared or Cloudflare refuses the upload.
test.provider(
"adopts a worker deployed with declarative exports",
(scratch) =>
Effect.gen(function* () {
const { accountId } = yield* yield* CloudflareEnvironment;
const physicalName = `alchemy-test-do-exports-${scratch.stage
.toLowerCase()
.replace(/[^a-z0-9-]/g, "-")}`;
const script = `${hostWorkerScript}\nexport class Unbound extends DurableObject {}\n`;
yield* workers
.deleteScript({ accountId, scriptName: physicalName, force: true })
.pipe(Effect.catchTag("WorkerNotFound", () => Effect.void));
// Phase 1: the Wrangler-shaped deploy — declarative `exports`, no
// migrations, no Alchemy tags.
yield* workers.putScript({
accountId,
scriptName: physicalName,
metadata: {
mainModule: "main.js",
bindings: [
{ type: "durable_object_namespace", name: "Counter", className: "Counter" },
],
exports: {
Counter: { type: "durable-object", storage: "sqlite" },
Unbound: { type: "durable-object", storage: "sqlite" },
},
compatibilityDate: "2026-03-17",
},
files: [new File([script], "main.js", { type: "application/javascript+module" })],
});
const namespacesOf = Effect.gen(function* () {
const namespaces = yield* durableObjects.listNamespaces.items({ accountId }).pipe(
Stream.filter((ns) => ns.script === physicalName),
Stream.runCollect,
);
return Object.fromEntries(Array.from(namespaces).map((ns) => [ns.class, ns.id]));
});
const before = yield* namespacesOf;
expect(Object.keys(before).sort()).toEqual(["Counter", "Unbound"]);
// Phase 2: adopt it. Only `Counter` is bound.
const deployAdopted = scratch
.deploy(
Effect.gen(function* () {
return yield* Cloudflare.Worker("AdoptExports", {
name: physicalName,
script,
env: { Counter: Cloudflare.DurableObject("Counter") },
});
}),
)
.pipe(adopt(true));
const adopted = yield* deployAdopted;
// Both namespaces survived the takeover unchanged.
expect(adopted.durableObjectNamespaces.Counter).toBe(before.Counter);
expect(yield* namespacesOf).toEqual(before);
yield* fetchJsonReady<{ ok: boolean }>(`${adopted.url}/reset`);
const written = yield* fetchJsonReady<{ value: number }>(`${adopted.url}/increment`);
expect(written.value).toBe(1);
// A routine redeploy keeps the data.
const redeployed = yield* deployAdopted;
const read = yield* fetchJsonReady<{ value: number }>(`${redeployed.url}/get`);
expect(read.value).toBe(1);
expect(yield* namespacesOf).toEqual(before);
yield* scratch.destroy();
expect(yield* namespacesOf).toEqual({});
}).pipe(logLevel),
{ timeout: 180_000 },
);
// #799: moving a Durable Object class from one Worker to another is
// *declared*: the new host names the former host with `transferredFrom` —
// here by Worker *logical id*, resolved to the actual script via alchemy's
// ownership tags (`alchemy:id:` + stack + stage) among scripts observed to
// host the class. Worker-a's deploy ships Cloudflare's data-preserving
// `transferred_classes` migration; worker-b's deploy converges on its own
// (no `deleted_classes` for a class that moved away).
//
// v1 — worker-b hosts `Counter` locally; write data into the namespace
// v2 — worker-a hosts `Counter` with `transferredFrom: "worker-b"`;
// worker-b re-binds it cross-script. The stored data must survive
// the move, reachable from both.
// v3 — redeploy of the same shape is inert (no re-transfer; the
// declaration stays in the code).
test.provider(
"durable object host move declared by worker logical id preserves data",
(scratch) =>
Effect.gen(function* () {
yield* scratch.destroy();
const v1 = yield* scratch.deploy(
Effect.gen(function* () {
return {
b: yield* Cloudflare.Worker("worker-b", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter") },
}),
};
}),
);
const originalNamespaceId = v1.b.durableObjectNamespaces.Counter;
expect(originalNamespaceId).toBeDefined();
// Write data while worker-b hosts the namespace.
yield* fetchJsonReady<{ ok: boolean }>(`${v1.b.url}/reset`);
const written = yield* fetchJsonReady<{ value: number }>(`${v1.b.url}/increment`);
expect(written.value).toBe(1);
const moved = Effect.gen(function* () {
const a = yield* Cloudflare.Worker("worker-a", {
script: hostWorkerScript,
env: {
Counter: Cloudflare.DurableObject("Counter", {
// The former host's Worker *logical id* — resolved to its
// physical script via alchemy's ownership tags.
transferredFrom: "worker-b",
}),
},
});
const b = yield* Cloudflare.Worker("worker-b", {
script: consumerWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter", { scriptName: a.workerName }) },
});
return { a, b };
});
const v2 = yield* scratch.deploy(moved);
expect(v2.a.durableObjectNamespaces.Counter).toBe(originalNamespaceId);
expect(v2.b.durableObjectNamespaces.Counter).toBe(originalNamespaceId);
// The namespace moved to worker-a with its data intact...
const viaA = yield* fetchJsonReady<{ value: number }>(`${v2.a.url}/get`);
expect(viaA.value).toBe(1);
// ...and worker-b reaches the same objects through the cross-script
// binding.
const viaB = yield* fetchJsonReady<{ value: number }>(`${v2.b.url}/increment`);
expect(viaB.value).toBe(2);
// Redeploying the same shape is inert: the class now lives on
// worker-a (tracked by its alchemy:do tag), so the standing
// declaration must not re-emit a transfer migration. Data intact.
const v3 = yield* scratch.deploy(moved);
const afterRedeploy = yield* fetchJsonReady<{ value: number }>(`${v3.a.url}/get`);
expect(afterRedeploy.value).toBe(2);
// ...and once the move has landed everywhere, the declaration can be
// removed entirely: the class is anchored by its alchemy:do tag, so
// dropping `transferredFrom` emits no migration and touches no data.
const v4 = yield* scratch.deploy(
Effect.gen(function* () {
const a = yield* Cloudflare.Worker("worker-a", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter") },
});
const b = yield* Cloudflare.Worker("worker-b", {
script: consumerWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter", { scriptName: a.workerName }) },
});
return { a, b };
}),
);
const afterRemoval = yield* fetchJsonReady<{ value: number }>(`${v4.a.url}/get`);
expect(afterRemoval.value).toBe(2);
yield* scratch.destroy();
}).pipe(logLevel),
{ timeout: 240_000 },
);
// #799: `transferredFrom` also accepts the former host's *physical script
// name* — the form required for cross-stack moves, where the new host
// deploys from a different plan entirely (modeled here with raw-string
// script names on a pre-existing worker).
test.provider(
"transferredFrom by physical script name transfers the namespace",
(scratch) =>
Effect.gen(function* () {
yield* scratch.destroy();
// v1: worker-b hosts the class; worker-a exists but has no DO yet —
// deploying it now is what makes its physical name knowable as a raw
// string in v2 (the cross-stack shape).
const v1 = yield* scratch.deploy(
Effect.gen(function* () {
return {
a: yield* Cloudflare.Worker("worker-a", {
script: `export default { fetch() { return new Response("plain"); } };`,
}),
b: yield* Cloudflare.Worker("worker-b", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter") },
}),
};
}),
);
yield* fetchJsonReady<{ ok: boolean }>(`${v1.b.url}/reset`);
const written = yield* fetchJsonReady<{ value: number }>(`${v1.b.url}/increment`);
expect(written.value).toBe(1);
const aScriptName = v1.a.workerName;
const bScriptName = v1.b.workerName;
const v2 = yield* scratch.deploy(
Effect.gen(function* () {
const a = yield* Cloudflare.Worker("worker-a", {
script: hostWorkerScript,
env: {
Counter: Cloudflare.DurableObject("Counter", {
// Thunk form — evaluated lazily at plan time and
// normalized to the plain script name.
transferredFrom: () => bScriptName,
}),
},
});
const b = yield* Cloudflare.Worker("worker-b", {
script: consumerWorkerScript,
env: {
// Service binding orders worker-b after worker-a (the raw
// string scriptName below carries no dependency edge).
A: a,
Counter: Cloudflare.DurableObject("Counter", { scriptName: aScriptName }),
},
});
return { a, b };
}),
);
const viaA = yield* fetchJsonReady<{ value: number }>(`${v2.a.url}/get`);
expect(viaA.value).toBe(1);
yield* scratch.destroy();
}).pipe(logLevel),
{ timeout: 240_000 },
);
// #799 (safety interlock): a host move WITHOUT `transferredFrom` must fail
// loudly before the former host uploads anything — moves are never
// inferred, the namespace (and its data) still lives on worker-b, and
// deleting the class would destroy it. The error names the exact
// declaration to add.
test.provider(
"undeclared host move fails with DurableObjectTransferRequired",
(scratch) =>
Effect.gen(function* () {
yield* scratch.destroy();
const v1 = yield* scratch.deploy(
Effect.gen(function* () {
return {
a: yield* Cloudflare.Worker("worker-a", {
script: `export default { fetch() { return new Response("plain"); } };`,
}),
b: yield* Cloudflare.Worker("worker-b", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter") },
}),
};
}),
);
// Data exists on worker-b's namespace — this is what the interlock
// protects.
yield* fetchJsonReady<{ ok: boolean }>(`${v1.b.url}/reset`);
yield* fetchJsonReady<{ value: number }>(`${v1.b.url}/increment`);
const aScriptName = v1.a.workerName;
const error = yield* scratch
.deploy(
Effect.gen(function* () {
const a = yield* Cloudflare.Worker("worker-a", {
script: hostWorkerScript,
env: {
// Fresh, empty namespace for the same class name — the
// move is not declared, so nothing transfers.
Counter: Cloudflare.DurableObject("Counter"),
},
});
const b = yield* Cloudflare.Worker("worker-b", {
script: consumerWorkerScript,
env: {
Counter: Cloudflare.DurableObject("Counter", { scriptName: aScriptName }),
},
});
return { a, b };
}),
)
.pipe(Effect.flip);
expect(error._tag).toEqual("DurableObjectTransferRequired");
expect((yield* fetchJsonReady<{ value: number }>(`${v1.b.url}/get`)).value).toBe(1);
yield* scratch.destroy();
}).pipe(logLevel),
{ timeout: 240_000 },
);
test.provider(
"a transferred namespace cannot be rebound to a different namespace",
(scratch) =>
Effect.gen(function* () {
yield* scratch.destroy();
const { accountId } = yield* yield* CloudflareEnvironment;
const v1 = yield* scratch.deploy(
Effect.gen(function* () {
return {
a: yield* Cloudflare.Worker("worker-a", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter") },
}),
};
}),
);
const originalNamespaceId = v1.a.durableObjectNamespaces.Counter;
expect(originalNamespaceId).toBeDefined();
yield* fetchJsonReady<{ ok: boolean }>(`${v1.a.url}/reset`);
expect((yield* fetchJsonReady<{ value: number }>(`${v1.a.url}/increment`)).value).toBe(1);
const transferredStack = (scriptName?: string) =>
Effect.gen(function* () {
const a = yield* Cloudflare.Worker("worker-a", {
script: scriptName === undefined ? hostWorkerScript : consumerWorkerScript,
env: {
Counter:
scriptName === undefined
? Cloudflare.DurableObject("Counter")
: Cloudflare.DurableObject("Counter", { scriptName }),
},
});
const b = yield* Cloudflare.Worker("worker-b", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter", { transferredFrom: a }) },
});
const c = yield* Cloudflare.Worker("worker-c", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter") },
});
return { a, b, c };
});
// A stays unchanged while B receives its namespace; C owns a fresh one.
const v2 = yield* scratch.deploy(transferredStack());
expect(v2.b.durableObjectNamespaces.Counter).toBe(originalNamespaceId);
const unrelatedNamespaceId = v2.c.durableObjectNamespaces.Counter;
expect(unrelatedNamespaceId).toBeDefined();
expect(unrelatedNamespaceId).not.toBe(originalNamespaceId);
const namespaces = yield* durableObjects.listNamespaces.items({ accountId }).pipe(
Stream.runCollect,
Effect.repeat({
schedule: Schedule.spaced("1 second"),
times: 8,
until: (namespaces) =>
namespaces.some(
(ns) => ns.id === originalNamespaceId && ns.script === v2.b.workerName,
) &&
namespaces.some(
(ns) => ns.id === unrelatedNamespaceId && ns.script === v2.c.workerName,
) &&
!namespaces.some((ns) => ns.script === v2.a.workerName && ns.class === "Counter"),
}),
);
expect(namespaces.find((ns) => ns.id === originalNamespaceId)).toMatchObject({
script: v2.b.workerName,
class: "Counter",
});
expect(namespaces.find((ns) => ns.id === unrelatedNamespaceId)).toMatchObject({
script: v2.c.workerName,
class: "Counter",
});
expect(
namespaces.some((ns) => ns.script === v2.a.workerName && ns.class === "Counter"),
).toBe(false);
expect((yield* fetchJsonReady<{ value: number }>(`${v2.b.url}/get`)).value).toBe(1);
expect((yield* fetchJsonReady<{ value: number }>(`${v2.c.url}/get`)).value).toBe(0);
const error = yield* scratch.deploy(transferredStack(v2.c.workerName)).pipe(Effect.flip);
expect(error._tag).toBe("DurableObjectTransferRequired");
expect((yield* fetchJsonReady<{ value: number }>(`${v2.b.url}/get`)).value).toBe(1);
expect((yield* fetchJsonReady<{ value: number }>(`${v2.c.url}/get`)).value).toBe(0);
yield* scratch.destroy();
}).pipe(logLevel),
{ timeout: 120_000 },
);
// A former host keeps its `alchemy:dos:` tag until its next deploy, while
// Cloudflare rewrites its binding to a className-less reference to the
// moved namespace (dangling once the new host is deleted). Naming that
// former host again — e.g. a host history `[b, a]` after b is gone — must
// treat it as not hosting the class and create a fresh namespace, not fail
// trying to locate a namespace that no longer exists.
test.provider(
"a former host with a stale class tag is not a transfer source",
(scratch) =>
Effect.gen(function* () {
yield* scratch.destroy();
const hostA = Cloudflare.Worker("worker-a", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter") },
});
// v1 — worker-b takes worker-a's namespace; worker-a is untouched.
const v1 = yield* scratch.deploy(
Effect.gen(function* () {
const a = yield* hostA;
const b = yield* Cloudflare.Worker("worker-b", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter", { transferredFrom: a }) },
});
return { a, b };
}),
);
const movedNamespaceId = v1.b.durableObjectNamespaces.Counter;
expect(movedNamespaceId).toBe(v1.a.durableObjectNamespaces.Counter);
// v2 — worker-b (and with it the moved namespace) is deleted.
yield* scratch.deploy(
Effect.gen(function* () {
return { a: yield* hostA };
}),
);
// v3 — worker-d names worker-a as its former host: worker-a no
// longer hosts Counter, so worker-d creates a fresh namespace.
const v3 = yield* scratch.deploy(
Effect.gen(function* () {
const a = yield* hostA;
const d = yield* Cloudflare.Worker("worker-d", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter", { transferredFrom: a }) },
});
return { a, d };
}),
);
const freshNamespaceId = v3.d.durableObjectNamespaces.Counter;
expect(freshNamespaceId).toBeDefined();
expect(freshNamespaceId).not.toBe(movedNamespaceId);
const { accountId } = yield* yield* CloudflareEnvironment;
const namespaces = yield* durableObjects.listNamespaces
.items({ accountId })
.pipe(Stream.runCollect);
expect(namespaces.find((ns) => ns.id === freshNamespaceId)).toMatchObject({
script: v3.d.workerName,
class: "Counter",
});
expect(namespaces.some((ns) => ns.id === movedNamespaceId)).toBe(false);
yield* scratch.destroy();
}).pipe(logLevel),
{ timeout: 120_000 },
);
// #799: the documented *pure move* — the former host drops the DO entirely,
// keeping no cross-script reference — done as two deploys. Phase 1 adds the
// class to worker-a, declaring the former host by **Worker resource
// reference** (`transferredFrom: b`, normalized at plan time to worker-b's
// logical id — no dependency edge on b); worker-b is untouched. Phase 2
// removes the DO from worker-b, whose deploy observes the class already
// transferred away and skips the delete.
test.provider(
"two-deploy pure move with a Worker resource reference",
(scratch) =>
Effect.gen(function* () {
yield* scratch.destroy();
const v1 = yield* scratch.deploy(
Effect.gen(function* () {
return {
b: yield* Cloudflare.Worker("worker-b", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter") },
}),
};
}),
);
yield* fetchJsonReady<{ ok: boolean }>(`${v1.b.url}/reset`);
const written = yield* fetchJsonReady<{ value: number }>(`${v1.b.url}/increment`);
expect(written.value).toBe(1);
// Phase 1: worker-a takes the class, naming the former host by
// resource reference. worker-b's declaration is unchanged (noop).
const v2 = yield* scratch.deploy(
Effect.gen(function* () {
const b = yield* Cloudflare.Worker("worker-b", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter") },
});
const a = yield* Cloudflare.Worker("worker-a", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter", { transferredFrom: b }) },
});
return { a, b };
}),
);
// The namespace moved to worker-a with its data intact.
const viaA = yield* fetchJsonReady<{ value: number }>(`${v2.a.url}/get`);
expect(viaA.value).toBe(1);
// Phase 2: worker-b drops the DO entirely. Its deploy observes the
// class already lives on worker-a and emits no delete migration.
const v3 = yield* scratch.deploy(
Effect.gen(function* () {
const b = yield* Cloudflare.Worker("worker-b", {
script: `export default { fetch() { return new Response("plain"); } };`,
});
const a = yield* Cloudflare.Worker("worker-a", {
script: hostWorkerScript,
env: { Counter: Cloudflare.DurableObject("Counter", { transferredFrom: b }) },
});
return { a, b };
}),
);
const afterRemoval = yield* fetchJsonReady<{ value: number }>(`${v3.a.url}/increment`);
expect(afterRemoval.value).toBe(2);
yield* scratch.destroy();
}).pipe(logLevel),
{ timeout: 240_000 },
);
// Reproduces #811: one script tag per DO binding blew Cloudflare's 10-tag
// limit at 7+ Durable Objects (3 ownership tags + 1 migration tag + N DO
// tags). The logical-id→class mapping is now packed into `alchemy:dos:`
// tags, so a worker with 20 DOs — double the count that used to consume the
// entire tag budget — deploys fine and the whole tag set stays within the
// limit. The second deploy renames a class and drops another to prove
// migrations are still driven by the packed mapping.
test.provider(
"worker with 20 durable objects deploys within the 10-tag limit",
(scratch) =>
Effect.gen(function* () {
yield* scratch.destroy();
const { accountId } = yield* yield* CloudflareEnvironment;
const ids = Array.from({ length: 20 }, (_, i) => `DO_${i}`);
const makeScript = (classes: string[], version: string) =>
`import { DurableObject } from "cloudflare:workers";
${classes.map((c) => `export class ${c} extends DurableObject {}`).join("\n")}
export default { async fetch() { return new Response("${version}"); } };
`;
const v1 = yield* scratch.deploy(
Effect.gen(function* () {
return {
worker: yield* Cloudflare.Worker("worker", {
script: makeScript(
ids.map((_, i) => `Class${i}`),
"v1",
),
env: Object.fromEntries(
ids.map((id, i) => [
id,
Cloudflare.DurableObject(id, { className: `Class${i}` }),
]),
),
}),
};
}),
);
expect(yield* fetchReady(v1.worker.url!, "v1")).toBe("v1");
const tags = yield* getWorkerTags(v1.worker.workerName, accountId);
expect(tags.length).toBeLessThanOrEqual(10);
expect(tags.filter((t) => t.startsWith("alchemy:dos:"))).toHaveLength(1);
expect(tags.filter((t) => t.startsWith("alchemy:do:"))).toHaveLength(0);
expect(Object.keys(v1.worker.durableObjectNamespaces).sort()).toEqual(
ids.map((_, i) => `Class${i}`).sort(),
);
// Rename Class0 → Class0V2 (same binding id) and delete DO_19 — both
// migrations resolve their previous class through the packed tag.
const v2 = yield* scratch.deploy(
Effect.gen(function* () {
return {
worker: yield* Cloudflare.Worker("worker", {
script: makeScript(
["Class0V2", ...ids.slice(1, 19).map((_, i) => `Class${i + 1}`)],
"v2",
),
env: Object.fromEntries(
ids.slice(0, 19).map((id, i) => [
id,
Cloudflare.DurableObject(id, {
className: i === 0 ? "Class0V2" : `Class${i}`,
}),
]),
),
}),
};
}),
);
expect(yield* fetchReady(v2.worker.url!, "v2")).toBe("v2");
expect(Object.keys(v2.worker.durableObjectNamespaces).sort()).toEqual(