From db7974cc2d7967f121f9d8b55d1293b89905418f Mon Sep 17 00:00:00 2001 From: "Arthur @Refzlund" Date: Mon, 30 Nov 2026 04:13:38 +0100 Subject: [PATCH 1/8] feat(containers): the durable_object scheduling policy, compiled and run locally through ctx.container A container entry may set schedulingPolicy: 'durable_object' with named images. It compiles to the fields Wrangler takes for that policy (class_name, scheduling_policy, name, images), and the schema refuses the application-wide fields Wrangler rejects there. devflare dev and createTestContext() build each named image with Docker or Podman, pull Miniflare's egress interceptor, and attach the container to its Durable Object in Miniflare with SQLite storage, the shape wrangler dev uses. The test gateway exports a container-backed module's WorkerEntrypoint classes so outbound intercepts can target ctx.exports. Windows is refused (workerd cannot reach a named pipe), workspace dev refuses such an app, and DEVFLARE_ENABLE_CONTAINERS=0 turns local containers off. A new workspace-ci job runs the engine-backed test on the runner's Docker and fails if it would skip. Co-Authored-By: Claude Opus 5.5 --- .../container-durable-object-scheduling.md | 39 ++ .github/workflows/workspace-ci.yml | 50 +- .../docs/content/bindings/compact-guides-2.ts | 88 ++- docs/CLOUDFLARE_SUPPORT_MATRIX.md | 10 + packages/devflare/LLM.md | 90 ++- .../src/config/compiler/core-helpers.ts | 71 ++- .../devflare/src/config/compiler/paths.ts | 47 +- .../devflare/src/config/compiler/types.ts | 11 +- packages/devflare/src/config/index.ts | 3 + .../devflare/src/config/schema-runtime.ts | 112 +++- .../src/config/schema-types-containers.ts | 231 ++++++++ .../src/config/schema-types-runtime.ts | 109 ---- packages/devflare/src/config/schema-types.ts | 3 +- packages/devflare/src/config/schema.ts | 7 + .../src/dev-server/dev-server-state.ts | 4 + .../src/dev-server/miniflare-dev-config.ts | 66 ++- .../src/dev-server/miniflare-worker-config.ts | 3 +- packages/devflare/src/dev-server/server.ts | 13 +- .../src/dev-server/workspace/prepare-app.ts | 34 ++ packages/devflare/src/test/containers.ts | 18 +- .../src/test/durable-object-containers.ts | 555 ++++++++++++++++++ .../test/simple-context-durable-objects.ts | 88 ++- packages/devflare/src/test/simple-context.ts | 21 +- .../durable-object-container.test.ts | 296 ++++++++++ .../unit/config/compiler/09-containers.ts | 65 ++ .../compiler/15-rebasewranglerconfigpaths.ts | 31 + .../tests/unit/config/schema-core.test.ts | 125 ++++ .../tests/unit/config/type-docs.test.ts | 3 +- .../config/wrangler-container-shape.test.ts | 143 +++++ .../dev-server/miniflare-dev-config.test.ts | 72 +++ ...orkspace-durable-object-containers.test.ts | 46 ++ .../test/container-gateway-exports.test.ts | 98 ++++ .../tests/unit/test/containers.test.ts | 21 + .../test/durable-object-containers.test.ts | 427 ++++++++++++++ 34 files changed, 2854 insertions(+), 146 deletions(-) create mode 100644 .changeset/container-durable-object-scheduling.md create mode 100644 packages/devflare/src/config/schema-types-containers.ts create mode 100644 packages/devflare/src/test/durable-object-containers.ts create mode 100644 packages/devflare/tests/integration/test-context/durable-object-container.test.ts create mode 100644 packages/devflare/tests/unit/config/wrangler-container-shape.test.ts create mode 100644 packages/devflare/tests/unit/dev-server/workspace-durable-object-containers.test.ts create mode 100644 packages/devflare/tests/unit/test/container-gateway-exports.test.ts create mode 100644 packages/devflare/tests/unit/test/durable-object-containers.test.ts diff --git a/.changeset/container-durable-object-scheduling.md b/.changeset/container-durable-object-scheduling.md new file mode 100644 index 00000000..61736b7c --- /dev/null +++ b/.changeset/container-durable-object-scheduling.md @@ -0,0 +1,39 @@ +--- +'devflare': minor +--- + +Containers can use Cloudflare's `durable_object` scheduling policy, where the Durable Object picks +the image and instance size each time it calls `ctx.container.start()`. Cloudflare has deprecated +the `default` policy and stops updating the `Container` class from `@cloudflare/containers` after +2026-12-31, so this is the shape new containers should take. + +```ts +containers: [ + { + className: 'Builder', + schedulingPolicy: 'durable_object', + images: { base: { dockerfile: './container/Dockerfile' } } + } +] +``` + +**It compiles to exactly what Wrangler takes for that policy:** `class_name`, `scheduling_policy`, +`name` and `images` (each a `{ dockerfile, build_context?, build_vars? }` or a digest-pinned +`{ image }`). The schema refuses `image`, `instanceType`, `maxInstances` and the rollout fields on +such an entry, as Wrangler does. Existing entries parse and compile unchanged; `schedulingPolicy: +'default'` may now be spelled out. + +**`devflare dev` and `createTestContext()` run it locally, as `wrangler dev` does.** Devflare builds +each Dockerfile image (or reuses or pulls a registry image) with Docker or Podman for `linux/amd64`, +pulls Miniflare's egress interceptor image, and attaches the container to its Durable Object in +Miniflare with SQLite storage. `ctx.container.images`, `start({ enableInternet: false })` and the +`interceptOutboundHttp()`, `interceptOutboundHttps()` and `interceptAllOutboundHttp()` rules then +run against a real local container. In `createTestContext()`, the `WorkerEntrypoint` classes a +container-backed Durable Object's module exports are exported from the test gateway too, so an +intercept can target `ctx.exports.`. + +Local containers need Linux or macOS: workerd cannot reach a Windows named pipe, so on Windows +devflare refuses and points at WSL, as Wrangler does. `DEVFLARE_ENABLE_CONTAINERS=0` starts without +them, leaving `ctx.container` undefined. `devflare workspace dev` does not run them yet and refuses +an app that declares one, and `containers.start()` refuses a `durable_object` entry, which only its +Durable Object can start. diff --git a/.github/workflows/workspace-ci.yml b/.github/workflows/workspace-ci.yml index 843c3864..8e7d596f 100644 --- a/.github/workflows/workspace-ci.yml +++ b/.github/workflows/workspace-ci.yml @@ -79,4 +79,52 @@ jobs: - name: Run cached devflare validation lane shell: bash - run: bun run devflare:ci \ No newline at end of file + run: bun run devflare:ci + + # Starts a real durable_object scheduling-policy container through + # createTestContext(): devflare builds the image, workerd drives it through + # ctx.container, and the test checks enableInternet: false and the outbound + # intercepts. The runner's Docker engine is what the validate lane lacks a + # flag for, so it runs here alone, and a skip fails the job. + durable-object-containers: + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + DEVFLARE_CONTAINER_TESTS: "1" + DEVFLARE_CONTAINER_TESTS_REQUIRED: "1" + DEVFLARE_CONTAINER_ENGINE: docker + + steps: + - name: Checkout + uses: actions/checkout@v5 + + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.2 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: "22" + + - name: Restore Bun install cache + uses: actions/cache@v4 + with: + path: ~/.bun/install/cache + key: ${{ runner.os }}-bun-1.4.2-${{ hashFiles('bun.lock') }} + restore-keys: | + ${{ runner.os }}-bun-1.4.2- + + - name: Install workspace dependencies + shell: bash + run: bun install --frozen-lockfile + + - name: Docker engine + shell: bash + run: docker info --format '{{.ServerVersion}} {{.OperatingSystem}}' + + - name: Run the durable_object container test + shell: bash + working-directory: packages/devflare + run: bun test tests/integration/test-context/durable-object-container.test.ts --max-concurrency=1 diff --git a/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts b/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts index b9a936c9..f9b559af 100644 --- a/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts +++ b/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts @@ -385,9 +385,10 @@ test('creates an in-memory artifact repo', async () => { categoryDescription: 'Cloudflare Containers config plus a Worker route that hands requests to a container-backed Durable Object.', configKey: 'containers', - authoringShape: 'Array<{ className; image; maxInstances?; instanceType?; imageBuildContext? }>', + authoringShape: + "Array<{ className; image; maxInstances?; instanceType?; imageBuildContext? } | { className; schedulingPolicy: 'durable_object'; images? }>", localStory: - 'Offline-native only when an explicit Docker/Podman engine is available and the image can run without pulling', + 'Offline-native only when an explicit Docker/Podman engine is available and the image can run without pulling; durable_object containers run under workerd on Linux or macOS', sourcePages: [ 'packages/devflare/src/config/schema-runtime.ts', 'packages/devflare/src/config/compiler.ts', @@ -396,6 +397,9 @@ test('creates an in-memory artifact repo', async () => { 'https://developers.cloudflare.com/containers/get-started/', 'https://developers.cloudflare.com/containers/platform-details/image-management/', 'https://developers.cloudflare.com/containers/container-class/', + 'https://developers.cloudflare.com/containers/configuration/scheduling-policy/', + 'https://developers.cloudflare.com/containers/api/durable-object-container/', + 'https://developers.cloudflare.com/containers/platform-details/outbound-traffic/', 'https://developers.cloudflare.com/workers/wrangler/configuration/#containers' ], compileTarget: 'Wrangler `containers`', @@ -476,6 +480,86 @@ test('container engine detection is explicit', async () => { })` }, overviewSections: [ + { + id: 'container-durable-object-policy', + title: 'Let the Durable Object choose the image: the durable_object scheduling policy', + paragraphs: [ + "Cloudflare's `durable_object` scheduling policy (public beta) moves the image and instance size out of config and into `ctx.container.start()`. Cloudflare marks the older `default` policy deprecated and stops updating the `@cloudflare/containers` `Container` class after 2026-12-31, so new containers should use this one. The policy is immutable per application: moving an existing application means a new one.", + "Set `schedulingPolicy: 'durable_object'` and list the images the object may start under `images`. Each key becomes a property of `ctx.container.images`. Devflare compiles the entry to Wrangler's `class_name`, `scheduling_policy`, `name` and `images` and nothing else, because Wrangler rejects `image`, `instance_type`, `max_instances` and rollouts for this policy; the schema refuses them first.", + "`devflare dev` and `createTestContext()` run it locally the way `wrangler dev` does: they build each Dockerfile image (or reuse or pull a registry image) with Docker or Podman for `linux/amd64`, pull Miniflare's egress interceptor image, and attach the container to the Durable Object in Miniflare. `ctx.container.start()`, `images`, `enableInternet` and the `interceptOutboundHttp()`, `interceptOutboundHttps()` and `interceptAllOutboundHttp()` rules then run against a real local container." + ], + snippets: [ + { + title: 'Declare a Durable Object-managed container', + language: 'ts', + code: String.raw`import { defineConfig } from 'devflare/config' + +export default defineConfig({ + name: 'builder-worker', + compatibilityDate: '2026-09-29', + files: { durableObjects: 'src/do.*.ts' }, + bindings: { + durableObjects: { BUILDER: 'Builder' } + }, + containers: [ + { + className: 'Builder', + schedulingPolicy: 'durable_object', + images: { + base: { dockerfile: './container/Dockerfile' } + } + } + ], + migrations: [{ tag: 'v1', new_sqlite_classes: ['Builder'] }] +})` + }, + { + title: 'Start it from the Durable Object, with the Internet off and one host allowed', + language: 'ts', + code: String.raw`import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers' + +export class AllowRelay extends WorkerEntrypoint { + fetch(request: Request) { + const url = new URL(request.url) + if (url.hostname !== 'relay.example.com') return new Response('Forbidden', { status: 403 }) + return fetch(request) + } +} + +export class Builder extends DurableObject { + async ensureStarted() { + const container = this.ctx.container! + if (container.running) return + await container.interceptOutboundHttps('relay.example.com', this.ctx.exports.AllowRelay) + container.start({ image: container.images.base, enableInternet: false }) + } +}` + }, + { + title: 'What it compiles to', + language: 'json', + filename: '.devflare/wrangler.jsonc', + code: String.raw`{ + "containers": [ + { + "class_name": "Builder", + "scheduling_policy": "durable_object", + "images": { "base": { "dockerfile": "./container/Dockerfile" } } + } + ] +}` + } + ], + bullets: [ + 'A named image is either `{ dockerfile, buildContext?, buildVars? }` or `{ image }`, a digest-pinned `registry.cloudflare.com//@sha256:`. Between 1 and 100 images, each name 1 to 128 characters.', + 'The Durable Object class must use SQLite storage. List it in `new_sqlite_classes`; local runs give container-backed namespaces SQLite storage, as Wrangler does.', + "Outbound intercepts target a `WorkerEntrypoint` through `ctx.exports`, which needs a compatibility date of 2025-11-17 or later. In `createTestContext()`, the `WorkerEntrypoint` classes exported from the Durable Object's own module are exported from the test gateway, so `ctx.exports.` resolves there too. A service binding also works as a target.", + 'HTTPS interception needs the container to trust `/etc/cloudflare/certs/cloudflare-containers-ca.crt`.', + "Local runs need Linux or macOS: workerd cannot reach a Windows named pipe, so on Windows devflare refuses and points at WSL, as Wrangler does. Set `DEVFLARE_ENABLE_CONTAINERS=0` to start without containers; `ctx.container` is then undefined. Devflare uses `WRANGLER_DOCKER_HOST` or `DOCKER_HOST` when set, then the engine's own socket.", + '`devflare workspace dev` does not run durable_object containers yet and refuses an app that declares one; run `devflare dev` in that app. The `containers.start()` helper starts only `default`-policy containers.', + 'Images are rebuilt each time the config loads; a change inside the container needs a restart.' + ] + }, { id: 'container-image-workflow', title: 'Build and reference the image deliberately', diff --git a/docs/CLOUDFLARE_SUPPORT_MATRIX.md b/docs/CLOUDFLARE_SUPPORT_MATRIX.md index aadaab21..f8ac9aa0 100644 --- a/docs/CLOUDFLARE_SUPPORT_MATRIX.md +++ b/docs/CLOUDFLARE_SUPPORT_MATRIX.md @@ -282,6 +282,16 @@ In the support matrix, containers are classified ✅ full local: Devflare can launch local Docker/Podman containers in explicit tests when an engine and cached images are available. +A container under the **`durable_object` scheduling policy** (`schedulingPolicy: +'durable_object'`) runs differently, the way `wrangler dev` runs it: `devflare dev` +and `createTestContext()` build its named images (pulling base layers as Docker +does), pull Miniflare's egress interceptor image, and attach the container to its +Durable Object in Miniflare, so `ctx.container`, `enableInternet` and the +outbound intercepts work against a real local container. That path is not +offline-first, needs Linux or macOS (devflare refuses Windows, as Wrangler does), +and is turned off with `DEVFLARE_ENABLE_CONTAINERS=0`. `devflare workspace dev` +does not run it yet. + ## How deploy auto-provisioning works When you deploy, Devflare materializes the resources your bindings reference. The diff --git a/packages/devflare/LLM.md b/packages/devflare/LLM.md index 226c06c8..2b92aacc 100644 --- a/packages/devflare/LLM.md +++ b/packages/devflare/LLM.md @@ -4836,7 +4836,7 @@ That is great once you already opened the right binding page. This index is for | Images | Full local support through Miniflare image bindings, persisted local state, and deterministic pure mocks | `createTestContext()` or `createOfflineEnv()` | | Media Transformations | Full local support through Miniflare media bindings and deterministic pure mocks for transform chains | `createTestContext()` or `createOfflineEnv()` with media fixtures | | Artifacts | Offline-fixture: repo metadata and token flows can be modeled in memory, not as real Git remotes | `createOfflineEnv()` with artifact fixtures | -| Containers | Offline-native only when an explicit Docker/Podman engine is available and the image can run without pulling | `devflare/test` containers helpers guarded by `shouldSkip.containers` | +| Containers | Offline-native only when an explicit Docker/Podman engine is available and the image can run without pulling; durable_object containers run under workerd on Linux or macOS | `devflare/test` containers helpers guarded by `shouldSkip.containers` | | Stream | Full local support through the native Miniflare Stream plugin (a local StreamObject backed by disk persistence) plus a deterministic pure mock for app-level tests | `createTestContext()` or `createOfflineEnv()` | | VPC Services | Remote boundary: Miniflare wires VPC services only as a remote proxy client, so there is no offline simulation | a deployed or remote-mode test against the real VPC service | | VPC Networks | Remote boundary: Miniflare wires VPC networks only as a remote proxy client, so there is no offline simulation | a deployed or remote-mode test against the real VPC network | @@ -15908,7 +15908,7 @@ Start with the config, wire the binding into worker code, then use the support s | Fact | Value | | --- | --- | | Config key | `containers` | -| Authoring shape | `Array<{ className; image; maxInstances?; instanceType?; imageBuildContext? }>` | +| Authoring shape | `Array<{ className; image; maxInstances?; instanceType?; imageBuildContext? } \| { className; schedulingPolicy: 'durable_object'; images? }>` | | Best for | routing requests to a stateful container instance that runs code outside the Workers runtime | #### Add the binding to config @@ -15986,6 +15986,88 @@ Containers have full local support when Docker or Podman is reachable and the im Use Cloudflare when the assertion depends on deployed limits, account state, lifecycle behavior, billing, or other production-only Containers details. +#### Let the Durable Object choose the image: the durable_object scheduling policy + +Cloudflare's `durable_object` scheduling policy (public beta) moves the image and instance size out of config and into `ctx.container.start()`. Cloudflare marks the older `default` policy deprecated and stops updating the `@cloudflare/containers` `Container` class after 2026-12-31, so new containers should use this one. The policy is immutable per application: moving an existing application means a new one. + +Set `schedulingPolicy: 'durable_object'` and list the images the object may start under `images`. Each key becomes a property of `ctx.container.images`. Devflare compiles the entry to Wrangler's `class_name`, `scheduling_policy`, `name` and `images` and nothing else, because Wrangler rejects `image`, `instance_type`, `max_instances` and rollouts for this policy; the schema refuses them first. + +`devflare dev` and `createTestContext()` run it locally the way `wrangler dev` does: they build each Dockerfile image (or reuse or pull a registry image) with Docker or Podman for `linux/amd64`, pull Miniflare's egress interceptor image, and attach the container to the Durable Object in Miniflare. `ctx.container.start()`, `images`, `enableInternet` and the `interceptOutboundHttp()`, `interceptOutboundHttps()` and `interceptAllOutboundHttp()` rules then run against a real local container. + +##### Key points + +- A named image is either `{ dockerfile, buildContext?, buildVars? }` or `{ image }`, a digest-pinned `registry.cloudflare.com//@sha256:`. Between 1 and 100 images, each name 1 to 128 characters. +- The Durable Object class must use SQLite storage. List it in `new_sqlite_classes`; local runs give container-backed namespaces SQLite storage, as Wrangler does. +- Outbound intercepts target a `WorkerEntrypoint` through `ctx.exports`, which needs a compatibility date of 2025-11-17 or later. In `createTestContext()`, the `WorkerEntrypoint` classes exported from the Durable Object's own module are exported from the test gateway, so `ctx.exports.` resolves there too. A service binding also works as a target. +- HTTPS interception needs the container to trust `/etc/cloudflare/certs/cloudflare-containers-ca.crt`. +- Local runs need Linux or macOS: workerd cannot reach a Windows named pipe, so on Windows devflare refuses and points at WSL, as Wrangler does. Set `DEVFLARE_ENABLE_CONTAINERS=0` to start without containers; `ctx.container` is then undefined. Devflare uses `WRANGLER_DOCKER_HOST` or `DOCKER_HOST` when set, then the engine's own socket. +- `devflare workspace dev` does not run durable_object containers yet and refuses an app that declares one; run `devflare dev` in that app. The `containers.start()` helper starts only `default`-policy containers. +- Images are rebuilt each time the config loads; a change inside the container needs a restart. + +##### Example — Declare a Durable Object-managed container + +```ts +import { defineConfig } from 'devflare/config' + +export default defineConfig({ + name: 'builder-worker', + compatibilityDate: '2026-09-29', + files: { durableObjects: 'src/do.*.ts' }, + bindings: { + durableObjects: { BUILDER: 'Builder' } + }, + containers: [ + { + className: 'Builder', + schedulingPolicy: 'durable_object', + images: { + base: { dockerfile: './container/Dockerfile' } + } + } + ], + migrations: [{ tag: 'v1', new_sqlite_classes: ['Builder'] }] +}) +``` + +##### Example — Start it from the Durable Object, with the Internet off and one host allowed + +```ts +import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers' + +export class AllowRelay extends WorkerEntrypoint { + fetch(request: Request) { + const url = new URL(request.url) + if (url.hostname !== 'relay.example.com') return new Response('Forbidden', { status: 403 }) + return fetch(request) + } +} + +export class Builder extends DurableObject { + async ensureStarted() { + const container = this.ctx.container! + if (container.running) return + await container.interceptOutboundHttps('relay.example.com', this.ctx.exports.AllowRelay) + container.start({ image: container.images.base, enableInternet: false }) + } +} +``` + +##### Example — What it compiles to + +###### File — .devflare/wrangler.jsonc + +```json +{ + "containers": [ + { + "class_name": "Builder", + "scheduling_policy": "durable_object", + "images": { "base": { "dockerfile": "./container/Dockerfile" } } + } + ] +} +``` + #### Build and reference the image deliberately Devflare treats the `containers` entry as the contract between the Worker class and a real container image. For local work, point `image` at a tag that already exists in Docker or Podman, or point it at a local Dockerfile path that Devflare can build from files on disk. @@ -16188,7 +16270,7 @@ export default defineConfig({ ##### Key points -- Offline-native only when an explicit Docker/Podman engine is available and the image can run without pulling +- Offline-native only when an explicit Docker/Podman engine is available and the image can run without pulling; durable_object containers run under workerd on Linux or macOS - The default docs recipe uses `devflare/test` containers helpers guarded by `shouldSkip.containers`. - Pure unit tests can use `detectContainerEngine()` / `createContainerManager()` / `containers` when the test only needs deterministic application behavior. @@ -16213,7 +16295,7 @@ Cloudflare Containers docs is the platform reference. Use this internals page wh | Question | Cloudflare docs | This Devflare page | | --- | --- | --- | | Primary focus | Platform reference for the Container class, container instances, and Worker interaction helpers. | How to author `containers`, what the runtime surface looks like, and how Containers fits a Devflare project. | -| Testing and runtime lens | Cloudflare’s docs focus on the raw binding API, product semantics, and platform limits for the binding itself. | Offline-native only when an explicit Docker/Podman engine is available and the image can run without pulling. Use the Devflare guidance when you need the honest local harness or the right remote gate instead of only the product API shape. | +| Testing and runtime lens | Cloudflare’s docs focus on the raw binding API, product semantics, and platform limits for the binding itself. | Offline-native only when an explicit Docker/Podman engine is available and the image can run without pulling; durable_object containers run under workerd on Linux or macOS. Use the Devflare guidance when you need the honest local harness or the right remote gate instead of only the product API shape. | | When to open it | When you need the platform contract, limits, APIs, or account-level product details. | When you are wiring, testing, previewing, or reviewing the binding inside a Devflare app. | --- diff --git a/packages/devflare/src/config/compiler/core-helpers.ts b/packages/devflare/src/config/compiler/core-helpers.ts index 2e0ba5f3..cd228c18 100644 --- a/packages/devflare/src/config/compiler/core-helpers.ts +++ b/packages/devflare/src/config/compiler/core-helpers.ts @@ -1,6 +1,13 @@ -import type { DevflareConfig } from '../schema' +import { + type ContainerConfig, + type DevflareConfig, + type DurableObjectPolicyContainerConfig, + isDurableObjectPolicyContainer +} from '../schema' import type { WranglerConfig } from './types' +type WranglerContainer = NonNullable[number] + export function compileWranglerMigrations( migrations: NonNullable ): NonNullable { @@ -48,13 +55,40 @@ export function compileModuleOptions(config: DevflareConfig, result: WranglerCon } } +/** + * Compile the `containers` array to Wrangler's top-level `containers`. + * + * Writes `result.containers` when the config declares any container, and + * leaves it untouched otherwise. + * + * @param config - The resolved devflare config. + * @param result - The Wrangler config being built; mutated in place. + */ export function compileContainers(config: DevflareConfig, result: WranglerConfig): void { if (!config.containers || config.containers.length === 0) { return } - result.containers = config.containers.map((container) => ({ + result.containers = config.containers.map(compileContainer) +} + +/** + * Compile one container entry, by its scheduling policy. + * + * @param container - One parsed container entry. + * @returns The snake_case Wrangler entry. A `durable_object` entry carries + * `scheduling_policy` and its named `images`; a `default` entry carries + * `scheduling_policy` only when the config spelled it, so configs written + * before the policy existed compile byte-for-byte as before. + */ +function compileContainer(container: ContainerConfig): WranglerContainer { + if (isDurableObjectPolicyContainer(container)) { + return compileDurableObjectPolicyContainer(container) + } + + return { class_name: container.className, + ...(container.schedulingPolicy && { scheduling_policy: container.schedulingPolicy }), image: container.image, ...(container.maxInstances !== undefined && { max_instances: container.maxInstances }), ...(container.instanceType && { instance_type: container.instanceType }), @@ -67,5 +101,36 @@ export function compileContainers(config: DevflareConfig, result: WranglerConfig ...(container.rolloutStepPercentage !== undefined && { rollout_step_percentage: container.rolloutStepPercentage }) - })) + } +} + +/** + * Compile a `durable_object` policy entry to the only fields Wrangler accepts + * for it: `class_name`, `scheduling_policy`, `name` and `images`. + * + * @param container - A Durable Object-managed container entry. + * @returns Its Wrangler entry, with each named image in snake_case. + */ +function compileDurableObjectPolicyContainer( + container: DurableObjectPolicyContainerConfig +): WranglerContainer { + return { + class_name: container.className, + scheduling_policy: 'durable_object', + ...(container.name && { name: container.name }), + ...(container.images && { + images: Object.fromEntries( + Object.entries(container.images).map(([imageName, image]) => [ + imageName, + 'dockerfile' in image + ? { + dockerfile: image.dockerfile, + ...(image.buildContext && { build_context: image.buildContext }), + ...(image.buildVars && { build_vars: image.buildVars }) + } + : { image: image.image } + ]) + ) + }) + } } diff --git a/packages/devflare/src/config/compiler/paths.ts b/packages/devflare/src/config/compiler/paths.ts index e9faa1a2..06e5fe68 100644 --- a/packages/devflare/src/config/compiler/paths.ts +++ b/packages/devflare/src/config/compiler/paths.ts @@ -88,6 +88,42 @@ export function isolateViteBuildOutputPaths( } } +type WranglerNamedContainerImages = NonNullable< + NonNullable[number]['images'] +> + +/** + * Rebase each named image's Dockerfile and build context from the project + * root onto the directory the Wrangler config is written to. Wrangler + * resolves both relative to its config file. A registry `image` is a + * reference, not a path, and is kept as written. + * + * @param projectRoot - Directory the devflare paths are relative to. + * @param configDir - Directory the Wrangler config is written to. + * @param images - A `durable_object` entry's named images. + * @returns The same map with its local paths rebased. + */ +function rebaseNamedContainerImages( + projectRoot: string, + configDir: string, + images: WranglerNamedContainerImages +): WranglerNamedContainerImages { + return Object.fromEntries( + Object.entries(images).map(([imageName, image]) => [ + imageName, + 'dockerfile' in image + ? { + ...image, + dockerfile: rebasePathForConfigDir(projectRoot, configDir, image.dockerfile), + ...(image.build_context && { + build_context: rebasePathForConfigDir(projectRoot, configDir, image.build_context) + }) + } + : image + ]) + ) +} + export function rebaseWranglerConfigPaths( projectRoot: string, configDir: string, @@ -108,15 +144,20 @@ export function rebaseWranglerConfigPaths( ? { containers: config.containers.map((container) => ({ ...container, - image: isLocalContainerPath(container.image) - ? rebasePathForConfigDir(projectRoot, configDir, container.image) - : container.image, + ...(container.image !== undefined && { + image: isLocalContainerPath(container.image) + ? rebasePathForConfigDir(projectRoot, configDir, container.image) + : container.image + }), ...(container.image_build_context && { image_build_context: rebasePathForConfigDir( projectRoot, configDir, container.image_build_context ) + }), + ...(container.images && { + images: rebaseNamedContainerImages(projectRoot, configDir, container.images) }) })) } diff --git a/packages/devflare/src/config/compiler/types.ts b/packages/devflare/src/config/compiler/types.ts index ffac4f8d..4af979db 100644 --- a/packages/devflare/src/config/compiler/types.ts +++ b/packages/devflare/src/config/compiler/types.ts @@ -149,7 +149,16 @@ export interface WranglerConfig { }> containers?: Array<{ class_name: string - image: string + /** Omitted means `default`; `durable_object` lets `ctx.container.start()` pick the image. */ + scheduling_policy?: 'default' | 'durable_object' + /** Application-wide image; `default` policy only. */ + image?: string + /** Named images for `ctx.container.images`; `durable_object` policy only. */ + images?: Record< + string, + | { dockerfile: string; build_context?: string; build_vars?: Record } + | { image: string } + > max_instances?: number instance_type?: string name?: string diff --git a/packages/devflare/src/config/index.ts b/packages/devflare/src/config/index.ts index 51fc9624..b0b0a5c6 100644 --- a/packages/devflare/src/config/index.ts +++ b/packages/devflare/src/config/index.ts @@ -102,11 +102,13 @@ export { type ContainerConfig, configSchema, type D1Binding, + type DefaultPolicyContainerConfig, type DevflareConfig, type DevflareConfigInput, type DevflareEnvConfig, type DispatchNamespaceBinding, type DurableObjectBinding, + type DurableObjectPolicyContainerConfig, type FlagshipBinding, getLocalD1DatabaseIdentifier, getLocalHyperdriveConfigIdentifier, @@ -114,6 +116,7 @@ export { getSingleBrowserBindingName, type HyperdriveBinding, type ImagesBinding, + isDurableObjectPolicyContainer, type KVBinding, type MediaBinding, type MigrationConfig, diff --git a/packages/devflare/src/config/schema-runtime.ts b/packages/devflare/src/config/schema-runtime.ts index 4583cc27..dbdd86ba 100644 --- a/packages/devflare/src/config/schema-runtime.ts +++ b/packages/devflare/src/config/schema-runtime.ts @@ -362,15 +362,19 @@ const rolloutStepPercentageSchema = z.union([ ]) /** - * Cloudflare Containers configuration. + * A Cloudflare Containers application under the `default` scheduling policy. * - * Devflare authors this in camelCase and compiles to Wrangler's top-level - * `containers` array. Runtime launch/testing is handled by the local - * container test shim, not by Miniflare itself. + * Wrangler configuration fixes one application-wide `image` and instance + * type, and Cloudflare rolls changes out across the application. Omitting + * `schedulingPolicy` selects this policy, which is why every entry written + * before the `durable_object` policy existed still parses unchanged. + * Runtime launch/testing for this policy is the local container test shim + * (`devflare/test` `containers`), not Miniflare. */ -export const containerConfigSchema = z +export const defaultPolicyContainerConfigSchema = z .object({ className: z.string().min(1), + schedulingPolicy: z.literal('default').optional(), image: z.string().min(1), maxInstances: z.number().int().positive().optional(), instanceType: z.string().min(1).optional(), @@ -382,6 +386,86 @@ export const containerConfigSchema = z }) .strict() +/** + * A named image Wrangler builds from a Dockerfile for a Durable + * Object-managed container. Compiles to `{ dockerfile, build_context?, + * build_vars? }` under `containers[].images.`. + */ +export const durableObjectContainerDockerfileImageSchema = z + .object({ + dockerfile: z.string().min(1), + buildContext: z.string().min(1).optional(), + buildVars: z.record(z.string(), z.string()).optional() + }) + .strict() + +/** + * A named image that already lives in the account's managed registry, + * digest-pinned. Compiles to `{ image }`. Wrangler validates the registry + * host and digest form at deploy, so Devflare does not restate that rule. + */ +export const durableObjectContainerRegistryImageSchema = z + .object({ + image: z.string().min(1) + }) + .strict() + +/** The largest named-image map Wrangler accepts for one application. */ +const MAX_DURABLE_OBJECT_CONTAINER_IMAGES = 100 + +/** The longest image name Wrangler accepts. */ +const MAX_DURABLE_OBJECT_CONTAINER_IMAGE_NAME_LENGTH = 128 + +/** + * A Cloudflare Containers application under the `durable_object` scheduling + * policy (public beta since 2026-09-30). + * + * The Durable Object picks the image and instance size each time it calls + * `ctx.container.start()`, so the Wrangler entry carries only the class, the + * application name, and the named images exposed on `ctx.container.images`. + * Wrangler rejects application-wide fields (`image`, `instance_type`, + * `max_instances`, rollouts) for this policy, and so does this strict schema. + * Local runs attach the container to the Durable Object in Miniflare, so + * `ctx.container` works in `devflare dev` and `createTestContext()`. + */ +export const durableObjectPolicyContainerConfigSchema = z + .object({ + className: z.string().min(1), + schedulingPolicy: z.literal('durable_object'), + name: z.string().min(1).optional(), + images: z + .record( + z.string().min(1).max(MAX_DURABLE_OBJECT_CONTAINER_IMAGE_NAME_LENGTH), + z.union([ + durableObjectContainerDockerfileImageSchema, + durableObjectContainerRegistryImageSchema + ]) + ) + .refine( + (images) => { + const count = Object.keys(images).length + return count > 0 && count <= MAX_DURABLE_OBJECT_CONTAINER_IMAGES + }, + { + message: `images must name between 1 and ${MAX_DURABLE_OBJECT_CONTAINER_IMAGES} images when present` + } + ) + .optional() + }) + .strict() + +/** + * Cloudflare Containers configuration. + * + * Devflare authors this in camelCase and compiles to Wrangler's top-level + * `containers` array. Each entry is one application, under either the + * `default` scheduling policy or the `durable_object` one. + */ +export const containerConfigSchema = z.union([ + durableObjectPolicyContainerConfigSchema, + defaultPolicyContainerConfigSchema +]) + export const containersConfigSchema = z.array(containerConfigSchema).optional() /** @@ -432,6 +516,10 @@ export const wranglerConfigSchema = z export type AssetsConfig = z.infer export type ContainerConfig = z.infer +export type DefaultPolicyContainerConfig = z.infer +export type DurableObjectPolicyContainerConfig = z.infer< + typeof durableObjectPolicyContainerConfigSchema +> export type MigrationConfig = z.infer export type ModuleRuleConfig = z.infer export type PlacementConfig = z.infer @@ -441,3 +529,17 @@ export type ServerConfig = z.infer export type TailConsumerConfig = z.infer export type StreamingTailConsumerConfig = z.infer export type WsRouteConfig = z.infer + +/** + * Whether a parsed container entry uses the `durable_object` scheduling + * policy, so its image is chosen by `ctx.container.start()` rather than + * fixed in config. + * + * @param container - One entry of a parsed config's `containers` array. + * @returns `true` for a Durable Object-managed container. + */ +export function isDurableObjectPolicyContainer( + container: ContainerConfig +): container is DurableObjectPolicyContainerConfig { + return container.schedulingPolicy === 'durable_object' +} diff --git a/packages/devflare/src/config/schema-types-containers.ts b/packages/devflare/src/config/schema-types-containers.ts new file mode 100644 index 00000000..17ba5203 --- /dev/null +++ b/packages/devflare/src/config/schema-types-containers.ts @@ -0,0 +1,231 @@ +/* + ────────────────────────────────────────────── + Containers config — authoring types + ────────────────────────────────────────────── + The `containers` entries, under the `default` scheduling policy or the + `durable_object` one. Mirrors containerConfigSchema in schema-runtime.ts. +*/ + +/** + * Cloudflare Container configuration: one application, under the `default` + * scheduling policy or the `durable_object` one. + */ +export type ContainerConfigInput = + | DefaultPolicyContainerConfigInput + | DurableObjectPolicyContainerConfigInput + +/** + * A named image Wrangler builds from a Dockerfile for a Durable + * Object-managed container. + */ +export interface DurableObjectContainerDockerfileImageInput { + /** + * Path to the Dockerfile, relative to the devflare config. Local runs build + * it with Docker or Podman for `linux/amd64`; `wrangler deploy` builds and + * pushes it. + * + * @example + * ```ts + * dockerfile: './container/Dockerfile' + * ``` + */ + dockerfile: string + + /** + * Build context, relative to the devflare config. + * + * @default The Dockerfile's directory. + */ + buildContext?: string + + /** + * Variables available to the image only while it is being built. + * + * @default No build variables. + */ + buildVars?: Record +} + +/** + * A named image that already lives in the account's managed registry. + */ +export interface DurableObjectContainerRegistryImageInput { + /** + * Digest-pinned image in the Cloudflare managed registry, in the form + * `registry.cloudflare.com//@sha256:`. + * Local runs use it when it is already present locally, and otherwise pull + * it, which needs `docker login registry.cloudflare.com`. + */ + image: string +} + +/** + * A Container application under the `durable_object` scheduling policy + * (Cloudflare public beta). The Durable Object chooses the image and instance + * size each time it calls `ctx.container.start()`, so this entry names only + * the class and the images the object may start. + * + * The Durable Object class must use SQLite storage (list it in a migration's + * `new_sqlite_classes`). + * + * @example + * ```ts + * containers: [ + * { + * className: 'Builder', + * schedulingPolicy: 'durable_object', + * images: { base: { dockerfile: './container/Dockerfile' } } + * } + * ] + * ``` + */ +export interface DurableObjectPolicyContainerConfigInput { + /** + * The Durable Object class the container is attached to. + */ + className: string + + /** + * Selects the `durable_object` scheduling policy. Cloudflare makes the + * policy immutable per application. + */ + schedulingPolicy: 'durable_object' + + /** + * Container application name. + * + * @default Wrangler derives `-` from the Worker name. + */ + name?: string + + /** + * Named images exposed to the Durable Object as `ctx.container.images`. + * Each key becomes a property; pass its value as `start({ image })`. + * Between 1 and 100 entries when present, names of 1 to 128 characters. + * + * @default No named images; start the Cloudflare-managed + * `cloudflare/debian-trixie` image instead. + */ + images?: Record< + string, + DurableObjectContainerDockerfileImageInput | DurableObjectContainerRegistryImageInput + > +} + +/** + * A Container application under the `default` scheduling policy, which + * Cloudflare has deprecated in favour of `durable_object`. Omitting + * `schedulingPolicy` selects it. + */ +export interface DefaultPolicyContainerConfigInput { + /** + * Selects the `default` scheduling policy explicitly. + * + * @default 'default' + */ + schedulingPolicy?: 'default' + + /** + * Container class name exported by the Worker. + * + * @example + * ```ts + * className: 'RendererContainer' + * ``` + */ + className: string + + /** + * Container image reference or build target. + * + * @example + * ```ts + * image: './Dockerfile' + * ``` + */ + image: string + + /** + * Maximum number of container instances. + * + * @default Cloudflare Containers default behavior. + * + * @example + * ```ts + * maxInstances: 3 + * ``` + */ + maxInstances?: number + + /** + * Container instance type. + * + * @default Cloudflare Containers default behavior. + * + * @example + * ```ts + * instanceType: 'standard' + * ``` + */ + instanceType?: string + + /** + * Optional generated container name. + * + * @default Devflare derives the name from the class when possible. + * + * @example + * ```ts + * name: 'renderer' + * ``` + */ + name?: string + + /** + * Docker build context. + * + * @default Container image path default. + * + * @example + * ```ts + * imageBuildContext: './containers/renderer' + * ``` + */ + imageBuildContext?: string + + /** + * Build-time variables for the container image. + * + * @default No image variables. + * + * @example + * ```ts + * imageVars: { NODE_ENV: 'production' } + * ``` + */ + imageVars?: Record + + /** + * Active grace period in seconds during rollout. + * + * @default Cloudflare Containers default behavior. + * + * @example + * ```ts + * rolloutActiveGracePeriod: 60 + * ``` + */ + rolloutActiveGracePeriod?: number + + /** + * Rollout step percentage or step percentages. + * + * @default Cloudflare Containers default behavior. + * + * @example + * ```ts + * rolloutStepPercentage: [10, 50, 100] + * ``` + */ + rolloutStepPercentage?: number | number[] +} diff --git a/packages/devflare/src/config/schema-types-runtime.ts b/packages/devflare/src/config/schema-types-runtime.ts index 6533997b..9820ca42 100644 --- a/packages/devflare/src/config/schema-types-runtime.ts +++ b/packages/devflare/src/config/schema-types-runtime.ts @@ -481,115 +481,6 @@ export interface AssetsConfigInput { run_worker_first?: boolean | string[] } -/** - * Cloudflare Container configuration. - */ -export interface ContainerConfigInput { - /** - * Container class name exported by the Worker. - * - * @example - * ```ts - * className: 'RendererContainer' - * ``` - */ - className: string - - /** - * Container image reference or build target. - * - * @example - * ```ts - * image: './Dockerfile' - * ``` - */ - image: string - - /** - * Maximum number of container instances. - * - * @default Cloudflare Containers default behavior. - * - * @example - * ```ts - * maxInstances: 3 - * ``` - */ - maxInstances?: number - - /** - * Container instance type. - * - * @default Cloudflare Containers default behavior. - * - * @example - * ```ts - * instanceType: 'standard' - * ``` - */ - instanceType?: string - - /** - * Optional generated container name. - * - * @default Devflare derives the name from the class when possible. - * - * @example - * ```ts - * name: 'renderer' - * ``` - */ - name?: string - - /** - * Docker build context. - * - * @default Container image path default. - * - * @example - * ```ts - * imageBuildContext: './containers/renderer' - * ``` - */ - imageBuildContext?: string - - /** - * Build-time variables for the container image. - * - * @default No image variables. - * - * @example - * ```ts - * imageVars: { NODE_ENV: 'production' } - * ``` - */ - imageVars?: Record - - /** - * Active grace period in seconds during rollout. - * - * @default Cloudflare Containers default behavior. - * - * @example - * ```ts - * rolloutActiveGracePeriod: 60 - * ``` - */ - rolloutActiveGracePeriod?: number - - /** - * Rollout step percentage or step percentages. - * - * @default Cloudflare Containers default behavior. - * - * @example - * ```ts - * rolloutStepPercentage: [10, 50, 100] - * ``` - */ - rolloutStepPercentage?: number | number[] -} - /** * Worker placement configuration. */ diff --git a/packages/devflare/src/config/schema-types.ts b/packages/devflare/src/config/schema-types.ts index 8577bff9..1e38a856 100644 --- a/packages/devflare/src/config/schema-types.ts +++ b/packages/devflare/src/config/schema-types.ts @@ -5,10 +5,10 @@ import type { ViteConfigInput, WranglerConfigInput } from './schema-types-build' +import type { ContainerConfigInput } from './schema-types-containers' import type { EmailConfigInput } from './schema-types-email' import type { AssetsConfigInput, - ContainerConfigInput, FilesConfigInput, LimitsConfigInput, MigrationConfigInput, @@ -571,6 +571,7 @@ export interface DevflareEnvConfigInput export type * from './schema-types-bindings' export type * from './schema-types-build' +export type * from './schema-types-containers' export type * from './schema-types-email' export type * from './schema-types-runtime' export type * from './schema-types-subscriptions' diff --git a/packages/devflare/src/config/schema.ts b/packages/devflare/src/config/schema.ts index 96ba7d29..b1219a88 100644 --- a/packages/devflare/src/config/schema.ts +++ b/packages/devflare/src/config/schema.ts @@ -356,6 +356,8 @@ export { export type { AssetsConfig, ContainerConfig, + DefaultPolicyContainerConfig, + DurableObjectPolicyContainerConfig, MigrationConfig, ModuleRuleConfig, PlacementConfig, @@ -366,6 +368,7 @@ export type { TailConsumerConfig, WsRouteConfig } from './schema-runtime' +export { isDurableObjectPolicyContainer } from './schema-runtime' export type { AiBindingInput, AiSearchInstanceBindingInput, @@ -381,6 +384,7 @@ export type { D1BindingByIdInput, D1BindingByNameInput, D1BindingInput, + DefaultPolicyContainerConfigInput, DevflareConfigInput, DevflareEnvConfigInput, DispatchNamespaceBindingInput, @@ -388,6 +392,9 @@ export type { DispatchNamespaceOutboundInput, DurableObjectBindingInput, DurableObjectBindingObjectInput, + DurableObjectContainerDockerfileImageInput, + DurableObjectContainerRegistryImageInput, + DurableObjectPolicyContainerConfigInput, FilesConfigInput, FlagshipBindingInput, HyperdriveBindingByIdInput, diff --git a/packages/devflare/src/dev-server/dev-server-state.ts b/packages/devflare/src/dev-server/dev-server-state.ts index b9e8b7e2..4a835c9e 100644 --- a/packages/devflare/src/dev-server/dev-server-state.ts +++ b/packages/devflare/src/dev-server/dev-server-state.ts @@ -16,6 +16,7 @@ import type { DevflareConfig } from '../config' import type { OutboundEmailService } from '../email/host-service' import type { InboundEmailPoller } from '../email/inbound-poller' import type { ResolvedEmailRuntime } from '../email/runtime-config' +import type { PreparedLocalDurableObjectContainers } from '../test/durable-object-containers' import type { resolveServiceBindings } from '../test/resolve-service-bindings' import { clearEmailDeliverySink } from '../utils/email-delivery' import { clearLocalSendEmailBindings } from '../utils/send-email' @@ -41,6 +42,8 @@ export interface DevServerState { viteProcess: import('node:child_process').ChildProcess | null config: DevflareConfig | null serviceBindingResolution: Awaited> | null + /** Prepared `durable_object` containers, rebuilt each time the config loads. */ + localContainers: PreparedLocalDurableObjectContainers | null browserShim: BrowserShim | null browserShimPort: number mainWorkerSurfacePaths: WorkerSurfacePaths @@ -79,6 +82,7 @@ export function createDevServerState(initial: { viteProcess: null, config: null, serviceBindingResolution: null, + localContainers: null, browserShim: null, browserShimPort: initial.browserShimPort ?? 8788, mainWorkerSurfacePaths: { diff --git a/packages/devflare/src/dev-server/miniflare-dev-config.ts b/packages/devflare/src/dev-server/miniflare-dev-config.ts index f1713241..cc26e617 100644 --- a/packages/devflare/src/dev-server/miniflare-dev-config.ts +++ b/packages/devflare/src/dev-server/miniflare-dev-config.ts @@ -15,6 +15,11 @@ import type { DevflareConfig } from '../config' import { getSingleBrowserBindingName } from '../config/schema' import { buildLocalSecretServiceBindingConfig } from '../secrets/local-secrets' import { buildLocalBindingShimServiceConfig } from '../shims/local-media-bindings' +import { + attachDurableObjectContainers, + type MiniflareDurableObjectContainerOption, + type PreparedLocalDurableObjectContainers +} from '../test/durable-object-containers' import type { resolveServiceBindings } from '../test/resolve-service-bindings' import { generatedDir } from '../utils/generated-dir' import type { RouteDiscoveryResult } from '../worker-entry/routes' @@ -84,6 +89,12 @@ export interface BuildMiniflareDevConfigInput { * unchanged. */ additionalInjectedVars?: Record + /** + * Prepared `durable_object` policy containers. Each is attached to the + * Durable Object worker that defines its class, so `ctx.container` is real + * there; `null` or omitted leaves every Durable Object without a container. + */ + localContainers?: PreparedLocalDurableObjectContainers | null logger?: ConsolaInstance } @@ -133,6 +144,7 @@ export function buildMiniflareDevConfig(input: BuildMiniflareDevConfigInput): an serviceBindingResolution, r2PresignSecret, additionalInjectedVars, + localContainers, logger } = input @@ -335,9 +347,13 @@ export function buildMiniflareDevConfig(input: BuildMiniflareDevConfigInput): an const workerConfig = createWorkerConfig({ name: workerName, scriptPath: bundlePath, - durableObjects: { - [bindingName]: className - }, + durableObjects: localContainers + ? attachDurableObjectContainers( + { [bindingName]: className }, + new Map([[bindingName, className]]), + pickContainerFor(localContainers.containersByClassName, className) + ) + : { [bindingName]: className }, serviceBindings: createServiceBindings( browserBindingName ? { @@ -383,8 +399,13 @@ export function buildMiniflareDevConfig(input: BuildMiniflareDevConfigInput): an } } + if (localContainers) { + assertEveryContainerHasAWorker(localContainers, doResult) + } + return { ...sharedOptions, + ...(localContainers && { containerEngine: localContainers.containerEngine }), workers: [ gatewayWorker, ...workers, @@ -394,3 +415,42 @@ export function buildMiniflareDevConfig(input: BuildMiniflareDevConfigInput): an ] } } + +/** + * Narrow the prepared containers to the one class a Durable Object worker + * defines, so attaching never reports another worker's class as unattached. + * + * @param containersByClassName - Every prepared container option. + * @param className - The class this worker defines. + * @returns A map holding that class's option, or an empty map. + */ +function pickContainerFor( + containersByClassName: Map, + className: string +): Map { + const container = containersByClassName.get(className) + return container === undefined ? new Map() : new Map([[className, container]]) +} + +/** + * Refuse a container whose class no Durable Object worker defines, which + * would otherwise leave its `ctx.container` silently undefined. + * + * @param localContainers - The prepared containers. + * @param doResult - The bundled Durable Objects. + * @throws When a container's class has no bundled Durable Object. + */ +function assertEveryContainerHasAWorker( + localContainers: PreparedLocalDurableObjectContainers, + doResult: DOBundleResult | null +): void { + const bundledClasses = new Set(doResult?.classes.values() ?? []) + const missing = [...localContainers.containersByClassName.keys()].filter( + (className) => !bundledClasses.has(className) + ) + if (missing.length > 0) { + throw new Error( + `durable_object containers name ${missing.map((name) => `"${name}"`).join(', ')}, but no Durable Object in files.durableObjects defines that class.` + ) + } +} diff --git a/packages/devflare/src/dev-server/miniflare-worker-config.ts b/packages/devflare/src/dev-server/miniflare-worker-config.ts index 24d08381..0fc56079 100644 --- a/packages/devflare/src/dev-server/miniflare-worker-config.ts +++ b/packages/devflare/src/dev-server/miniflare-worker-config.ts @@ -14,6 +14,7 @@ import { normalizeR2Binding } from '../config/schema' import type { LocalSecretServiceBindingConfig } from '../secrets/local-secrets' +import type { MiniflareDurableObjectEntry } from '../test/durable-object-containers' import type { buildAiSearchInstancesConfig, buildAiSearchNamespacesConfig, @@ -116,7 +117,7 @@ export interface MakeMiniflareWorkerOptions { name: string script?: string scriptPath?: string - durableObjects?: Record + durableObjects?: Record serviceBindings?: Record queueConsumers?: Record> /** diff --git a/packages/devflare/src/dev-server/server.ts b/packages/devflare/src/dev-server/server.ts index 63083326..e7350fbf 100644 --- a/packages/devflare/src/dev-server/server.ts +++ b/packages/devflare/src/dev-server/server.ts @@ -13,6 +13,7 @@ import { checkRemoteBindingRequirements } from '../cli/wrangler-auth' import { resolveDevConfig } from '../config/dev-config' import { EnvVarResolutionError, getDevflareDotenvPaths } from '../config/env-vars' import { loadConfig } from '../config/loader' +import { prepareLocalDurableObjectContainers } from '../test/durable-object-containers' import { resolveServiceBindings } from '../test/resolve-service-bindings' import { generatedDir } from '../utils/generated-dir' import { toMiniflareOptions } from '../utils/miniflare-options' @@ -301,6 +302,7 @@ export function createDevServer(options: DevServerOptions): DevServer { doResult, serviceBindingResolution: state.serviceBindingResolution, r2PresignSecret, + localContainers: state.localContainers, logger }) } @@ -429,12 +431,15 @@ export function createDevServer(options: DevServerOptions): DevServer { cwd, configPath: state.resolvedWorkerConfigPath ?? configPath }) + const configDir = state.resolvedWorkerConfigPath ? dirname(state.resolvedWorkerConfigPath) : cwd state.serviceBindingResolution = state.config.bindings?.services - ? await resolveServiceBindings( - state.config, - state.resolvedWorkerConfigPath ? dirname(state.resolvedWorkerConfigPath) : cwd - ) + ? await resolveServiceBindings(state.config, configDir) : null + state.localContainers = await prepareLocalDurableObjectContainers({ + config: state.config, + configDir, + onProgress: (message) => logger?.info(message) + }) } /** diff --git a/packages/devflare/src/dev-server/workspace/prepare-app.ts b/packages/devflare/src/dev-server/workspace/prepare-app.ts index da0a42d5..e8e4fde3 100644 --- a/packages/devflare/src/dev-server/workspace/prepare-app.ts +++ b/packages/devflare/src/dev-server/workspace/prepare-app.ts @@ -27,6 +27,11 @@ import { getSingleBrowserBindingName, normalizeR2Binding } from '../../config/schema' +import { + areLocalContainersDisabled, + ENABLE_CONTAINERS_ENV, + planLocalDurableObjectContainers +} from '../../test/durable-object-containers' import { resolveServiceBindings } from '../../test/resolve-service-bindings' import { generatedDir } from '../../utils/generated-dir' import { prepareComposedWorkerEntrypoint } from '../../worker-entry/composed-worker' @@ -223,6 +228,8 @@ export async function prepareWorkspaceApp( await browserShim.start() } + assertNoLocalDurableObjectContainers(appName, config, appCwd) + // --- build this app's worker set (reused verbatim) ------------------------ const built = buildMiniflareDevConfig({ config, @@ -275,3 +282,30 @@ export async function prepareWorkspaceApp( sharedIds } } + +/** + * Refuse an app whose config declares `durable_object` policy containers. The + * workspace coordinator builds one shared Miniflare from each app's workers and + * carries no container engine, so such an app would run with `ctx.container` + * silently undefined. + * + * @param appName - The workspace app, for the message. + * @param config - Its resolved config. + * @param appCwd - Its directory. + * @throws When the app has a Durable Object-managed container and + * `DEVFLARE_ENABLE_CONTAINERS=0` is not set. + */ +export function assertNoLocalDurableObjectContainers( + appName: string, + config: DevflareConfig, + appCwd: string +): void { + if (areLocalContainersDisabled(process.env)) return + const containers = planLocalDurableObjectContainers(config, appCwd) + if (containers.length === 0) return + + const classNames = containers.map((container) => container.className).join(', ') + throw new Error( + `Workspace app "${appName}" declares durable_object containers (${classNames}), which workspace dev does not run yet. Run \`devflare dev\` in that app, or set ${ENABLE_CONTAINERS_ENV}=0 to start it without containers.` + ) +} diff --git a/packages/devflare/src/test/containers.ts b/packages/devflare/src/test/containers.ts index 7a984061..fc545f44 100644 --- a/packages/devflare/src/test/containers.ts +++ b/packages/devflare/src/test/containers.ts @@ -5,7 +5,12 @@ import { createConnection } from 'node:net' import { basename, dirname, isAbsolute, join, resolve } from 'node:path' import { setTimeout as delay } from 'node:timers/promises' import { execa } from 'execa' -import { type ContainerConfig, type DevflareConfig, loadConfig } from '../config' +import { + type DefaultPolicyContainerConfig, + type DevflareConfig, + isDurableObjectPolicyContainer, + loadConfig +} from '../config' import { resolveDevConfig } from '../config/dev-config' import { findNearestConfig, getAvailablePort, getCallerDirectory } from './simple-context-paths' @@ -89,7 +94,7 @@ export interface LocalContainerState { interface ResolvedContainerStart { configDir: string image: string - config?: ContainerConfig + config?: DefaultPolicyContainerConfig } interface PreparedImage { @@ -342,6 +347,15 @@ async function resolveContainerStart( throw new Error(`Container "${className}" was not found in devflare config.`) } + // A Durable Object-managed container has no application-wide image: its + // Durable Object picks one per `ctx.container.start()`. Starting it here, + // outside workerd, would skip the outbound policy the object applies. + if (isDurableObjectPolicyContainer(container)) { + throw new Error( + `Container "${className}" uses the durable_object scheduling policy, so its Durable Object starts it through ctx.container. Drive it through createTestContext() instead, or pass an explicit image to containers.start().` + ) + } + return { configDir, image: container.image, diff --git a/packages/devflare/src/test/durable-object-containers.ts b/packages/devflare/src/test/durable-object-containers.ts new file mode 100644 index 00000000..d8d70b96 --- /dev/null +++ b/packages/devflare/src/test/durable-object-containers.ts @@ -0,0 +1,555 @@ +/* + ────────────────────────────────────────────── + Local Durable Object-managed containers + ────────────────────────────────────────────── + Runs `durable_object` scheduling-policy containers locally the way + `wrangler dev` does: each named image is built (or pulled) with Docker or + Podman, then attached to its Durable Object in Miniflare, so workerd backs + `ctx.container` — `start()`, `images`, `enableInternet`, and the outbound + intercepts — with a real local container. + + → The plan (which images, under which tags) is pure; only + prepareLocalDurableObjectContainers() runs the engine. + → GOTCHA: workerd cannot reach a Windows named pipe. With the container + option set, every Durable Object construction fails with + `getaddrinfo(): DNS lookup failed. host = //./pipe/docker_engine` + (measured, Miniflare 5.20261006.1-alpha on Windows 11). Wrangler refuses + Windows for the same reason, so this module refuses it too and points at WSL. + → GOTCHA: workerd needs Miniflare's egress interceptor sidecar image for + `enableInternet` and the `interceptOutbound*` rules. Wrangler pulls it + before every dev session; so does this module. Its name mirrors + Miniflare's private constant, and a unit test pins the two together. +*/ + +import { createHash } from 'node:crypto' +import { resolve } from 'node:path' +import { + type DevflareConfig, + type DurableObjectPolicyContainerConfig, + isDurableObjectPolicyContainer, + normalizeDOBinding +} from '../config' +import { + type ContainerCommandResult, + type ContainerCommandRunner, + type ContainerEngineName, + type ContainerEnginePreference, + detectContainerEngine, + realContainerCommandRunner +} from './containers' + +/** + * Miniflare's default egress interceptor image + * (`DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE`, not exported by Miniflare). + * `MINIFLARE_CONTAINER_EGRESS_IMAGE` overrides it, for Miniflare and here alike. + */ +export const DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE = + 'cloudflare/proxy-everything:3cb1195@sha256:0ef6716c52430096900b150d84a3302057d6cd2319dae7987128c85d0733e3c8' + +/** + * The platform every Cloudflare container runs on. Wrangler builds and pulls + * local images for it too, so a local run exercises the deployed binary. + */ +const CONTAINER_PLATFORM = 'linux/amd64' + +/** How long one image build or pull may take before it is reported as failed. */ +const IMAGE_PREPARATION_TIMEOUT_MS = 15 * 60_000 + +/** The environment flag that turns local Durable Object containers off. */ +export const ENABLE_CONTAINERS_ENV = 'DEVFLARE_ENABLE_CONTAINERS' + +/** Where one named image comes from. */ +export type LocalContainerImageSource = + | { + /** Built from a Dockerfile on disk. */ + kind: 'dockerfile' + /** Absolute path to the Dockerfile. */ + dockerfile: string + /** Absolute build context directory. */ + buildContext: string + /** Build-time variables, passed as `--build-arg`. */ + buildVars?: Record + } + | { + /** A prebuilt image reference, used when present locally and pulled otherwise. */ + kind: 'registry' + /** The configured reference. */ + image: string + } + +/** One named image of a Durable Object-managed container, ready to prepare. */ +export interface LocalContainerImage { + /** The key under `images`, and so under `ctx.container.images`. */ + name: string + /** The local tag workerd starts, which `ctx.container.images.` resolves to. */ + tag: string + /** How the tag is produced. */ + source: LocalContainerImageSource +} + +/** One Durable Object class whose container runs locally. */ +export interface LocalDurableObjectContainer { + /** The Durable Object class the container is attached to. */ + className: string + /** Its named images; empty when it starts only Cloudflare-managed images. */ + images: LocalContainerImage[] +} + +/** The `container` option Miniflare takes on a Durable Object namespace. */ +export interface MiniflareDurableObjectContainerOption { + /** Named images, each mapped to the local tag workerd starts. */ + images?: Array<{ name: string; image: string }> +} + +/** Miniflare's shared `containerEngine` option. */ +export interface MiniflareContainerEngineOption { + /** The local Docker-compatible engine workerd drives. */ + localDocker: { + /** The engine's API socket, as a `unix://` URL. */ + socketPath: string + } +} + +/** What a local run needs to give its Durable Objects real containers. */ +export interface PreparedLocalDurableObjectContainers { + /** The engine that built the images and that workerd will drive. */ + engine: ContainerEngineName + /** Miniflare's shared `containerEngine` option. */ + containerEngine: MiniflareContainerEngineOption + /** The per-class `container` option, keyed by Durable Object class name. */ + containersByClassName: Map +} + +/** Options for {@link prepareLocalDurableObjectContainers}. */ +export interface PrepareLocalDurableObjectContainersOptions { + /** The resolved devflare config. */ + config: DevflareConfig + /** The directory the config's paths are relative to. */ + configDir: string + /** Process environment to read the opt-out and engine overrides from. */ + env?: Record + /** Which engine to use. @default 'auto' (Docker, then Podman) */ + engine?: ContainerEnginePreference + /** Command runner; tests replace it. */ + runner?: ContainerCommandRunner + /** Host platform; tests replace it. @default process.platform */ + platform?: NodeJS.Platform + /** Progress messages, one per image. */ + onProgress?: (message: string) => void +} + +/** + * List the config's Durable Object-managed containers with the local tag of + * every named image. Pure. + * + * @param config - The resolved devflare config. + * @param configDir - The directory the config's paths are relative to. + * @returns One entry per `durable_object` policy container, in config order. + * @throws When two entries attach a container to the same class. + */ +export function planLocalDurableObjectContainers( + config: DevflareConfig, + configDir: string +): LocalDurableObjectContainer[] { + const containers = (config.containers ?? []).filter(isDurableObjectPolicyContainer) + const seen = new Set() + + return containers.map((container) => { + if (seen.has(container.className)) { + throw new Error( + `Durable Object class "${container.className}" has more than one durable_object container entry; a Durable Object has one container.` + ) + } + seen.add(container.className) + + return { + className: container.className, + images: planContainerImages(container, configDir) + } + }) +} + +/** + * Resolve one container's named images to local tags and absolute paths. + * + * @param container - A Durable Object-managed container entry. + * @param configDir - The directory its paths are relative to. + * @returns Its images, in config order. + */ +function planContainerImages( + container: DurableObjectPolicyContainerConfig, + configDir: string +): LocalContainerImage[] { + return Object.entries(container.images ?? {}).map(([name, image]) => { + const tag = localContainerImageTag(configDir, container.className, name) + if ('dockerfile' in image) { + const dockerfile = resolve(configDir, image.dockerfile) + return { + name, + tag, + source: { + kind: 'dockerfile', + dockerfile, + buildContext: image.buildContext + ? resolve(configDir, image.buildContext) + : resolve(dockerfile, '..'), + ...(image.buildVars && { buildVars: image.buildVars }) + } + } + } + + return { name, tag, source: { kind: 'registry', image: image.image } } + }) +} + +/** + * The local tag for one named image. Stable per project, class and image, so + * a rebuild replaces the previous tag instead of accumulating new ones, and + * two projects with the same class names cannot overwrite each other's images. + * + * @param configDir - The project the image belongs to. + * @param className - The Durable Object class. + * @param imageName - The key under `images`. + * @returns A lowercase Docker tag under the `devflare-dev/` repository prefix. + */ +export function localContainerImageTag( + configDir: string, + className: string, + imageName: string +): string { + const hash = createHash('sha256') + .update(`${resolve(configDir)}\0${className}\0${imageName}`) + .digest('hex') + .slice(0, 12) + return `devflare-dev/${toTagSlug(className)}-${toTagSlug(imageName)}:${hash}` +} + +/** + * Lowercase a name into the characters a Docker repository path allows. + * + * @param value - A class or image name. + * @returns The slug, or `image` when nothing usable is left. + */ +function toTagSlug(value: string): string { + return ( + value + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') || 'image' + ) +} + +/** + * The Miniflare `container` option for one planned container. Pure. + * + * @param container - One planned Durable Object container. + * @returns `{ images }` mapping each name to its local tag, or `{}` when it has + * no named images (the option still marks the namespace as container-backed). + */ +export function toMiniflareContainerOption( + container: LocalDurableObjectContainer +): MiniflareDurableObjectContainerOption { + if (container.images.length === 0) { + return {} + } + return { images: container.images.map(({ name, tag }) => ({ name, image: tag })) } +} + +/** + * Whether local Durable Object containers were turned off with + * `DEVFLARE_ENABLE_CONTAINERS=0` (or `false`/`no`), the counterpart of + * Wrangler's `--enable-containers=false`. + * + * @param env - Process environment. + * @returns `true` when the flag is set to a false value. + */ +export function areLocalContainersDisabled(env: Record): boolean { + const value = env[ENABLE_CONTAINERS_ENV]?.trim().toLowerCase() + return value === '0' || value === 'false' || value === 'no' +} + +/** + * Build or pull every named image of the config's Durable Object-managed + * containers, pull Miniflare's egress interceptor image when it is missing, + * and return the Miniflare options that attach the containers. + * + * Side effects: runs `docker`/`podman` commands (`info`, `build`, `image + * inspect`, `pull`, `tag`, `context inspect`), which can download images. + * + * @param options - The config, its directory, and the overrides tests use. + * @returns `null` when the config has no Durable Object-managed container, or + * when `DEVFLARE_ENABLE_CONTAINERS=0` turned them off (the objects then run + * with no `ctx.container`, as under Wrangler's `--enable-containers=false`). + * @throws On Windows, when no engine answers, or when an image cannot be built + * or pulled — each message names the remedy. + */ +export async function prepareLocalDurableObjectContainers( + options: PrepareLocalDurableObjectContainersOptions +): Promise { + const env = options.env ?? process.env + const plan = planLocalDurableObjectContainers(options.config, options.configDir) + if (plan.length === 0 || areLocalContainersDisabled(env)) { + return null + } + + const classNames = plan.map((container) => container.className).join(', ') + if ((options.platform ?? process.platform) === 'win32') { + throw new Error( + `Local Durable Object containers (${classNames}) cannot run on Windows: workerd cannot reach the Docker engine's named pipe. Run devflare inside WSL, or set ${ENABLE_CONTAINERS_ENV}=0 to start without containers (ctx.container is then undefined).` + ) + } + + const runner = options.runner ?? realContainerCommandRunner + const status = await detectContainerEngine({ engine: options.engine, runner }) + if (!status.available) { + throw new Error( + `Local Durable Object containers (${classNames}) need a running Docker or Podman engine: ${status.reason}. Start one, or set ${ENABLE_CONTAINERS_ENV}=0 to start without containers.` + ) + } + + const engine = status.engine + for (const container of plan) { + for (const image of container.images) { + options.onProgress?.(`Preparing container image ${container.className}.${image.name}`) + await prepareImage(engine, runner, image) + } + } + await ensureEgressInterceptorImage(engine, runner, env) + + return { + engine, + containerEngine: { + localDocker: { socketPath: await resolveEngineSocket(engine, runner, env) } + }, + containersByClassName: new Map( + plan.map((container) => [container.className, toMiniflareContainerOption(container)]) + ) + } +} + +/** + * Produce one image's local tag: build its Dockerfile, or reuse or pull its + * registry reference and tag it. + * + * @param engine - The engine to run. + * @param runner - Command runner. + * @param image - The planned image. + * @throws When the build, the pull or the tag fails. + */ +async function prepareImage( + engine: ContainerEngineName, + runner: ContainerCommandRunner, + image: LocalContainerImage +): Promise { + if (image.source.kind === 'dockerfile') { + const buildArgs = Object.entries(image.source.buildVars ?? {}).flatMap(([key, value]) => [ + '--build-arg', + `${key}=${value}` + ]) + await runOrThrow( + runner, + engine, + [ + 'build', + '--platform', + CONTAINER_PLATFORM, + '-t', + image.tag, + '-f', + image.source.dockerfile, + ...buildArgs, + image.source.buildContext + ], + `build container image "${image.name}" from ${image.source.dockerfile}` + ) + return + } + + const reference = image.source.image + const inspect = await runner.exec(engine, ['image', 'inspect', reference]) + if (inspect.exitCode !== 0) { + await runOrThrow( + runner, + engine, + ['pull', '--platform', CONTAINER_PLATFORM, reference], + `pull container image "${image.name}" (${reference}); a Cloudflare registry image needs \`docker login registry.cloudflare.com\` first` + ) + } + await runOrThrow( + runner, + engine, + ['tag', reference, image.tag], + `tag ${reference} as ${image.tag}` + ) +} + +/** + * Pull the egress interceptor sidecar unless it is already present. + * + * @param engine - The engine to run. + * @param runner - Command runner. + * @param env - Process environment, for `MINIFLARE_CONTAINER_EGRESS_IMAGE`. + * @throws When the image is missing and the pull fails. + */ +async function ensureEgressInterceptorImage( + engine: ContainerEngineName, + runner: ContainerCommandRunner, + env: Record +): Promise { + const image = env.MINIFLARE_CONTAINER_EGRESS_IMAGE ?? DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE + const inspect = await runner.exec(engine, ['image', 'inspect', image]) + if (inspect.exitCode === 0) { + return + } + + const platform = env.MINIFLARE_CONTAINER_EGRESS_IMAGE_PLATFORM + await runOrThrow( + runner, + engine, + ['pull', image, ...(platform ? ['--platform', platform] : [])], + `pull the container egress interceptor image ${image}, which enableInternet and the outbound intercepts need` + ) +} + +/** + * Find the engine's API socket for workerd, in Wrangler's order: an explicit + * `WRANGLER_DOCKER_HOST` or `DOCKER_HOST`, then the engine's own answer + * (Docker's current context, Podman's remote socket), then Docker's default. + * + * @param engine - The engine that answered. + * @param runner - Command runner. + * @param env - Process environment. + * @returns A socket URL such as `unix:///var/run/docker.sock`. + */ +export async function resolveEngineSocket( + engine: ContainerEngineName, + runner: ContainerCommandRunner, + env: Record +): Promise { + const explicit = env.WRANGLER_DOCKER_HOST ?? env.DOCKER_HOST + if (explicit) { + return toSocketUrl(explicit) + } + + const query = + engine === 'docker' + ? ['context', 'inspect', '--format', '{{.Endpoints.docker.Host}}'] + : ['info', '--format', '{{.Host.RemoteSocket.Path}}'] + const answer = await runner.exec(engine, query) + const socket = answer.exitCode === 0 ? answer.stdout.trim() : '' + + return socket ? toSocketUrl(socket) : 'unix:///var/run/docker.sock' +} + +/** + * Give a bare socket path the `unix://` scheme workerd expects. + * + * @param value - A socket path or URL. + * @returns The URL form. + */ +function toSocketUrl(value: string): string { + return value.startsWith('/') ? `unix://${value}` : value +} + +/** + * Run an engine command and throw a readable error when it fails. + * + * @param runner - Command runner. + * @param engine - The engine to run. + * @param args - Its arguments. + * @param action - What the command does, for the error message. + * @throws When the command exits non-zero. + */ +async function runOrThrow( + runner: ContainerCommandRunner, + engine: ContainerEngineName, + args: string[], + action: string +): Promise { + const result = await runner.exec(engine, args, { timeoutMs: IMAGE_PREPARATION_TIMEOUT_MS }) + if (result.exitCode !== 0) { + const detail = (result.stderr || result.stdout || `exit code ${result.exitCode}`).trim() + throw new Error(`Could not ${action}: ${detail}`) + } + return result +} + +/** A Miniflare Durable Object namespace entry: a class name, or its object form. */ +export type MiniflareDurableObjectEntry = + | string + | { + /** The class workerd instantiates. */ + className: string + /** The worker that exports the class, when it is not this one. */ + scriptName?: string + /** SQLite-backed storage, which a container-attached class requires. */ + useSQLite?: boolean + /** The container workerd attaches to every object of the class. */ + container?: MiniflareDurableObjectContainerOption + } + +/** + * Attach the prepared containers to the Durable Object namespaces that serve + * their classes. Pure: returns a new map and leaves the input alone. + * + * @param durableObjects - Miniflare namespaces keyed by binding name. + * @param bindingClassNames - The configured class behind each binding name. A + * namespace may run a generated wrapper class, so the configured class is + * what a container entry is matched against. + * @param containersByClassName - The prepared `container` options. + * @returns The namespaces, with each container-backed one in object form + * carrying `useSQLite: true` (Cloudflare requires SQLite storage for a + * container-attached class) and its `container` option. + * @throws When a container names a class no namespace in this worker serves, + * which would otherwise leave `ctx.container` silently undefined. + */ +export function attachDurableObjectContainers( + durableObjects: Record, + bindingClassNames: Map, + containersByClassName: Map +): Record { + const attached = new Set() + const result: Record = {} + + for (const [bindingName, entry] of Object.entries(durableObjects)) { + const configuredClassName = bindingClassNames.get(bindingName) + const container = + configuredClassName === undefined ? undefined : containersByClassName.get(configuredClassName) + if (container === undefined || configuredClassName === undefined) { + result[bindingName] = entry + continue + } + + attached.add(configuredClassName) + const objectEntry = typeof entry === 'string' ? { className: entry } : entry + result[bindingName] = { ...objectEntry, useSQLite: true, container } + } + + const unattached = [...containersByClassName.keys()].filter( + (className) => !attached.has(className) + ) + if (unattached.length > 0) { + throw new Error( + `durable_object containers name ${unattached.map((name) => `"${name}"`).join(', ')}, but no Durable Object binding in this worker serves that class. Add a bindings.durableObjects entry for it; a container attached to another worker's class runs with that worker.` + ) + } + + return result +} + +/** + * The configured class behind each Durable Object binding, skipping + * unresolved `ref()` bindings. Pure. + * + * @param config - The resolved devflare config. + * @returns Binding name → class name. + */ +export function getDurableObjectBindingClassNames(config: DevflareConfig): Map { + const classNames = new Map() + for (const [bindingName, binding] of Object.entries(config.bindings?.durableObjects ?? {})) { + const normalized = normalizeDOBinding(binding) + if (normalized.__ref) continue + classNames.set(bindingName, normalized.className) + } + return classNames +} diff --git a/packages/devflare/src/test/simple-context-durable-objects.ts b/packages/devflare/src/test/simple-context-durable-objects.ts index 024cf95b..11ad8e7b 100644 --- a/packages/devflare/src/test/simple-context-durable-objects.ts +++ b/packages/devflare/src/test/simple-context-durable-objects.ts @@ -35,6 +35,57 @@ function classSupportsNativeDurableObjectRpc(code: string, className: string): b return nativeRpcPattern.test(code) } +/** + * Find the `WorkerEntrypoint` classes a module exports, the targets a + * container's outbound intercepts reach through `ctx.exports`. + * + * @param code - Module source. + * @returns The exported class names, in source order. + */ +function findExportedWorkerEntrypoints(code: string): string[] { + const entrypointPattern = /export\s+class\s+(\w+)\s+extends\s+WorkerEntrypoint\b/g + return [...code.matchAll(entrypointPattern)].map((match) => match[1]) +} + +/** A class the gateway re-exports from a Durable Object module. */ +interface GatewayEntrypointExport { + /** The exported class name. */ + name: string + /** The module that exports it. */ + scriptPath: string +} + +/** + * Collect the `WorkerEntrypoint` classes exported beside each container-backed + * Durable Object, so `ctx.exports.` resolves in the test gateway as it + * does in the deployed Worker. A plain Durable Object's module keeps exporting + * only its class, as before. + * + * @param doInfos - The Durable Objects bundled into the gateway. + * @param containerClassNames - Classes that have a `durable_object` container. + * @returns The entrypoints to re-export, without names the gateway already exports. + */ +async function findContainerEntrypointExports( + doInfos: LocalDurableObjectInfo[], + containerClassNames: ReadonlySet +): Promise { + const taken = new Set(doInfos.map((info) => info.className)) + const exports: GatewayEntrypointExport[] = [] + + for (const info of doInfos) { + if (!containerClassNames.has(info.className)) continue + + const code = await readFile(info.scriptPath, 'utf-8') + for (const name of findExportedWorkerEntrypoints(code)) { + if (taken.has(name)) continue + taken.add(name) + exports.push({ name, scriptPath: info.scriptPath }) + } + } + + return exports +} + function toGeneratedIdentifier(value: string): string { const normalized = value.replace(/[^A-Za-z0-9_$]/g, '_') return /^[A-Za-z_$]/.test(normalized) ? normalized : `_${normalized}` @@ -210,7 +261,8 @@ export class ${info.runtimeClassName} { function buildVirtualEntrySource( configDir: string, doInfos: LocalDurableObjectInfo[], - transportFile: string | null + transportFile: string | null, + entrypointExports: GatewayEntrypointExport[] = [] ): string { const virtualImports: string[] = [] const virtualExports: string[] = [] @@ -228,6 +280,13 @@ function buildVirtualEntrySource( virtualExports.push(`export { ${info.className} }`) } + for (const entrypoint of entrypointExports) { + virtualImports.push( + `import { ${entrypoint.name} } from '${entrypoint.scriptPath.replace(/\\/g, '/')}'` + ) + virtualExports.push(`export { ${entrypoint.name} }`) + } + if (virtualImports.length === 0) { return '' } @@ -262,9 +321,10 @@ async function describeBundleBuilder(): Promise { async function bundleDurableObjectModules( configDir: string, doInfos: LocalDurableObjectInfo[], - transportFile: string | null + transportFile: string | null, + entrypointExports: GatewayEntrypointExport[] = [] ): Promise { - const virtualEntry = buildVirtualEntrySource(configDir, doInfos, transportFile) + const virtualEntry = buildVirtualEntrySource(configDir, doInfos, transportFile, entrypointExports) if (!virtualEntry) { return '' } @@ -323,10 +383,22 @@ async function bundleDurableObjectModules( } } +/** + * Build the test gateway script and the Durable Object namespaces it serves. + * + * @param config - The resolved devflare config. + * @param configDir - The directory holding it. + * @param transportFile - The transport module, relative to `configDir`, or null. + * @param containerClassNames - Durable Object classes with a `durable_object` + * container; their modules' `WorkerEntrypoint` classes are exported too, so + * outbound intercepts can target `ctx.exports.`. + * @returns The gateway script, and the class each Durable Object binding runs. + */ export async function buildDurableObjectGateway( config: DevflareConfig, configDir: string, - transportFile: string | null + transportFile: string | null, + containerClassNames: ReadonlySet = new Set() ): Promise<{ durableObjects?: Record script: string @@ -340,7 +412,13 @@ export async function buildDurableObjectGateway( } const { doConfig, doInfos } = await resolveLocalDurableObjects(config, configDir) - const bundledCode = await bundleDurableObjectModules(configDir, doInfos, transportFile) + const entrypointExports = await findContainerEntrypointExports(doInfos, containerClassNames) + const bundledCode = await bundleDurableObjectModules( + configDir, + doInfos, + transportFile, + entrypointExports + ) const wrapperCode = buildWrapperCode(doInfos) const entrypointCode = [workflowEntrypointScript, bundledCode].filter(Boolean).join('\n\n') const nativeRpcBindingNames = doInfos.filter((info) => info.nativeRpc).map((info) => info.name) diff --git a/packages/devflare/src/test/simple-context.ts b/packages/devflare/src/test/simple-context.ts index 9b58fc75..0fb70150 100644 --- a/packages/devflare/src/test/simple-context.ts +++ b/packages/devflare/src/test/simple-context.ts @@ -18,6 +18,11 @@ import { resolveEmailRuntime } from '../email/runtime-config' import { __setTestContext, type EnvDisposeOptions } from '../env' import { setEmailDeliverySink } from '../utils/email-delivery' import { extractBindingHints } from './binding-hints' +import { + attachDurableObjectContainers, + getDurableObjectBindingClassNames, + prepareLocalDurableObjectContainers +} from './durable-object-containers' import { hasCrossWorkerDOs, hasServiceBindings, @@ -136,11 +141,25 @@ export async function createTestContext(configPath?: string): Promise { state.transportDecode = await loadTransportDecoders(configDir, transportFile) } - const gateway = await buildDurableObjectGateway(config, configDir, transportFile) + const localContainers = await prepareLocalDurableObjectContainers({ config, configDir }) + const gateway = await buildDurableObjectGateway( + config, + configDir, + transportFile, + new Set(localContainers?.containersByClassName.keys()) + ) mfConfig.script = gateway.script if (gateway.durableObjects) { mfConfig.durableObjects = gateway.durableObjects } + if (localContainers) { + mfConfig.containerEngine = localContainers.containerEngine + mfConfig.durableObjects = attachDurableObjectContainers( + mfConfig.durableObjects ?? {}, + getDurableObjectBindingClassNames(config), + localContainers.containersByClassName + ) + } const hasMultiWorkerServices = serviceBindingResolution && serviceBindingResolution.workers.length > 0 diff --git a/packages/devflare/tests/integration/test-context/durable-object-container.test.ts b/packages/devflare/tests/integration/test-context/durable-object-container.test.ts new file mode 100644 index 00000000..b3509254 --- /dev/null +++ b/packages/devflare/tests/integration/test-context/durable-object-container.test.ts @@ -0,0 +1,296 @@ +// ============================================================================= +// A durable_object scheduling-policy container, end to end on a real engine +// ============================================================================= +// One project defines a container with `schedulingPolicy: 'durable_object'`. +// The test compiles it to Wrangler's shape, then starts it through +// `createTestContext()`: devflare builds the named image with Docker or Podman +// and attaches it to the Durable Object in Miniflare, and the object drives the +// container through `ctx.container` — `images`, `start({ enableInternet: false })`, +// and the outbound intercepts, which must reach the Worker's `WorkerEntrypoint`. +// +// → Needs DEVFLARE_CONTAINER_TESTS=1, a reachable engine, Linux or macOS (workerd +// cannot reach a Windows named pipe), and network access to build the image +// and pull Miniflare's egress interceptor. Without them it is reported as a +// skip, never as a pass. +// ============================================================================= + +import { afterAll, beforeAll, describe, expect, test } from 'bun:test' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'pathe' +import { env } from '../../../src' +import { compileConfig } from '../../../src/config/compiler' +import { brandAsLocalConfig } from '../../../src/config/resolve-phased' +import { configSchema, type DevflareConfig } from '../../../src/config/schema' +import { createTestContext, getContainerSkipReason } from '../../../src/test' +import { localContainerImageTag } from '../../../src/test/durable-object-containers' + +/** Building the image and starting the container can take minutes on a cold runner. */ +const CONTAINER_TEST_TIMEOUT_MS = 300_000 + +const engine = (process.env.DEVFLARE_CONTAINER_ENGINE as 'docker' | 'podman' | undefined) ?? 'auto' +const skipReason = + process.platform === 'win32' + ? 'workerd cannot reach a container engine on Windows; run this inside WSL.' + : await getContainerSkipReason({ engine }) + +if (skipReason && process.env.DEVFLARE_CONTAINER_TESTS_REQUIRED === '1') { + // The CI lane that exists to run this test sets the flag, so a missing + // engine there fails the lane instead of reading as a green skip. + throw new Error(`durable_object container test is required but cannot run: ${skipReason}`) +} +if (skipReason) { + console.warn(`[devflare] skipping durable_object container integration test: ${skipReason}`) +} + +/** The devflare config the fixture project carries, as a plain object. */ +const projectConfig = { + name: 'durable-object-container-fixture', + compatibilityDate: '2026-09-29', + files: { durableObjects: 'src/do.*.ts' }, + bindings: { durableObjects: { BUILDER: 'Builder' } }, + containers: [ + { + className: 'Builder', + schedulingPolicy: 'durable_object', + images: { base: { dockerfile: './container/Dockerfile' } } + } + ], + migrations: [{ tag: 'v1', new_sqlite_classes: ['Builder'] }] +} as const + +/** + * The Durable Object and its outbound handler. `probe` starts a container + * under one intercept set, asks it to fetch each URL, and reports what the + * container saw. + */ +const durableObjectSource = String.raw` +import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers' + +export class OutboundHandler extends WorkerEntrypoint { + fetch(request) { + const url = new URL(request.url) + return new Response('intercepted ' + request.method + ' ' + url.protocol + '//' + url.host + url.pathname) + } +} + +export class Builder extends DurableObject { + images() { + return { ...this.ctx.container.images } + } + + async probe(mode, urls) { + const container = this.ctx.container + const handler = this.ctx.exports.OutboundHandler + if (mode === 'named') { + await container.interceptOutboundHttp('named.devflare.test', handler) + await container.interceptOutboundHttps('secure.devflare.test', handler) + } + if (mode === 'catch-all') { + await container.interceptAllOutboundHttp(handler) + await container.interceptOutboundHttps('*', handler) + } + + container.start({ image: container.images.base, enableInternet: false }) + try { + const port = container.getTcpPort(8080) + const deadline = Date.now() + 120000 + for (;;) { + try { + const health = await port.fetch('http://container/health') + if (health.ok) break + } catch (error) { + if (Date.now() > deadline) throw error + } + await new Promise((resolve) => setTimeout(resolve, 250)) + } + + const results = [] + for (const url of urls) { + const response = await port.fetch('http://container/probe?url=' + encodeURIComponent(url)) + results.push({ url, ...(await response.json()) }) + } + return results + } finally { + await container.destroy() + } + } +} +` + +/** A Node server inside the container that fetches a URL on request. */ +const containerServerSource = String.raw` +import http from 'node:http' +import https from 'node:https' +import { readFileSync } from 'node:fs' + +const CA_PATH = '/etc/cloudflare/certs/cloudflare-containers-ca.crt' + +function fetchOnce(target) { + return new Promise((resolve) => { + const url = new URL(target) + const client = url.protocol === 'https:' ? https : http + let ca + if (url.protocol === 'https:') { + try { ca = readFileSync(CA_PATH) } catch (error) { resolve({ ok: false, error: 'no CA at ' + CA_PATH }) ; return } + } + const request = client.get(url, { timeout: 8000, ca }, (response) => { + let body = '' + response.setEncoding('utf8') + response.on('data', (chunk) => { body += chunk }) + response.on('end', () => resolve({ ok: true, status: response.statusCode, body })) + }) + request.on('timeout', () => request.destroy(new Error('timed out'))) + request.on('error', (error) => resolve({ ok: false, error: String(error.code ?? error.message) })) + }) +} + +http.createServer(async (request, response) => { + const url = new URL(request.url, 'http://localhost') + if (url.pathname === '/health') { + response.end('ok') + return + } + const result = await fetchOnce(url.searchParams.get('url')) + response.setHeader('content-type', 'application/json') + response.end(JSON.stringify(result)) +}).listen(8080, '0.0.0.0') +` + +/** One probe result, as the container reports it. */ +interface ProbeResult { + /** The URL the container fetched. */ + url: string + /** Whether a response came back at all. */ + ok: boolean + /** Its status, when one came back. */ + status?: number + /** Its body, when one came back. */ + body?: string + /** Why nothing came back. */ + error?: string +} + +/** The Durable Object stub the test drives. */ +interface BuilderStub { + images(): Promise> + probe(mode: 'none' | 'named' | 'catch-all', urls: string[]): Promise +} + +let projectDir = '' + +/** Write the fixture project, Dockerfile included, into a fresh temp directory. */ +async function writeProject(): Promise { + const dir = await mkdtemp(join(tmpdir(), 'devflare-do-container-')) + await mkdir(join(dir, 'src'), { recursive: true }) + await mkdir(join(dir, 'container'), { recursive: true }) + await writeFile( + join(dir, 'devflare.config.ts'), + `export default ${JSON.stringify(projectConfig, null, '\t')}\n` + ) + await writeFile(join(dir, 'src', 'do.builder.ts'), durableObjectSource) + await writeFile(join(dir, 'container', 'server.mjs'), containerServerSource) + await writeFile( + join(dir, 'container', 'Dockerfile'), + [ + 'FROM node:22-alpine', + 'COPY server.mjs /app/server.mjs', + 'CMD ["node", "/app/server.mjs"]', + '' + ].join('\n') + ) + return dir +} + +/** The Durable Object behind `env.BUILDER`, by name. */ +function builder(name: string): BuilderStub { + const namespace = (env as unknown as Record) + .BUILDER + return namespace.getByName(name) +} + +describe.skipIf(skipReason !== null)('durable_object container through createTestContext', () => { + beforeAll(async () => { + if (skipReason !== null) return + projectDir = await writeProject() + await createTestContext(join(projectDir, 'devflare.config.ts')) + }, CONTAINER_TEST_TIMEOUT_MS) + + afterAll(async () => { + if (skipReason !== null) return + await env.dispose() + if (projectDir) await rm(projectDir, { recursive: true, force: true }) + }) + + test('compiles to Wrangler durable_object shape', () => { + const config = brandAsLocalConfig(configSchema.parse(projectConfig) as DevflareConfig) + expect(compileConfig(config).containers).toEqual([ + { + class_name: 'Builder', + scheduling_policy: 'durable_object', + images: { base: { dockerfile: './container/Dockerfile' } } + } + ]) + }) + + test('ctx.container.images names the image devflare built', async () => { + expect(await builder('images').images()).toEqual({ + base: localContainerImageTag(projectDir, 'Builder', 'base') + }) + }) + + test( + 'enableInternet: false holds: with no intercept, no request leaves the container', + async () => { + const results = await builder('none').probe('none', [ + 'http://example.com/', + 'https://example.com/' + ]) + + for (const result of results) { + expect(result).toMatchObject({ ok: false }) + } + }, + CONTAINER_TEST_TIMEOUT_MS + ) + + test( + 'interceptOutboundHttp and interceptOutboundHttps reach the Worker; other hosts stay blocked', + async () => { + const results = await builder('named').probe('named', [ + 'http://named.devflare.test/a', + 'https://secure.devflare.test/b', + 'http://example.com/' + ]) + + expect(results[0]).toMatchObject({ + ok: true, + status: 200, + body: 'intercepted GET http://named.devflare.test/a' + }) + expect(results[1]).toMatchObject({ + ok: true, + status: 200, + body: 'intercepted GET https://secure.devflare.test/b' + }) + expect(results[2]).toMatchObject({ ok: false }) + }, + CONTAINER_TEST_TIMEOUT_MS + ) + + test( + 'interceptAllOutboundHttp and interceptOutboundHttps("*") catch every host', + async () => { + const results = await builder('catch-all').probe('catch-all', [ + 'http://anything.example/c', + 'https://anything.example/d' + ]) + + expect(results.map((result) => result.body)).toEqual([ + 'intercepted GET http://anything.example/c', + 'intercepted GET https://anything.example/d' + ]) + }, + CONTAINER_TEST_TIMEOUT_MS + ) +}) diff --git a/packages/devflare/tests/unit/config/compiler/09-containers.ts b/packages/devflare/tests/unit/config/compiler/09-containers.ts index f4e7d033..84eb9e6b 100644 --- a/packages/devflare/tests/unit/config/compiler/09-containers.ts +++ b/packages/devflare/tests/unit/config/compiler/09-containers.ts @@ -61,5 +61,70 @@ describe('compileConfig', () => { } ]) }) + + test('compiles a durable_object container to the fields Wrangler accepts for that policy', () => { + const result = compileConfig({ + ...baseConfig, + containers: [ + { + className: 'Builder', + schedulingPolicy: 'durable_object', + name: 'builder', + images: { + base: { + dockerfile: './container/Dockerfile', + buildContext: './container', + buildVars: { BUN_VERSION: '1.4.2' } + }, + plain: { dockerfile: './plain/Dockerfile' }, + pinned: { image: 'registry.cloudflare.com/acct/builder@sha256:abc' } + } + } + ] + }) + + expect(result.containers).toEqual([ + { + class_name: 'Builder', + scheduling_policy: 'durable_object', + name: 'builder', + images: { + base: { + dockerfile: './container/Dockerfile', + build_context: './container', + build_vars: { BUN_VERSION: '1.4.2' } + }, + plain: { dockerfile: './plain/Dockerfile' }, + pinned: { image: 'registry.cloudflare.com/acct/builder@sha256:abc' } + } + } + ]) + }) + + test('compiles a durable_object container with no images to class and policy alone', () => { + const result = compileConfig({ + ...baseConfig, + containers: [{ className: 'Sandbox', schedulingPolicy: 'durable_object' }] + }) + + expect(result.containers).toEqual([ + { class_name: 'Sandbox', scheduling_policy: 'durable_object' } + ]) + }) + + test('writes scheduling_policy for a default container only when the config spells it', () => { + const result = compileConfig({ + ...baseConfig, + containers: [ + { className: 'Explicit', schedulingPolicy: 'default', image: './Dockerfile' }, + { className: 'Implicit', image: './Dockerfile' } + ] + }) + + expect(result.containers).toEqual([ + { class_name: 'Explicit', scheduling_policy: 'default', image: './Dockerfile' }, + { class_name: 'Implicit', image: './Dockerfile' } + ]) + }) }) }) diff --git a/packages/devflare/tests/unit/config/compiler/15-rebasewranglerconfigpaths.ts b/packages/devflare/tests/unit/config/compiler/15-rebasewranglerconfigpaths.ts index 05d24433..1dc4389a 100644 --- a/packages/devflare/tests/unit/config/compiler/15-rebasewranglerconfigpaths.ts +++ b/packages/devflare/tests/unit/config/compiler/15-rebasewranglerconfigpaths.ts @@ -88,5 +88,36 @@ describe('compileConfig', () => { } ]) }) + + test('rebases each named image Dockerfile and build context, and keeps registry images', () => { + const rebased = rebaseWranglerConfigPaths('/project', '/project/.devflare', { + name: 'my-worker', + compatibility_date: '2026-09-29', + containers: [ + { + class_name: 'Builder', + scheduling_policy: 'durable_object', + images: { + base: { dockerfile: './container/Dockerfile', build_context: './container' }, + bare: { dockerfile: './bare/Dockerfile' }, + pinned: { image: 'registry.cloudflare.com/acct/builder@sha256:abc' } + } + } + ] + }) + + expect(rebased.containers).toEqual([ + { + class_name: 'Builder', + scheduling_policy: 'durable_object', + images: { + base: { dockerfile: '../container/Dockerfile', build_context: '../container' }, + bare: { dockerfile: '../bare/Dockerfile' }, + pinned: { image: 'registry.cloudflare.com/acct/builder@sha256:abc' } + } + } + ]) + expect(rebased.containers?.[0]).not.toHaveProperty('image') + }) }) }) diff --git a/packages/devflare/tests/unit/config/schema-core.test.ts b/packages/devflare/tests/unit/config/schema-core.test.ts index 20078f91..5f153f59 100644 --- a/packages/devflare/tests/unit/config/schema-core.test.ts +++ b/packages/devflare/tests/unit/config/schema-core.test.ts @@ -458,6 +458,131 @@ describe('configSchema', () => { } }) + test('accepts a durable_object scheduling-policy container with named images', () => { + const container = { + className: 'Builder', + schedulingPolicy: 'durable_object', + name: 'builder', + images: { + base: { + dockerfile: './container/Dockerfile', + buildContext: './container', + buildVars: { BUN_VERSION: '1.4.2' } + }, + pinned: { + image: `registry.cloudflare.com/acct/builder@sha256:${'a'.repeat(64)}` + } + } + } + const result = configSchema.safeParse({ + name: 'my-worker', + compatibilityDate: '2026-09-29', + containers: [container] + }) + + expect(result.success).toBe(true) + if (result.success) { + expect(result.data.containers?.[0]).toEqual(container) + } + }) + + test('accepts a durable_object container with no named images', () => { + const result = configSchema.safeParse({ + name: 'my-worker', + compatibilityDate: '2026-09-29', + containers: [{ className: 'Sandbox', schedulingPolicy: 'durable_object' }] + }) + + expect(result.success).toBe(true) + }) + + test('accepts an explicit default scheduling policy beside the application image', () => { + const result = configSchema.safeParse({ + name: 'my-worker', + compatibilityDate: '2026-09-29', + containers: [{ className: 'Api', schedulingPolicy: 'default', image: './Dockerfile' }] + }) + + expect(result.success).toBe(true) + }) + + test.each([ + ['an application-wide image', { image: './Dockerfile' }], + ['maxInstances', { maxInstances: 2 }], + ['instanceType', { instanceType: 'basic' }], + ['rolloutStepPercentage', { rolloutStepPercentage: 100 }] + ])('rejects %s on a durable_object container, as Wrangler does', (_label, extra) => { + const result = configSchema.safeParse({ + name: 'my-worker', + compatibilityDate: '2026-09-29', + containers: [ + { + className: 'Builder', + schedulingPolicy: 'durable_object', + images: { base: { dockerfile: './Dockerfile' } }, + ...extra + } + ] + }) + + expect(result.success).toBe(false) + }) + + test.each([ + ['both a dockerfile and an image', { base: { dockerfile: './Dockerfile', image: 'x' } }], + ['neither a dockerfile nor an image', { base: {} }], + ['a build context on a registry image', { base: { image: 'x', buildContext: '.' } }], + ['an empty map', {}], + ['an empty image name', { '': { dockerfile: './Dockerfile' } }], + ['an image name over 128 characters', { ['n'.repeat(129)]: { dockerfile: './Dockerfile' } }], + [ + 'more than 100 images', + Object.fromEntries( + Array.from({ length: 101 }, (_, index) => [`i${index}`, { dockerfile: './Dockerfile' }]) + ) + ] + ])('rejects named images with %s', (_label, images) => { + const result = configSchema.safeParse({ + name: 'my-worker', + compatibilityDate: '2026-09-29', + containers: [{ className: 'Builder', schedulingPolicy: 'durable_object', images }] + }) + + expect(result.success).toBe(false) + }) + + test('accepts exactly 100 named images and a 128-character name', () => { + const images = Object.fromEntries( + Array.from({ length: 100 }, (_, index) => [ + index === 0 ? 'n'.repeat(128) : `i${index}`, + { dockerfile: './Dockerfile' } + ]) + ) + const result = configSchema.safeParse({ + name: 'my-worker', + compatibilityDate: '2026-09-29', + containers: [{ className: 'Builder', schedulingPolicy: 'durable_object', images }] + }) + + expect(result.success).toBe(true) + }) + + test('rejects named images on a default-policy container', () => { + const result = configSchema.safeParse({ + name: 'my-worker', + compatibilityDate: '2026-09-29', + containers: [ + { + className: 'Api', + image: './Dockerfile', + images: { base: { dockerfile: './Dockerfile' } } + } + ] + }) + + expect(result.success).toBe(false) + }) + test('rejects Containers config without a class name', () => { const result = configSchema.safeParse({ name: 'my-worker', diff --git a/packages/devflare/tests/unit/config/type-docs.test.ts b/packages/devflare/tests/unit/config/type-docs.test.ts index 2f3e2c61..b431e14f 100644 --- a/packages/devflare/tests/unit/config/type-docs.test.ts +++ b/packages/devflare/tests/unit/config/type-docs.test.ts @@ -20,7 +20,8 @@ const schemaTypesPaths = [ // none and nobody notices. Add every new `schema-types-*.ts` to this list in the same change. 'src/config/schema-types-email.ts', 'src/config/schema-types-zones.ts', - 'src/config/schema-types-subscriptions.ts' + 'src/config/schema-types-subscriptions.ts', + 'src/config/schema-types-containers.ts' ].map((path) => resolve(devflareRoot, path)) const fixtureSource = ` diff --git a/packages/devflare/tests/unit/config/wrangler-container-shape.test.ts b/packages/devflare/tests/unit/config/wrangler-container-shape.test.ts new file mode 100644 index 00000000..d305ae1d --- /dev/null +++ b/packages/devflare/tests/unit/config/wrangler-container-shape.test.ts @@ -0,0 +1,143 @@ +// ============================================================================= +// Wrangler accepts what devflare compiles for a durable_object container, and +// maps it to the same Miniflare Durable Object options devflare's local runs use. +// ============================================================================= +// The oracle is the installed Wrangler itself: `unstable_readConfig` runs its +// config validation (which rejects any field the durable_object policy does not +// take), and `unstable_getMiniflareWorkerOptions` is how `wrangler dev` attaches +// the container. Asserting against a hand-written copy of either would only +// prove devflare agrees with this file. +// ============================================================================= + +import { afterAll, describe, expect, test } from 'bun:test' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { compileConfig } from '../../../src/config/compiler' +import { brandAsLocalConfig } from '../../../src/config/resolve-phased' +import { configSchema, type DevflareConfig } from '../../../src/config/schema' +import { + attachDurableObjectContainers, + getDurableObjectBindingClassNames, + planLocalDurableObjectContainers, + toMiniflareContainerOption +} from '../../../src/test/durable-object-containers' + +const projectDir = mkdtempSync(join(tmpdir(), 'devflare-wrangler-container-')) +afterAll(() => rmSync(projectDir, { recursive: true, force: true })) + +mkdirSync(join(projectDir, 'container'), { recursive: true }) +mkdirSync(join(projectDir, 'src'), { recursive: true }) +writeFileSync(join(projectDir, 'container', 'Dockerfile'), 'FROM alpine:3.20\n') +writeFileSync(join(projectDir, 'src', 'index.ts'), 'export class Builder {}\nexport default {}\n') + +/** Parse a devflare config the way loadConfig does, so defaults and unions apply. */ +function parseConfig(input: Record): DevflareConfig { + return brandAsLocalConfig(configSchema.parse(input) as DevflareConfig) +} + +/** Write a compiled Wrangler config and read it back through Wrangler's own validator. */ +async function readThroughWrangler(config: DevflareConfig): Promise<{ + containers: unknown + durableObjects: Record +}> { + const wranglerConfigPath = join(projectDir, 'wrangler.json') + writeFileSync( + wranglerConfigPath, + JSON.stringify({ ...compileConfig(config), main: 'src/index.ts' }, null, 2) + ) + const wrangler = await import('wrangler') + const read = wrangler.unstable_readConfig({ config: wranglerConfigPath }) + const options = wrangler.unstable_getMiniflareWorkerOptions(wranglerConfigPath, undefined, { + containerBuildId: 'parity' + }) + return { + containers: read.containers, + durableObjects: options.workerOptions.durableObjects as Record + } +} + +/** Importing Wrangler takes seconds; under a loaded unit lane the 5s default is too tight. */ +const WRANGLER_TEST_TIMEOUT_MS = 30_000 + +const durableObjectPolicyConfig = { + name: 'builder', + compatibilityDate: '2026-09-29', + bindings: { durableObjects: { BUILDER: 'Builder' } }, + containers: [ + { + className: 'Builder', + schedulingPolicy: 'durable_object', + images: { base: { dockerfile: './container/Dockerfile' } } + } + ], + migrations: [{ tag: 'v1', new_sqlite_classes: ['Builder'] }] +} + +describe('durable_object containers against the installed Wrangler', () => { + test( + 'Wrangler validates the compiled entry', + async () => { + const { containers } = await readThroughWrangler(parseConfig(durableObjectPolicyConfig)) + + expect(containers).toEqual([ + { + class_name: 'Builder', + scheduling_policy: 'durable_object', + images: { base: { dockerfile: './container/Dockerfile' } }, + name: 'builder-builder' + } + ]) + }, + WRANGLER_TEST_TIMEOUT_MS + ) + + test( + "devflare attaches the same Durable Object container option as wrangler dev, up to each image's local tag", + async () => { + const config = parseConfig(durableObjectPolicyConfig) + const { durableObjects } = await readThroughWrangler(config) + + const [planned] = planLocalDurableObjectContainers(config, projectDir) + const devflareEntry = attachDurableObjectContainers( + { BUILDER: 'Builder' }, + getDurableObjectBindingClassNames(config), + new Map([[planned.className, toMiniflareContainerOption(planned)]]) + ) + + const withoutTags = (entry: unknown) => + JSON.parse(JSON.stringify(entry).replace(/"image":"[^"]+"/g, '"image":""')) + expect(withoutTags(devflareEntry)).toEqual(withoutTags(durableObjects)) + expect(durableObjects.BUILDER).toMatchObject({ useSQLite: true }) + }, + WRANGLER_TEST_TIMEOUT_MS + ) + + test( + 'Wrangler rejects an application-wide field on the durable_object policy, which the schema refuses first', + async () => { + const input = { + ...durableObjectPolicyConfig, + containers: [{ ...durableObjectPolicyConfig.containers[0], maxInstances: 2 }] + } + expect(configSchema.safeParse(input).success).toBe(false) + + const forced = parseConfig(durableObjectPolicyConfig) + const compiled = compileConfig(forced) + const wranglerConfigPath = join(projectDir, 'wrangler.json') + writeFileSync( + wranglerConfigPath, + JSON.stringify({ + ...compiled, + main: 'src/index.ts', + containers: [{ ...compiled.containers?.[0], max_instances: 2 }] + }) + ) + const wrangler = await import('wrangler') + expect(() => wrangler.unstable_readConfig({ config: wranglerConfigPath })).toThrow( + 'Unsupported fields for Durable Object-managed Containers' + ) + }, + WRANGLER_TEST_TIMEOUT_MS + ) +}) diff --git a/packages/devflare/tests/unit/dev-server/miniflare-dev-config.test.ts b/packages/devflare/tests/unit/dev-server/miniflare-dev-config.test.ts index 9071577b..707742aa 100644 --- a/packages/devflare/tests/unit/dev-server/miniflare-dev-config.test.ts +++ b/packages/devflare/tests/unit/dev-server/miniflare-dev-config.test.ts @@ -192,4 +192,76 @@ describe('buildMiniflareDevConfig', () => { expect(browserWorker.script).toContain('http://127.0.0.1:9911') expect(browserWorker.script).not.toContain('8788') }) + + describe('durable_object containers', () => { + const doResult = { + bundles: new Map([ + ['BUILDER', 'C:/repo/site/.devflare/do-bundles/Builder/index.js'], + ['COUNTER', 'C:/repo/site/.devflare/do-bundles/Counter/index.js'] + ]), + classes: new Map([ + ['BUILDER', 'Builder'], + ['COUNTER', 'Counter'] + ]), + sourceFiles: new Map(), + errors: [] + } + const localContainers = { + engine: 'docker' as const, + containerEngine: { localDocker: { socketPath: 'unix:///var/run/docker.sock' } }, + containersByClassName: new Map([ + ['Builder', { images: [{ name: 'base', image: 'devflare-dev/builder-base:1' }] }] + ]) + } + + test('attaches the container to the Durable Object worker that defines its class, and sets the engine', () => { + const mfConfig = buildMiniflareDevConfig( + buildBaseInput({ config: { name: 'site-worker' }, doResult, localContainers }) + ) + + const builderWorker = mfConfig.workers.find( + (worker: { name: string }) => worker.name === 'do-builder' + ) + const counterWorker = mfConfig.workers.find( + (worker: { name: string }) => worker.name === 'do-counter' + ) + expect(builderWorker.durableObjects).toEqual({ + BUILDER: { + className: 'Builder', + useSQLite: true, + container: { images: [{ name: 'base', image: 'devflare-dev/builder-base:1' }] } + } + }) + expect(counterWorker.durableObjects).toEqual({ COUNTER: 'Counter' }) + expect(mfConfig.containerEngine).toEqual(localContainers.containerEngine) + expect(mfConfig.workers[0].durableObjects.BUILDER).toEqual({ + className: 'Builder', + scriptName: 'do-builder' + }) + }) + + test('leaves every Durable Object and the engine untouched without prepared containers', () => { + const mfConfig = buildMiniflareDevConfig( + buildBaseInput({ config: { name: 'site-worker' }, doResult }) + ) + + const builderWorker = mfConfig.workers.find( + (worker: { name: string }) => worker.name === 'do-builder' + ) + expect(builderWorker.durableObjects).toEqual({ BUILDER: 'Builder' }) + expect(mfConfig).not.toHaveProperty('containerEngine') + }) + + test('refuses a container whose class no bundled Durable Object defines', () => { + expect(() => + buildMiniflareDevConfig( + buildBaseInput({ + config: { name: 'site-worker' }, + doResult: { ...doResult, bundles: new Map(), classes: new Map() }, + localContainers + }) + ) + ).toThrow('no Durable Object in files.durableObjects defines that class') + }) + }) }) diff --git a/packages/devflare/tests/unit/dev-server/workspace-durable-object-containers.test.ts b/packages/devflare/tests/unit/dev-server/workspace-durable-object-containers.test.ts new file mode 100644 index 00000000..b716316c --- /dev/null +++ b/packages/devflare/tests/unit/dev-server/workspace-durable-object-containers.test.ts @@ -0,0 +1,46 @@ +import { afterEach, describe, expect, test } from 'bun:test' +import type { DevflareConfig } from '../../../src/config' +import { assertNoLocalDurableObjectContainers } from '../../../src/dev-server/workspace/prepare-app' + +const originalFlag = process.env.DEVFLARE_ENABLE_CONTAINERS + +afterEach(() => { + if (originalFlag === undefined) delete process.env.DEVFLARE_ENABLE_CONTAINERS + else process.env.DEVFLARE_ENABLE_CONTAINERS = originalFlag +}) + +/** An app config with one container under the given scheduling policy. */ +function appConfig(schedulingPolicy: 'durable_object' | 'default'): DevflareConfig { + return { + name: 'builder', + compatibilityDate: '2026-09-29', + containers: [ + schedulingPolicy === 'durable_object' + ? { className: 'Builder', schedulingPolicy } + : { className: 'Builder', image: './Dockerfile' } + ] + } as DevflareConfig +} + +describe('workspace dev and durable_object containers', () => { + test('refuses an app with a durable_object container, naming the class and the opt-out', () => { + delete process.env.DEVFLARE_ENABLE_CONTAINERS + expect(() => + assertNoLocalDurableObjectContainers('render', appConfig('durable_object'), '/apps/render') + ).toThrow( + /"render" declares durable_object containers \(Builder\).*DEVFLARE_ENABLE_CONTAINERS=0/ + ) + }) + + test('admits it with DEVFLARE_ENABLE_CONTAINERS=0, and admits a default-policy container', () => { + process.env.DEVFLARE_ENABLE_CONTAINERS = '0' + expect(() => + assertNoLocalDurableObjectContainers('render', appConfig('durable_object'), '/apps/render') + ).not.toThrow() + + delete process.env.DEVFLARE_ENABLE_CONTAINERS + expect(() => + assertNoLocalDurableObjectContainers('render', appConfig('default'), '/apps/render') + ).not.toThrow() + }) +}) diff --git a/packages/devflare/tests/unit/test/container-gateway-exports.test.ts b/packages/devflare/tests/unit/test/container-gateway-exports.test.ts new file mode 100644 index 00000000..32e23153 --- /dev/null +++ b/packages/devflare/tests/unit/test/container-gateway-exports.test.ts @@ -0,0 +1,98 @@ +import { afterAll, beforeEach, describe, expect, test } from 'bun:test' +import { mkdirSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import type { DevflareConfig } from '../../../src/config' +import { __resetDurableObjectBundleCache } from '../../../src/test/durable-object-bundle-cache' +import { buildDurableObjectGateway } from '../../../src/test/simple-context-durable-objects' +import { createTrackedTempDirectories } from '../../helpers/tracked-temp-directories' + +const tempDirectories = createTrackedTempDirectories() + +afterAll(() => { + tempDirectories.cleanup() +}) + +beforeEach(() => { + __resetDurableObjectBundleCache() +}) + +const config: DevflareConfig = { + name: 'container-gateway-project', + compatibilityDate: '2026-09-29', + bindings: { + durableObjects: { + BUILDER: { className: 'Builder' }, + COUNTER: { className: 'Counter' } + } + } +} as DevflareConfig + +/** + * A project whose container-backed Durable Object module also exports the + * `WorkerEntrypoint` its outbound intercepts target, beside a plain Durable + * Object module that exports one too. + */ +function createProject(): string { + const projectDir = tempDirectories.create('devflare-container-gateway-') + mkdirSync(join(projectDir, 'src'), { recursive: true }) + writeFileSync( + join(projectDir, 'src', 'do.builder.ts'), + [ + "import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers'", + 'export class OutboundHandler extends WorkerEntrypoint {', + " fetch() { return new Response('intercepted') }", + '}', + 'export class Builder extends DurableObject {', + " ping() { return 'pong' }", + '}', + '' + ].join('\n') + ) + writeFileSync( + join(projectDir, 'src', 'do.counter.ts'), + [ + "import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers'", + 'export class CounterSideEntrypoint extends WorkerEntrypoint {}', + 'export class Counter extends DurableObject {}', + '' + ].join('\n') + ) + return projectDir +} + +/** The names a bundled gateway script lists in its `export { … }` statements. */ +function exportedNames(script: string): string[] { + return [...script.matchAll(/export\s*\{([^}]*)\}/g)].flatMap((match) => + match[1] + .split(',') + .map( + (name) => + name + .trim() + .split(/\s+as\s+/) + .pop() ?? '' + ) + .filter(Boolean) + ) +} + +describe('test gateway exports for durable_object containers', () => { + test('exports the WorkerEntrypoint beside a container-backed class, so ctx.exports can reach it', async () => { + const projectDir = createProject() + const gateway = await buildDurableObjectGateway(config, projectDir, null, new Set(['Builder'])) + + const names = exportedNames(gateway.script) + expect(names).toContain('Builder') + expect(names).toContain('OutboundHandler') + expect(names).not.toContain('CounterSideEntrypoint') + }) + + test('exports only Durable Object classes when no class has a container', async () => { + const projectDir = createProject() + const gateway = await buildDurableObjectGateway(config, projectDir, null) + + const names = exportedNames(gateway.script) + expect(names).toContain('Builder') + expect(names).not.toContain('OutboundHandler') + }) +}) diff --git a/packages/devflare/tests/unit/test/containers.test.ts b/packages/devflare/tests/unit/test/containers.test.ts index 0fa1d960..d2e9945a 100644 --- a/packages/devflare/tests/unit/test/containers.test.ts +++ b/packages/devflare/tests/unit/test/containers.test.ts @@ -305,4 +305,25 @@ describe('createContainerManager', () => { expect(buildCall?.args).toContain(dockerfile) expect(buildCall?.args).toContain(tempDir) }) + + test('refuses to start a durable_object container outside its Durable Object, before touching the engine', async () => { + const tempDir = await mkdtemp(join(tmpdir(), 'devflare-container-')) + tempDirs.push(tempDir) + await writeFile( + join(tempDir, 'devflare.config.ts'), + `export default { + name: 'builder-worker', + compatibilityDate: '2026-09-29', + containers: [{ className: 'Builder', schedulingPolicy: 'durable_object' }] +} +` + ) + const { runner, calls } = createContainerRunner() + const manager = createContainerManager({ runner, cwd: tempDir }) + + await expect( + manager.start('Builder', { configPath: 'devflare.config.ts', port: 8080 }) + ).rejects.toThrow('Drive it through createTestContext()') + expect(calls).toEqual([]) + }) }) diff --git a/packages/devflare/tests/unit/test/durable-object-containers.test.ts b/packages/devflare/tests/unit/test/durable-object-containers.test.ts new file mode 100644 index 00000000..7fdc92ab --- /dev/null +++ b/packages/devflare/tests/unit/test/durable-object-containers.test.ts @@ -0,0 +1,427 @@ +import { describe, expect, test } from 'bun:test' +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { resolve } from 'node:path' +import { brandAsLocalConfig } from '../../../src/config/resolve-phased' +import type { DevflareConfig } from '../../../src/config/schema' +import type { ContainerCommandResult, ContainerCommandRunner } from '../../../src/test/containers' +import { + areLocalContainersDisabled, + attachDurableObjectContainers, + DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE, + getDurableObjectBindingClassNames, + localContainerImageTag, + planLocalDurableObjectContainers, + prepareLocalDurableObjectContainers, + resolveEngineSocket, + toMiniflareContainerOption +} from '../../../src/test/durable-object-containers' + +const configDir = resolve('/project') + +/** A config with one Durable Object-managed container and one default-policy one. */ +function makeConfig(overrides: Partial = {}): DevflareConfig { + return brandAsLocalConfig({ + name: 'builder-worker', + compatibilityDate: '2026-09-29', + bindings: { + durableObjects: { + BUILDER: 'Builder', + COUNTER: 'Counter', + API: 'Api' + } + }, + containers: [ + { + className: 'Builder', + schedulingPolicy: 'durable_object', + images: { + base: { + dockerfile: './container/Dockerfile', + buildVars: { BUN_VERSION: '1.4.2' } + }, + pinned: { image: 'registry.cloudflare.com/acct/builder@sha256:abc' } + } + }, + { className: 'Api', image: './api/Dockerfile' } + ], + ...overrides + } satisfies DevflareConfig) +} + +/** A runner that answers from a table and records every command it was asked to run. */ +function createRecordingRunner( + answer: (command: string, args: string[]) => Partial = () => ({}) +): { runner: ContainerCommandRunner; calls: string[] } { + const calls: string[] = [] + return { + calls, + runner: { + async exec(command, args) { + calls.push([command, ...args].join(' ')) + return { exitCode: 0, stdout: '', stderr: '', ...answer(command, args) } + } + } + } +} + +describe('planLocalDurableObjectContainers', () => { + test('plans only durable_object containers, with absolute paths and a tag per image', () => { + const plan = planLocalDurableObjectContainers(makeConfig(), configDir) + + expect(plan).toEqual([ + { + className: 'Builder', + images: [ + { + name: 'base', + tag: localContainerImageTag(configDir, 'Builder', 'base'), + source: { + kind: 'dockerfile', + dockerfile: resolve(configDir, 'container/Dockerfile'), + buildContext: resolve(configDir, 'container'), + buildVars: { BUN_VERSION: '1.4.2' } + } + }, + { + name: 'pinned', + tag: localContainerImageTag(configDir, 'Builder', 'pinned'), + source: { + kind: 'registry', + image: 'registry.cloudflare.com/acct/builder@sha256:abc' + } + } + ] + } + ]) + }) + + test('uses an explicit build context over the Dockerfile directory', () => { + const plan = planLocalDurableObjectContainers( + makeConfig({ + containers: [ + { + className: 'Builder', + schedulingPolicy: 'durable_object', + images: { base: { dockerfile: './container/Dockerfile', buildContext: '.' } } + } + ] + }), + configDir + ) + + expect(plan[0].images[0].source).toMatchObject({ buildContext: configDir }) + }) + + test('refuses two durable_object entries for one class', () => { + const config = makeConfig({ + containers: [ + { className: 'Builder', schedulingPolicy: 'durable_object' }, + { className: 'Builder', schedulingPolicy: 'durable_object' } + ] + }) + + expect(() => planLocalDurableObjectContainers(config, configDir)).toThrow( + 'more than one durable_object container entry' + ) + }) +}) + +describe('localContainerImageTag', () => { + test('is a lowercase Docker tag that differs by project, class and image', () => { + const tag = localContainerImageTag(configDir, 'My_Builder', 'Base Image') + + expect(tag).toMatch(/^devflare-dev\/my-builder-base-image:[a-f0-9]{12}$/) + expect(localContainerImageTag(resolve('/other'), 'My_Builder', 'Base Image')).not.toBe(tag) + expect(localContainerImageTag(configDir, 'Other', 'Base Image')).not.toBe(tag) + expect(localContainerImageTag(configDir, 'My_Builder', 'other')).not.toBe(tag) + expect(localContainerImageTag(configDir, 'My_Builder', 'Base Image')).toBe(tag) + }) +}) + +describe('toMiniflareContainerOption', () => { + test('maps each image name to its local tag, and an image-less container to {}', () => { + expect( + toMiniflareContainerOption({ + className: 'Builder', + images: [ + { + name: 'base', + tag: 'devflare-dev/builder-base:1', + source: { kind: 'registry', image: 'x' } + } + ] + }) + ).toEqual({ images: [{ name: 'base', image: 'devflare-dev/builder-base:1' }] }) + expect(toMiniflareContainerOption({ className: 'Sandbox', images: [] })).toEqual({}) + }) +}) + +describe('attachDurableObjectContainers', () => { + const containers = new Map([['Builder', { images: [{ name: 'base', image: 'tag:1' }] }]]) + + test('turns the container-backed namespace into a SQLite one carrying the container', () => { + const attached = attachDurableObjectContainers( + { BUILDER: 'Builder', COUNTER: 'Counter' }, + new Map([ + ['BUILDER', 'Builder'], + ['COUNTER', 'Counter'] + ]), + containers + ) + + expect(attached).toEqual({ + BUILDER: { + className: 'Builder', + useSQLite: true, + container: { images: [{ name: 'base', image: 'tag:1' }] } + }, + COUNTER: 'Counter' + }) + }) + + test('matches the configured class when the namespace runs a generated wrapper', () => { + const attached = attachDurableObjectContainers( + { BUILDER: '__DevflareBUILDERRpcWrapper' }, + new Map([['BUILDER', 'Builder']]), + containers + ) + + expect(attached.BUILDER).toMatchObject({ + className: '__DevflareBUILDERRpcWrapper', + container: { images: [{ name: 'base', image: 'tag:1' }] } + }) + }) + + test('refuses a container whose class no namespace serves', () => { + expect(() => + attachDurableObjectContainers( + { COUNTER: 'Counter' }, + new Map([['COUNTER', 'Counter']]), + containers + ) + ).toThrow('no Durable Object binding in this worker serves that class') + }) +}) + +describe('getDurableObjectBindingClassNames', () => { + test('reads string and object bindings', () => { + const names = getDurableObjectBindingClassNames( + makeConfig({ + bindings: { + durableObjects: { A: 'Alpha', B: { className: 'Beta', scriptName: 'beta.ts' } } + } + }) + ) + + expect([...names]).toEqual([ + ['A', 'Alpha'], + ['B', 'Beta'] + ]) + }) +}) + +describe('areLocalContainersDisabled', () => { + test.each([ + ['0', true], + ['false', true], + ['NO', true], + ['1', false], + [undefined, false] + ])('DEVFLARE_ENABLE_CONTAINERS=%p → %p', (value, expected) => { + expect(areLocalContainersDisabled({ DEVFLARE_ENABLE_CONTAINERS: value })).toBe(expected) + }) +}) + +describe('prepareLocalDurableObjectContainers', () => { + test('returns null and runs nothing when the config has no durable_object container', async () => { + const { runner, calls } = createRecordingRunner() + const prepared = await prepareLocalDurableObjectContainers({ + config: makeConfig({ containers: [{ className: 'Api', image: './Dockerfile' }] }), + configDir, + env: {}, + runner, + platform: 'linux' + }) + + expect(prepared).toBeNull() + expect(calls).toEqual([]) + }) + + test('returns null and runs nothing when DEVFLARE_ENABLE_CONTAINERS=0', async () => { + const { runner, calls } = createRecordingRunner() + const prepared = await prepareLocalDurableObjectContainers({ + config: makeConfig(), + configDir, + env: { DEVFLARE_ENABLE_CONTAINERS: '0' }, + runner, + platform: 'win32' + }) + + expect(prepared).toBeNull() + expect(calls).toEqual([]) + }) + + test('refuses Windows before touching the engine', async () => { + const { runner, calls } = createRecordingRunner() + + await expect( + prepareLocalDurableObjectContainers({ + config: makeConfig(), + configDir, + env: {}, + runner, + platform: 'win32' + }) + ).rejects.toThrow('cannot run on Windows') + expect(calls).toEqual([]) + }) + + test('refuses when no engine answers, naming the opt-out', async () => { + const { runner } = createRecordingRunner(() => ({ exitCode: 1, stderr: 'daemon down' })) + + await expect( + prepareLocalDurableObjectContainers({ + config: makeConfig(), + configDir, + env: {}, + runner, + platform: 'linux' + }) + ).rejects.toThrow('DEVFLARE_ENABLE_CONTAINERS=0') + }) + + test('builds Dockerfile images, pulls a missing registry image, pulls the egress image, and returns the options', async () => { + const pinned = 'registry.cloudflare.com/acct/builder@sha256:abc' + const { runner, calls } = createRecordingRunner((_command, args) => { + if (args[0] === 'image' && args[1] === 'inspect') return { exitCode: 1 } + if (args[0] === 'context') return { stdout: 'unix:///run/docker.sock\n' } + return {} + }) + + const prepared = await prepareLocalDurableObjectContainers({ + config: makeConfig(), + configDir, + env: {}, + engine: 'docker', + runner, + platform: 'linux' + }) + + const baseTag = localContainerImageTag(configDir, 'Builder', 'base') + const pinnedTag = localContainerImageTag(configDir, 'Builder', 'pinned') + expect(calls).toEqual([ + 'docker info', + [ + 'docker build --platform linux/amd64', + `-t ${baseTag}`, + `-f ${resolve(configDir, 'container/Dockerfile')}`, + '--build-arg BUN_VERSION=1.4.2', + resolve(configDir, 'container') + ].join(' '), + `docker image inspect ${pinned}`, + `docker pull --platform linux/amd64 ${pinned}`, + `docker tag ${pinned} ${pinnedTag}`, + `docker image inspect ${DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE}`, + `docker pull ${DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE}`, + 'docker context inspect --format {{.Endpoints.docker.Host}}' + ]) + expect(prepared?.engine).toBe('docker') + expect(prepared?.containerEngine).toEqual({ + localDocker: { socketPath: 'unix:///run/docker.sock' } + }) + expect([...(prepared?.containersByClassName ?? [])]).toEqual([ + [ + 'Builder', + { + images: [ + { name: 'base', image: baseTag }, + { name: 'pinned', image: pinnedTag } + ] + } + ] + ]) + }) + + test('reuses images already present and honours the egress image override', async () => { + const { runner, calls } = createRecordingRunner() + + await prepareLocalDurableObjectContainers({ + config: makeConfig({ + containers: [ + { + className: 'Builder', + schedulingPolicy: 'durable_object', + images: { pinned: { image: 'registry.cloudflare.com/acct/b@sha256:abc' } } + } + ] + }), + configDir, + env: { MINIFLARE_CONTAINER_EGRESS_IMAGE: 'local/egress:1', DOCKER_HOST: '/tmp/d.sock' }, + engine: 'docker', + runner, + platform: 'linux' + }) + + expect(calls.filter((call) => call.includes(' pull '))).toEqual([]) + expect(calls).toContain('docker image inspect local/egress:1') + }) + + test('names the image when a build fails', async () => { + const { runner } = createRecordingRunner((_command, args) => + args[0] === 'build' ? { exitCode: 1, stderr: 'no such file' } : {} + ) + + await expect( + prepareLocalDurableObjectContainers({ + config: makeConfig(), + configDir, + env: {}, + engine: 'docker', + runner, + platform: 'linux' + }) + ).rejects.toThrow('Could not build container image "base"') + }) +}) + +describe('resolveEngineSocket', () => { + test('prefers WRANGLER_DOCKER_HOST, then DOCKER_HOST, adding the unix scheme to a bare path', async () => { + const { runner, calls } = createRecordingRunner() + + expect( + await resolveEngineSocket('docker', runner, { + WRANGLER_DOCKER_HOST: '/a.sock', + DOCKER_HOST: 'unix:///b.sock' + }) + ).toBe('unix:///a.sock') + expect(await resolveEngineSocket('docker', runner, { DOCKER_HOST: 'unix:///b.sock' })).toBe( + 'unix:///b.sock' + ) + expect(calls).toEqual([]) + }) + + test("asks Podman for its remote socket and falls back to Docker's default", async () => { + const podman = createRecordingRunner(() => ({ stdout: '/run/user/1000/podman/podman.sock' })) + expect(await resolveEngineSocket('podman', podman.runner, {})).toBe( + 'unix:///run/user/1000/podman/podman.sock' + ) + expect(podman.calls).toEqual(['podman info --format {{.Host.RemoteSocket.Path}}']) + + const silent = createRecordingRunner(() => ({ exitCode: 1 })) + expect(await resolveEngineSocket('docker', silent.runner, {})).toBe( + 'unix:///var/run/docker.sock' + ) + }) +}) + +describe('DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE', () => { + test("matches the installed Miniflare's own default", () => { + const require = createRequire(import.meta.url) + const miniflareEntry = require.resolve('miniflare') + const source = readFileSync(miniflareEntry, 'utf8') + const match = /DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE = "([^"]+)"/.exec(source) + + expect(match?.[1]).toBe(DEFAULT_CONTAINER_EGRESS_INTERCEPTOR_IMAGE) + }) +}) From bcaa39c22e0ebcc65656cb8f3566448caca7e7a1 Mon Sep 17 00:00:00 2001 From: "Arthur @Refzlund" Date: Mon, 30 Nov 2026 04:22:50 +0100 Subject: [PATCH 2/8] test(containers): a positive enableInternet control, network-error assertions, and the Wrangler parity test in a serial lane Importing Wrangler in the unit lane left two other files holding a method-less Miniflare on Linux CI, so the parity test moves to the serial test-context lane. Co-Authored-By: Claude Opus 5.5 --- .../durable-object-container.test.ts | 34 ++++++++++++++++--- .../wrangler-container-shape.test.ts | 5 +++ 2 files changed, 35 insertions(+), 4 deletions(-) rename packages/devflare/tests/{unit/config => integration/test-context}/wrangler-container-shape.test.ts (94%) diff --git a/packages/devflare/tests/integration/test-context/durable-object-container.test.ts b/packages/devflare/tests/integration/test-context/durable-object-container.test.ts index b3509254..c953b288 100644 --- a/packages/devflare/tests/integration/test-context/durable-object-container.test.ts +++ b/packages/devflare/tests/integration/test-context/durable-object-container.test.ts @@ -91,7 +91,7 @@ export class Builder extends DurableObject { await container.interceptOutboundHttps('*', handler) } - container.start({ image: container.images.base, enableInternet: false }) + container.start({ image: container.images.base, enableInternet: mode === 'open' }) try { const port = container.getTcpPort(8080) const deadline = Date.now() + 120000 @@ -122,6 +122,7 @@ export class Builder extends DurableObject { const containerServerSource = String.raw` import http from 'node:http' import https from 'node:https' +import tls from 'node:tls' import { readFileSync } from 'node:fs' const CA_PATH = '/etc/cloudflare/certs/cloudflare-containers-ca.crt' @@ -131,8 +132,10 @@ function fetchOnce(target) { const url = new URL(target) const client = url.protocol === 'https:' ? https : http let ca + // Trust the intercept CA when it is mounted, beside the system roots, so a + // failure below is always the network's answer, never a missing file. if (url.protocol === 'https:') { - try { ca = readFileSync(CA_PATH) } catch (error) { resolve({ ok: false, error: 'no CA at ' + CA_PATH }) ; return } + try { ca = [...tls.rootCertificates, readFileSync(CA_PATH, 'utf8')] } catch { ca = undefined } } const request = client.get(url, { timeout: 8000, ca }, (response) => { let body = '' @@ -157,6 +160,14 @@ http.createServer(async (request, response) => { }).listen(8080, '0.0.0.0') ` +/** + * How a request the network refused reads from inside the container: a DNS + * lookup that fails or times out, or a connection nobody answers. Anything else + * (a TLS error, a crashed probe) would not prove the request was blocked. + */ +const NETWORK_REFUSAL = + /ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ETIMEDOUT|ENETUNREACH|EHOSTUNREACH|timed out/ + /** One probe result, as the container reports it. */ interface ProbeResult { /** The URL the container fetched. */ @@ -174,7 +185,7 @@ interface ProbeResult { /** The Durable Object stub the test drives. */ interface BuilderStub { images(): Promise> - probe(mode: 'none' | 'named' | 'catch-all', urls: string[]): Promise + probe(mode: 'open' | 'none' | 'named' | 'catch-all', urls: string[]): Promise } let projectDir = '' @@ -239,6 +250,17 @@ describe.skipIf(skipReason !== null)('durable_object container through createTes }) }) + test( + 'control: with enableInternet: true the same container reaches the Internet', + async () => { + const results = await builder('open').probe('open', ['http://example.com/']) + + console.log('[durable_object container] open:', JSON.stringify(results)) + expect(results[0]).toMatchObject({ ok: true, status: 200 }) + }, + CONTAINER_TEST_TIMEOUT_MS + ) + test( 'enableInternet: false holds: with no intercept, no request leaves the container', async () => { @@ -247,8 +269,10 @@ describe.skipIf(skipReason !== null)('durable_object container through createTes 'https://example.com/' ]) + console.log('[durable_object container] blocked:', JSON.stringify(results)) for (const result of results) { - expect(result).toMatchObject({ ok: false }) + expect(result.ok).toBe(false) + expect(result.error).toMatch(NETWORK_REFUSAL) } }, CONTAINER_TEST_TIMEOUT_MS @@ -273,7 +297,9 @@ describe.skipIf(skipReason !== null)('durable_object container through createTes status: 200, body: 'intercepted GET https://secure.devflare.test/b' }) + console.log('[durable_object container] named:', JSON.stringify(results)) expect(results[2]).toMatchObject({ ok: false }) + expect(results[2].error).toMatch(NETWORK_REFUSAL) }, CONTAINER_TEST_TIMEOUT_MS ) diff --git a/packages/devflare/tests/unit/config/wrangler-container-shape.test.ts b/packages/devflare/tests/integration/test-context/wrangler-container-shape.test.ts similarity index 94% rename from packages/devflare/tests/unit/config/wrangler-container-shape.test.ts rename to packages/devflare/tests/integration/test-context/wrangler-container-shape.test.ts index d305ae1d..785c56a2 100644 --- a/packages/devflare/tests/unit/config/wrangler-container-shape.test.ts +++ b/packages/devflare/tests/integration/test-context/wrangler-container-shape.test.ts @@ -2,6 +2,11 @@ // Wrangler accepts what devflare compiles for a durable_object container, and // maps it to the same Miniflare Durable Object options devflare's local runs use. // ============================================================================= +// → GOTCHA: this lives in a serial integration lane, not tests/unit, because +// importing Wrangler loads Miniflare through CommonJS. In the unit lane's one +// process that left other files' `await import('miniflare')` holding a +// method-less instance on Linux CI (`runtime.dispose is not a function`). +// // The oracle is the installed Wrangler itself: `unstable_readConfig` runs its // config validation (which rejects any field the durable_object policy does not // take), and `unstable_getMiniflareWorkerOptions` is how `wrangler dev` attaches From cc862968424f3ec748c4693c3551edbd14e875be Mon Sep 17 00:00:00 2001 From: "Arthur @Refzlund" Date: Mon, 30 Nov 2026 04:33:14 +0100 Subject: [PATCH 3/8] test(unit): the bootTestRuntime mocks forward to the real modules outside their own tests mock.module is process-global and the unit lane runs every file in one process in directory order. Adding test files on Linux put simple-context-runtime.test.ts before simple-context-multi-worker and local-secrets, which then built its FakeMiniflare (no dispose, fake getBindings). The mocks now fake only while that file's tests run. Co-Authored-By: Claude Opus 5.5 --- .../unit/test/simple-context-runtime.test.ts | 53 ++++++++++++++++--- 1 file changed, 46 insertions(+), 7 deletions(-) diff --git a/packages/devflare/tests/unit/test/simple-context-runtime.test.ts b/packages/devflare/tests/unit/test/simple-context-runtime.test.ts index 02bf54ba..7b5ab658 100644 --- a/packages/devflare/tests/unit/test/simple-context-runtime.test.ts +++ b/packages/devflare/tests/unit/test/simple-context-runtime.test.ts @@ -6,7 +6,25 @@ // `client` is preserved while the multi-worker path leaves it null. // ============================================================================= -import { describe, expect, mock, test } from 'bun:test' +import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test' + +// → GOTCHA: Bun's `mock.module()` is process-global and outlives this file. The +// unit lane runs every file in ONE process, in directory order, so a mock +// that only fakes would reach every file that runs after this one. That +// order is the filesystem's: adding unrelated test files on Linux put this +// file before simple-context-multi-worker and local-secrets, whose +// `new Miniflare()` then built the fake (`runtime.dispose is not a +// function`). So each mock below forwards to the real module unless this +// file's own tests are running. +let faking = false + +beforeAll(() => { + faking = true +}) + +afterAll(() => { + faking = false +}) // We mock the two collaborators via module patching at import time. const startBridgeBackedTestContextMock = mock(async (_mfConfig: any) => ({ @@ -18,11 +36,30 @@ const startBridgeBackedTestContextMock = mock(async (_mfConfig: any) => ({ const getAvailablePortMock = mock(async () => 5678) +// Loaded before the mocks are installed, so a forwarded call reaches the real +// export and the real v4→v5 option conversion (toMiniflareOptions) still runs +// on the boot path. +const realStartup = await import('../../../src/test/simple-context-startup') +const realPaths = await import('../../../src/test/simple-context-paths') +const realMiniflare = await import('miniflare') +// Held as values now: if Bun patches a module namespace in place, reading them +// through the namespace later would return the mocks and recurse. +const RealMiniflare = realMiniflare.Miniflare +const realStartBridgeBackedTestContext = realStartup.startBridgeBackedTestContext +const realGetAvailablePort = realPaths.getAvailablePort +const realResolveTransportFile = realPaths.resolveTransportFile + const miniflareCtorCalls: any[] = [] class FakeMiniflare { ready = Promise.resolve() private _port: number constructor(opts: any) { + if (!faking) { + // Outside this file's tests, construct the real thing; a constructor + // may return a different object. + // biome-ignore lint/correctness/noConstructorReturn: forwarding outside this file's tests + return new RealMiniflare(opts) as unknown as FakeMiniflare + } miniflareCtorCalls.push(opts) this._port = opts.port } @@ -32,17 +69,19 @@ class FakeMiniflare { } mock.module('../../../src/test/simple-context-startup', () => ({ - startBridgeBackedTestContext: startBridgeBackedTestContextMock + ...realStartup, + startBridgeBackedTestContext: (mfConfig: any) => + faking ? startBridgeBackedTestContextMock(mfConfig) : realStartBridgeBackedTestContext(mfConfig) })) mock.module('../../../src/test/simple-context-paths', () => ({ - getAvailablePort: getAvailablePortMock, - resolveTransportFile: () => null + ...realPaths, + getAvailablePort: () => (faking ? getAvailablePortMock() : realGetAvailablePort()), + resolveTransportFile: (...args: Parameters) => + faking ? null : realResolveTransportFile(...args) })) -// Loaded before the mock is installed: only the Miniflare class is faked, so the -// real v4→v5 option conversion (toMiniflareOptions) still runs on the boot path. -const realMiniflare = await import('miniflare') +// Only the Miniflare class is faked, and only while this file's tests run. mock.module('miniflare', () => ({ ...realMiniflare, Miniflare: FakeMiniflare From e679539907786a3a15bf0d744e1a8b5b960eaa84 Mon Sep 17 00:00:00 2001 From: "Arthur @Refzlund" Date: Mon, 30 Nov 2026 05:49:18 +0100 Subject: [PATCH 4/8] fix(containers): QA round 1 (1 red, 6 yellow): devflare dev is engine-tested, builds load into the engine's store - red: the devflare dev path had never run a real container and no test reached its wiring. A dev-server integration test now drives the same Durable Object through createDevServer, and the CI container job runs it. - docker builds pass Wrangler's --load and --provenance=false, so a buildx docker-container builder cannot keep the image out of the store. - Podman on macOS reads the machine's host-side socket. - a container class that failed to bundle names the bundle error; the workspace refusal runs before anything starts; the refusal for an unserved class no longer sends readers to another worker, and the docs say referenced workers' containers do not run locally. - the deprecation and 2026-12-31 claims name their sources. Co-Authored-By: Claude Opus 5.5 --- .../container-durable-object-scheduling.md | 13 +- .github/workflows/workspace-ci.yml | 10 +- .../docs/content/bindings/compact-guides-2.ts | 4 +- packages/devflare/LLM.md | 3 +- .../devflare/src/config/schema-runtime.ts | 2 +- .../src/dev-server/miniflare-dev-config.ts | 12 +- .../src/dev-server/workspace/prepare-app.ts | 4 +- .../src/test/durable-object-containers.ts | 25 ++- .../durable-object-container-dev.test.ts | 151 +++++++++++++ .../durable-object-container.fixture.ts | 210 ++++++++++++++++++ .../durable-object-container.test.ts | 181 ++------------- .../dev-server/miniflare-dev-config.test.ts | 19 +- .../test/durable-object-containers.test.ts | 14 +- 13 files changed, 464 insertions(+), 184 deletions(-) create mode 100644 packages/devflare/tests/integration/dev-server/durable-object-container-dev.test.ts create mode 100644 packages/devflare/tests/integration/helpers/durable-object-container.fixture.ts diff --git a/.changeset/container-durable-object-scheduling.md b/.changeset/container-durable-object-scheduling.md index 61736b7c..c9f9780b 100644 --- a/.changeset/container-durable-object-scheduling.md +++ b/.changeset/container-durable-object-scheduling.md @@ -3,9 +3,10 @@ --- Containers can use Cloudflare's `durable_object` scheduling policy, where the Durable Object picks -the image and instance size each time it calls `ctx.container.start()`. Cloudflare has deprecated -the `default` policy and stops updating the `Container` class from `@cloudflare/containers` after -2026-12-31, so this is the shape new containers should take. +the image and instance size each time it calls `ctx.container.start()`. Cloudflare's +scheduling-policy docs mark the `default` policy deprecated, and its 2026-09-30 announcement says +the `Container` class from `@cloudflare/containers` gets no updates after 2026-12-31, so this is the +shape new containers should take. ```ts containers: [ @@ -37,3 +38,9 @@ devflare refuses and points at WSL, as Wrangler does. `DEVFLARE_ENABLE_CONTAINER them, leaving `ctx.container` undefined. `devflare workspace dev` does not run them yet and refuses an app that declares one, and `containers.start()` refuses a `durable_object` entry, which only its Durable Object can start. + +**For TypeScript consumers:** a `containers` entry's type is now a union of the two policies' +shapes, so code that reads `config.containers[i].image` must first check `schedulingPolicy`. Only a +container on a Durable Object that +the worker under test or under `devflare dev` defines runs locally; one declared by a worker it only +references does not. diff --git a/.github/workflows/workspace-ci.yml b/.github/workflows/workspace-ci.yml index 8e7d596f..117a123d 100644 --- a/.github/workflows/workspace-ci.yml +++ b/.github/workflows/workspace-ci.yml @@ -82,7 +82,7 @@ jobs: run: bun run devflare:ci # Starts a real durable_object scheduling-policy container through - # createTestContext(): devflare builds the image, workerd drives it through + # createTestContext() and devflare dev: devflare builds the image, workerd drives it through # ctx.container, and the test checks enableInternet: false and the outbound # intercepts. The runner's Docker engine is what the validate lane lacks a # flag for, so it runs here alone, and a skip fails the job. @@ -124,7 +124,13 @@ jobs: shell: bash run: docker info --format '{{.ServerVersion}} {{.OperatingSystem}}' - - name: Run the durable_object container test + - name: Run the durable_object container test through createTestContext shell: bash working-directory: packages/devflare run: bun test tests/integration/test-context/durable-object-container.test.ts --max-concurrency=1 + + # devflare dev hosts the object in a worker of its own, so it is graded separately. + - name: Run the durable_object container test through devflare dev + shell: bash + working-directory: packages/devflare + run: bun test tests/integration/dev-server/durable-object-container-dev.test.ts --max-concurrency=1 diff --git a/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts b/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts index f9b559af..0f17daf8 100644 --- a/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts +++ b/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts @@ -400,6 +400,7 @@ test('creates an in-memory artifact repo', async () => { 'https://developers.cloudflare.com/containers/configuration/scheduling-policy/', 'https://developers.cloudflare.com/containers/api/durable-object-container/', 'https://developers.cloudflare.com/containers/platform-details/outbound-traffic/', + 'https://blog.cloudflare.com/faster-agent-sandboxes/', 'https://developers.cloudflare.com/workers/wrangler/configuration/#containers' ], compileTarget: 'Wrangler `containers`', @@ -484,7 +485,7 @@ test('container engine detection is explicit', async () => { id: 'container-durable-object-policy', title: 'Let the Durable Object choose the image: the durable_object scheduling policy', paragraphs: [ - "Cloudflare's `durable_object` scheduling policy (public beta) moves the image and instance size out of config and into `ctx.container.start()`. Cloudflare marks the older `default` policy deprecated and stops updating the `@cloudflare/containers` `Container` class after 2026-12-31, so new containers should use this one. The policy is immutable per application: moving an existing application means a new one.", + "Cloudflare's `durable_object` scheduling policy (public beta) moves the image and instance size out of config and into `ctx.container.start()`. Cloudflare's scheduling-policy page marks the older `default` policy deprecated, and its 2026-09-30 announcement says the `@cloudflare/containers` `Container` class gets no updates after 2026-12-31, so new containers should use this one. The policy is immutable per application: moving an existing application means a new one.", "Set `schedulingPolicy: 'durable_object'` and list the images the object may start under `images`. Each key becomes a property of `ctx.container.images`. Devflare compiles the entry to Wrangler's `class_name`, `scheduling_policy`, `name` and `images` and nothing else, because Wrangler rejects `image`, `instance_type`, `max_instances` and rollouts for this policy; the schema refuses them first.", "`devflare dev` and `createTestContext()` run it locally the way `wrangler dev` does: they build each Dockerfile image (or reuse or pull a registry image) with Docker or Podman for `linux/amd64`, pull Miniflare's egress interceptor image, and attach the container to the Durable Object in Miniflare. `ctx.container.start()`, `images`, `enableInternet` and the `interceptOutboundHttp()`, `interceptOutboundHttps()` and `interceptAllOutboundHttp()` rules then run against a real local container." ], @@ -557,6 +558,7 @@ export class Builder extends DurableObject { 'HTTPS interception needs the container to trust `/etc/cloudflare/certs/cloudflare-containers-ca.crt`.', "Local runs need Linux or macOS: workerd cannot reach a Windows named pipe, so on Windows devflare refuses and points at WSL, as Wrangler does. Set `DEVFLARE_ENABLE_CONTAINERS=0` to start without containers; `ctx.container` is then undefined. Devflare uses `WRANGLER_DOCKER_HOST` or `DOCKER_HOST` when set, then the engine's own socket.", '`devflare workspace dev` does not run durable_object containers yet and refuses an app that declares one; run `devflare dev` in that app. The `containers.start()` helper starts only `default`-policy containers.', + 'Only the worker under test or under `devflare dev` runs its containers. A container declared by a worker this one only references (through a service binding or a cross-worker Durable Object) does not run locally, so its `ctx.container` is undefined there.', 'Images are rebuilt each time the config loads; a change inside the container needs a restart.' ] }, diff --git a/packages/devflare/LLM.md b/packages/devflare/LLM.md index 2b92aacc..9bedd079 100644 --- a/packages/devflare/LLM.md +++ b/packages/devflare/LLM.md @@ -15988,7 +15988,7 @@ Use Cloudflare when the assertion depends on deployed limits, account state, lif #### Let the Durable Object choose the image: the durable_object scheduling policy -Cloudflare's `durable_object` scheduling policy (public beta) moves the image and instance size out of config and into `ctx.container.start()`. Cloudflare marks the older `default` policy deprecated and stops updating the `@cloudflare/containers` `Container` class after 2026-12-31, so new containers should use this one. The policy is immutable per application: moving an existing application means a new one. +Cloudflare's `durable_object` scheduling policy (public beta) moves the image and instance size out of config and into `ctx.container.start()`. Cloudflare's scheduling-policy page marks the older `default` policy deprecated, and its 2026-09-30 announcement says the `@cloudflare/containers` `Container` class gets no updates after 2026-12-31, so new containers should use this one. The policy is immutable per application: moving an existing application means a new one. Set `schedulingPolicy: 'durable_object'` and list the images the object may start under `images`. Each key becomes a property of `ctx.container.images`. Devflare compiles the entry to Wrangler's `class_name`, `scheduling_policy`, `name` and `images` and nothing else, because Wrangler rejects `image`, `instance_type`, `max_instances` and rollouts for this policy; the schema refuses them first. @@ -16002,6 +16002,7 @@ Set `schedulingPolicy: 'durable_object'` and list the images the object may star - HTTPS interception needs the container to trust `/etc/cloudflare/certs/cloudflare-containers-ca.crt`. - Local runs need Linux or macOS: workerd cannot reach a Windows named pipe, so on Windows devflare refuses and points at WSL, as Wrangler does. Set `DEVFLARE_ENABLE_CONTAINERS=0` to start without containers; `ctx.container` is then undefined. Devflare uses `WRANGLER_DOCKER_HOST` or `DOCKER_HOST` when set, then the engine's own socket. - `devflare workspace dev` does not run durable_object containers yet and refuses an app that declares one; run `devflare dev` in that app. The `containers.start()` helper starts only `default`-policy containers. +- Only the worker under test or under `devflare dev` runs its containers. A container declared by a worker this one only references (through a service binding or a cross-worker Durable Object) does not run locally, so its `ctx.container` is undefined there. - Images are rebuilt each time the config loads; a change inside the container needs a restart. ##### Example — Declare a Durable Object-managed container diff --git a/packages/devflare/src/config/schema-runtime.ts b/packages/devflare/src/config/schema-runtime.ts index dbdd86ba..f818ae3a 100644 --- a/packages/devflare/src/config/schema-runtime.ts +++ b/packages/devflare/src/config/schema-runtime.ts @@ -418,7 +418,7 @@ const MAX_DURABLE_OBJECT_CONTAINER_IMAGE_NAME_LENGTH = 128 /** * A Cloudflare Containers application under the `durable_object` scheduling - * policy (public beta since 2026-09-30). + * policy (a public beta, per Cloudflare's scheduling-policy docs). * * The Durable Object picks the image and instance size each time it calls * `ctx.container.start()`, so the Wrangler entry carries only the class, the diff --git a/packages/devflare/src/dev-server/miniflare-dev-config.ts b/packages/devflare/src/dev-server/miniflare-dev-config.ts index cc26e617..79a6bf46 100644 --- a/packages/devflare/src/dev-server/miniflare-dev-config.ts +++ b/packages/devflare/src/dev-server/miniflare-dev-config.ts @@ -438,7 +438,8 @@ function pickContainerFor( * * @param localContainers - The prepared containers. * @param doResult - The bundled Durable Objects. - * @throws When a container's class has no bundled Durable Object. + * @throws When a container's class has no bundled Durable Object, naming any + * bundle error that caused it. */ function assertEveryContainerHasAWorker( localContainers: PreparedLocalDurableObjectContainers, @@ -449,8 +450,15 @@ function assertEveryContainerHasAWorker( (className) => !bundledClasses.has(className) ) if (missing.length > 0) { + // A class whose module failed to bundle is missing too; name that cause + // first, or the message would send the reader looking at the config. + const bundleErrors = doResult?.errors.map((error) => error.message) ?? [] + const cause = + bundleErrors.length > 0 + ? ` Durable Object bundling failed: ${bundleErrors.join('; ')}` + : ' No Durable Object in files.durableObjects defines that class.' throw new Error( - `durable_object containers name ${missing.map((name) => `"${name}"`).join(', ')}, but no Durable Object in files.durableObjects defines that class.` + `durable_object containers name ${missing.map((name) => `"${name}"`).join(', ')}, but no bundled Durable Object serves it.${cause}` ) } } diff --git a/packages/devflare/src/dev-server/workspace/prepare-app.ts b/packages/devflare/src/dev-server/workspace/prepare-app.ts index e8e4fde3..ba6b541e 100644 --- a/packages/devflare/src/dev-server/workspace/prepare-app.ts +++ b/packages/devflare/src/dev-server/workspace/prepare-app.ts @@ -144,6 +144,8 @@ export async function prepareWorkspaceApp( const loaded = await loadConfig({ cwd: appCwd, configFile: configPath }) const config = await resolveDevConfig(loaded, { cwd: appCwd, configPath }) const appName = input.appName ?? config.name + // Refused before anything starts (shim, bundler), since it reads only the config. + assertNoLocalDurableObjectContainers(appName, config, appCwd) const serviceBindingResolution = config.bindings?.services ? await resolveServiceBindings(config, appCwd) : null @@ -228,8 +230,6 @@ export async function prepareWorkspaceApp( await browserShim.start() } - assertNoLocalDurableObjectContainers(appName, config, appCwd) - // --- build this app's worker set (reused verbatim) ------------------------ const built = buildMiniflareDevConfig({ config, diff --git a/packages/devflare/src/test/durable-object-containers.ts b/packages/devflare/src/test/durable-object-containers.ts index d8d70b96..b1db103a 100644 --- a/packages/devflare/src/test/durable-object-containers.ts +++ b/packages/devflare/src/test/durable-object-containers.ts @@ -319,7 +319,9 @@ export async function prepareLocalDurableObjectContainers( return { engine, containerEngine: { - localDocker: { socketPath: await resolveEngineSocket(engine, runner, env) } + localDocker: { + socketPath: await resolveEngineSocket(engine, runner, env, options.platform) + } }, containersByClassName: new Map( plan.map((container) => [container.className, toMiniflareContainerOption(container)]) @@ -351,6 +353,10 @@ async function prepareImage( engine, [ 'build', + // Wrangler's own flags: `--load` puts the image in the engine's store + // even under a buildx `docker-container` builder, which otherwise + // keeps it in the build cache where workerd cannot start it. + ...(engine === 'docker' ? ['--load', '--provenance=false'] : []), '--platform', CONTAINER_PLATFORM, '-t', @@ -414,17 +420,24 @@ async function ensureEgressInterceptorImage( /** * Find the engine's API socket for workerd, in Wrangler's order: an explicit * `WRANGLER_DOCKER_HOST` or `DOCKER_HOST`, then the engine's own answer - * (Docker's current context, Podman's remote socket), then Docker's default. + * (Docker's current context; Podman's host-side socket), then Docker's default. + * + * → GOTCHA: on macOS Podman runs in a VM, and `podman info` reports the + * socket's path inside it, which the host cannot open; the machine's + * connection info names the host-side socket. Neither Podman branch has run + * against a real Podman; only Docker on Linux is engine-tested. * * @param engine - The engine that answered. * @param runner - Command runner. * @param env - Process environment. + * @param platform - Host platform. @default process.platform * @returns A socket URL such as `unix:///var/run/docker.sock`. */ export async function resolveEngineSocket( engine: ContainerEngineName, runner: ContainerCommandRunner, - env: Record + env: Record, + platform: NodeJS.Platform = process.platform ): Promise { const explicit = env.WRANGLER_DOCKER_HOST ?? env.DOCKER_HOST if (explicit) { @@ -434,7 +447,9 @@ export async function resolveEngineSocket( const query = engine === 'docker' ? ['context', 'inspect', '--format', '{{.Endpoints.docker.Host}}'] - : ['info', '--format', '{{.Host.RemoteSocket.Path}}'] + : platform === 'darwin' + ? ['machine', 'inspect', '--format', '{{.ConnectionInfo.PodmanSocket.Path}}'] + : ['info', '--format', '{{.Host.RemoteSocket.Path}}'] const answer = await runner.exec(engine, query) const socket = answer.exitCode === 0 ? answer.stdout.trim() : '' @@ -530,7 +545,7 @@ export function attachDurableObjectContainers( ) if (unattached.length > 0) { throw new Error( - `durable_object containers name ${unattached.map((name) => `"${name}"`).join(', ')}, but no Durable Object binding in this worker serves that class. Add a bindings.durableObjects entry for it; a container attached to another worker's class runs with that worker.` + `durable_object containers name ${unattached.map((name) => `"${name}"`).join(', ')}, but no Durable Object binding in this worker serves that class. Add a bindings.durableObjects entry for that class to this config. A container on a Durable Object that another worker defines is not run locally.` ) } diff --git a/packages/devflare/tests/integration/dev-server/durable-object-container-dev.test.ts b/packages/devflare/tests/integration/dev-server/durable-object-container-dev.test.ts new file mode 100644 index 00000000..b5e3049d --- /dev/null +++ b/packages/devflare/tests/integration/dev-server/durable-object-container-dev.test.ts @@ -0,0 +1,151 @@ +// ============================================================================= +// A durable_object scheduling-policy container under `devflare dev` +// ============================================================================= +// The dev server hosts each Durable Object in a worker of its own +// (`do-`), bundles its module with the dev Durable Object transform, +// and reaches it from the gateway through `scriptName`. That is a different +// shape from createTestContext(), so it is graded on its own: the same +// container, started from the same Durable Object, must see its intercepts +// reach the `WorkerEntrypoint` its module exports, and nothing else leave. +// +// → Needs DEVFLARE_CONTAINER_TESTS=1, a reachable engine, and Linux or macOS; +// see the fixture's resolveContainerTestSkipReason(). +// ============================================================================= + +import { afterAll, beforeAll, describe, expect, test } from 'bun:test' +import { join } from 'pathe' +import { createDevServer, type DevServer } from '../../../src/dev-server' +import { localContainerImageTag } from '../../../src/test/durable-object-containers' +import { cleanupTempDirs, getAvailablePort } from '../helpers/built-devflare.helpers' +import { + builderContainerConfig, + CONTAINER_TEST_TIMEOUT_MS, + durableObjectModuleSource, + NETWORK_REFUSAL, + type ProbeResult, + resolveContainerTestSkipReason, + writeContainerImage +} from '../helpers/durable-object-container.fixture' +import { createProject } from './worker-only-multi-surface.helpers' + +const skipReason = await resolveContainerTestSkipReason() +const tempDirs: string[] = [] + +/** + * The Durable Object's fetch entry: `/images` answers `ctx.container.images`, + * and `/probe?mode=…&url=…` runs one probe. + */ +const builderFetchSource = String.raw` + async fetch({ request }) { + const url = new URL(request.url) + if (url.pathname === '/images') return Response.json(this.images()) + return Response.json(await this.probe(url.searchParams.get('mode'), url.searchParams.getAll('url'))) + } +` + +describe.skipIf(skipReason !== null)('durable_object container under devflare dev', () => { + let projectDir = '' + let devServer: DevServer | null = null + let workerUrl = '' + + beforeAll(async () => { + if (skipReason !== null) return + const port = await getAvailablePort() + workerUrl = `http://127.0.0.1:${port}` + projectDir = await createProject(tempDirs, { + prefix: 'devflare-do-container-dev-', + config: `export default ${JSON.stringify( + { + name: 'durable-object-container-dev', + compatibilityDate: '2026-09-29', + files: { fetch: 'src/fetch.ts', durableObjects: 'src/do/*.ts' }, + bindings: { durableObjects: { BUILDER: 'Builder' } }, + ...builderContainerConfig + }, + null, + '\t' + )}`, + files: { + 'src/fetch.ts': String.raw` +export async function fetch({ request, env }) { + const url = new URL(request.url) + const name = url.searchParams.get('mode') ?? 'images' + return env.BUILDER.get(env.BUILDER.idFromName(name)).fetch(request) +} +`.trim(), + 'src/do/builder.ts': durableObjectModuleSource(builderFetchSource) + } + }) + await writeContainerImage(projectDir) + + devServer = createDevServer({ + cwd: projectDir, + miniflarePort: port, + enableVite: false, + persist: false + }) + await devServer.start() + }, CONTAINER_TEST_TIMEOUT_MS) + + afterAll(async () => { + if (devServer) await devServer.stop() + await cleanupTempDirs(tempDirs) + }, CONTAINER_TEST_TIMEOUT_MS) + + /** Run one probe through the dev server's gateway. */ + async function probe(mode: string, urls: string[]): Promise { + const query = new URLSearchParams({ mode }) + for (const url of urls) query.append('url', url) + const response = await fetch(`${workerUrl}/probe?${query}`) + expect(response.status).toBe(200) + return (await response.json()) as ProbeResult[] + } + + test('ctx.container.images names the image the dev server built', async () => { + const response = await fetch(`${workerUrl}/images`) + + expect(await response.json()).toEqual({ + base: localContainerImageTag(projectDir, 'Builder', 'base') + }) + }) + + test( + 'intercepts reach the module WorkerEntrypoint; enableInternet: false blocks the rest', + async () => { + const results = await probe('named', [ + 'http://named.devflare.test/a', + 'https://secure.devflare.test/b', + 'http://example.com/' + ]) + + console.log('[durable_object container, dev] named:', JSON.stringify(results)) + expect(results[0]).toMatchObject({ + ok: true, + body: 'intercepted GET http://named.devflare.test/a' + }) + expect(results[1]).toMatchObject({ + ok: true, + body: 'intercepted GET https://secure.devflare.test/b' + }) + expect(results[2].ok).toBe(false) + expect(results[2].error).toMatch(NETWORK_REFUSAL) + }, + CONTAINER_TEST_TIMEOUT_MS + ) + + test( + 'the catch-all intercepts reach the module WorkerEntrypoint', + async () => { + const results = await probe('catch-all', [ + 'http://anything.example/c', + 'https://anything.example/d' + ]) + + expect(results.map((result) => result.body)).toEqual([ + 'intercepted GET http://anything.example/c', + 'intercepted GET https://anything.example/d' + ]) + }, + CONTAINER_TEST_TIMEOUT_MS + ) +}) diff --git a/packages/devflare/tests/integration/helpers/durable-object-container.fixture.ts b/packages/devflare/tests/integration/helpers/durable-object-container.fixture.ts new file mode 100644 index 00000000..1c96de9a --- /dev/null +++ b/packages/devflare/tests/integration/helpers/durable-object-container.fixture.ts @@ -0,0 +1,210 @@ +// ============================================================================= +// Shared fixture for the durable_object container integration tests +// ============================================================================= +// One Durable Object, `Builder`, starts a Node container under a chosen intercept +// set and asks it to fetch URLs; `OutboundHandler` is the intercept target. The +// test-context test drives it over RPC and the dev-server test over fetch, so +// both read the same container behaviour. +// ============================================================================= + +import { mkdir, writeFile } from 'node:fs/promises' +import { join } from 'pathe' +import { getContainerSkipReason } from '../../../src/test' + +/** Building the image and starting the container can take minutes on a cold runner. */ +export const CONTAINER_TEST_TIMEOUT_MS = 300_000 + +/** + * Why the engine-backed tests cannot run here, or `null` when they can. + * + * @returns The reason, for `describe.skipIf`. + * @throws When `DEVFLARE_CONTAINER_TESTS_REQUIRED=1` and they cannot run: the + * CI lane that exists to run them sets it, so a missing engine fails that + * lane instead of reading as a green skip. + */ +export async function resolveContainerTestSkipReason(): Promise { + const engine = + (process.env.DEVFLARE_CONTAINER_ENGINE as 'docker' | 'podman' | undefined) ?? 'auto' + const reason = + process.platform === 'win32' + ? 'workerd cannot reach a container engine on Windows; run this inside WSL.' + : await getContainerSkipReason({ engine }) + + if (reason && process.env.DEVFLARE_CONTAINER_TESTS_REQUIRED === '1') { + throw new Error(`durable_object container test is required but cannot run: ${reason}`) + } + if (reason) { + console.warn(`[devflare] skipping durable_object container integration test: ${reason}`) + } + return reason +} + +/** The `containers` entry and migration both fixtures declare. */ +export const builderContainerConfig = { + containers: [ + { + className: 'Builder', + schedulingPolicy: 'durable_object', + images: { base: { dockerfile: './container/Dockerfile' } } + } + ], + migrations: [{ tag: 'v1', new_sqlite_classes: ['Builder'] }] +} as const + +/** The intercept target: answers with what it received. */ +const outboundHandlerSource = String.raw` +export class OutboundHandler extends WorkerEntrypoint { + fetch(request) { + const url = new URL(request.url) + return new Response('intercepted ' + request.method + ' ' + url.protocol + '//' + url.host + url.pathname) + } +} +` + +/** + * The `images()` and `probe(mode, urls)` methods. `probe` registers one + * intercept set, starts the container (with the Internet on only for `open`), + * asks it to fetch each URL, and destroys it. + */ +const builderMethodsSource = String.raw` + images() { + return { ...this.ctx.container.images } + } + + async probe(mode, urls) { + const container = this.ctx.container + const handler = this.ctx.exports.OutboundHandler + if (mode === 'named') { + await container.interceptOutboundHttp('named.devflare.test', handler) + await container.interceptOutboundHttps('secure.devflare.test', handler) + } + if (mode === 'catch-all') { + await container.interceptAllOutboundHttp(handler) + await container.interceptOutboundHttps('*', handler) + } + + container.start({ image: container.images.base, enableInternet: mode === 'open' }) + try { + const port = container.getTcpPort(8080) + const deadline = Date.now() + 120000 + for (;;) { + try { + const health = await port.fetch('http://container/health') + if (health.ok) break + } catch (error) { + if (Date.now() > deadline) throw error + } + await new Promise((resolve) => setTimeout(resolve, 250)) + } + + const results = [] + for (const url of urls) { + const response = await port.fetch('http://container/probe?url=' + encodeURIComponent(url)) + results.push({ url, ...(await response.json()) }) + } + return results + } finally { + await container.destroy() + } + }` + +/** + * The Durable Object module. + * + * @param extraMethods - Methods added to `Builder`, such as a fetch entry. + * @returns Source for `cloudflare:workers` with both classes exported. + */ +export function durableObjectModuleSource(extraMethods = ''): string { + return [ + "import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers'", + outboundHandlerSource, + 'export class Builder extends DurableObject {', + builderMethodsSource, + extraMethods, + '}', + '' + ].join('\n') +} + +/** A Node server inside the container that fetches a URL on request. */ +const containerServerSource = String.raw` +import http from 'node:http' +import https from 'node:https' +import tls from 'node:tls' +import { readFileSync } from 'node:fs' + +const CA_PATH = '/etc/cloudflare/certs/cloudflare-containers-ca.crt' + +function fetchOnce(target) { + return new Promise((resolve) => { + const url = new URL(target) + const client = url.protocol === 'https:' ? https : http + let ca + // Trust the intercept CA when it is mounted, beside the system roots, so a + // failure below is always the network's answer, never a missing file. + if (url.protocol === 'https:') { + try { ca = [...tls.rootCertificates, readFileSync(CA_PATH, 'utf8')] } catch { ca = undefined } + } + const request = client.get(url, { timeout: 8000, ca }, (response) => { + let body = '' + response.setEncoding('utf8') + response.on('data', (chunk) => { body += chunk }) + response.on('end', () => resolve({ ok: true, status: response.statusCode, body })) + }) + request.on('timeout', () => request.destroy(new Error('timed out'))) + request.on('error', (error) => resolve({ ok: false, error: String(error.code ?? error.message) })) + }) +} + +http.createServer(async (request, response) => { + const url = new URL(request.url, 'http://localhost') + if (url.pathname === '/health') { + response.end('ok') + return + } + const result = await fetchOnce(url.searchParams.get('url')) + response.setHeader('content-type', 'application/json') + response.end(JSON.stringify(result)) +}).listen(8080, '0.0.0.0') +` + +/** + * Write the container image's files into `/container`. + * + * @param projectDir - The fixture project. + */ +export async function writeContainerImage(projectDir: string): Promise { + await mkdir(join(projectDir, 'container'), { recursive: true }) + await writeFile(join(projectDir, 'container', 'server.mjs'), containerServerSource) + await writeFile( + join(projectDir, 'container', 'Dockerfile'), + [ + 'FROM node:22-alpine', + 'COPY server.mjs /app/server.mjs', + 'CMD ["node", "/app/server.mjs"]', + '' + ].join('\n') + ) +} + +/** + * How a request the network refused reads from inside the container: a DNS + * lookup that fails or times out, or a connection nobody answers. Anything else + * (a TLS error, a crashed probe) would not prove the request was blocked. + */ +export const NETWORK_REFUSAL = + /ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ETIMEDOUT|ENETUNREACH|EHOSTUNREACH|timed out/ + +/** One probe result, as the container reports it. */ +export interface ProbeResult { + /** The URL the container fetched. */ + url: string + /** Whether a response came back at all. */ + ok: boolean + /** Its status, when one came back. */ + status?: number + /** Its body, when one came back. */ + body?: string + /** Why nothing came back. */ + error?: string +} diff --git a/packages/devflare/tests/integration/test-context/durable-object-container.test.ts b/packages/devflare/tests/integration/test-context/durable-object-container.test.ts index c953b288..8a6eeab8 100644 --- a/packages/devflare/tests/integration/test-context/durable-object-container.test.ts +++ b/packages/devflare/tests/integration/test-context/durable-object-container.test.ts @@ -7,6 +7,7 @@ // and attaches it to the Durable Object in Miniflare, and the object drives the // container through `ctx.container` — `images`, `start({ enableInternet: false })`, // and the outbound intercepts, which must reach the Worker's `WorkerEntrypoint`. +// The `devflare dev` path is graded by dev-server/durable-object-container-dev.test.ts. // // → Needs DEVFLARE_CONTAINER_TESTS=1, a reachable engine, Linux or macOS (workerd // cannot reach a Windows named pipe), and network access to build the image @@ -22,26 +23,19 @@ import { env } from '../../../src' import { compileConfig } from '../../../src/config/compiler' import { brandAsLocalConfig } from '../../../src/config/resolve-phased' import { configSchema, type DevflareConfig } from '../../../src/config/schema' -import { createTestContext, getContainerSkipReason } from '../../../src/test' +import { createTestContext } from '../../../src/test' import { localContainerImageTag } from '../../../src/test/durable-object-containers' - -/** Building the image and starting the container can take minutes on a cold runner. */ -const CONTAINER_TEST_TIMEOUT_MS = 300_000 - -const engine = (process.env.DEVFLARE_CONTAINER_ENGINE as 'docker' | 'podman' | undefined) ?? 'auto' -const skipReason = - process.platform === 'win32' - ? 'workerd cannot reach a container engine on Windows; run this inside WSL.' - : await getContainerSkipReason({ engine }) - -if (skipReason && process.env.DEVFLARE_CONTAINER_TESTS_REQUIRED === '1') { - // The CI lane that exists to run this test sets the flag, so a missing - // engine there fails the lane instead of reading as a green skip. - throw new Error(`durable_object container test is required but cannot run: ${skipReason}`) -} -if (skipReason) { - console.warn(`[devflare] skipping durable_object container integration test: ${skipReason}`) -} +import { + builderContainerConfig, + CONTAINER_TEST_TIMEOUT_MS, + durableObjectModuleSource, + NETWORK_REFUSAL, + type ProbeResult, + resolveContainerTestSkipReason, + writeContainerImage +} from '../helpers/durable-object-container.fixture' + +const skipReason = await resolveContainerTestSkipReason() /** The devflare config the fixture project carries, as a plain object. */ const projectConfig = { @@ -49,137 +43,7 @@ const projectConfig = { compatibilityDate: '2026-09-29', files: { durableObjects: 'src/do.*.ts' }, bindings: { durableObjects: { BUILDER: 'Builder' } }, - containers: [ - { - className: 'Builder', - schedulingPolicy: 'durable_object', - images: { base: { dockerfile: './container/Dockerfile' } } - } - ], - migrations: [{ tag: 'v1', new_sqlite_classes: ['Builder'] }] -} as const - -/** - * The Durable Object and its outbound handler. `probe` starts a container - * under one intercept set, asks it to fetch each URL, and reports what the - * container saw. - */ -const durableObjectSource = String.raw` -import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers' - -export class OutboundHandler extends WorkerEntrypoint { - fetch(request) { - const url = new URL(request.url) - return new Response('intercepted ' + request.method + ' ' + url.protocol + '//' + url.host + url.pathname) - } -} - -export class Builder extends DurableObject { - images() { - return { ...this.ctx.container.images } - } - - async probe(mode, urls) { - const container = this.ctx.container - const handler = this.ctx.exports.OutboundHandler - if (mode === 'named') { - await container.interceptOutboundHttp('named.devflare.test', handler) - await container.interceptOutboundHttps('secure.devflare.test', handler) - } - if (mode === 'catch-all') { - await container.interceptAllOutboundHttp(handler) - await container.interceptOutboundHttps('*', handler) - } - - container.start({ image: container.images.base, enableInternet: mode === 'open' }) - try { - const port = container.getTcpPort(8080) - const deadline = Date.now() + 120000 - for (;;) { - try { - const health = await port.fetch('http://container/health') - if (health.ok) break - } catch (error) { - if (Date.now() > deadline) throw error - } - await new Promise((resolve) => setTimeout(resolve, 250)) - } - - const results = [] - for (const url of urls) { - const response = await port.fetch('http://container/probe?url=' + encodeURIComponent(url)) - results.push({ url, ...(await response.json()) }) - } - return results - } finally { - await container.destroy() - } - } -} -` - -/** A Node server inside the container that fetches a URL on request. */ -const containerServerSource = String.raw` -import http from 'node:http' -import https from 'node:https' -import tls from 'node:tls' -import { readFileSync } from 'node:fs' - -const CA_PATH = '/etc/cloudflare/certs/cloudflare-containers-ca.crt' - -function fetchOnce(target) { - return new Promise((resolve) => { - const url = new URL(target) - const client = url.protocol === 'https:' ? https : http - let ca - // Trust the intercept CA when it is mounted, beside the system roots, so a - // failure below is always the network's answer, never a missing file. - if (url.protocol === 'https:') { - try { ca = [...tls.rootCertificates, readFileSync(CA_PATH, 'utf8')] } catch { ca = undefined } - } - const request = client.get(url, { timeout: 8000, ca }, (response) => { - let body = '' - response.setEncoding('utf8') - response.on('data', (chunk) => { body += chunk }) - response.on('end', () => resolve({ ok: true, status: response.statusCode, body })) - }) - request.on('timeout', () => request.destroy(new Error('timed out'))) - request.on('error', (error) => resolve({ ok: false, error: String(error.code ?? error.message) })) - }) -} - -http.createServer(async (request, response) => { - const url = new URL(request.url, 'http://localhost') - if (url.pathname === '/health') { - response.end('ok') - return - } - const result = await fetchOnce(url.searchParams.get('url')) - response.setHeader('content-type', 'application/json') - response.end(JSON.stringify(result)) -}).listen(8080, '0.0.0.0') -` - -/** - * How a request the network refused reads from inside the container: a DNS - * lookup that fails or times out, or a connection nobody answers. Anything else - * (a TLS error, a crashed probe) would not prove the request was blocked. - */ -const NETWORK_REFUSAL = - /ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ETIMEDOUT|ENETUNREACH|EHOSTUNREACH|timed out/ - -/** One probe result, as the container reports it. */ -interface ProbeResult { - /** The URL the container fetched. */ - url: string - /** Whether a response came back at all. */ - ok: boolean - /** Its status, when one came back. */ - status?: number - /** Its body, when one came back. */ - body?: string - /** Why nothing came back. */ - error?: string + ...builderContainerConfig } /** The Durable Object stub the test drives. */ @@ -194,22 +58,13 @@ let projectDir = '' async function writeProject(): Promise { const dir = await mkdtemp(join(tmpdir(), 'devflare-do-container-')) await mkdir(join(dir, 'src'), { recursive: true }) - await mkdir(join(dir, 'container'), { recursive: true }) await writeFile( join(dir, 'devflare.config.ts'), - `export default ${JSON.stringify(projectConfig, null, '\t')}\n` - ) - await writeFile(join(dir, 'src', 'do.builder.ts'), durableObjectSource) - await writeFile(join(dir, 'container', 'server.mjs'), containerServerSource) - await writeFile( - join(dir, 'container', 'Dockerfile'), - [ - 'FROM node:22-alpine', - 'COPY server.mjs /app/server.mjs', - 'CMD ["node", "/app/server.mjs"]', - '' - ].join('\n') + `export default ${JSON.stringify(projectConfig, null, ' ')} +` ) + await writeFile(join(dir, 'src', 'do.builder.ts'), durableObjectModuleSource()) + await writeContainerImage(dir) return dir } diff --git a/packages/devflare/tests/unit/dev-server/miniflare-dev-config.test.ts b/packages/devflare/tests/unit/dev-server/miniflare-dev-config.test.ts index 707742aa..6c00e4df 100644 --- a/packages/devflare/tests/unit/dev-server/miniflare-dev-config.test.ts +++ b/packages/devflare/tests/unit/dev-server/miniflare-dev-config.test.ts @@ -240,6 +240,23 @@ describe('buildMiniflareDevConfig', () => { }) }) + test('names the bundle error when the container class failed to bundle', () => { + expect(() => + buildMiniflareDevConfig( + buildBaseInput({ + config: { name: 'site-worker' }, + doResult: { + ...doResult, + bundles: new Map(), + classes: new Map(), + errors: [new Error('src/do/builder.ts: Unexpected token')] + }, + localContainers + }) + ) + ).toThrow('Durable Object bundling failed: src/do/builder.ts: Unexpected token') + }) + test('leaves every Durable Object and the engine untouched without prepared containers', () => { const mfConfig = buildMiniflareDevConfig( buildBaseInput({ config: { name: 'site-worker' }, doResult }) @@ -261,7 +278,7 @@ describe('buildMiniflareDevConfig', () => { localContainers }) ) - ).toThrow('no Durable Object in files.durableObjects defines that class') + ).toThrow('No Durable Object in files.durableObjects defines that class') }) }) }) diff --git a/packages/devflare/tests/unit/test/durable-object-containers.test.ts b/packages/devflare/tests/unit/test/durable-object-containers.test.ts index 7fdc92ab..c6ab0d88 100644 --- a/packages/devflare/tests/unit/test/durable-object-containers.test.ts +++ b/packages/devflare/tests/unit/test/durable-object-containers.test.ts @@ -313,7 +313,7 @@ describe('prepareLocalDurableObjectContainers', () => { expect(calls).toEqual([ 'docker info', [ - 'docker build --platform linux/amd64', + 'docker build --load --provenance=false --platform linux/amd64', `-t ${baseTag}`, `-f ${resolve(configDir, 'container/Dockerfile')}`, '--build-arg BUN_VERSION=1.4.2', @@ -401,13 +401,21 @@ describe('resolveEngineSocket', () => { expect(calls).toEqual([]) }) - test("asks Podman for its remote socket and falls back to Docker's default", async () => { + test("asks Podman for its host-side socket, per platform, and falls back to Docker's default", async () => { const podman = createRecordingRunner(() => ({ stdout: '/run/user/1000/podman/podman.sock' })) - expect(await resolveEngineSocket('podman', podman.runner, {})).toBe( + expect(await resolveEngineSocket('podman', podman.runner, {}, 'linux')).toBe( 'unix:///run/user/1000/podman/podman.sock' ) expect(podman.calls).toEqual(['podman info --format {{.Host.RemoteSocket.Path}}']) + const machine = createRecordingRunner(() => ({ stdout: '/Users/me/podman.sock\n' })) + expect(await resolveEngineSocket('podman', machine.runner, {}, 'darwin')).toBe( + 'unix:///Users/me/podman.sock' + ) + expect(machine.calls).toEqual([ + 'podman machine inspect --format {{.ConnectionInfo.PodmanSocket.Path}}' + ]) + const silent = createRecordingRunner(() => ({ exitCode: 1 })) expect(await resolveEngineSocket('docker', silent.runner, {})).toBe( 'unix:///var/run/docker.sock' From bfe890f3ccfd1da5a583564b924a35b9629dfc19 Mon Sep 17 00:00:00 2001 From: "Arthur @Refzlund" Date: Mon, 30 Nov 2026 10:00:20 +0100 Subject: [PATCH 5/8] feat(containers): run a referenced worker's durable_object containers locally A config that reaches a container only through a worker it references (a ref() service binding, or a cross-worker Durable Object binding to its class) now gets that worker's containers in createTestContext() and devflare dev: devflare builds the images from the referenced config, attaches them where it hosts that worker's Durable Objects, and exports the WorkerEntrypoint classes their modules declare so an intercept can target ctx.exports. workspace dev refuses such an app, and the Vite plugin leaves them out, as documented. Graded end to end by three new container-lane integration tests (service binding, cross-worker DO ref, devflare dev) and by unit tests of the refuse, ignore and turned-off modes. Co-Authored-By: Claude Opus 5.5 --- .../container-durable-object-scheduling.md | 14 +- .github/workflows/workspace-ci.yml | 18 ++ .../docs/content/bindings/compact-guides-2.ts | 3 +- docs/CLOUDFLARE_SUPPORT_MATRIX.md | 7 +- packages/devflare/LLM.md | 3 +- .../src/dev-server/miniflare-dev-config.ts | 5 +- packages/devflare/src/dev-server/server.ts | 7 +- .../src/dev-server/workspace/prepare-app.ts | 7 +- .../src/test/durable-object-containers.ts | 20 +- .../src/test/resolve-service-bindings.ts | 234 +++++++++++++-- .../test/simple-context-durable-objects.ts | 13 +- packages/devflare/src/test/simple-context.ts | 19 +- ...enced-durable-object-container-dev.test.ts | 121 ++++++++ .../durable-object-container.fixture.ts | 71 +++++ ...ed-durable-object-container-do-ref.test.ts | 115 ++++++++ ...eferenced-durable-object-container.test.ts | 127 ++++++++ ...ferenced-durable-object-containers.test.ts | 271 ++++++++++++++++++ 17 files changed, 995 insertions(+), 60 deletions(-) create mode 100644 packages/devflare/tests/integration/dev-server/referenced-durable-object-container-dev.test.ts create mode 100644 packages/devflare/tests/integration/test-context/referenced-durable-object-container-do-ref.test.ts create mode 100644 packages/devflare/tests/integration/test-context/referenced-durable-object-container.test.ts create mode 100644 packages/devflare/tests/unit/test/referenced-durable-object-containers.test.ts diff --git a/.changeset/container-durable-object-scheduling.md b/.changeset/container-durable-object-scheduling.md index c9f9780b..b1d2fed9 100644 --- a/.changeset/container-durable-object-scheduling.md +++ b/.changeset/container-durable-object-scheduling.md @@ -39,8 +39,14 @@ them, leaving `ctx.container` undefined. `devflare workspace dev` does not run t an app that declares one, and `containers.start()` refuses a `durable_object` entry, which only its Durable Object can start. +**A worker that is only referenced runs its containers too.** When the config under test or under +`devflare dev` reaches a worker through a `ref()` service binding, or binds a Durable Object class of +another worker, that worker's `durable_object` containers are built from its own config and attached +where devflare hosts its Durable Objects, with the intercept targets its modules export. So a test +can drive a container through the service binding that production uses. A config that references +such a worker now needs an engine in those runs (or `DEVFLARE_ENABLE_CONTAINERS=0`), even when it +declares no container itself. `devflare workspace dev` refuses an app that references one, and the +Vite plugin leaves a referenced worker's containers out, so `ctx.container` is undefined there. + **For TypeScript consumers:** a `containers` entry's type is now a union of the two policies' -shapes, so code that reads `config.containers[i].image` must first check `schedulingPolicy`. Only a -container on a Durable Object that -the worker under test or under `devflare dev` defines runs locally; one declared by a worker it only -references does not. +shapes, so code that reads `config.containers[i].image` must first check `schedulingPolicy`. diff --git a/.github/workflows/workspace-ci.yml b/.github/workflows/workspace-ci.yml index 117a123d..f9810d88 100644 --- a/.github/workflows/workspace-ci.yml +++ b/.github/workflows/workspace-ci.yml @@ -134,3 +134,21 @@ jobs: shell: bash working-directory: packages/devflare run: bun test tests/integration/dev-server/durable-object-container-dev.test.ts --max-concurrency=1 + + # A worker the test only references runs its containers too: through a service + # binding, through a cross-worker Durable Object binding, and under devflare dev. + # One process each, since a test context is process-wide. + - name: Run the referenced worker's container through a service binding + shell: bash + working-directory: packages/devflare + run: bun test tests/integration/test-context/referenced-durable-object-container.test.ts --max-concurrency=1 + + - name: Run the referenced worker's container through a cross-worker Durable Object + shell: bash + working-directory: packages/devflare + run: bun test tests/integration/test-context/referenced-durable-object-container-do-ref.test.ts --max-concurrency=1 + + - name: Run the referenced worker's container through devflare dev + shell: bash + working-directory: packages/devflare + run: bun test tests/integration/dev-server/referenced-durable-object-container-dev.test.ts --max-concurrency=1 diff --git a/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts b/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts index 0f17daf8..385c4be5 100644 --- a/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts +++ b/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts @@ -558,7 +558,8 @@ export class Builder extends DurableObject { 'HTTPS interception needs the container to trust `/etc/cloudflare/certs/cloudflare-containers-ca.crt`.', "Local runs need Linux or macOS: workerd cannot reach a Windows named pipe, so on Windows devflare refuses and points at WSL, as Wrangler does. Set `DEVFLARE_ENABLE_CONTAINERS=0` to start without containers; `ctx.container` is then undefined. Devflare uses `WRANGLER_DOCKER_HOST` or `DOCKER_HOST` when set, then the engine's own socket.", '`devflare workspace dev` does not run durable_object containers yet and refuses an app that declares one; run `devflare dev` in that app. The `containers.start()` helper starts only `default`-policy containers.', - 'Only the worker under test or under `devflare dev` runs its containers. A container declared by a worker this one only references (through a service binding or a cross-worker Durable Object) does not run locally, so its `ctx.container` is undefined there.', + 'A worker this one only references runs its containers too, in `createTestContext()` and `devflare dev`: through a service binding to it, or a cross-worker Durable Object binding to its class, devflare builds its images from its own config and attaches them where it hosts that Durable Object. So once a worker references one with a container, those runs need an engine (and on Windows, WSL or `DEVFLARE_ENABLE_CONTAINERS=0`) even when its own config declares none.', + "The Vite plugin (`vite dev` of a SvelteKit app) does not attach a referenced worker's containers, so `ctx.container` is undefined in it there; test that path with `createTestContext()` or run the referenced worker under `devflare dev`.", 'Images are rebuilt each time the config loads; a change inside the container needs a restart.' ] }, diff --git a/docs/CLOUDFLARE_SUPPORT_MATRIX.md b/docs/CLOUDFLARE_SUPPORT_MATRIX.md index f8ac9aa0..92394e2a 100644 --- a/docs/CLOUDFLARE_SUPPORT_MATRIX.md +++ b/docs/CLOUDFLARE_SUPPORT_MATRIX.md @@ -289,8 +289,11 @@ does), pull Miniflare's egress interceptor image, and attach the container to it Durable Object in Miniflare, so `ctx.container`, `enableInternet` and the outbound intercepts work against a real local container. That path is not offline-first, needs Linux or macOS (devflare refuses Windows, as Wrangler does), -and is turned off with `DEVFLARE_ENABLE_CONTAINERS=0`. `devflare workspace dev` -does not run it yet. +and is turned off with `DEVFLARE_ENABLE_CONTAINERS=0`. A worker reached through a +`ref()` service binding or a cross-worker Durable Object binding runs its +containers the same way in those two runtimes. `devflare workspace dev` does not +run them yet and refuses an app that declares or references one; the Vite plugin +leaves a referenced worker's containers out. ## How deploy auto-provisioning works diff --git a/packages/devflare/LLM.md b/packages/devflare/LLM.md index 9bedd079..9efeac15 100644 --- a/packages/devflare/LLM.md +++ b/packages/devflare/LLM.md @@ -16002,7 +16002,8 @@ Set `schedulingPolicy: 'durable_object'` and list the images the object may star - HTTPS interception needs the container to trust `/etc/cloudflare/certs/cloudflare-containers-ca.crt`. - Local runs need Linux or macOS: workerd cannot reach a Windows named pipe, so on Windows devflare refuses and points at WSL, as Wrangler does. Set `DEVFLARE_ENABLE_CONTAINERS=0` to start without containers; `ctx.container` is then undefined. Devflare uses `WRANGLER_DOCKER_HOST` or `DOCKER_HOST` when set, then the engine's own socket. - `devflare workspace dev` does not run durable_object containers yet and refuses an app that declares one; run `devflare dev` in that app. The `containers.start()` helper starts only `default`-policy containers. -- Only the worker under test or under `devflare dev` runs its containers. A container declared by a worker this one only references (through a service binding or a cross-worker Durable Object) does not run locally, so its `ctx.container` is undefined there. +- A worker this one only references runs its containers too, in `createTestContext()` and `devflare dev`: through a service binding to it, or a cross-worker Durable Object binding to its class, devflare builds its images from its own config and attaches them where it hosts that Durable Object. So once a worker references one with a container, those runs need an engine (and on Windows, WSL or `DEVFLARE_ENABLE_CONTAINERS=0`) even when its own config declares none. +- The Vite plugin (`vite dev` of a SvelteKit app) does not attach a referenced worker's containers, so `ctx.container` is undefined in it there; test that path with `createTestContext()` or run the referenced worker under `devflare dev`. - Images are rebuilt each time the config loads; a change inside the container needs a restart. ##### Example — Declare a Durable Object-managed container diff --git a/packages/devflare/src/dev-server/miniflare-dev-config.ts b/packages/devflare/src/dev-server/miniflare-dev-config.ts index 79a6bf46..691b1ab1 100644 --- a/packages/devflare/src/dev-server/miniflare-dev-config.ts +++ b/packages/devflare/src/dev-server/miniflare-dev-config.ts @@ -402,10 +402,13 @@ export function buildMiniflareDevConfig(input: BuildMiniflareDevConfigInput): an if (localContainers) { assertEveryContainerHasAWorker(localContainers, doResult) } + // One engine serves this worker's containers and its referenced workers'. + const containerEngine = + localContainers?.containerEngine ?? serviceBindingResolution?.containerEngine return { ...sharedOptions, - ...(localContainers && { containerEngine: localContainers.containerEngine }), + ...(containerEngine && { containerEngine }), workers: [ gatewayWorker, ...workers, diff --git a/packages/devflare/src/dev-server/server.ts b/packages/devflare/src/dev-server/server.ts index e7350fbf..d21ae8f9 100644 --- a/packages/devflare/src/dev-server/server.ts +++ b/packages/devflare/src/dev-server/server.ts @@ -14,7 +14,7 @@ import { resolveDevConfig } from '../config/dev-config' import { EnvVarResolutionError, getDevflareDotenvPaths } from '../config/env-vars' import { loadConfig } from '../config/loader' import { prepareLocalDurableObjectContainers } from '../test/durable-object-containers' -import { resolveServiceBindings } from '../test/resolve-service-bindings' +import { resolveServiceBindingsFor } from '../test/resolve-service-bindings' import { generatedDir } from '../utils/generated-dir' import { toMiniflareOptions } from '../utils/miniflare-options' import { prepareComposedWorkerEntrypoint } from '../worker-entry/composed-worker' @@ -433,7 +433,10 @@ export function createDevServer(options: DevServerOptions): DevServer { }) const configDir = state.resolvedWorkerConfigPath ? dirname(state.resolvedWorkerConfigPath) : cwd state.serviceBindingResolution = state.config.bindings?.services - ? await resolveServiceBindings(state.config, configDir) + ? await resolveServiceBindingsFor(state.config, configDir, { + referencedEnv: 'local', + containers: 'attach' + }) : null state.localContainers = await prepareLocalDurableObjectContainers({ config: state.config, diff --git a/packages/devflare/src/dev-server/workspace/prepare-app.ts b/packages/devflare/src/dev-server/workspace/prepare-app.ts index ba6b541e..4dd8868a 100644 --- a/packages/devflare/src/dev-server/workspace/prepare-app.ts +++ b/packages/devflare/src/dev-server/workspace/prepare-app.ts @@ -32,7 +32,7 @@ import { ENABLE_CONTAINERS_ENV, planLocalDurableObjectContainers } from '../../test/durable-object-containers' -import { resolveServiceBindings } from '../../test/resolve-service-bindings' +import { resolveServiceBindingsFor } from '../../test/resolve-service-bindings' import { generatedDir } from '../../utils/generated-dir' import { prepareComposedWorkerEntrypoint } from '../../worker-entry/composed-worker' import { discoverRoutes } from '../../worker-entry/routes' @@ -147,7 +147,10 @@ export async function prepareWorkspaceApp( // Refused before anything starts (shim, bundler), since it reads only the config. assertNoLocalDurableObjectContainers(appName, config, appCwd) const serviceBindingResolution = config.bindings?.services - ? await resolveServiceBindings(config, appCwd) + ? await resolveServiceBindingsFor(config, appCwd, { + referencedEnv: 'local', + containers: 'refuse' + }) : null // --- Vite integration (may downgrade to worker-only if no vite config) ---- diff --git a/packages/devflare/src/test/durable-object-containers.ts b/packages/devflare/src/test/durable-object-containers.ts index b1db103a..eed7d51b 100644 --- a/packages/devflare/src/test/durable-object-containers.ts +++ b/packages/devflare/src/test/durable-object-containers.ts @@ -122,8 +122,8 @@ export interface PreparedLocalDurableObjectContainers { /** Options for {@link prepareLocalDurableObjectContainers}. */ export interface PrepareLocalDurableObjectContainersOptions { - /** The resolved devflare config. */ - config: DevflareConfig + /** The resolved devflare config; only its `containers` are read. */ + config: Pick /** The directory the config's paths are relative to. */ configDir: string /** Process environment to read the opt-out and engine overrides from. */ @@ -148,7 +148,7 @@ export interface PrepareLocalDurableObjectContainersOptions { * @throws When two entries attach a container to the same class. */ export function planLocalDurableObjectContainers( - config: DevflareConfig, + config: Pick, configDir: string ): LocalDurableObjectContainer[] { const containers = (config.containers ?? []).filter(isDurableObjectPolicyContainer) @@ -545,7 +545,7 @@ export function attachDurableObjectContainers( ) if (unattached.length > 0) { throw new Error( - `durable_object containers name ${unattached.map((name) => `"${name}"`).join(', ')}, but no Durable Object binding in this worker serves that class. Add a bindings.durableObjects entry for that class to this config. A container on a Durable Object that another worker defines is not run locally.` + `durable_object containers name ${unattached.map((name) => `"${name}"`).join(', ')}, but no Durable Object binding in this worker serves that class. Add a bindings.durableObjects entry for that class to this config: a container is declared by the worker that defines its Durable Object class.` ) } @@ -568,3 +568,15 @@ export function getDurableObjectBindingClassNames(config: DevflareConfig): Map match[1]) +} diff --git a/packages/devflare/src/test/resolve-service-bindings.ts b/packages/devflare/src/test/resolve-service-bindings.ts index 6efbb80a..ac560a0e 100644 --- a/packages/devflare/src/test/resolve-service-bindings.ts +++ b/packages/devflare/src/test/resolve-service-bindings.ts @@ -9,6 +9,7 @@ import { existsSync, readFileSync } from 'fs' import { dirname, join, resolve } from 'path' import { type DevflareConfig, + type DevflareConfigInput, type DOBindingRef, type DurableObjectBinding, getLocalD1DatabaseIdentifier, @@ -17,6 +18,7 @@ import { normalizeR2Binding } from '../config' import type { RefResult, WorkerBinding } from '../config/ref' +import { containersConfigSchema } from '../config/schema-runtime' import { buildAiSearchInstancesConfig, buildAiSearchNamespacesConfig, @@ -39,6 +41,16 @@ import { findDurableObjectClasses } from '../transform/durable-object' import { transformWorkerEntrypoint } from '../transform/worker-entrypoint' import { discoverEntrypointsSync } from '../utils/entrypoint-discovery' import { DEFAULT_DO_PATTERN, findFilesSync } from '../utils/glob' +import { + areLocalContainersDisabled, + attachDurableObjectContainers, + ENABLE_CONTAINERS_ENV, + findExportedWorkerEntrypoints, + type MiniflareContainerEngineOption, + type MiniflareDurableObjectEntry, + planLocalDurableObjectContainers, + prepareLocalDurableObjectContainers +} from './durable-object-containers' import { type ReferencedEnv, resolveReferencedConfig, @@ -155,7 +167,7 @@ export interface ResolvedWorker { /** Service bindings to other workers */ serviceBindings?: Record /** Durable Object bindings for classes hosted by this worker or another script */ - durableObjects?: Record + durableObjects?: Record ratelimits?: Record versionMetadata?: string workerLoaders?: Record> @@ -195,6 +207,11 @@ export interface ServiceBindingResolution { workers: ResolvedWorker[] /** Service bindings for the primary worker */ primaryServiceBindings: Record + /** + * Miniflare's shared `containerEngine`, when a referenced worker's Durable + * Objects carry `durable_object` containers that were attached. + */ + containerEngine?: MiniflareContainerEngineOption } function findDefaultServiceWorkerEntrypoint(refConfigDir: string): string | null { @@ -305,18 +322,132 @@ export interface ResolveServiceBindingsOptions { * reach a build output must name a mode, and only one that cannot may say `'local'`. */ referencedEnv: ReferencedEnv + /** + * What to do with a referenced worker's `durable_object` containers; see + * {@link ReferencedContainerMode}. @default 'ignore' + */ + containers?: ReferencedContainerMode +} + +/** + * How a referenced worker's `durable_object` containers are treated. + * + * - `attach`: build their images and attach them to the worker that hosts the + * Durable Object, so `ctx.container` is real there (createTestContext and + * `devflare dev`). + * - `refuse`: throw when there are any, for a runtime that cannot run them + * (workspace dev), so `ctx.container` is never silently undefined. + * - `ignore`: leave them out. For callers whose result can reach a build + * output (the Vite plugin), where starting an engine would be wrong. + */ +export type ReferencedContainerMode = 'attach' | 'refuse' | 'ignore' + +/** A Durable Object class to host, and the module it comes from. */ +interface DurableObjectClassToBundle { + bindingName: string + className: string + scriptPath: string +} + +/** What a referenced worker's Durable Object host needs for its containers. */ +interface ReferencedContainerSetup { + /** `WorkerEntrypoint` classes to export beside the classes, for `ctx.exports`. */ + entrypointExports: Array<{ name: string; scriptPath: string }> + /** Attach the prepared containers to the host's namespaces. */ + attach( + durableObjects: Record + ): Record + /** The engine option, when containers were prepared. */ + containerEngine?: MiniflareContainerEngineOption +} + +/** + * Prepare a referenced worker's `durable_object` containers by `mode`. + * + * Side effects under `attach`: builds or pulls images (see + * prepareLocalDurableObjectContainers). + * + * @param refConfig - The referenced worker's config, parsed or not; only its + * `containers` are read. + * @param refConfigDir - Its directory. + * @param workerName - Its name, for messages. + * @param doClasses - The classes its host bundles. + * @param mode - attach, refuse or ignore. + * @returns The exports and attachment for the host; a no-op one when there is + * nothing to attach. + * @throws Under `refuse` when it declares any (and they are not turned off), + * and under `attach` as prepareLocalDurableObjectContainers does. + */ +async function prepareReferencedContainers( + refConfig: Pick, + refConfigDir: string, + workerName: string, + doClasses: DurableObjectClassToBundle[], + mode: ReferencedContainerMode +): Promise { + const none: ReferencedContainerSetup = { entrypointExports: [], attach: (dos) => dos } + if (mode === 'ignore') return none + + // A cross-worker Durable Object's referenced config arrives unparsed, so its + // containers are validated here, by the same schema the worker's own uses. + const containerConfig = { containers: containersConfigSchema.parse(refConfig.containers) } + + if (mode === 'refuse') { + const planned = planLocalDurableObjectContainers(containerConfig, refConfigDir) + if (planned.length > 0 && !areLocalContainersDisabled(process.env)) { + const classNames = planned.map((container) => container.className).join(', ') + throw new Error( + `Referenced worker "${workerName}" declares durable_object containers (${classNames}), which this runtime does not run. Run it under \`devflare dev\` or createTestContext(), or set ${ENABLE_CONTAINERS_ENV}=0 to start without containers.` + ) + } + return none + } + + const prepared = await prepareLocalDurableObjectContainers({ + config: containerConfig, + configDir: refConfigDir + }) + if (!prepared) return none + + const entrypointExports: Array<{ name: string; scriptPath: string }> = [] + const taken = new Set(doClasses.map((doClass) => doClass.className)) + for (const doClass of doClasses) { + if (!prepared.containersByClassName.has(doClass.className)) continue + for (const name of findExportedWorkerEntrypoints(readFileSync(doClass.scriptPath, 'utf-8'))) { + if (taken.has(name)) continue + taken.add(name) + entrypointExports.push({ name, scriptPath: doClass.scriptPath }) + } + } + + const bindingClassNames = new Map( + doClasses.map((doClass) => [doClass.bindingName, doClass.className]) + ) + return { + entrypointExports, + containerEngine: prepared.containerEngine, + attach: (durableObjects) => + attachDurableObjectContainers( + durableObjects, + bindingClassNames, + prepared.containersByClassName + ) + } } interface ReferencedDurableObjectResolution { workers: ResolvedWorker[] bindings: Record + /** Set when the host's Durable Objects carry attached containers. */ + containerEngine?: MiniflareContainerEngineOption } async function resolveReferencedLocalDurableObjects( config: DevflareConfig, configDir: string, workerName: string, - serviceBindings: Record = {} + serviceBindings: Record = {}, + containerMode: ReferencedContainerMode = 'ignore' ): Promise { const doPattern = config.files?.durableObjects const dosConfig = config.bindings?.durableObjects @@ -326,7 +457,7 @@ async function resolveReferencedLocalDurableObjects( } const discoveredDOs = discoverDOFilesSync(configDir, doPattern) - const doClasses: Array<{ bindingName: string; className: string; scriptPath: string }> = [] + const doClasses: DurableObjectClassToBundle[] = [] for (const [bindingName, rawDoConfig] of Object.entries(dosConfig)) { const doConfig = normalizeDOBinding(rawDoConfig as DurableObjectBinding) @@ -350,13 +481,20 @@ async function resolveReferencedLocalDurableObjects( } const doWorkerName = `${workerName}-durable-objects` - const script = await bundleDOClasses(doClasses, doWorkerName) + const containers = await prepareReferencedContainers( + config, + configDir, + workerName, + doClasses, + containerMode + ) + const script = await bundleDOClasses(doClasses, doWorkerName, containers.entrypointExports) if (!script) { return { workers: [], bindings: {} } } - const durableObjects = Object.fromEntries( - doClasses.map((do_) => [do_.bindingName, do_.className]) + const durableObjects = containers.attach( + Object.fromEntries(doClasses.map((do_) => [do_.bindingName, do_.className])) ) const runtimeConfig = buildReferencedWorkerRuntimeConfig(config) const doRuntimeConfig = { ...runtimeConfig } @@ -380,6 +518,7 @@ async function resolveReferencedLocalDurableObjects( durableObjects } ], + ...(containers.containerEngine && { containerEngine: containers.containerEngine }), bindings: Object.fromEntries( doClasses.map((do_) => [ do_.bindingName, @@ -442,6 +581,7 @@ export async function resolveServiceBindingsFor( // Track resolved workers by name to avoid duplicates const workersByName = new Map() const primaryServiceBindings: Record = {} + let containerEngine: MiniflareContainerEngineOption | undefined for (const [bindingName, binding] of Object.entries(services)) { const workerBinding = binding as WorkerBinding @@ -488,13 +628,16 @@ export async function resolveServiceBindingsFor( workersByName.set(nestedWorker.name, nestedWorker) } } + containerEngine ??= nested.containerEngine const localDOs = await resolveReferencedLocalDurableObjects( refConfig, refConfigDir, workerName, - nested.primaryServiceBindings + nested.primaryServiceBindings, + options.containers ) + containerEngine ??= localDOs.containerEngine worker.durableObjects = { ...(worker.durableObjects ?? {}), ...localDOs.bindings @@ -525,7 +668,8 @@ export async function resolveServiceBindingsFor( return { workers: [...workersByName.values()], - primaryServiceBindings + primaryServiceBindings, + ...(containerEngine && { containerEngine }) } } @@ -723,6 +867,14 @@ export interface DOBindingResolution { workers: ResolvedWorker[] /** DO bindings for the primary worker (pointing to cross-worker DO hosting workers) */ crossWorkerDOBindings: Record + /** Set when a hosting worker's Durable Objects carry attached containers. */ + containerEngine?: MiniflareContainerEngineOption +} + +/** Options for {@link resolveDOBindings}. */ +export interface ResolveDOBindingsOptions { + /** What to do with the referenced workers' `durable_object` containers. @default 'ignore' */ + containers?: ReferencedContainerMode } /** @@ -744,7 +896,8 @@ export function hasCrossWorkerDOs(config: DevflareConfig): boolean { */ export async function resolveDOBindings( config: DevflareConfig, - configDir: string + configDir: string, + options: ResolveDOBindingsOptions = {} ): Promise { const dos = config.bindings?.durableObjects if (!dos) { @@ -753,6 +906,7 @@ export async function resolveDOBindings( const workersByName = new Map() const crossWorkerDOBindings: Record = {} + let containerEngine: MiniflareContainerEngineOption | undefined for (const [bindingName, rawDoConfig] of Object.entries(dos)) { // Check for __ref first (before normalizing) to detect cross-worker DOs @@ -776,9 +930,10 @@ export async function resolveDOBindings( // Bundle the worker if not already done if (!workersByName.has(workerName)) { - const worker = await resolveDORefWorker(ref, configDir) - if (worker) { - workersByName.set(workerName, worker) + const resolved = await resolveDORefWorker(ref, configDir, options.containers ?? 'ignore') + if (resolved) { + workersByName.set(workerName, resolved.worker) + containerEngine ??= resolved.containerEngine } } @@ -791,7 +946,8 @@ export async function resolveDOBindings( return { workers: [...workersByName.values()], - crossWorkerDOBindings + crossWorkerDOBindings, + ...(containerEngine && { containerEngine }) } } @@ -801,8 +957,9 @@ export async function resolveDOBindings( */ async function resolveDORefWorker( ref: RefResult, - parentConfigDir: string -): Promise { + parentConfigDir: string, + containerMode: ReferencedContainerMode +): Promise<{ worker: ResolvedWorker; containerEngine?: MiniflareContainerEngineOption } | null> { const config = ref.config if (!config) return null @@ -825,7 +982,7 @@ async function resolveDORefWorker( const discoveredDOs = discoverDOFilesSync(refConfigDir) // Collect DO classes to bundle - const doClasses: Array<{ bindingName: string; className: string; scriptPath: string }> = [] + const doClasses: DurableObjectClassToBundle[] = [] for (const [bindingName, rawDoConfig] of Object.entries(dosConfig)) { const doConfig = normalizeDOBinding(rawDoConfig as DurableObjectBinding) @@ -864,8 +1021,16 @@ async function resolveDORefWorker( return null } + const containers = await prepareReferencedContainers( + config, + refConfigDir, + ref.name, + doClasses, + containerMode + ) + // Bundle DO classes (native RPC, no wrappers needed) - const script = await bundleDOClasses(doClasses, ref.name) + const script = await bundleDOClasses(doClasses, ref.name, containers.entrypointExports) if (!script) return null // Build DO bindings for Miniflare - use original class names (native RPC) @@ -875,11 +1040,14 @@ async function resolveDORefWorker( } return { - name: ref.name, - script, - modules: true, - compatibilityDate: config.compatibilityDate ?? '2025-01-01', - durableObjects + worker: { + name: ref.name, + script, + modules: true, + compatibilityDate: config.compatibilityDate ?? '2025-01-01', + durableObjects: containers.attach(durableObjects) + }, + ...(containers.containerEngine && { containerEngine: containers.containerEngine }) } } @@ -887,10 +1055,14 @@ async function resolveDORefWorker( * Bundle DO classes with RPC wrappers for Miniflare */ async function bundleDOClasses( - doClasses: Array<{ bindingName: string; className: string; scriptPath: string }>, - workerName: string + doClasses: DurableObjectClassToBundle[], + workerName: string, + entrypointExports: Array<{ name: string; scriptPath: string }> = [] ): Promise { - const cacheKey = `do:${doClasses.map((d) => `${d.scriptPath}::${d.className}`).join('|')}` + const cacheKey = `do:${[ + ...doClasses.map((d) => `${d.scriptPath}::${d.className}`), + ...entrypointExports.map((e) => `${e.scriptPath}::${e.name}`) + ].join('|')}` const cached = bundleCache.get(cacheKey) if (cached) return cached @@ -908,11 +1080,17 @@ async function bundleDOClasses( const { writeFileSync, mkdirSync, unlinkSync } = await import('fs') // Build imports and exports for DO classes - const imports = doClasses - .map((d) => `import { ${d.className} } from '${d.scriptPath.replace(/\\/g, '/')}'`) + // A container-backed class's module also exports the WorkerEntrypoint its + // outbound intercepts target through ctx.exports. + const exported = [ + ...doClasses.map((d) => ({ name: d.className, scriptPath: d.scriptPath })), + ...entrypointExports + ] + const imports = exported + .map((e) => `import { ${e.name} } from '${e.scriptPath.replace(/\\/g, '/')}'`) .join('\n') - const exports = doClasses.map((d) => d.className).join(', ') + const exports = exported.map((e) => e.name).join(', ') // Build the final script - no wrappers, native RPC via DurableObject base class const entryCode = ` diff --git a/packages/devflare/src/test/simple-context-durable-objects.ts b/packages/devflare/src/test/simple-context-durable-objects.ts index 11ad8e7b..c636a402 100644 --- a/packages/devflare/src/test/simple-context-durable-objects.ts +++ b/packages/devflare/src/test/simple-context-durable-objects.ts @@ -9,6 +9,7 @@ import { readCachedDurableObjectBundle, writeCachedDurableObjectBundle } from './durable-object-bundle-cache' +import { findExportedWorkerEntrypoints } from './durable-object-containers' import { buildGatewayScript } from './simple-context-gateway-script' import { getBunRuntime } from './simple-context-paths' @@ -35,18 +36,6 @@ function classSupportsNativeDurableObjectRpc(code: string, className: string): b return nativeRpcPattern.test(code) } -/** - * Find the `WorkerEntrypoint` classes a module exports, the targets a - * container's outbound intercepts reach through `ctx.exports`. - * - * @param code - Module source. - * @returns The exported class names, in source order. - */ -function findExportedWorkerEntrypoints(code: string): string[] { - const entrypointPattern = /export\s+class\s+(\w+)\s+extends\s+WorkerEntrypoint\b/g - return [...code.matchAll(entrypointPattern)].map((match) => match[1]) -} - /** A class the gateway re-exports from a Durable Object module. */ interface GatewayEntrypointExport { /** The exported class name. */ diff --git a/packages/devflare/src/test/simple-context.ts b/packages/devflare/src/test/simple-context.ts index 0fb70150..e242ee74 100644 --- a/packages/devflare/src/test/simple-context.ts +++ b/packages/devflare/src/test/simple-context.ts @@ -27,7 +27,8 @@ import { hasCrossWorkerDOs, hasServiceBindings, resolveDOBindings, - resolveServiceBindings + type resolveServiceBindings, + resolveServiceBindingsFor } from './resolve-service-bindings' import { buildRemoteAndStaticBindings } from './simple-context-bindings' import { buildDurableObjectGateway } from './simple-context-durable-objects' @@ -114,10 +115,15 @@ export async function createTestContext(configPath?: string): Promise { let doBindingResolution: Awaited> | null = null if (needsMultiWorkerForServices) { - serviceBindingResolution = await resolveServiceBindings(config, configDir) + // Referenced workers' durable_object containers run too, so a test that + // reaches a container through a service binding gets a real one. + serviceBindingResolution = await resolveServiceBindingsFor(config, configDir, { + referencedEnv: 'local', + containers: 'attach' + }) } if (needsMultiWorkerForDOs) { - doBindingResolution = await resolveDOBindings(config, configDir) + doBindingResolution = await resolveDOBindings(config, configDir, { containers: 'attach' }) } const mfConfig: any = buildInlineBridgeMfConfig(config, { cwd: configDir }) @@ -161,6 +167,13 @@ export async function createTestContext(configPath?: string): Promise { ) } + // One engine serves every worker's containers; it is a Miniflare-wide option. + const referencedContainerEngine = + serviceBindingResolution?.containerEngine ?? doBindingResolution?.containerEngine + if (referencedContainerEngine && !mfConfig.containerEngine) { + mfConfig.containerEngine = referencedContainerEngine + } + const hasMultiWorkerServices = serviceBindingResolution && serviceBindingResolution.workers.length > 0 const hasMultiWorkerDOs = doBindingResolution && doBindingResolution.workers.length > 0 diff --git a/packages/devflare/tests/integration/dev-server/referenced-durable-object-container-dev.test.ts b/packages/devflare/tests/integration/dev-server/referenced-durable-object-container-dev.test.ts new file mode 100644 index 00000000..8b24ef51 --- /dev/null +++ b/packages/devflare/tests/integration/dev-server/referenced-durable-object-container-dev.test.ts @@ -0,0 +1,121 @@ +// ============================================================================= +// A referenced worker's durable_object container under `devflare dev` +// ============================================================================= +// The dev server's own worker has no container: its fetch handler calls a +// builder worker it only references, through a service binding, and the +// builder forwards to its container-backed Durable Object. The dev server +// resolves referenced workers the way createTestContext() does, so the same +// attachment must hold here, under the dev server's own Miniflare options. +// +// → Needs DEVFLARE_CONTAINER_TESTS=1, a reachable engine and Linux or macOS; +// see the fixture's resolveContainerTestSkipReason(). +// ============================================================================= + +import { afterAll, beforeAll, describe, expect, test } from 'bun:test' +import { createDevServer, type DevServer } from '../../../src/dev-server' +import { localContainerImageTag } from '../../../src/test/durable-object-containers' +import { cleanupTempDirs, getAvailablePort } from '../helpers/built-devflare.helpers' +import { + CONTAINER_TEST_TIMEOUT_MS, + NETWORK_REFUSAL, + type ProbeResult, + REFERENCED_BUILDER_ENTRYPOINT, + referencedBuilderPrelude, + resolveContainerTestSkipReason, + writeReferencedBuilder +} from '../helpers/durable-object-container.fixture' +import { createProject } from './worker-only-multi-surface.helpers' + +const skipReason = await resolveContainerTestSkipReason() +const tempDirs: string[] = [] + +describe.skipIf(skipReason !== null)( + "a referenced worker's durable_object container under devflare dev", + () => { + let builderDir = '' + let devServer: DevServer | null = null + let workerUrl = '' + + beforeAll(async () => { + if (skipReason !== null) return + const port = await getAvailablePort() + workerUrl = `http://127.0.0.1:${port}` + const projectDir = await createProject(tempDirs, { + prefix: 'devflare-ref-do-container-dev-', + config: [ + referencedBuilderPrelude(), + 'export default {', + "\tname: 'referenced-container-dev',", + "\tcompatibilityDate: '2026-09-29',", + "\tfiles: { fetch: 'src/fetch.ts' },", + `\tbindings: { services: { BUILDER_SERVICE: builder.worker('${REFERENCED_BUILDER_ENTRYPOINT}') } }`, + '}' + ].join('\n'), + files: { + 'src/fetch.ts': String.raw` +export async function fetch({ request, env }) { + const url = new URL(request.url) + if (url.pathname === '/images') return Response.json(await env.BUILDER_SERVICE.images()) + return Response.json( + await env.BUILDER_SERVICE.probe(url.searchParams.get('mode'), url.searchParams.getAll('url')) + ) +} +`.trim() + } + }) + builderDir = await writeReferencedBuilder(projectDir) + + devServer = createDevServer({ + cwd: projectDir, + miniflarePort: port, + enableVite: false, + persist: false + }) + await devServer.start() + }, CONTAINER_TEST_TIMEOUT_MS) + + afterAll(async () => { + if (devServer) await devServer.stop() + await cleanupTempDirs(tempDirs) + }, CONTAINER_TEST_TIMEOUT_MS) + + test('ctx.container.images names the image built from the referenced config', async () => { + const response = await fetch(`${workerUrl}/images`) + + expect(response.status).toBe(200) + expect(await response.json()).toEqual({ + base: localContainerImageTag(builderDir, 'Builder', 'base') + }) + }) + + test( + 'intercepts reach the referenced module WorkerEntrypoint; enableInternet: false blocks the rest', + async () => { + const query = new URLSearchParams({ mode: 'named' }) + for (const url of [ + 'http://named.devflare.test/a', + 'https://secure.devflare.test/b', + 'http://example.com/' + ]) { + query.append('url', url) + } + const response = await fetch(`${workerUrl}/probe?${query}`) + expect(response.status).toBe(200) + const results = (await response.json()) as ProbeResult[] + + console.log('[referenced durable_object container, dev] named:', JSON.stringify(results)) + expect(results[0]).toMatchObject({ + ok: true, + body: 'intercepted GET http://named.devflare.test/a' + }) + expect(results[1]).toMatchObject({ + ok: true, + body: 'intercepted GET https://secure.devflare.test/b' + }) + expect(results[2].ok).toBe(false) + expect(results[2].error).toMatch(NETWORK_REFUSAL) + }, + CONTAINER_TEST_TIMEOUT_MS + ) + } +) diff --git a/packages/devflare/tests/integration/helpers/durable-object-container.fixture.ts b/packages/devflare/tests/integration/helpers/durable-object-container.fixture.ts index 1c96de9a..db859e35 100644 --- a/packages/devflare/tests/integration/helpers/durable-object-container.fixture.ts +++ b/packages/devflare/tests/integration/helpers/durable-object-container.fixture.ts @@ -8,6 +8,7 @@ // ============================================================================= import { mkdir, writeFile } from 'node:fs/promises' +import { pathToFileURL } from 'node:url' import { join } from 'pathe' import { getContainerSkipReason } from '../../../src/test' @@ -208,3 +209,73 @@ export interface ProbeResult { /** Why nothing came back. */ error?: string } + +/** The referenced builder worker's name. */ +export const REFERENCED_BUILDER_NAME = 'container-builder' + +/** The named entrypoint a service binding to the referenced builder targets. */ +export const REFERENCED_BUILDER_ENTRYPOINT = 'BuilderEntrypoint' + +/** + * The referenced builder's RPC surface: it forwards to its own + * container-backed Durable Object, the way the plan's server builder does. + */ +const referencedBuilderEntrypointSource = String.raw` +import { WorkerEntrypoint } from 'cloudflare:workers' + +export class BuilderEntrypoint extends WorkerEntrypoint { + images() { + return this.env.BUILDER.getByName('images').images() + } + + probe(mode, urls) { + return this.env.BUILDER.getByName(mode).probe(mode, urls) + } +} +` + +/** + * Write a builder worker that the test's own config only references: its + * config, its named entrypoint, its container-backed Durable Object and its + * image, under `/builder`. + * + * @param projectDir - The referencing project. + * @returns The builder's directory, which its image tags are derived from. + */ +export async function writeReferencedBuilder(projectDir: string): Promise { + const builderDir = join(projectDir, 'builder') + await mkdir(join(builderDir, 'src'), { recursive: true }) + await writeFile( + join(builderDir, 'devflare.config.ts'), + `export default ${JSON.stringify( + { + name: REFERENCED_BUILDER_NAME, + compatibilityDate: '2026-09-29', + files: { fetch: false, entrypoints: 'src/ep.*.ts', durableObjects: 'src/do.*.ts' }, + bindings: { durableObjects: { BUILDER: 'Builder' } }, + ...builderContainerConfig + }, + null, + '\t' + )}\n` + ) + await writeFile(join(builderDir, 'src', 'ep.builder.ts'), referencedBuilderEntrypointSource) + await writeFile(join(builderDir, 'src', 'do.builder.ts'), durableObjectModuleSource()) + await writeContainerImage(builderDir) + return builderDir +} + +/** + * The lines a referencing config starts with: devflare's `ref()`, imported + * from source, and a `builder` ref to the config writeReferencedBuilder wrote. + * + * @returns Source declaring `builder`, for `builder.worker(...)` or `builder.BUILDER`. + */ +export function referencedBuilderPrelude(): string { + const refModule = pathToFileURL(join(import.meta.dirname, '../../../src/config/ref.ts')).href + return [ + `import { ref } from '${refModule}'`, + "const builder = ref(() => import('./builder/devflare.config.ts'))", + '' + ].join('\n') +} diff --git a/packages/devflare/tests/integration/test-context/referenced-durable-object-container-do-ref.test.ts b/packages/devflare/tests/integration/test-context/referenced-durable-object-container-do-ref.test.ts new file mode 100644 index 00000000..fb978852 --- /dev/null +++ b/packages/devflare/tests/integration/test-context/referenced-durable-object-container-do-ref.test.ts @@ -0,0 +1,115 @@ +// ============================================================================= +// A cross-worker Durable Object ref to a container-backed class +// ============================================================================= +// The test's config binds `BUILDER` to the referenced builder's `Builder` +// class (`builder.BUILDER`), so devflare hosts the class in a worker named +// after the builder and the test drives the Durable Object directly. The +// container must be attached in that hosting worker, and its intercept target +// exported from it. The service-binding route is graded by +// referenced-durable-object-container.test.ts. +// +// → Needs DEVFLARE_CONTAINER_TESTS=1, a reachable engine and Linux or macOS; +// see the fixture's resolveContainerTestSkipReason(). +// ============================================================================= + +import { afterAll, beforeAll, describe, expect, test } from 'bun:test' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'pathe' +import { env } from '../../../src' +import { createTestContext } from '../../../src/test' +import { localContainerImageTag } from '../../../src/test/durable-object-containers' +import { + CONTAINER_TEST_TIMEOUT_MS, + NETWORK_REFUSAL, + type ProbeResult, + referencedBuilderPrelude, + resolveContainerTestSkipReason, + writeReferencedBuilder +} from '../helpers/durable-object-container.fixture' + +const skipReason = await resolveContainerTestSkipReason() + +/** The Durable Object stub the test drives. */ +interface BuilderStub { + images(): Promise> + probe(mode: 'open' | 'none' | 'named' | 'catch-all', urls: string[]): Promise +} + +let projectDir = '' +let builderDir = '' + +/** The referenced Durable Object behind `env.BUILDER`, by name. */ +function builder(name: string): BuilderStub { + const namespace = (env as unknown as Record) + .BUILDER + return namespace.getByName(name) +} + +describe.skipIf(skipReason !== null)( + 'a cross-worker Durable Object ref to a durable_object container', + () => { + beforeAll(async () => { + if (skipReason !== null) return + projectDir = await mkdtemp(join(tmpdir(), 'devflare-ref-do-container-doref-')) + builderDir = await writeReferencedBuilder(projectDir) + await mkdir(join(projectDir, 'src'), { recursive: true }) + await writeFile( + join(projectDir, 'src', 'fetch.ts'), + "export default async function fetch() { return new Response('gateway') }\n" + ) + await writeFile( + join(projectDir, 'devflare.config.ts'), + [ + referencedBuilderPrelude(), + 'export default {', + "\tname: 'referenced-container-do-ref',", + "\tcompatibilityDate: '2026-09-29',", + '\tbindings: { durableObjects: { BUILDER: builder.BUILDER } }', + '}', + '' + ].join('\n') + ) + await createTestContext(join(projectDir, 'devflare.config.ts')) + }, CONTAINER_TEST_TIMEOUT_MS) + + afterAll(async () => { + if (skipReason !== null) return + await env.dispose() + if (projectDir) await rm(projectDir, { recursive: true, force: true }) + }) + + test('ctx.container.images names the image built from the referenced config', async () => { + expect(await builder('images').images()).toEqual({ + base: localContainerImageTag(builderDir, 'Builder', 'base') + }) + }) + + test( + 'the catch-all intercepts reach the hosting worker WorkerEntrypoint', + async () => { + const results = await builder('catch-all').probe('catch-all', [ + 'http://anything.example/c', + 'https://anything.example/d' + ]) + + expect(results.map((result) => result.body)).toEqual([ + 'intercepted GET http://anything.example/c', + 'intercepted GET https://anything.example/d' + ]) + }, + CONTAINER_TEST_TIMEOUT_MS + ) + + test( + 'enableInternet: false holds: with no intercept, no request leaves the container', + async () => { + const results = await builder('none').probe('none', ['http://example.com/']) + + expect(results[0].ok).toBe(false) + expect(results[0].error).toMatch(NETWORK_REFUSAL) + }, + CONTAINER_TEST_TIMEOUT_MS + ) + } +) diff --git a/packages/devflare/tests/integration/test-context/referenced-durable-object-container.test.ts b/packages/devflare/tests/integration/test-context/referenced-durable-object-container.test.ts new file mode 100644 index 00000000..46add441 --- /dev/null +++ b/packages/devflare/tests/integration/test-context/referenced-durable-object-container.test.ts @@ -0,0 +1,127 @@ +// ============================================================================= +// A referenced worker's durable_object container, through createTestContext() +// ============================================================================= +// The test's own config has no container. It reaches one through a service +// binding to a builder worker it only references with `ref()`, and the builder +// forwards to its own container-backed Durable Object, as the server builder +// in the lean-renders plan does. devflare hosts that Durable Object in the +// referenced worker's `-durable-objects` worker, so the container has to +// be attached there, with the Durable Object module's `WorkerEntrypoint` +// exported beside it for `ctx.exports`. +// A cross-worker Durable Object ref is the other way to reach a referenced +// worker's class; referenced-durable-object-container-do-ref.test.ts grades it. +// +// → Needs DEVFLARE_CONTAINER_TESTS=1, a reachable engine and Linux or macOS; +// see the fixture's resolveContainerTestSkipReason(). +// ============================================================================= + +import { afterAll, beforeAll, describe, expect, test } from 'bun:test' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'pathe' +import { env } from '../../../src' +import { createTestContext } from '../../../src/test' +import { localContainerImageTag } from '../../../src/test/durable-object-containers' +import { + CONTAINER_TEST_TIMEOUT_MS, + NETWORK_REFUSAL, + type ProbeResult, + REFERENCED_BUILDER_ENTRYPOINT, + referencedBuilderPrelude, + resolveContainerTestSkipReason, + writeReferencedBuilder +} from '../helpers/durable-object-container.fixture' + +const skipReason = await resolveContainerTestSkipReason() + +/** The referenced builder's entrypoint, as the service binding exposes it. */ +interface BuilderService { + images(): Promise> + probe(mode: 'open' | 'none' | 'named' | 'catch-all', urls: string[]): Promise +} + +let projectDir = '' +let builderDir = '' + +/** The service binding to the referenced builder. */ +function builderService(): BuilderService { + return (env as unknown as { BUILDER_SERVICE: BuilderService }).BUILDER_SERVICE +} + +describe.skipIf(skipReason !== null)( + "a referenced worker's durable_object container through createTestContext", + () => { + beforeAll(async () => { + if (skipReason !== null) return + projectDir = await mkdtemp(join(tmpdir(), 'devflare-ref-do-container-')) + builderDir = await writeReferencedBuilder(projectDir) + await mkdir(join(projectDir, 'src'), { recursive: true }) + await writeFile( + join(projectDir, 'src', 'fetch.ts'), + "export default async function fetch() { return new Response('gateway') }\n" + ) + await writeFile( + join(projectDir, 'devflare.config.ts'), + [ + referencedBuilderPrelude(), + 'export default {', + "\tname: 'referenced-container-gateway',", + "\tcompatibilityDate: '2026-09-29',", + `\tbindings: { services: { BUILDER_SERVICE: builder.worker('${REFERENCED_BUILDER_ENTRYPOINT}') } }`, + '}', + '' + ].join('\n') + ) + await createTestContext(join(projectDir, 'devflare.config.ts')) + }, CONTAINER_TEST_TIMEOUT_MS) + + afterAll(async () => { + if (skipReason !== null) return + await env.dispose() + if (projectDir) await rm(projectDir, { recursive: true, force: true }) + }) + + test('ctx.container.images names the image built from the referenced config', async () => { + expect(await builderService().images()).toEqual({ + base: localContainerImageTag(builderDir, 'Builder', 'base') + }) + }) + + test( + 'intercepts reach the referenced module WorkerEntrypoint; enableInternet: false blocks the rest', + async () => { + const results = await builderService().probe('named', [ + 'http://named.devflare.test/a', + 'https://secure.devflare.test/b', + 'http://example.com/' + ]) + + console.log('[referenced durable_object container] named:', JSON.stringify(results)) + expect(results[0]).toMatchObject({ + ok: true, + status: 200, + body: 'intercepted GET http://named.devflare.test/a' + }) + expect(results[1]).toMatchObject({ + ok: true, + status: 200, + body: 'intercepted GET https://secure.devflare.test/b' + }) + expect(results[2]).toMatchObject({ ok: false }) + expect(results[2].error).toMatch(NETWORK_REFUSAL) + }, + CONTAINER_TEST_TIMEOUT_MS + ) + + test( + 'control: with enableInternet: true the same container reaches the Internet', + async () => { + const results = await builderService().probe('open', ['http://example.com/']) + + console.log('[referenced durable_object container] open:', JSON.stringify(results)) + expect(results[0]).toMatchObject({ ok: true, status: 200 }) + }, + CONTAINER_TEST_TIMEOUT_MS + ) + } +) diff --git a/packages/devflare/tests/unit/test/referenced-durable-object-containers.test.ts b/packages/devflare/tests/unit/test/referenced-durable-object-containers.test.ts new file mode 100644 index 00000000..6bb4a15c --- /dev/null +++ b/packages/devflare/tests/unit/test/referenced-durable-object-containers.test.ts @@ -0,0 +1,271 @@ +// ============================================================================= +// Referenced workers' durable_object containers: what each mode does +// ============================================================================= +// Attaching needs a container engine, so the attach path itself is graded by +// the integration tests under tests/integration/{test-context,dev-server}/ +// referenced-durable-object-container*.test.ts. These cases grade what needs +// no engine: `refuse` throws, `ignore` and a turned-off attach leave the +// namespaces plain, and a referenced worker without containers is unaffected. +// ============================================================================= + +import { afterAll, afterEach, beforeEach, describe, expect, test } from 'bun:test' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { RefResult } from '../../../src/config/ref' +import type { DevflareConfig } from '../../../src/config/schema' +import { ENABLE_CONTAINERS_ENV } from '../../../src/test/durable-object-containers' +import { + clearBundleCache, + type ReferencedContainerMode, + resolveDOBindings, + resolveServiceBindingsFor +} from '../../../src/test/resolve-service-bindings' + +const tempDirs: string[] = [] +const savedEnableContainers = process.env[ENABLE_CONTAINERS_ENV] + +beforeEach(() => { + clearBundleCache() + delete process.env[ENABLE_CONTAINERS_ENV] +}) + +afterEach(() => { + if (savedEnableContainers === undefined) delete process.env[ENABLE_CONTAINERS_ENV] + else process.env[ENABLE_CONTAINERS_ENV] = savedEnableContainers +}) + +afterAll(async () => { + for (const tempDir of tempDirs) { + await rm(tempDir, { recursive: true, force: true }) + } +}) + +/** + * A ref that is already resolved, as `loadConfig` leaves one. + * + * @param config - The referenced worker's config. + * @param configPath - Its path, relative to the referencing config's directory. + * @returns The ref. + */ +function resolvedRef(config: DevflareConfig, configPath: string): RefResult { + const resolved = { name: config.name, config, configPath } + return { + get name() { + return resolved.name + }, + get config() { + return resolved.config + }, + get configPath() { + return resolved.configPath + }, + get BUILDER() { + return { className: 'Builder', scriptName: config.name, __ref: this } + }, + __import: async () => ({ default: config }), + async resolve() { + return resolved + } + } as unknown as RefResult +} + +/** + * Write a referenced builder: a named entrypoint, a `Builder` Durable Object + * whose module also exports an intercept target, and, unless `withContainers` + * is false, a durable_object container on `Builder`. + * + * @param withContainers - Whether the config declares the container. + * @returns The referencing project's directory and the builder's ref. + */ +async function writeBuilder( + withContainers = true +): Promise<{ projectDir: string; ref: RefResult }> { + const projectDir = await mkdtemp(join(tmpdir(), 'devflare-ref-containers-')) + tempDirs.push(projectDir) + const builderDir = join(projectDir, 'builder') + await mkdir(join(builderDir, 'src'), { recursive: true }) + await writeFile( + join(builderDir, 'src', 'ep.builder.ts'), + "import { WorkerEntrypoint } from 'cloudflare:workers'\n\nexport class BuilderEntrypoint extends WorkerEntrypoint {\n\tping() {\n\t\treturn 'PONG'\n\t}\n}\n" + ) + await writeFile( + join(builderDir, 'src', 'do.builder.ts'), + "import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers'\n\nexport class OutboundHandler extends WorkerEntrypoint {}\n\nexport class Builder extends DurableObject {\n\tping() {\n\t\treturn 'DO_PONG'\n\t}\n}\n" + ) + + const config = { + name: 'container-builder', + compatibilityDate: '2026-09-29', + files: { fetch: false, entrypoints: 'src/ep.*.ts', durableObjects: 'src/do.*.ts' }, + bindings: { durableObjects: { BUILDER: 'Builder' } }, + ...(withContainers && { + containers: [ + { + className: 'Builder', + schedulingPolicy: 'durable_object', + images: { base: { dockerfile: './container/Dockerfile' } } + } + ] + }) + } as unknown as DevflareConfig + return { projectDir, ref: resolvedRef(config, './builder/devflare.config.ts') } +} + +/** + * Resolve a gateway whose service binding targets the builder. + * + * @param projectDir - The gateway's directory. + * @param ref - The builder's ref. + * @param containers - The mode under test. + */ +function resolveThroughServiceBinding( + projectDir: string, + ref: RefResult, + containers: ReferencedContainerMode +): ReturnType { + const gateway = { + name: 'gateway', + compatibilityDate: '2026-09-29', + bindings: { + services: { + BUILDER_SERVICE: { + service: 'container-builder', + entrypoint: 'BuilderEntrypoint', + __ref: ref + } + } + } + } as unknown as DevflareConfig + return resolveServiceBindingsFor(gateway, projectDir, { referencedEnv: 'local', containers }) +} + +describe('referenced durable_object containers through a service binding', () => { + test('refuse throws, naming the worker, its class and the way to start without them', async () => { + const { projectDir, ref } = await writeBuilder() + + const resolution = resolveThroughServiceBinding(projectDir, ref, 'refuse') + + await expect(resolution).rejects.toThrow( + /Referenced worker "container-builder" declares durable_object containers \(Builder\)/ + ) + await expect(resolveThroughServiceBinding(projectDir, ref, 'refuse')).rejects.toThrow( + `${ENABLE_CONTAINERS_ENV}=0` + ) + }) + + test(`refuse lets ${ENABLE_CONTAINERS_ENV}=0 through, with the namespace left plain`, async () => { + const { projectDir, ref } = await writeBuilder() + process.env[ENABLE_CONTAINERS_ENV] = '0' + + const result = await resolveThroughServiceBinding(projectDir, ref, 'refuse') + const host = result.workers.find( + (worker) => worker.name === 'container-builder-durable-objects' + ) + + expect(host?.durableObjects).toEqual({ BUILDER: 'Builder' }) + expect(result.containerEngine).toBeUndefined() + }) + + test('refuse leaves a referenced worker without containers alone', async () => { + const { projectDir, ref } = await writeBuilder(false) + + const result = await resolveThroughServiceBinding(projectDir, ref, 'refuse') + const host = result.workers.find( + (worker) => worker.name === 'container-builder-durable-objects' + ) + + expect(host?.durableObjects).toEqual({ BUILDER: 'Builder' }) + }) + + test('ignore neither attaches nor exports the intercept target', async () => { + const { projectDir, ref } = await writeBuilder() + + const result = await resolveThroughServiceBinding(projectDir, ref, 'ignore') + const host = result.workers.find( + (worker) => worker.name === 'container-builder-durable-objects' + ) + + expect(host?.durableObjects).toEqual({ BUILDER: 'Builder' }) + expect(host?.script).not.toContain('OutboundHandler') + expect(result.containerEngine).toBeUndefined() + }) + + // Windows refuses before any engine is asked, so there attach can be seen to + // reach the preparation without one; elsewhere the integration tests grade it. + test.skipIf(process.platform !== 'win32')( + 'attach prepares the containers (on Windows, refused with the WSL advice)', + async () => { + const { projectDir, ref } = await writeBuilder() + + await expect(resolveThroughServiceBinding(projectDir, ref, 'attach')).rejects.toThrow( + /Local Durable Object containers \(Builder\) cannot run on Windows/ + ) + } + ) + + test(`attach with ${ENABLE_CONTAINERS_ENV}=0 starts no engine and attaches nothing`, async () => { + const { projectDir, ref } = await writeBuilder() + process.env[ENABLE_CONTAINERS_ENV] = '0' + + const result = await resolveThroughServiceBinding(projectDir, ref, 'attach') + const host = result.workers.find( + (worker) => worker.name === 'container-builder-durable-objects' + ) + + expect(host?.durableObjects).toEqual({ BUILDER: 'Builder' }) + expect(result.containerEngine).toBeUndefined() + }) +}) + +describe('referenced durable_object containers through a cross-worker Durable Object ref', () => { + /** + * Resolve a config whose `BUILDER` is the builder's class. + * + * @param projectDir - The config's directory. + * @param ref - The builder's ref. + * @param containers - The mode under test, or none for the default. + */ + function resolveThroughDORef( + projectDir: string, + ref: RefResult, + containers?: ReferencedContainerMode + ): ReturnType { + const config = { + name: 'site', + compatibilityDate: '2026-09-29', + bindings: { durableObjects: { BUILDER: (ref as unknown as { BUILDER: unknown }).BUILDER } } + } as unknown as DevflareConfig + return resolveDOBindings(config, projectDir, containers ? { containers } : {}) + } + + test('the default leaves the hosting namespace plain', async () => { + const { projectDir, ref } = await writeBuilder() + + const result = await resolveThroughDORef(projectDir, ref) + + expect(result.workers[0]?.durableObjects).toEqual({ BUILDER: 'Builder' }) + expect(result.crossWorkerDOBindings).toEqual({ + BUILDER: { className: 'Builder', scriptName: 'container-builder' } + }) + expect(result.containerEngine).toBeUndefined() + }) + + test(`attach with ${ENABLE_CONTAINERS_ENV}=0 attaches nothing`, async () => { + const { projectDir, ref } = await writeBuilder() + process.env[ENABLE_CONTAINERS_ENV] = '0' + + const result = await resolveThroughDORef(projectDir, ref, 'attach') + + expect(result.workers[0]?.durableObjects).toEqual({ BUILDER: 'Builder' }) + expect(result.containerEngine).toBeUndefined() + }) + + test('refuse throws for the hosting worker', async () => { + const { projectDir, ref } = await writeBuilder() + + await expect(resolveThroughDORef(projectDir, ref, 'refuse')).rejects.toThrow( + /Referenced worker "container-builder" declares durable_object containers/ + ) + }) +}) From 4226aa9d8363cb38f12fdb322551f85a185c9c06 Mon Sep 17 00:00:00 2001 From: "Arthur @Refzlund" Date: Mon, 30 Nov 2026 17:53:28 +0100 Subject: [PATCH 6/8] fix(containers): QA round 1 on referenced workers' containers (3 red) - resolve-service-bindings.ts was 1,147 lines against the 1,000-line ceiling, which reddened validate. The referenced-container decision moves to referenced-containers.ts, and Bun detection, the bundle cache and the Durable Object host bundler to durable-object-bundle.ts (906 lines left; clearBundleCache and ReferencedContainerMode are still exported from it). - A referenced worker's container engine reaching Miniflare was graded by nothing, because Miniflare's default socket hid a dropped option. The test-context merge moves into applyMultiWorkerConfig, and unit cases on a non-default socket grade it there and in buildMiniflareDevConfig. - The workspace-dev refusal was graded only through the function it calls. A test now runs prepareWorkspaceApp against an app that references a container-backed builder. - Docs no longer say a cross-worker Durable Object ref's containers run under devflare dev, which resolves no such refs. They say the devflare dev path is tested for a worker-only project. Co-Authored-By: Claude Opus 5.5 --- .../container-durable-object-scheduling.md | 14 +- .../docs/content/bindings/compact-guides-2.ts | 4 +- docs/CLOUDFLARE_SUPPORT_MATRIX.md | 9 +- packages/devflare/LLM.md | 4 +- .../src/test/durable-object-bundle.ts | 164 +++++++++++ .../src/test/referenced-containers.ts | 121 ++++++++ .../src/test/resolve-service-bindings.ts | 262 +----------------- .../src/test/simple-context-multi-worker.ts | 9 + packages/devflare/src/test/simple-context.ts | 7 - .../dev-server/miniflare-dev-config.test.ts | 34 +++ ...orkspace-durable-object-containers.test.ts | 95 ++++++- .../test/simple-context-multi-worker.test.ts | 60 ++++ 12 files changed, 509 insertions(+), 274 deletions(-) create mode 100644 packages/devflare/src/test/durable-object-bundle.ts create mode 100644 packages/devflare/src/test/referenced-containers.ts diff --git a/.changeset/container-durable-object-scheduling.md b/.changeset/container-durable-object-scheduling.md index b1d2fed9..65adced3 100644 --- a/.changeset/container-durable-object-scheduling.md +++ b/.changeset/container-durable-object-scheduling.md @@ -39,14 +39,16 @@ them, leaving `ctx.container` undefined. `devflare workspace dev` does not run t an app that declares one, and `containers.start()` refuses a `durable_object` entry, which only its Durable Object can start. -**A worker that is only referenced runs its containers too.** When the config under test or under -`devflare dev` reaches a worker through a `ref()` service binding, or binds a Durable Object class of -another worker, that worker's `durable_object` containers are built from its own config and attached -where devflare hosts its Durable Objects, with the intercept targets its modules export. So a test +**A worker that is only referenced runs its containers too.** When the config reaches a worker +through a `ref()` service binding (in `createTestContext()` and in `devflare dev`), or binds a Durable +Object class of another worker (in `createTestContext()`), that worker's `durable_object` containers +are built from its own config and attached where devflare hosts its Durable Objects, with the +intercept targets its modules export. So a test can drive a container through the service binding that production uses. A config that references such a worker now needs an engine in those runs (or `DEVFLARE_ENABLE_CONTAINERS=0`), even when it -declares no container itself. `devflare workspace dev` refuses an app that references one, and the -Vite plugin leaves a referenced worker's containers out, so `ctx.container` is undefined there. +declares no container itself. `devflare workspace dev` refuses an app that reaches one through a service +binding, and the Vite plugin leaves a referenced worker's containers out, so `ctx.container` is +undefined there. **For TypeScript consumers:** a `containers` entry's type is now a union of the two policies' shapes, so code that reads `config.containers[i].image` must first check `schedulingPolicy`. diff --git a/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts b/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts index 385c4be5..949666ae 100644 --- a/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts +++ b/apps/documentation/src/lib/docs/content/bindings/compact-guides-2.ts @@ -558,8 +558,8 @@ export class Builder extends DurableObject { 'HTTPS interception needs the container to trust `/etc/cloudflare/certs/cloudflare-containers-ca.crt`.', "Local runs need Linux or macOS: workerd cannot reach a Windows named pipe, so on Windows devflare refuses and points at WSL, as Wrangler does. Set `DEVFLARE_ENABLE_CONTAINERS=0` to start without containers; `ctx.container` is then undefined. Devflare uses `WRANGLER_DOCKER_HOST` or `DOCKER_HOST` when set, then the engine's own socket.", '`devflare workspace dev` does not run durable_object containers yet and refuses an app that declares one; run `devflare dev` in that app. The `containers.start()` helper starts only `default`-policy containers.', - 'A worker this one only references runs its containers too, in `createTestContext()` and `devflare dev`: through a service binding to it, or a cross-worker Durable Object binding to its class, devflare builds its images from its own config and attaches them where it hosts that Durable Object. So once a worker references one with a container, those runs need an engine (and on Windows, WSL or `DEVFLARE_ENABLE_CONTAINERS=0`) even when its own config declares none.', - "The Vite plugin (`vite dev` of a SvelteKit app) does not attach a referenced worker's containers, so `ctx.container` is undefined in it there; test that path with `createTestContext()` or run the referenced worker under `devflare dev`.", + 'A worker this one only references runs its containers too. Through a `ref()` service binding to it, in `createTestContext()` and in `devflare dev`, or through a cross-worker Durable Object binding to its class, in `createTestContext()`, devflare builds its images from its own config and attaches them where it hosts that Durable Object. So once a worker references one with a container, those runs need an engine (and on Windows, WSL or `DEVFLARE_ENABLE_CONTAINERS=0`) even when its own config declares none.', + "The Vite plugin (`vite dev` of a SvelteKit app) does not attach a referenced worker's containers, so `ctx.container` is undefined in it there. The `devflare dev` path above is tested for a worker-only project; test a SvelteKit app's call into such a worker with `createTestContext()`. `devflare workspace dev` refuses an app that reaches one through a service binding.", 'Images are rebuilt each time the config loads; a change inside the container needs a restart.' ] }, diff --git a/docs/CLOUDFLARE_SUPPORT_MATRIX.md b/docs/CLOUDFLARE_SUPPORT_MATRIX.md index 92394e2a..4f15afb5 100644 --- a/docs/CLOUDFLARE_SUPPORT_MATRIX.md +++ b/docs/CLOUDFLARE_SUPPORT_MATRIX.md @@ -290,10 +290,11 @@ Durable Object in Miniflare, so `ctx.container`, `enableInternet` and the outbound intercepts work against a real local container. That path is not offline-first, needs Linux or macOS (devflare refuses Windows, as Wrangler does), and is turned off with `DEVFLARE_ENABLE_CONTAINERS=0`. A worker reached through a -`ref()` service binding or a cross-worker Durable Object binding runs its -containers the same way in those two runtimes. `devflare workspace dev` does not -run them yet and refuses an app that declares or references one; the Vite plugin -leaves a referenced worker's containers out. +`ref()` service binding runs its containers the same way in both runtimes, and one +reached through a cross-worker Durable Object binding does in `createTestContext()`. +`devflare workspace dev` does not run them yet and refuses an app that declares one +or reaches one through a service binding; the Vite plugin leaves a referenced +worker's containers out. ## How deploy auto-provisioning works diff --git a/packages/devflare/LLM.md b/packages/devflare/LLM.md index 9efeac15..4504a23f 100644 --- a/packages/devflare/LLM.md +++ b/packages/devflare/LLM.md @@ -16002,8 +16002,8 @@ Set `schedulingPolicy: 'durable_object'` and list the images the object may star - HTTPS interception needs the container to trust `/etc/cloudflare/certs/cloudflare-containers-ca.crt`. - Local runs need Linux or macOS: workerd cannot reach a Windows named pipe, so on Windows devflare refuses and points at WSL, as Wrangler does. Set `DEVFLARE_ENABLE_CONTAINERS=0` to start without containers; `ctx.container` is then undefined. Devflare uses `WRANGLER_DOCKER_HOST` or `DOCKER_HOST` when set, then the engine's own socket. - `devflare workspace dev` does not run durable_object containers yet and refuses an app that declares one; run `devflare dev` in that app. The `containers.start()` helper starts only `default`-policy containers. -- A worker this one only references runs its containers too, in `createTestContext()` and `devflare dev`: through a service binding to it, or a cross-worker Durable Object binding to its class, devflare builds its images from its own config and attaches them where it hosts that Durable Object. So once a worker references one with a container, those runs need an engine (and on Windows, WSL or `DEVFLARE_ENABLE_CONTAINERS=0`) even when its own config declares none. -- The Vite plugin (`vite dev` of a SvelteKit app) does not attach a referenced worker's containers, so `ctx.container` is undefined in it there; test that path with `createTestContext()` or run the referenced worker under `devflare dev`. +- A worker this one only references runs its containers too. Through a `ref()` service binding to it, in `createTestContext()` and in `devflare dev`, or through a cross-worker Durable Object binding to its class, in `createTestContext()`, devflare builds its images from its own config and attaches them where it hosts that Durable Object. So once a worker references one with a container, those runs need an engine (and on Windows, WSL or `DEVFLARE_ENABLE_CONTAINERS=0`) even when its own config declares none. +- The Vite plugin (`vite dev` of a SvelteKit app) does not attach a referenced worker's containers, so `ctx.container` is undefined in it there. The `devflare dev` path above is tested for a worker-only project; test a SvelteKit app's call into such a worker with `createTestContext()`. `devflare workspace dev` refuses an app that reaches one through a service binding. - Images are rebuilt each time the config loads; a change inside the container needs a restart. ##### Example — Declare a Durable Object-managed container diff --git a/packages/devflare/src/test/durable-object-bundle.ts b/packages/devflare/src/test/durable-object-bundle.ts new file mode 100644 index 00000000..4bc457fa --- /dev/null +++ b/packages/devflare/src/test/durable-object-bundle.ts @@ -0,0 +1,164 @@ +// ============================================================================= +// Referenced-worker bundling — Bun detection, the shared cache, Durable Objects +// ============================================================================= +// resolve-service-bindings builds a referenced worker's scripts with Bun.build; +// this module holds what both of its bundlers share and the Durable Object +// host bundler, so that file stays within the source-size ceiling. +// ============================================================================= + +import { dirname, join } from 'node:path' + +// ----------------------------------------------------------------------------- +// Bun Runtime Detection +// ----------------------------------------------------------------------------- + +/** Bun, when this process runs under it; bundling a worker needs it. */ +export function getBunRuntime(): + | { + build: (options: { + entrypoints: string[] + target: string + format: string + minify: boolean + external?: string[] + }) => Promise<{ + success: boolean + logs: string[] + outputs: Array<{ text: () => Promise }> + }> + } + | undefined { + const g = globalThis as { Bun?: unknown } + if (typeof g.Bun === 'object' && g.Bun !== null) { + return g.Bun as ReturnType + } + return undefined +} + +// ----------------------------------------------------------------------------- +// Bundle Cache +// ----------------------------------------------------------------------------- + +/** + * Cache for bundled worker scripts to avoid re-bundling in repeated test runs. + * Key: entryPath + entrypoint, Value: bundled script code + */ +export const bundleCache = new Map() + +/** + * Clear the bundle cache (useful between test suites) + */ +export function clearBundleCache(): void { + bundleCache.clear() +} + +/** A Durable Object class to host, and the module it comes from. */ +export interface DurableObjectClassToBundle { + bindingName: string + className: string + scriptPath: string +} + +/** + * Bundle the Durable Object classes a referenced worker hosts into one module + * worker for Miniflare, re-exporting each class (native RPC, no wrappers). + * + * Side effects: writes and then removes a temporary entry under the first + * class's `.devflare/` directory; caches the result in {@link bundleCache}. + * + * @param doClasses - The classes, each with the module it comes from. + * @param workerName - The hosting worker's name, for the entry file and messages. + * @param entrypointExports - `WorkerEntrypoint` classes to export beside them, + * so a container's outbound intercepts can target `ctx.exports.`. + * @returns The bundled script, or `null` (with a warning) when it cannot be built. + */ +export async function bundleDOClasses( + doClasses: DurableObjectClassToBundle[], + workerName: string, + entrypointExports: Array<{ name: string; scriptPath: string }> = [] +): Promise { + const cacheKey = `do:${[ + ...doClasses.map((d) => `${d.scriptPath}::${d.className}`), + ...entrypointExports.map((e) => `${e.scriptPath}::${e.name}`) + ].join('|')}` + const cached = bundleCache.get(cacheKey) + if (cached) return cached + + const bun = getBunRuntime() + if (!bun) { + console.warn( + `[devflare] Cannot bundle Durable Object worker "${workerName}" — the Bun runtime is required to bundle DO classes, ` + + 'but this process is not running under Bun. The Durable Object binding will be left unresolved. ' + + 'Run your tests with `bun test` (or the devflare test runner) to enable cross-worker Durable Objects.' + ) + return null + } + + try { + const { writeFileSync, mkdirSync, unlinkSync } = await import('node:fs') + + // Build imports and exports for DO classes + // A container-backed class's module also exports the WorkerEntrypoint its + // outbound intercepts target through ctx.exports. + const exported = [ + ...doClasses.map((d) => ({ name: d.className, scriptPath: d.scriptPath })), + ...entrypointExports + ] + const imports = exported + .map((e) => `import { ${e.name} } from '${e.scriptPath.replace(/\\/g, '/')}'`) + .join('\n') + + const exports = exported.map((e) => e.name).join(', ') + + // Build the final script - no wrappers, native RPC via DurableObject base class + const entryCode = ` +${imports} + +// Re-export DO classes for Miniflare binding +export { ${exports} } + +// Default export with fetch handler +export default { + async fetch(request, env) { + return new Response('DO Worker: ${workerName}') + } +} +` + + // Write and bundle + const tempDir = join(dirname(doClasses[0].scriptPath), '.devflare') + mkdirSync(tempDir, { recursive: true }) + const entryPath = join(tempDir, `__do_entry_${workerName}.ts`) + writeFileSync(entryPath, entryCode) + + try { + const result = await bun.build({ + entrypoints: [entryPath], + target: 'browser', + format: 'esm', + minify: false, + external: ['cloudflare:workers', 'cloudflare:*'] + }) + + if (!result.success) { + console.warn( + `[devflare] Failed to bundle DO worker "${workerName}": ${result.logs.join('\n')}` + ) + return null + } + + const bundledCode = await result.outputs[0].text() + bundleCache.set(cacheKey, bundledCode) + return bundledCode + } finally { + try { + unlinkSync(entryPath) + } catch { + /* ignore */ + } + } + } catch (error) { + console.warn(`[devflare] Error bundling DO worker "${workerName}":`, error) + return null + } +} diff --git a/packages/devflare/src/test/referenced-containers.ts b/packages/devflare/src/test/referenced-containers.ts new file mode 100644 index 00000000..69675aa5 --- /dev/null +++ b/packages/devflare/src/test/referenced-containers.ts @@ -0,0 +1,121 @@ +// ============================================================================= +// Referenced workers' durable_object containers +// ============================================================================= +// When a test or `devflare dev` reaches a worker it only references, that +// worker's Durable Objects run in a host devflare builds for it. This module +// decides what happens to the containers its config attaches to them. +// ============================================================================= + +import { readFileSync } from 'node:fs' +import type { DevflareConfigInput } from '../config' +import { containersConfigSchema } from '../config/schema-runtime' +import type { DurableObjectClassToBundle } from './durable-object-bundle' +import { + areLocalContainersDisabled, + attachDurableObjectContainers, + ENABLE_CONTAINERS_ENV, + findExportedWorkerEntrypoints, + type MiniflareContainerEngineOption, + type MiniflareDurableObjectEntry, + planLocalDurableObjectContainers, + prepareLocalDurableObjectContainers +} from './durable-object-containers' + +/** + * How a referenced worker's `durable_object` containers are treated. + * + * - `attach`: build their images and attach them to the worker that hosts the + * Durable Object, so `ctx.container` is real there (createTestContext and + * `devflare dev`). + * - `refuse`: throw when there are any, for a runtime that cannot run them + * (workspace dev), so `ctx.container` is never silently undefined. + * - `ignore`: leave them out. For callers whose result can reach a build + * output (the Vite plugin), where starting an engine would be wrong. + */ +export type ReferencedContainerMode = 'attach' | 'refuse' | 'ignore' + +/** What a referenced worker's Durable Object host needs for its containers. */ +export interface ReferencedContainerSetup { + /** `WorkerEntrypoint` classes to export beside the classes, for `ctx.exports`. */ + entrypointExports: Array<{ name: string; scriptPath: string }> + /** Attach the prepared containers to the host's namespaces. */ + attach( + durableObjects: Record + ): Record + /** The engine option, when containers were prepared. */ + containerEngine?: MiniflareContainerEngineOption +} + +/** + * Prepare a referenced worker's `durable_object` containers by `mode`. + * + * Side effects under `attach`: builds or pulls images (see + * prepareLocalDurableObjectContainers). + * + * @param refConfig - The referenced worker's config, parsed or not; only its + * `containers` are read. + * @param refConfigDir - Its directory. + * @param workerName - Its name, for messages. + * @param doClasses - The classes its host bundles. + * @param mode - attach, refuse or ignore. + * @returns The exports and attachment for the host; a no-op one when there is + * nothing to attach. + * @throws Under `refuse` when it declares any (and they are not turned off), + * and under `attach` as prepareLocalDurableObjectContainers does. + */ +export async function prepareReferencedContainers( + refConfig: Pick, + refConfigDir: string, + workerName: string, + doClasses: DurableObjectClassToBundle[], + mode: ReferencedContainerMode +): Promise { + const none: ReferencedContainerSetup = { entrypointExports: [], attach: (dos) => dos } + if (mode === 'ignore') return none + + // A cross-worker Durable Object's referenced config arrives unparsed, so its + // containers are validated here, by the same schema the worker's own uses. + const containerConfig = { containers: containersConfigSchema.parse(refConfig.containers) } + + if (mode === 'refuse') { + const planned = planLocalDurableObjectContainers(containerConfig, refConfigDir) + if (planned.length > 0 && !areLocalContainersDisabled(process.env)) { + const classNames = planned.map((container) => container.className).join(', ') + throw new Error( + `Referenced worker "${workerName}" declares durable_object containers (${classNames}), which this runtime does not run. Run it under \`devflare dev\` or createTestContext(), or set ${ENABLE_CONTAINERS_ENV}=0 to start without containers.` + ) + } + return none + } + + const prepared = await prepareLocalDurableObjectContainers({ + config: containerConfig, + configDir: refConfigDir + }) + if (!prepared) return none + + const entrypointExports: Array<{ name: string; scriptPath: string }> = [] + const taken = new Set(doClasses.map((doClass) => doClass.className)) + for (const doClass of doClasses) { + if (!prepared.containersByClassName.has(doClass.className)) continue + for (const name of findExportedWorkerEntrypoints(readFileSync(doClass.scriptPath, 'utf-8'))) { + if (taken.has(name)) continue + taken.add(name) + entrypointExports.push({ name, scriptPath: doClass.scriptPath }) + } + } + + const bindingClassNames = new Map( + doClasses.map((doClass) => [doClass.bindingName, doClass.className]) + ) + return { + entrypointExports, + containerEngine: prepared.containerEngine, + attach: (durableObjects) => + attachDurableObjectContainers( + durableObjects, + bindingClassNames, + prepared.containersByClassName + ) + } +} diff --git a/packages/devflare/src/test/resolve-service-bindings.ts b/packages/devflare/src/test/resolve-service-bindings.ts index ac560a0e..bfc0a691 100644 --- a/packages/devflare/src/test/resolve-service-bindings.ts +++ b/packages/devflare/src/test/resolve-service-bindings.ts @@ -18,7 +18,6 @@ import { normalizeR2Binding } from '../config' import type { RefResult, WorkerBinding } from '../config/ref' -import { containersConfigSchema } from '../config/schema-runtime' import { buildAiSearchInstancesConfig, buildAiSearchNamespacesConfig, @@ -42,46 +41,21 @@ import { transformWorkerEntrypoint } from '../transform/worker-entrypoint' import { discoverEntrypointsSync } from '../utils/entrypoint-discovery' import { DEFAULT_DO_PATTERN, findFilesSync } from '../utils/glob' import { - areLocalContainersDisabled, - attachDurableObjectContainers, - ENABLE_CONTAINERS_ENV, - findExportedWorkerEntrypoints, - type MiniflareContainerEngineOption, - type MiniflareDurableObjectEntry, - planLocalDurableObjectContainers, - prepareLocalDurableObjectContainers + bundleCache, + bundleDOClasses, + type DurableObjectClassToBundle, + getBunRuntime +} from './durable-object-bundle' +import type { + MiniflareContainerEngineOption, + MiniflareDurableObjectEntry } from './durable-object-containers' import { type ReferencedEnv, resolveReferencedConfig, resolveReferencedConfigDir } from './referenced-config' - -// ----------------------------------------------------------------------------- -// Bun Runtime Detection -// ----------------------------------------------------------------------------- - -function getBunRuntime(): - | { - build: (options: { - entrypoints: string[] - target: string - format: string - minify: boolean - external?: string[] - }) => Promise<{ - success: boolean - logs: string[] - outputs: Array<{ text: () => Promise }> - }> - } - | undefined { - const g = globalThis as { Bun?: unknown } - if (typeof g.Bun === 'object' && g.Bun !== null) { - return g.Bun as ReturnType - } - return undefined -} +import { prepareReferencedContainers, type ReferencedContainerMode } from './referenced-containers' // Entrypoint discovery imported from shared utils: discoverEntrypointsSync @@ -124,22 +98,8 @@ function discoverDOFilesSync( return classToPath } -// ----------------------------------------------------------------------------- -// Bundle Cache -// ----------------------------------------------------------------------------- - -/** - * Cache for bundled worker scripts to avoid re-bundling in repeated test runs. - * Key: entryPath + entrypoint, Value: bundled script code - */ -const bundleCache = new Map() - -/** - * Clear the bundle cache (useful between test suites) - */ -export function clearBundleCache(): void { - bundleCache.clear() -} +export { clearBundleCache } from './durable-object-bundle' +export type { ReferencedContainerMode } from './referenced-containers' // ----------------------------------------------------------------------------- // Types @@ -329,112 +289,6 @@ export interface ResolveServiceBindingsOptions { containers?: ReferencedContainerMode } -/** - * How a referenced worker's `durable_object` containers are treated. - * - * - `attach`: build their images and attach them to the worker that hosts the - * Durable Object, so `ctx.container` is real there (createTestContext and - * `devflare dev`). - * - `refuse`: throw when there are any, for a runtime that cannot run them - * (workspace dev), so `ctx.container` is never silently undefined. - * - `ignore`: leave them out. For callers whose result can reach a build - * output (the Vite plugin), where starting an engine would be wrong. - */ -export type ReferencedContainerMode = 'attach' | 'refuse' | 'ignore' - -/** A Durable Object class to host, and the module it comes from. */ -interface DurableObjectClassToBundle { - bindingName: string - className: string - scriptPath: string -} - -/** What a referenced worker's Durable Object host needs for its containers. */ -interface ReferencedContainerSetup { - /** `WorkerEntrypoint` classes to export beside the classes, for `ctx.exports`. */ - entrypointExports: Array<{ name: string; scriptPath: string }> - /** Attach the prepared containers to the host's namespaces. */ - attach( - durableObjects: Record - ): Record - /** The engine option, when containers were prepared. */ - containerEngine?: MiniflareContainerEngineOption -} - -/** - * Prepare a referenced worker's `durable_object` containers by `mode`. - * - * Side effects under `attach`: builds or pulls images (see - * prepareLocalDurableObjectContainers). - * - * @param refConfig - The referenced worker's config, parsed or not; only its - * `containers` are read. - * @param refConfigDir - Its directory. - * @param workerName - Its name, for messages. - * @param doClasses - The classes its host bundles. - * @param mode - attach, refuse or ignore. - * @returns The exports and attachment for the host; a no-op one when there is - * nothing to attach. - * @throws Under `refuse` when it declares any (and they are not turned off), - * and under `attach` as prepareLocalDurableObjectContainers does. - */ -async function prepareReferencedContainers( - refConfig: Pick, - refConfigDir: string, - workerName: string, - doClasses: DurableObjectClassToBundle[], - mode: ReferencedContainerMode -): Promise { - const none: ReferencedContainerSetup = { entrypointExports: [], attach: (dos) => dos } - if (mode === 'ignore') return none - - // A cross-worker Durable Object's referenced config arrives unparsed, so its - // containers are validated here, by the same schema the worker's own uses. - const containerConfig = { containers: containersConfigSchema.parse(refConfig.containers) } - - if (mode === 'refuse') { - const planned = planLocalDurableObjectContainers(containerConfig, refConfigDir) - if (planned.length > 0 && !areLocalContainersDisabled(process.env)) { - const classNames = planned.map((container) => container.className).join(', ') - throw new Error( - `Referenced worker "${workerName}" declares durable_object containers (${classNames}), which this runtime does not run. Run it under \`devflare dev\` or createTestContext(), or set ${ENABLE_CONTAINERS_ENV}=0 to start without containers.` - ) - } - return none - } - - const prepared = await prepareLocalDurableObjectContainers({ - config: containerConfig, - configDir: refConfigDir - }) - if (!prepared) return none - - const entrypointExports: Array<{ name: string; scriptPath: string }> = [] - const taken = new Set(doClasses.map((doClass) => doClass.className)) - for (const doClass of doClasses) { - if (!prepared.containersByClassName.has(doClass.className)) continue - for (const name of findExportedWorkerEntrypoints(readFileSync(doClass.scriptPath, 'utf-8'))) { - if (taken.has(name)) continue - taken.add(name) - entrypointExports.push({ name, scriptPath: doClass.scriptPath }) - } - } - - const bindingClassNames = new Map( - doClasses.map((doClass) => [doClass.bindingName, doClass.className]) - ) - return { - entrypointExports, - containerEngine: prepared.containerEngine, - attach: (durableObjects) => - attachDurableObjectContainers( - durableObjects, - bindingClassNames, - prepared.containersByClassName - ) - } -} - interface ReferencedDurableObjectResolution { workers: ResolvedWorker[] bindings: Record @@ -1050,97 +904,3 @@ async function resolveDORefWorker( ...(containers.containerEngine && { containerEngine: containers.containerEngine }) } } - -/** - * Bundle DO classes with RPC wrappers for Miniflare - */ -async function bundleDOClasses( - doClasses: DurableObjectClassToBundle[], - workerName: string, - entrypointExports: Array<{ name: string; scriptPath: string }> = [] -): Promise { - const cacheKey = `do:${[ - ...doClasses.map((d) => `${d.scriptPath}::${d.className}`), - ...entrypointExports.map((e) => `${e.scriptPath}::${e.name}`) - ].join('|')}` - const cached = bundleCache.get(cacheKey) - if (cached) return cached - - const bun = getBunRuntime() - if (!bun) { - console.warn( - `[devflare] Cannot bundle Durable Object worker "${workerName}" — the Bun runtime is required to bundle DO classes, ` + - 'but this process is not running under Bun. The Durable Object binding will be left unresolved. ' + - 'Run your tests with `bun test` (or the devflare test runner) to enable cross-worker Durable Objects.' - ) - return null - } - - try { - const { writeFileSync, mkdirSync, unlinkSync } = await import('fs') - - // Build imports and exports for DO classes - // A container-backed class's module also exports the WorkerEntrypoint its - // outbound intercepts target through ctx.exports. - const exported = [ - ...doClasses.map((d) => ({ name: d.className, scriptPath: d.scriptPath })), - ...entrypointExports - ] - const imports = exported - .map((e) => `import { ${e.name} } from '${e.scriptPath.replace(/\\/g, '/')}'`) - .join('\n') - - const exports = exported.map((e) => e.name).join(', ') - - // Build the final script - no wrappers, native RPC via DurableObject base class - const entryCode = ` -${imports} - -// Re-export DO classes for Miniflare binding -export { ${exports} } - -// Default export with fetch handler -export default { - async fetch(request, env) { - return new Response('DO Worker: ${workerName}') - } -} -` - - // Write and bundle - const tempDir = join(dirname(doClasses[0].scriptPath), '.devflare') - mkdirSync(tempDir, { recursive: true }) - const entryPath = join(tempDir, `__do_entry_${workerName}.ts`) - writeFileSync(entryPath, entryCode) - - try { - const result = await bun.build({ - entrypoints: [entryPath], - target: 'browser', - format: 'esm', - minify: false, - external: ['cloudflare:workers', 'cloudflare:*'] - }) - - if (!result.success) { - console.warn( - `[devflare] Failed to bundle DO worker "${workerName}": ${result.logs.join('\n')}` - ) - return null - } - - const bundledCode = await result.outputs[0].text() - bundleCache.set(cacheKey, bundledCode) - return bundledCode - } finally { - try { - unlinkSync(entryPath) - } catch { - /* ignore */ - } - } - } catch (error) { - console.warn(`[devflare] Error bundling DO worker "${workerName}":`, error) - return null - } -} diff --git a/packages/devflare/src/test/simple-context-multi-worker.ts b/packages/devflare/src/test/simple-context-multi-worker.ts index abda83e8..51c36735 100644 --- a/packages/devflare/src/test/simple-context-multi-worker.ts +++ b/packages/devflare/src/test/simple-context-multi-worker.ts @@ -37,6 +37,10 @@ type AuxiliaryWorker = ServiceBindingResolution['workers'][number] * @param doBindingResolution - workers and primary bindings for cross-worker DOs * @param runtime - the loaded `miniflare` module, whose schema names the * Miniflare-wide options that stay at the top level + * + * A referenced worker's attached containers need the engine its resolution + * prepared; `containerEngine` is Miniflare-wide, so it lands at the top level + * unless this worker's own containers already set one. */ export function applyMultiWorkerConfig( mfConfig: any, @@ -48,6 +52,11 @@ export function applyMultiWorkerConfig( const { __devflareLocalSecretWorkers, __devflareLocalBindingWorkers, ...singleWorkerOptions } = mfConfig const { shared, worker } = splitSharedOptions(runtime, singleWorkerOptions) + const referencedContainerEngine = + serviceBindingResolution?.containerEngine ?? doBindingResolution?.containerEngine + if (referencedContainerEngine && shared.containerEngine === undefined) { + shared.containerEngine = referencedContainerEngine + } const { durableObjects, serviceBindings, ...workerOptions } = worker const primaryDurableObjects = { diff --git a/packages/devflare/src/test/simple-context.ts b/packages/devflare/src/test/simple-context.ts index e242ee74..b706fd5d 100644 --- a/packages/devflare/src/test/simple-context.ts +++ b/packages/devflare/src/test/simple-context.ts @@ -167,13 +167,6 @@ export async function createTestContext(configPath?: string): Promise { ) } - // One engine serves every worker's containers; it is a Miniflare-wide option. - const referencedContainerEngine = - serviceBindingResolution?.containerEngine ?? doBindingResolution?.containerEngine - if (referencedContainerEngine && !mfConfig.containerEngine) { - mfConfig.containerEngine = referencedContainerEngine - } - const hasMultiWorkerServices = serviceBindingResolution && serviceBindingResolution.workers.length > 0 const hasMultiWorkerDOs = doBindingResolution && doBindingResolution.workers.length > 0 diff --git a/packages/devflare/tests/unit/dev-server/miniflare-dev-config.test.ts b/packages/devflare/tests/unit/dev-server/miniflare-dev-config.test.ts index 6c00e4df..f87563da 100644 --- a/packages/devflare/tests/unit/dev-server/miniflare-dev-config.test.ts +++ b/packages/devflare/tests/unit/dev-server/miniflare-dev-config.test.ts @@ -280,5 +280,39 @@ describe('buildMiniflareDevConfig', () => { ) ).toThrow('No Durable Object in files.durableObjects defines that class') }) + + // A worker with no container of its own that references one: the engine + // comes from the service-binding resolution. Not Miniflare's default + // socket, so a dropped option cannot pass by falling back to it. + const referencedEngine = { localDocker: { socketPath: 'unix:///tmp/referenced-engine.sock' } } + const referencedBuilder = { + primaryServiceBindings: { BUILDER_SERVICE: { name: 'container-builder' } }, + workers: [{ name: 'container-builder', modules: true, script: 'export default {}' }], + containerEngine: referencedEngine + } + + test("sets a referenced worker's engine when this worker prepared none", () => { + const mfConfig = buildMiniflareDevConfig( + buildBaseInput({ + config: { name: 'site-worker' }, + serviceBindingResolution: referencedBuilder + }) + ) + + expect(mfConfig.containerEngine).toEqual(referencedEngine) + }) + + test("keeps this worker's own engine over a referenced worker's", () => { + const mfConfig = buildMiniflareDevConfig( + buildBaseInput({ + config: { name: 'site-worker' }, + doResult, + localContainers, + serviceBindingResolution: referencedBuilder + }) + ) + + expect(mfConfig.containerEngine).toEqual(localContainers.containerEngine) + }) }) }) diff --git a/packages/devflare/tests/unit/dev-server/workspace-durable-object-containers.test.ts b/packages/devflare/tests/unit/dev-server/workspace-durable-object-containers.test.ts index b716316c..73f0d6b4 100644 --- a/packages/devflare/tests/unit/dev-server/workspace-durable-object-containers.test.ts +++ b/packages/devflare/tests/unit/dev-server/workspace-durable-object-containers.test.ts @@ -1,6 +1,19 @@ -import { afterEach, describe, expect, test } from 'bun:test' +import { afterAll, afterEach, describe, expect, test } from 'bun:test' +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' import type { DevflareConfig } from '../../../src/config' -import { assertNoLocalDurableObjectContainers } from '../../../src/dev-server/workspace/prepare-app' +import { + assertNoLocalDurableObjectContainers, + prepareWorkspaceApp +} from '../../../src/dev-server/workspace/prepare-app' + +const tempDirs: string[] = [] + +afterAll(async () => { + for (const dir of tempDirs) await rm(dir, { recursive: true, force: true }) +}) const originalFlag = process.env.DEVFLARE_ENABLE_CONTAINERS @@ -44,3 +57,81 @@ describe('workspace dev and durable_object containers', () => { ).not.toThrow() }) }) + +/** + * Write an app whose only service binding is a `ref()` to a builder worker + * whose Durable Object carries a durable_object container. + * + * @returns The app's config path. + */ +async function writeAppReferencingABuilder(): Promise { + const appDir = await mkdtemp(join(tmpdir(), 'devflare-ws-ref-container-')) + tempDirs.push(appDir) + const builderDir = join(appDir, 'builder') + await mkdir(join(builderDir, 'src'), { recursive: true }) + await writeFile( + join(builderDir, 'src', 'ep.builder.ts'), + "import { WorkerEntrypoint } from 'cloudflare:workers'\nexport class BuilderEntrypoint extends WorkerEntrypoint {}\n" + ) + await writeFile( + join(builderDir, 'src', 'do.builder.ts'), + "import { DurableObject } from 'cloudflare:workers'\nexport class Builder extends DurableObject {}\n" + ) + await writeFile( + join(builderDir, 'devflare.config.ts'), + `export default ${JSON.stringify({ + name: 'container-builder', + compatibilityDate: '2026-09-29', + files: { fetch: false, entrypoints: 'src/ep.*.ts', durableObjects: 'src/do.*.ts' }, + bindings: { durableObjects: { BUILDER: 'Builder' } }, + containers: [ + { + className: 'Builder', + schedulingPolicy: 'durable_object', + images: { base: { dockerfile: './container/Dockerfile' } } + } + ] + })}\n` + ) + const refModule = pathToFileURL(join(import.meta.dir, '../../../src/config/ref.ts')).href + const configPath = join(appDir, 'devflare.config.ts') + await writeFile( + configPath, + [ + `import { ref } from '${refModule}'`, + "const builder = ref(() => import('./builder/devflare.config.ts'))", + 'export default {', + "\tname: 'render',", + "\tcompatibilityDate: '2026-09-29',", + "\tbindings: { services: { BUILDER_SERVICE: builder.worker('BuilderEntrypoint') } }", + '}', + '' + ].join('\n') + ) + return configPath +} + +describe("workspace dev and a referenced worker's durable_object containers", () => { + test('prepareWorkspaceApp refuses an app that reaches one through a service binding', async () => { + delete process.env.DEVFLARE_ENABLE_CONTAINERS + const configPath = await writeAppReferencingABuilder() + + await expect( + prepareWorkspaceApp({ + configPath, + appCwd: join(configPath, '..'), + directSocketPort: 0, + vite: false, + vitePort: 0, + persist: false, + debug: false, + verbose: false, + browserShimPort: 0, + r2PresignSecret: 'test-secret', + host: '127.0.0.1' + }) + ).rejects.toThrow( + /Referenced worker "container-builder" declares durable_object containers \(Builder\)/ + ) + }, 30_000) +}) diff --git a/packages/devflare/tests/unit/test/simple-context-multi-worker.test.ts b/packages/devflare/tests/unit/test/simple-context-multi-worker.test.ts index 64c28e3e..54401605 100644 --- a/packages/devflare/tests/unit/test/simple-context-multi-worker.test.ts +++ b/packages/devflare/tests/unit/test/simple-context-multi-worker.test.ts @@ -77,4 +77,64 @@ describe('applyMultiWorkerConfig', () => { await runtime.dispose() } }, 30_000) + + describe("a referenced worker's container engine", () => { + // Not Miniflare's default socket, so a dropped option cannot pass by falling back to it. + const referencedEngine = { localDocker: { socketPath: 'unix:///tmp/referenced-engine.sock' } } + const ownEngine = { localDocker: { socketPath: 'unix:///tmp/own-engine.sock' } } + + /** The single-worker baseline, with this worker's own engine when given. */ + function baseline(engine?: typeof ownEngine) { + const mfConfig = buildInlineBridgeMfConfig(config) + mfConfig.script = 'export default {}' + if (engine) mfConfig.containerEngine = engine + return mfConfig + } + + test('a service-bound worker carries its engine to the top level', () => { + const mfConfig = baseline() + applyMultiWorkerConfig( + mfConfig, + config, + { ...serviceBindingResolution, containerEngine: referencedEngine }, + null, + miniflare + ) + + expect(mfConfig.containerEngine).toEqual(referencedEngine) + expect(mfConfig.workers[0].containerEngine).toBeUndefined() + }) + + test('a cross-worker Durable Object host carries its engine to the top level', () => { + const mfConfig = baseline() + const doBindingResolution = { + workers: [{ name: 'host-worker', modules: true, script: 'export default {}' }], + crossWorkerDOBindings: { BUILDER: { className: 'Builder', scriptName: 'host-worker' } }, + containerEngine: referencedEngine + } as unknown as Parameters[3] + applyMultiWorkerConfig(mfConfig, config, null, doBindingResolution, miniflare) + + expect(mfConfig.containerEngine).toEqual(referencedEngine) + }) + + test("this worker's own engine is kept over a referenced one", () => { + const mfConfig = baseline(ownEngine) + applyMultiWorkerConfig( + mfConfig, + config, + { ...serviceBindingResolution, containerEngine: referencedEngine }, + null, + miniflare + ) + + expect(mfConfig.containerEngine).toEqual(ownEngine) + }) + + test('no engine is set when nothing prepared one', () => { + const mfConfig = baseline() + applyMultiWorkerConfig(mfConfig, config, serviceBindingResolution, null, miniflare) + + expect('containerEngine' in mfConfig).toBe(false) + }) + }) }) From 72b63be46eb2901265a04cb6a27b5a21b5190c3f Mon Sep 17 00:00:00 2001 From: "Arthur @Refzlund" Date: Mon, 30 Nov 2026 17:56:30 +0100 Subject: [PATCH 7/8] test(generated-dir): allow durable-object-bundle.ts its .devflare temp dirs The Durable Object host bundler moved out of resolve-service-bindings.ts and still writes its temporary entry beside the classes it bundles, so the census of hardcoded .devflare paths names the new file with the same reason. Co-Authored-By: Claude Opus 5.5 --- packages/devflare/tests/unit/utils/generated-dir-sites.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/devflare/tests/unit/utils/generated-dir-sites.test.ts b/packages/devflare/tests/unit/utils/generated-dir-sites.test.ts index dd3590c2..b2bf2bef 100644 --- a/packages/devflare/tests/unit/utils/generated-dir-sites.test.ts +++ b/packages/devflare/tests/unit/utils/generated-dir-sites.test.ts @@ -41,6 +41,8 @@ const ALLOWED: Record = { 'secrets.local.json is AUTHORED input, not generated output — an instance with its own root must still find the secrets the user wrote', 'cli/commands/deploy/prepare.ts': 'reads a build directory the user passes on the command line; the literal is a fallback guess for their layout', + 'test/durable-object-bundle.ts': + "per-test temp dirs beside a referenced worker's Durable Object classes", 'test/resolve-service-bindings.ts': 'per-test temp dirs beside the entrypoint under test', 'test/simple-context-durable-objects.ts': 'a per-test virtual entry path' } From 1f352be87765d7d252cb6d09c2fec52c116100b8 Mon Sep 17 00:00:00 2001 From: "Arthur @Refzlund" Date: Mon, 30 Nov 2026 18:04:41 +0100 Subject: [PATCH 8/8] fix(containers): type the startup-retry clone for workers-types checkers resolve-service-bindings now imports the container modules, which brings src/test/containers.ts into apps/documentation's svelte-check. Under @cloudflare/workers-types, Request.clone() is typed with the class's own generic parameters, which fetch does not accept, so that check failed on fetchWithStartupRetries. The clone is asserted back to Request. Co-Authored-By: Claude Opus 5.5 --- packages/devflare/src/test/containers.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/devflare/src/test/containers.ts b/packages/devflare/src/test/containers.ts index fc545f44..e83733d4 100644 --- a/packages/devflare/src/test/containers.ts +++ b/packages/devflare/src/test/containers.ts @@ -640,7 +640,10 @@ async function fetchWithStartupRetries( while (Date.now() < deadline) { try { - return await fetchImpl(request.clone()) + // Under @cloudflare/workers-types (a docs or app check reaching this + // file), `clone()` is typed with the class's own generic parameters, + // which `fetch` does not accept; the clone is the same Request. + return await fetchImpl(request.clone() as Request) } catch (error) { if (!isTransientContainerFetchError(error)) { throw error