From bce853d2a95e093bb0e5884a4e021b051e999862 Mon Sep 17 00:00:00 2001 From: Isak Gustavsen Date: Wed, 25 Nov 2026 01:09:50 +0100 Subject: [PATCH 01/13] feat(void): add Cloudflare Workflows through a workflows/ convention Each default-exported defineWorkflow() or defineWorkflowEntrypoint() module in workflows/ becomes a Cloudflare Workflow with a WORKFLOW_ binding and Workflow class, started from routes with Definition.create(), createBatch() and get(). Params can be validated with a Standard Schema. Discovery follows queues/: subdirectories are joined with '-' and paths with a '_'-prefixed segment are ignored, so step helpers can live beside the workflows. Deploys to Cloudflare name each Workflow -, since Workflow names are account-scoped, and verify the emitted set before upload. Void platform deploys, framework mode and Node targets reject workflows/ for now. The generated Worker entry now imports convention modules through their namespace and fails startup with a named error when a module does not default-export a definition; this also covers durable-objects/. Closes #779 Co-Authored-By: Claude Opus 5.5 --- docs/.vitepress/config.ts | 2 + docs/guide/workflows.md | 162 ++++++++++++ docs/reference/api.md | 2 + docs/reference/api/workflows.md | 57 ++++ docs/reference/cli/setup.md | 4 +- docs/reference/resource-inference.md | 4 + docs/reference/structure.md | 5 + packages/void/AGENTS.md | 3 +- packages/void/package.json | 5 + packages/void/skills/void/SKILL.md | 1 + packages/void/src/application-analysis.ts | 4 + .../src/cli/deploy-artifact-validation.ts | 24 ++ .../void/src/cli/deploy-binding-snapshot.ts | 18 ++ .../void/src/cli/deploy-cloudflare-build.ts | 8 +- .../void/src/cli/deploy-cloudflare-migrate.ts | 2 + .../src/cli/deploy-cloudflare-preflight.ts | 10 + packages/void/src/cli/deploy.ts | 2 + packages/void/src/cli/info.ts | 11 +- packages/void/src/deploy.ts | 2 + packages/void/src/index.ts | 35 +++ packages/void/src/plugin-client-stubs.ts | 5 +- packages/void/src/plugin-cloudflare-config.ts | 12 +- packages/void/src/plugin-routing.ts | 9 + packages/void/src/plugin-worker-bindings.ts | 36 ++- packages/void/src/router/compile.ts | 86 ++++-- packages/void/src/runtime/workflows/index.ts | 246 ++++++++++++++++++ packages/void/src/shared/env.ts | 6 + .../void/src/shared/resource-definition.ts | 4 +- packages/void/src/workflows/config.ts | 55 ++++ packages/void/src/workflows/platform.ts | 10 + packages/void/src/workflows/scan.ts | 111 ++++++++ .../cloudflare-durable-build.test.ts | 106 +++++++- .../test/integration/workflow-runtime.test.ts | 222 ++++++++++++++++ packages/void/test/unit/compile.test.ts | 52 +++- packages/void/test/unit/info.test.ts | 31 +++ .../void/test/unit/plugin-inference.test.ts | 64 ++++- .../void/test/unit/workflow-runtime.test.ts | 151 +++++++++++ packages/void/test/unit/workflow-scan.test.ts | 165 ++++++++++++ packages/void/vite.config.ts | 1 + 39 files changed, 1700 insertions(+), 33 deletions(-) create mode 100644 docs/guide/workflows.md create mode 100644 docs/reference/api/workflows.md create mode 100644 packages/void/src/runtime/workflows/index.ts create mode 100644 packages/void/src/workflows/config.ts create mode 100644 packages/void/src/workflows/platform.ts create mode 100644 packages/void/src/workflows/scan.ts create mode 100644 packages/void/test/integration/workflow-runtime.test.ts create mode 100644 packages/void/test/unit/workflow-runtime.test.ts create mode 100644 packages/void/test/unit/workflow-scan.test.ts diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index af2f1a1aaf..c0be1394b0 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -126,6 +126,7 @@ const referenceItems: Array = [ { text: 'Authentication', link: '/reference/api/auth' }, { text: 'Fetch Client', link: '/reference/api/client' }, { text: 'Durable State and WebSockets', link: '/reference/api/durable' }, + { text: 'Workflows', link: '/reference/api/workflows' }, { text: 'Deployment artifacts', link: '/reference/api/deploy' }, { text: 'Database and Seeding', link: '/reference/api/database' }, { text: 'Resource Clients', link: '/reference/api/resources' }, @@ -385,6 +386,7 @@ export default extendConfig( { text: 'Sandboxes', link: '/guide/sandboxes' }, { text: 'Cron Jobs', link: '/guide/jobs' }, { text: 'Queues', link: '/guide/queues' }, + { text: 'Workflows', link: '/guide/workflows' }, { text: 'WebSockets', link: '/guide/websockets' }, { text: 'Server-Sent Events', link: '/guide/sse' }, { text: 'Live Event Streams', link: '/guide/live' }, diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md new file mode 100644 index 0000000000..90cc4617f5 --- /dev/null +++ b/docs/guide/workflows.md @@ -0,0 +1,162 @@ +--- +description: 'Run durable multi-step jobs with Cloudflare Workflows: retried steps, sleeps, and typed params.' +outline: deep +--- + +# Workflows + +Use a Workflow for work that runs across several steps and must finish even if one fails, such as onboarding emails, imports, or payment follow-ups. Each step's result is saved, failed steps are retried, and a Workflow can sleep for minutes or days between steps. + +Create a module in `workflows/` with `defineWorkflow()`. Void creates the Cloudflare Workflow and its binding for you. Workflows run in local development and in direct Cloudflare deployments (`void deploy --platform cloudflare`). + +## Define a workflow + +```ts +// workflows/onboarding.ts +import { defineWorkflow } from 'void/workflows'; +import type { WorkflowEvent } from 'void/workflows'; + +export const Onboarding = defineWorkflow({ + async run(event: WorkflowEvent<{ userId: string }>, step) { + await step.do('send welcome email', async () => { + await sendWelcomeEmail(event.payload.userId); + }); + await step.sleep('wait a day', '1 day'); + await step.do('send tips', async () => { + await sendTips(event.payload.userId); + }); + }, +}); + +export default Onboarding; +``` + +Default-export the object returned by `defineWorkflow()`. Named-export it too so routes can import it. + +TypeScript and JavaScript files are supported. Subdirectories are scanned too, and files or directories starting with `_` are ignored, so keep shared step helpers in files such as `workflows/_email.ts`. + +`run` receives: + +- `event`, with the `payload` passed to `create()`, the `instanceId`, and a `timestamp` +- `step`, Cloudflare's [`WorkflowStep`](https://developers.cloudflare.com/workflows/build/workers-api/#workflowstep) with `step.do()`, `step.sleep()`, `step.sleepUntil()`, and `step.waitForEvent()` +- a context with the Worker `env` + +Imports such as `void/env`, `void/db`, and `void/kv` work inside steps. Keep side effects inside `step.do()` so a retry or a resumed instance doesn't repeat them. + +## Start an instance from a route + +```ts +// routes/api/signup.ts +import { defineHandler } from 'void'; +import { Onboarding } from '../../workflows/onboarding'; + +export const POST = defineHandler(async () => { + const instance = await Onboarding.create({ params: { userId: 'user_123' } }); + return { instanceId: instance.id }; +}); +``` + +`create()` accepts the same options as Cloudflare's [`Workflow.create()`](https://developers.cloudflare.com/workflows/build/workers-api/#create), such as `id` and `retention`. Its `params` are typed from your definition. Use `createBatch()` to start up to 100 instances at once. + +Check on an instance with `get()`: + +```ts +// routes/api/onboarding/[id].ts +import { defineHandler } from 'void'; +import { Onboarding } from '../../../workflows/onboarding'; + +export const GET = defineHandler(async (c) => { + const instance = await Onboarding.get(c.req.param('id')); + return instance.status(); +}); +``` + +The returned instance can also `pause()`, `resume()`, `restart()`, `terminate()`, and `sendEvent()`. + +## Validate params + +Pass a [Standard Schema](https://standardschema.dev) validator, such as Zod, Valibot, or ArkType, as `params`. `create()` and `createBatch()` validate the params before starting an instance, and `run` receives the parsed value: + +```ts +import * as v from 'valibot'; +// workflows/import.ts +import { defineWorkflow } from 'void/workflows'; + +export const Import = defineWorkflow({ + params: v.object({ fileKey: v.string(), notify: v.optional(v.boolean(), false) }), + async run(event, step) { + const rows = await step.do('parse', () => parseFile(event.payload.fileKey)); + if (event.payload.notify) { + await step.do('notify', () => notifyOwner(rows.length)); + } + }, +}); + +export default Import; +``` + +Invalid params throw a `WorkflowParamsError`. Its `issues` list each message and path. + +## Native Workflow classes + +Use `defineWorkflowEntrypoint()` to keep a class that extends Cloudflare's `WorkflowEntrypoint`. Void binds and exports the class without changing it, and reads the params type from its `run` method: + +```ts +// workflows/report.ts +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; +import { defineWorkflowEntrypoint } from 'void/workflows'; + +class ReportWorkflow extends WorkflowEntrypoint { + async run(event: WorkflowEvent<{ month: string }>, step: WorkflowStep) { + return step.do('build report', () => buildReport(event.payload.month)); + } +} + +export const Report = defineWorkflowEntrypoint({ class: ReportWorkflow }); +export default Report; +``` + +`Report.create()`, `Report.createBatch()`, and `Report.get()` work as they do for `defineWorkflow()`. + +## Names and bindings + +Void derives the names from the file's path in `workflows/`, joining directories with `-` as it does for [queues](./queues.md#defining-queues). `workflows/send-welcome.ts` creates: + +- the `WORKFLOW_SEND_WELCOME` binding +- the exported `SendWelcomeWorkflow` class +- a Cloudflare Workflow named `-send-welcome`, since Workflow names must be unique within your Cloudflare account + +`workflows/order/notifications.ts` creates `WORKFLOW_ORDER_NOTIFICATIONS`, `OrderNotificationsWorkflow`, and `-order-notifications`. Each Workflow must have a unique name. + +Instances belong to the Workflow name. Renaming the file or the Worker starts a new, empty Workflow, and instances of the old one stop running. To move a file without changing its name, run `void info` first and add the name it suggests: + +```ts +export const Onboarding = defineWorkflow({ + name: 'onboarding', + async run(event, step) { + // ... + }, +}); +``` + +`name` must be a static string containing words that start with a letter. To choose the Cloudflare Workflow name yourself, add an entry for the generated binding and class in `void.config.ts`: + +```ts +// void.config.ts +import { defineConfig } from 'void/config'; + +export default defineConfig({ + cloudflare: { + workflows: [ + { name: 'onboarding', binding: 'WORKFLOW_ONBOARDING', class_name: 'OnboardingWorkflow' }, + ], + }, +}); +``` + +## Deployment support + +Workflows are available on the Workers Free plan, within [Cloudflare's Workflows limits](https://developers.cloudflare.com/workflows/reference/limits/). Deploy to your own Cloudflare account with `void deploy --platform cloudflare`. + +Void platforms do not support Workflows yet: `void deploy` to a Void platform stops with an error while `workflows/` contains modules. Workflows are also unavailable in meta-framework apps and on Node.js, Bun, and Deno. diff --git a/docs/reference/api.md b/docs/reference/api.md index 05a09b43da..258377b18c 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -24,6 +24,7 @@ Use this reference to find public imports, signatures, and return types. For set | [Authentication](./api/auth.md) | Sessions, users, and the auth client. | | [Fetch client](./api/client.md) | Typed requests and errors. | | [Durable State and WebSockets](./api/durable.md) | Persistent objects and typed connections. | +| [Workflows](./api/workflows.md) | Durable multi-step jobs. | | [Database and seeding](./api/database.md) | Queries, operators, and seed scripts. | | [KV, storage, AI, and logging](./api/resources.md) | Resource clients, cache revalidation, and logs. | | [Deployment artifacts](./api/deploy.md) | Package built apps for managed deployment. | @@ -45,6 +46,7 @@ Import Void's app-facing APIs from these paths: | `void/ws` | `defineRoom`, `defineWebSocket`, `connect`, WebSocket context, connection and action types | | `void/ws/server` | `getRoom`, `RoomHandle`, `RoomOptions`, `RoomPath`. Server-only: call room actions from routes, auth hooks, queues and cron jobs. | | `void/durable` | `defineDurableState`, `defineDurableObject`, typed state/RPC/context/migration types | +| `void/workflows` | `defineWorkflow`, `defineWorkflowEntrypoint`, `WorkflowParamsError`, Workflow event/step/API types. Server-only. | | `void/sse` | `eventStream`, `formatSse`, `formatSseText`, `getLastEventId`, `SseStreamClosedError`, SSE message and stream types | | `void/sse/client` | `connectEventStream`, browser `EventSource` wrapper types | | `void/live` | `defineLiveStream`, SSE topic fanout runtime types. Server-only. | diff --git a/docs/reference/api/workflows.md b/docs/reference/api/workflows.md new file mode 100644 index 0000000000..e45f14e55c --- /dev/null +++ b/docs/reference/api/workflows.md @@ -0,0 +1,57 @@ +--- +description: 'Durable multi-step Workflows from void/workflows.' +outline: deep +--- + +# Workflows + +Imported from `"void/workflows"`. See [Workflows](../../guide/workflows.md) for the file convention and deployment support. + +## `defineWorkflow(definition)` {#defineworkflow-definition} + +Defines a Cloudflare Workflow from a run function. The returned object must be the default export of a module under `workflows/`; named-export the same object to start instances elsewhere in the app. + +```ts +function defineWorkflow(definition: { + name?: string; + params?: StandardSchemaV1; + run( + event: Readonly>, + step: WorkflowStep, + context: { env: TEnv; ctx: ExecutionContext }, + ): Promise; +}): WorkflowApi, TParams>; +``` + +With `params`, `run` receives the schema's output type and `create()` accepts its input type. Without it, the params type comes from the `event` annotation. + +## `defineWorkflowEntrypoint(definition)` {#defineworkflowentrypoint-definition} + +Registers a class that extends Cloudflare's `WorkflowEntrypoint` without changing it. The params type is read from the class's `run(event)` annotation. + +```ts +function defineWorkflowEntrypoint(definition: { + name?: string; + class: TClass; +}): WorkflowApi; +``` + +## `WorkflowApi` {#workflowapi} + +| Member | Description | +| ------------------------------ | ----------------------------------------------------------------------------------------------------- | +| `class` | The Workflow class Void exports from the Worker. | +| `create(options?)` | Starts an instance. Options match Cloudflare's `create()`; `params` are typed and validated. | +| `createBatch(instances)` | Starts up to 100 instances and returns Cloudflare's `{ created, errors }` result. | +| `get(id)` | Returns a `WorkflowInstance` for `status()`, `pause()`, `resume()`, `terminate()`, and `sendEvent()`. | +| `create(binding, options?)`, … | Each method also accepts an explicit `Workflow` binding as its first argument. | + +`name` optionally fixes the resource identity instead of deriving it from the filename. Run `void info` and pin the displayed name before moving a deployed definition. + +## `WorkflowParamsError` {#workflowparamserror} + +Thrown by `create()` and `createBatch()` when params fail the definition's schema. `issues` is an array of `{ message, path? }`. + +## Types {#types} + +`WorkflowEvent`, `WorkflowStep`, `WorkflowContext`, `WorkflowCreateOptions`, `WorkflowApi`, and `WorkflowRun`. diff --git a/docs/reference/cli/setup.md b/docs/reference/cli/setup.md index cdaeba5a14..d9d815357b 100644 --- a/docs/reference/cli/setup.md +++ b/docs/reference/cli/setup.md @@ -12,9 +12,9 @@ void info void info --json ``` -Shows each Durable State and WebSocket definition's source file, inferred or explicit name, Worker class, and binding. WebSocket entries also include their route in JSON output. It runs locally without authentication, network requests, or file generation. +Shows each Durable State, WebSocket, and Workflow definition's source file, inferred or explicit name, Worker class, and binding. WebSocket entries also include their route in JSON output. It runs locally without authentication, network requests, or file generation. -Before moving a deployed definition, copy the suggested `name` into `defineDurableState()`, `defineRoom()`, or `defineWebSocket()`. Keep that name after moving the file to preserve the resource. See [Durable State](../../guide/durable-state.md#rename-a-file-while-keeping-its-state) and [WebSockets](../../guide/websockets.md#move-a-route-while-keeping-its-state) for migration flows, including WebSocket parameter renames. +Before moving a deployed definition, copy the suggested `name` into `defineDurableState()`, `defineRoom()`, `defineWebSocket()`, or `defineWorkflow()`. Keep that name after moving the file to preserve the resource. See [Durable State](../../guide/durable-state.md#rename-a-file-while-keeping-its-state) [WebSockets](../../guide/websockets.md#move-a-route-while-keeping-its-state), and [Workflows](../../guide/workflows.md#names-and-bindings) for migration flows, including WebSocket parameter renames. Resources recorded in `void.lock.json` without a matching definition appear separately. Adopt a suggested name only after identifying the resource you moved. If Void cannot suggest a name, restore its original source and inspect it before moving it again. diff --git a/docs/reference/resource-inference.md b/docs/reference/resource-inference.md index 0f0e3104b1..13407199dc 100644 --- a/docs/reference/resource-inference.md +++ b/docs/reference/resource-inference.md @@ -20,6 +20,7 @@ Void automatically detects which Cloudflare resources your project uses by scann | `QUEUE_*` | `Queue` | `import { queues } from "void/queues"` | `env.QUEUE_*` | | `VOID_LIVE` | `DurableObjectNamespace` | `import { defineLiveStream } from "void/live"` | n/a | | filename-derived | `DurableObjectNamespace` | A default-exported `defineDurableState()` module in `durable-objects/` | n/a | +| `WORKFLOW_*` | `Workflow` | A default-exported `defineWorkflow()` or `defineWorkflowEntrypoint()` module in `workflows/` | n/a | Auth detection also triggers when importing the `auth` specifier from `void/client` or a framework-specific client subpath such as `void/client/react` (but not when importing only `fetch`). @@ -29,6 +30,8 @@ use [explicit binding overrides](#explicit-binding-overrides). Durable state is inferred from files in `durable-objects/`. For example, `durable-objects/shopping-cart.ts` creates the `SHOPPING_CART` binding, exports `ShoppingCartDurableObject`, and records its migration. See [Durable State](../guide/durable-state.md). +Workflows are inferred from files in `workflows/`, including subdirectories; paths with a `_`-prefixed segment are ignored. For example, `workflows/send-welcome.ts` creates the `WORKFLOW_SEND_WELCOME` binding and exports `SendWelcomeWorkflow`. See [Workflows](../guide/workflows.md). + ## Scanned Directories ### Standard mode @@ -68,6 +71,7 @@ Regardless of mode, these are always checked: - **SSR entry** such as `src/main.ssr.ts`, for SSR apps that access bindings during rendering - **Application source** in `src/` or your configured `sourceDir`, including resource and auth imports - **`durable-objects/`**, which is scanned for typed Durable Object state modules in native Void apps +- **`workflows/`**, which is scanned for Workflow modules in native Void apps ## Custom Scan Directories diff --git a/docs/reference/structure.md b/docs/reference/structure.md index 954d5818be..59b9ecb7d4 100644 --- a/docs/reference/structure.md +++ b/docs/reference/structure.md @@ -13,6 +13,7 @@ const items = [ { name: "queues/", description: "Async queue consumers", link: "#queues" }, { name: "email/", description: "Inbound email handlers", link: "#email" }, { name: "durable-objects/", description: "Durable State modules", link: "#durable-objects" }, + { name: "workflows/", description: "Durable multi-step Workflows", link: "#workflows" }, { name: "src/", description: "Shared app code", link: "#src" }, { name: "public/", description: "Static assets (served as-is)", link: "#public" }, { name: ".void/", description: "Auto-generated (gitignored)", link: "#void" }, @@ -126,6 +127,10 @@ Generate schema with `void gen model` or write it by hand. Generate migrations w [Durable State](/guide/durable-state) modules. Each file default-exports a `defineDurableState()` definition. +## `workflows/` + +[Workflow](/guide/workflows) modules. Each file default-exports a `defineWorkflow()` or `defineWorkflowEntrypoint()` definition. + ## `src/` Shared application code such as components, utilities, and types. This directory has no special convention, so organize it however you like. diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index 2df952b689..7bd23dc518 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -146,7 +146,8 @@ generated entries must preserve the module-boundary rules below. - **Framework env schema**: `env` has no schema in a Worker whose own modules have not loaded `env.ts`, whatever the Vite plugin loaded in its process, so it returns raw values. The Class A wrapper (TanStack Start, React Router, vinext) imports `env.ts` ahead of the framework entry and awaits `_prepareEnv(env)` on every request, in dev and build. Unlike `_validateEnvOnce`, it never rejects: a read of a key that failed throws that key's error, async validators included, so requests that do not read it and a build-time prerender without production secrets still run. Both keep one result per key, reuse a validation for the same raw values, and keep the results with the env object they received. Reads through another object (the `cloudflare:workers` env that a D1 app's framework reads outside a request scope, the remote dev copy) get the latest validation's result while they hold the raw value it came from; never copy results to that object, which can come to hold other values. A validation in which a validator threw serves its reads but runs again on the next call. Results live on the process-global registry because `void deploy` bundles cron and queue jobs apart from the app, with a copy of `void/env` of their own: the jobs call `registry.prepare`, the `_prepareEnv` of the copy that registered the schema (key in `shared/env-registry.ts`). SvelteKit, Nuxt, Analog and Astro Workers do not load `env.ts` yet. - **Reserved `__VOID_*` names**: `envSchemaPlugin.config` (every mode, with or without `env.ts`) and `void env check` reject `__VOID_*` names in the root `.env` or declared in `env.ts`. Do not try to strip them from dev `vars` instead: Wrangler reads `.env` itself and writes it over `vars`, so a strip cannot be enforced. Manual trigger auth is a compile-time literal (`__VOID_SERVE` from `CompileOptions.dev`, false in builds and `vite preview`): dev accepts only `x-void-dev-trigger`, builds use the proxy token or build key. Never key it on `import.meta.env.DEV`, which is true in a `NODE_ENV=development` build. - **Typed Durable State convention**: each default-exported `defineDurableState()` definition in `durable-objects/*.ts` becomes a filename-derived binding and worker class (`shopping-cart.ts` → `SHOPPING_CART` / `ShoppingCartDurableObject`). The generated entry calls the internal `__bind()` hook so named imports can use `State.get(name)` without touching `c.env`, exports `State.class`, and emits a stable `new_sqlite_classes` migration. `syncWranglerDurableObjects()` persists bindings and append-only class migration history in `void.lock.json` through the generated Cloudflare config; never regenerate migration order solely from the current sorted files. The generated class extends `DurableObject` from `cloudflare:workers` so namespace stubs expose real RPC methods; runtime state and helpers use JavaScript private fields and methods. Runtime operations are serialized and persisted after successful typed RPC, `fetch`, or `alarm` handlers; versioned value migrations run on load. This is native-Void + Cloudflare only and is supported by direct Cloudflare deploys. Typed `*.ws.ts` routes likewise use SQLite-backed classes; their root-config sync uses the comment-preserving writer, retains legacy `new_classes` histories, and appends a new migration tag only for new classes. -- **Persistent resource names**: optional static `name` on Durable State and WebSocket definitions uses the same identity derivation as unnamed filenames/routes. Preserve unnamed defaults exactly. `void info` reports names and verified unmatched lock identities without executing source or writing files. Scanners use the shared AST reader; runtime validation imports only the Worker-safe `shared/resource-name.ts` leaf. Carry explicit names through generated metadata and `__bind()`; runtime mismatches fail instead of selecting an inferred replacement. WebSocket `key({ params })` is shared by namespace selection and hook `ctx.id`; absent keys keep the existing ordered `param=value` format. +- **Workflows convention**: each default-exported `defineWorkflow()` / `defineWorkflowEntrypoint()` under `workflows/` becomes `WORKFLOW_` / `Workflow` (`send-welcome.ts` → `WORKFLOW_SEND_WELCOME` / `SendWelcomeWorkflow`), bound through the same `__bind()` hook as Durable State. The binding prefix matches `QUEUE_*`. Discovery follows `queues/` rather than `durable-objects/`: subdirectories are joined with `-` (`order/notifications.ts` → `order-notifications`) and `_`-prefixed path segments are skipped. Workflows need no class migrations, so they are not written to `void.lock.json`; `mergeWorkerBindings()` emits only the additions (the Cloudflare plugin concatenates arrays) via `planWorkflowAdditions()`, naming each `-` because Workflow names are account-scoped. `void deploy --platform cloudflare` passes its Worker name to the build as `VOID_CLOUDFLARE_WORKER_NAME`, and `reconstructExpectedWorkflows()` pins the exact emitted set for `verifyGeneratedDeployConfig()`. An authored entry with the same binding and class keeps its name. Void platform deploys, framework mode and Node targets reject `workflows/` until platform provisioning exists. The generated entry imports convention modules through their namespace and fails Worker startup with a named error when the default export is not a definition; this guard also covers `durable-objects/`. +- **Persistent resource names**: optional static `name` on Durable State, WebSocket, and Workflow definitions uses the same identity derivation as unnamed filenames/routes. Preserve unnamed defaults exactly. `void info` reports names and verified unmatched lock identities without executing source or writing files. Scanners use the shared AST reader; runtime validation imports only the Worker-safe `shared/resource-name.ts` leaf. Carry explicit names through generated metadata and `__bind()`; runtime mismatches fail instead of selecting an inferred replacement. WebSocket `key({ params })` is shared by namespace selection and hook `ctx.id`; absent keys keep the existing ordered `param=value` format. - **Server room actions**: `defineRoom({ actions })` keeps each action's declared parameters and return type (`RoomActions` accepts any annotated parameter list, so unannotated parameters become `never`). Codegen adds `actions` to `WebSocketRouteMap` for room routes only, and `getRoom()` from `void/ws/server` resolves the same `bindingName` plus `buildWebSocketInstanceId()` key as `forwardWebSocketRequest()`. The generated route table registers route metadata once, after attaching `key`, through `__registerWebSocketRoutes`; the map lives on `globalThis` because dev can evaluate the module twice. Dispatch is Durable Object RPC (`__voidRoomAction`), so the WebSocket DO class extends `DurableObject` from `cloudflare:workers`; its own helpers are `#` methods so they stay off that RPC surface, and actions are never reachable from `fetch`, `webSocketMessage`, or client HTTP. - **Journal coherence invariant**: `db/migrations/*.sql` and `db/migrations/meta/_journal.json` must stay in sync — every `.sql` file has a matching journal entry (by `tag`) and vice versa. `assertJournalCoherence` in `src/migrations/validate.ts` is the gate, called from `deploy`, `db status`, `db migrate`, and `db reset`. The two CLI commands that mutate migration state — `void gen migration` and `void db rename-migrations` — are responsible for keeping the journal coherent themselves: when the journal has entries, the first delegates to `drizzle-kit generate --custom --name `, which writes the empty `.sql`, appends the journal entry, and writes a snapshot of the current schema (it refuses if the last entry's snapshot is missing and byte-restores the journal if drizzle-kit fails); with no journal entries it writes a plain timestamped `.sql`. The second rewrites `tag` values alongside the file renames and also renames the matching `meta/_snapshot.json` (with byte-level rollback on failure). Drift will fail loudly before touching any remote DB. This prevents an orphan scaffolded `.sql` file from half-applying against D1 and blocking later deploys. diff --git a/packages/void/package.json b/packages/void/package.json index ae781040ae..fbaddad40f 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -170,6 +170,11 @@ "import": "./dist/runtime/durable/index.mjs", "require": "./dist/runtime/durable/index.mjs" }, + "./workflows": { + "types": "./dist/runtime/workflows/index.d.mts", + "import": "./dist/runtime/workflows/index.mjs", + "require": "./dist/runtime/workflows/index.mjs" + }, "./seed": { "types": "./dist/runtime/db/seed.d.mts", "import": "./dist/runtime/db/seed.mjs", diff --git a/packages/void/skills/void/SKILL.md b/packages/void/skills/void/SKILL.md index f36ee0b6e0..25acb4eae7 100644 --- a/packages/void/skills/void/SKILL.md +++ b/packages/void/skills/void/SKILL.md @@ -51,6 +51,7 @@ Use `void deploy --skip-migrations` when database migrations run separately; it | AI inference (Workers AI, providers) | `docs/guide/ai.md` | | Platform AI logging policy | `docs/reference/cli/platform-users.md#ai-gateway-logging` | | Durable State and WebSockets | `docs/guide/durable-state.md`, `docs/guide/websockets.md` | +| Workflows | `docs/guide/workflows.md`, `docs/reference/api/workflows.md` | | Server-sent events and live streams | `docs/guide/sse.md`, `docs/guide/live.md` | | Sandboxes | `docs/guide/sandboxes.md` | | Email | `docs/guide/email.md`, then the matching guide under `docs/guide/email/` | diff --git a/packages/void/src/application-analysis.ts b/packages/void/src/application-analysis.ts index 7c21af1673..3dd814094e 100644 --- a/packages/void/src/application-analysis.ts +++ b/packages/void/src/application-analysis.ts @@ -15,6 +15,7 @@ import type { RouteEnvironment } from './router/parse-filename.ts'; import { scanMiddlewareSync, scanRoutePatternsSync } from './router/scan.ts'; import { scanWebSocketRoutesSync } from './router/websocket.ts'; import { isSandboxEnabled } from './sandbox/config.ts'; +import { scanWorkflowModules } from './workflows/scan.ts'; export type ApplicationReasons = { database: Array; @@ -40,6 +41,7 @@ export type ApplicationAnalysis = { websockets: ReturnType; allWebsockets: ReturnType; durableObjects: ReturnType; + workflows: ReturnType; email: ReturnType; routes: ReturnType; middleware: ReturnType; @@ -81,6 +83,7 @@ export function analyzeApplicationSync( ); // Typed durable modules currently use the root convention on every target. const durableObjects = scanDurableObjectModules(root); + const workflows = scanWorkflowModules(root); const email = scanEmailHandlersSync(paths.sourceRoot); const overrides = config.inference?.bindings; const bindingReason = ( @@ -127,6 +130,7 @@ export function analyzeApplicationSync( websockets, allWebsockets, durableObjects, + workflows, email, routes: scanRoutePatternsSync(root, paths, environment), middleware: scanMiddlewareSync(root, paths), diff --git a/packages/void/src/cli/deploy-artifact-validation.ts b/packages/void/src/cli/deploy-artifact-validation.ts index 8a05b1b0fb..69c45cf288 100644 --- a/packages/void/src/cli/deploy-artifact-validation.ts +++ b/packages/void/src/cli/deploy-artifact-validation.ts @@ -138,6 +138,8 @@ export function removeDeployPointer(root: string): void { const byName = (left: Record, right: Record) => String(left.name).localeCompare(String(right.name)); +const byBinding = (left: Record, right: Record) => + String(left.binding).localeCompare(String(right.binding)); /** * Check the generated deploy config before upload: the pinned account and Worker name, required @@ -168,6 +170,8 @@ export function verifyGeneratedDeployConfig( expectedContainers?: Array>; /** Exact pre-build Durable Object bindings, including Void's sandbox and live additions. */ expectedDurableObjectBindings?: Array>; + /** Exact pre-build Workflow entries, including Void's `workflows/` additions. */ + expectedWorkflows?: Array>; /** Exact pre-build migration sequence, including Void's sandbox and live additions. */ expectedMigrations?: Array>; /** Cron schedules the build should emit, derived from the source before the build. */ @@ -442,6 +446,26 @@ export function verifyGeneratedDeployConfig( }; } } + if (expected.expectedWorkflows) { + if (generated.workflows !== undefined && !Array.isArray(generated.workflows)) { + return { ok: false, reason: 'generated config workflows could not be verified.' }; + } + const emittedWorkflows = Array.isArray(generated.workflows) + ? (generated.workflows as Array>) + : []; + if ( + !deepEqual( + [...emittedWorkflows].sort(byBinding), + [...expected.expectedWorkflows].sort(byBinding), + ) + ) { + return { + ok: false, + reason: + 'generated config workflows differ from the pre-build Workflow set — refusing to deploy a Workflow the build added, removed, or retargeted.', + }; + } + } if (expected.expectedMigrations) { if (generated.migrations !== undefined && !Array.isArray(generated.migrations)) { return { ok: false, reason: 'generated config migrations could not be verified.' }; diff --git a/packages/void/src/cli/deploy-binding-snapshot.ts b/packages/void/src/cli/deploy-binding-snapshot.ts index f98147cc90..846d234cd3 100644 --- a/packages/void/src/cli/deploy-binding-snapshot.ts +++ b/packages/void/src/cli/deploy-binding-snapshot.ts @@ -20,6 +20,7 @@ import { SANDBOX_MIGRATION_TAG, hasSandboxSqliteMigration, } from '../sandbox/config.ts'; +import { planWorkflowAdditions, workflowConfigEntries } from '../workflows/config.ts'; import type { BindingIdentitySnapshot } from './deploy-types.ts'; import { resolveCloudflareOperationArgv } from './preset.ts'; import type { DesiredResourceSet, ProvisionDriftEntry } from './provision.ts'; @@ -125,6 +126,7 @@ export const DEPLOY_PASSTHROUGH_EXCLUDE_FIELDS: ReadonlySet = new Set, + workerName: string, + analysis?: ApplicationAnalysis, +): Array> { + const configured = workflowConfigEntries(rootConfig.workflows); + const modules = (analysis ?? analyzeApplicationSync(root, { config })).workflows; + return [...configured, ...planWorkflowAdditions(configured, modules, workerName)]; +} + export function reconstructExpectedDurableObjectState( config: VoidConfig, root: string, diff --git a/packages/void/src/cli/deploy-cloudflare-build.ts b/packages/void/src/cli/deploy-cloudflare-build.ts index dbfd0f040d..14decdbdf1 100644 --- a/packages/void/src/cli/deploy-cloudflare-build.ts +++ b/packages/void/src/cli/deploy-cloudflare-build.ts @@ -10,7 +10,11 @@ import type { VoidConfig } from '../config.ts'; import { collectMigrations } from '../migrations/collect.ts'; import { SqliteMigrationError } from '../migrations/sqlite-validation.ts'; import type { detectFramework } from '../plugin-inference.ts'; -import { CLOUDFLARE_DEPLOY_BUILD_ENV, CLOUDFLARE_QUEUE_NAMES_BUILD_ENV } from '../shared/env.ts'; +import { + CLOUDFLARE_DEPLOY_BUILD_ENV, + CLOUDFLARE_QUEUE_NAMES_BUILD_ENV, + CLOUDFLARE_WORKER_NAME_BUILD_ENV, +} from '../shared/env.ts'; import { CLOUDFLARE_PRESERVE_BINDINGS_BUILD_ENV } from '../shared/version-metadata.ts'; import { prepareCfBuildOutput, prepareCfFrameworkBuildOutput } from './cf-build-output.ts'; import { @@ -82,6 +86,8 @@ export async function buildCloudflareWorker(input: { // but local files cannot be serialized into the artifact this command uploads. deleteEnvVarCaseAware(buildChildEnv, CLOUDFLARE_DEPLOY_BUILD_ENV); buildChildEnv[CLOUDFLARE_DEPLOY_BUILD_ENV] = '1'; + deleteEnvVarCaseAware(buildChildEnv, CLOUDFLARE_WORKER_NAME_BUILD_ENV); + buildChildEnv[CLOUDFLARE_WORKER_NAME_BUILD_ENV] = workerName; deleteEnvVarCaseAware(buildChildEnv, CLOUDFLARE_QUEUE_NAMES_BUILD_ENV); if (desired.queueNames) { buildChildEnv[CLOUDFLARE_QUEUE_NAMES_BUILD_ENV] = JSON.stringify(desired.queueNames); diff --git a/packages/void/src/cli/deploy-cloudflare-migrate.ts b/packages/void/src/cli/deploy-cloudflare-migrate.ts index 9707dac368..f5fadef6c1 100644 --- a/packages/void/src/cli/deploy-cloudflare-migrate.ts +++ b/packages/void/src/cli/deploy-cloudflare-migrate.ts @@ -58,6 +58,7 @@ export async function migrateCloudflareWorker(input: { passthroughRawFields, expectedContainers, expectedDurableObjectState, + expectedWorkflows, runWrangler, assertUploaderStillPinned, schemaFacts, @@ -78,6 +79,7 @@ export async function migrateCloudflareWorker(input: { authEnabled, expectedContainers, expectedDurableObjectBindings: expectedDurableObjectState.bindings, + expectedWorkflows, expectedMigrations: expectedDurableObjectState.migrations, expectedCrons, }; diff --git a/packages/void/src/cli/deploy-cloudflare-preflight.ts b/packages/void/src/cli/deploy-cloudflare-preflight.ts index 1db27af462..2e719f616f 100644 --- a/packages/void/src/cli/deploy-cloudflare-preflight.ts +++ b/packages/void/src/cli/deploy-cloudflare-preflight.ts @@ -33,6 +33,7 @@ import { snapshotPassthroughRawFields, reconstructExpectedContainers, reconstructExpectedDurableObjectState, + reconstructExpectedWorkflows, } from './deploy-binding-snapshot.ts'; import { isWranglerNonInteractiveOrCI, @@ -225,6 +226,7 @@ export async function preflightCloudflareWorker(input: { passthroughRawFields: ReturnType; expectedContainers: ReturnType; expectedDurableObjectState: ReturnType; + expectedWorkflows: ReturnType; }> { const { root, @@ -691,6 +693,13 @@ export async function preflightCloudflareWorker(input: { preBuildRootConfig, { needsSandbox, needsLive, analysis: source.analysis }, ); + const expectedWorkflows = reconstructExpectedWorkflows( + voidConfig, + root, + preBuildRootConfig, + workerName, + source.analysis, + ); return { apiBaseUrl, complianceRegion, @@ -712,5 +721,6 @@ export async function preflightCloudflareWorker(input: { passthroughRawFields, expectedContainers, expectedDurableObjectState, + expectedWorkflows, }; } diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 9e5109756c..483c022693 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -5,6 +5,7 @@ import { stashCloudflareDeployPointer } from '../cloudflare-config.ts'; import { readConfig } from '../config.ts'; import { detectFramework } from '../plugin-inference.ts'; import { buildEnv } from '../shared/untrusted-env.ts'; +import { assertNoWorkflowsForPlatform } from '../workflows/platform.ts'; import { getApiUrl, getToken, getTokenSource } from './auth.ts'; import { isExpiredTokenError, PlatformClient } from './client.ts'; import { maybeLinkCloudflareDeploy } from './cloudflare-link.ts'; @@ -300,6 +301,7 @@ async function runManagedDeploy( // Resolve the app type: void.config.ts > CLI flags > auto-detection. const voidConfig = readConfig(root); + assertNoWorkflowsForPlatform(root); cliLog.info('config_resolved', { target: voidConfig.target, appType: voidConfig.inference?.appType, diff --git a/packages/void/src/cli/info.ts b/packages/void/src/cli/info.ts index b2b9ee90c1..e768986a13 100644 --- a/packages/void/src/cli/info.ts +++ b/packages/void/src/cli/info.ts @@ -9,11 +9,12 @@ import { deriveWebSocketClassNameFromName, inferWebSocketResourceName, } from '../router/websocket.ts'; +import { inferWorkflowResourceName } from '../workflows/scan.ts'; import type { InfoArgs } from './info-args.ts'; export type PersistentResourceInfo = { file: string; - definition: 'defineDurableState' | 'defineRoom' | 'defineWebSocket'; + definition: 'defineDurableState' | 'defineRoom' | 'defineWebSocket' | 'defineWorkflow'; name: string; nameSource: 'inferred' | 'explicit'; className: string; @@ -135,6 +136,14 @@ export function getProjectInfo(root: string): ProjectInfo { className: module.className, bindingName: module.bindingName, })), + ...analysis.workflows.map((module) => ({ + file: relative(root, module.filePath), + definition: 'defineWorkflow' as const, + name: module.name ?? inferWorkflowResourceName(module.relativePath), + nameSource: module.name === undefined ? ('inferred' as const) : ('explicit' as const), + className: module.className, + bindingName: module.bindingName, + })), ]; resources.sort((a, b) => a.file.localeCompare(b.file)); return { resources, recordedResources: readRecordedResources(root, resources) }; diff --git a/packages/void/src/deploy.ts b/packages/void/src/deploy.ts index 0216c529fa..f9a6d9c3e7 100644 --- a/packages/void/src/deploy.ts +++ b/packages/void/src/deploy.ts @@ -23,6 +23,7 @@ import { readConfig, isNodeTarget } from './config.ts'; import { collectRevalidate } from './isr-config.ts'; import { hasEmailHandlers } from './router/email.ts'; import { validateSsrEntry } from './ssr/entry.ts'; +import { assertNoWorkflowsForPlatform } from './workflows/platform.ts'; /** * A disposable Cloudflare Build Output directory. Experimental: it follows Cloudflare's draft @@ -83,6 +84,7 @@ export async function prepareDeployArtifact( if (isNodeTarget(config.target) || config.output === 'static') { throw new Error('Artifact preparation requires a Void Cloudflare Worker build.'); } + assertNoWorkflowsForPlatform(root); let preset = resolveStaticDeployPreset(root, config); let analysis: Awaited> | undefined; if (!preset) { diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index c878b5caf0..7ebf27faaa 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -263,6 +263,32 @@ export function voidPlugin(options?: { 'durable: durable-objects/ is currently supported in Void apps only, not framework adapter mode.', ); } + const workflows = application.workflows; + if (detected && workflows.length > 0) { + throw new Error( + 'workflows: workflows/ is currently supported in Void apps only, not framework adapter mode.', + ); + } + for (const module of workflows) { + const owner = + websocketRoutes.find( + (route) => route.bindingName === module.bindingName || route.className === module.className, + )?.filePath ?? + durableObjects.find( + (durable) => + durable.bindingName === module.bindingName || durable.className === module.className, + )?.filePath; + if ( + owner !== undefined || + (sandboxConfig && + (sandboxConfig.binding === module.bindingName || + sandboxConfig.className === module.className)) + ) { + throw new Error( + `workflows: workflows/${module.relativePath} conflicts with ${owner === undefined ? 'the configured Sandbox binding or class' : `'${owner}'`}. Rename one of the files.`, + ); + } + } for (const module of durableObjects) { const websocketCollision = websocketRoutes.find( (route) => route.bindingName === module.bindingName || route.className === module.className, @@ -299,10 +325,12 @@ export function voidPlugin(options?: { reservedBindings: [ ...websocketRoutes.map((route) => route.bindingName), ...durableObjects.map((module) => module.bindingName), + ...workflows.map((module) => module.bindingName), ], reservedClasses: [ ...websocketRoutes.map((route) => route.className), ...durableObjects.map((module) => module.className), + ...workflows.map((module) => module.className), sandboxConfig?.className, ], }) @@ -404,6 +432,7 @@ export function voidPlugin(options?: { devTriggerToken, queues, durableObjects, + workflows, sandboxConfig, shouldEmitLive, liveConfig, @@ -844,6 +873,11 @@ export function voidPlugin(options?: { `durable: durable-objects/ requires target: "cloudflare". It is not available with target: '${config.target}'.`, ); } + if (workflows.length > 0) { + throw new Error( + `workflows: workflows/ requires target: "cloudflare". It is not available with target: '${config.target}'.`, + ); + } // `compileNodeApp` imports only the Hono app from the route table; the // `__emailHandler` the table exports for `email/` is never invoked, so // without this the build succeeds and every inbound handler is dead code. @@ -1000,6 +1034,7 @@ export function voidPlugin(options?: { return shouldEmitLive() ? liveConfig : undefined; }, durableObjects, + workflows, websocketTombstones, onDevAssetRoutingPolicyChange: updateDevAssetRoutingPolicy, // Native builds of eligible apps let Cloudflare serve hashed build files directly. diff --git a/packages/void/src/plugin-client-stubs.ts b/packages/void/src/plugin-client-stubs.ts index 25f759b04e..469192edb8 100644 --- a/packages/void/src/plugin-client-stubs.ts +++ b/packages/void/src/plugin-client-stubs.ts @@ -59,6 +59,7 @@ export function createClientStubsPlugin(): Plugin { `, 'void/live': '', 'void/durable': '', + 'void/workflows': '', }; const STUB_RESOLVE_FILTER = new RegExp( `^(${Object.keys(SERVER_ONLY_STUBS) @@ -75,11 +76,11 @@ export function createClientStubsPlugin(): Plugin { filter: { id: STUB_RESOLVE_FILTER }, handler(id) { if (this.environment?.name === 'client') { - if (id === 'void/live' || id === 'void/durable') { + if (id === 'void/live' || id === 'void/durable' || id === 'void/workflows') { this.error( id === 'void/live' ? 'void/live is server-only and cannot be imported by browser code. Import void/live/client instead.' - : 'void/durable is server-only and cannot be imported by browser code.', + : `${id} is server-only and cannot be imported by browser code.`, ); } return STUB_PREFIX + id; diff --git a/packages/void/src/plugin-cloudflare-config.ts b/packages/void/src/plugin-cloudflare-config.ts index a409a82273..de56041927 100644 --- a/packages/void/src/plugin-cloudflare-config.ts +++ b/packages/void/src/plugin-cloudflare-config.ts @@ -47,17 +47,23 @@ export function mergeCloudflareConfig(patch: object, fallback: object): Record; + workflows?: Array<{ + bindingName: string; + className: string; + filePath: string; + relativePath?: string; + name?: string; + }>; /** Data-preserving exports for removed WebSocket Durable Object routes. */ websocketTombstones?: Array; onDevAssetRoutingPolicyChange?: (policy: AssetRoutingPolicy) => boolean; @@ -654,6 +661,7 @@ export function routingPlugin( isr, notFound: policy.assetConfig.not_found_handling ?? 'none', durableObjects: options.durableObjects, + workflows: options.workflows, }), ); } @@ -681,6 +689,7 @@ export function routingPlugin( sandbox: sandboxEntry, live: options.live, durableObjects: options.durableObjects, + workflows: options.workflows, }), ); } diff --git a/packages/void/src/plugin-worker-bindings.ts b/packages/void/src/plugin-worker-bindings.ts index e966e3081b..6b6cd82396 100644 --- a/packages/void/src/plugin-worker-bindings.ts +++ b/packages/void/src/plugin-worker-bindings.ts @@ -16,6 +16,7 @@ import { readVoidDevCredentials, } from './plugin-ai-setup.ts'; import { hasBinding, shouldInjectEmailDevInboxVar } from './plugin-binding-utils.ts'; +import { defaultCloudflareWorkerName } from './plugin-cloudflare-config.ts'; import type { WorkerConfig } from './plugin-cloudflare-config.ts'; import type { EnvSchemaFacts } from './plugin-env-schema.ts'; import { cloudflareQueueName, readDeployBuildQueueNames } from './queues/cloudflare-names.ts'; @@ -29,11 +30,12 @@ import { sandboxContainerConfig, assertSandboxNamespaceConfig, } from './sandbox/config.ts'; -import { CLOUDFLARE_DEPLOY_BUILD_ENV } from './shared/env.ts'; +import { CLOUDFLARE_DEPLOY_BUILD_ENV, CLOUDFLARE_WORKER_NAME_BUILD_ENV } from './shared/env.ts'; import { CLOUDFLARE_PRESERVE_BINDINGS_BUILD_ENV, selectNativeVersionMetadataBinding, } from './shared/version-metadata.ts'; +import { planWorkflowAdditions, workflowConfigEntries } from './workflows/config.ts'; type DurableObjectBinding = { name: string; class_name: string }; type DurableObjectMigration = { @@ -63,6 +65,34 @@ function currentMigrations( return Array.isArray(current) ? (current as Array) : []; } +/** + * Add a `workflows` entry for each `workflows/` module. The Cloudflare plugin + * concatenates this patch with the resolved config, so only additions are emitted. + */ +function mergeWorkflowBindings( + result: Record, + resolved: WorkerConfig, + workflows: ApplicationAnalysis['workflows'], + root: string, +): void { + if (workflows.length === 0) { + return; + } + const patchEntries = workflowConfigEntries(result.workflows); + const deployWorkerName = + process.env[CLOUDFLARE_DEPLOY_BUILD_ENV] === '1' + ? process.env[CLOUDFLARE_WORKER_NAME_BUILD_ENV] + : undefined; + const additions = planWorkflowAdditions( + [...patchEntries, ...workflowConfigEntries((resolved as Record).workflows)], + workflows, + deployWorkerName || ((resolved as { name?: string }).name ?? defaultCloudflareWorkerName(root)), + ); + if (additions.length > 0) { + result.workflows = [...patchEntries, ...additions]; + } +} + export function mergeWorkerBindings( resolved: WorkerConfig, input: { @@ -81,6 +111,7 @@ export function mergeWorkerBindings( readonly devTriggerToken: string; readonly queues: ApplicationAnalysis['queues']; readonly durableObjects: ApplicationAnalysis['durableObjects']; + readonly workflows: ApplicationAnalysis['workflows']; readonly sandboxConfig: ReturnType | undefined; readonly shouldEmitLive: () => boolean; readonly liveConfig: ReturnType | undefined; @@ -104,6 +135,7 @@ export function mergeWorkerBindings( devTriggerToken, queues, durableObjects, + workflows, sandboxConfig, shouldEmitLive, liveConfig, @@ -390,6 +422,8 @@ export function mergeWorkerBindings( } } + mergeWorkflowBindings(result, resolved, workflows, root); + if (bindings.needsSandbox && sandboxConfig) { assertSandboxNamespaceConfig({ ...resolved, ...result }, sandboxConfig); const existingDurableObjectBindings = currentDurableObjectBindings(result, resolved); diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index 9683661503..25b7669234 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -1198,12 +1198,55 @@ export interface WorkerEntryOptions { * imported from `filePath`, bound to `bindingName`, and re-exported as * `className` so wrangler's `durable_objects.bindings` can find it. */ - durableObjects?: Array<{ - bindingName: string; - className: string; - filePath: string; - name?: string; - }>; + durableObjects?: Array; + /** + * Workflow definitions (`workflows/` directory). Each entry is imported from + * `filePath`, bound to `bindingName`, and re-exported as `className` so + * the Cloudflare `workflows` config can find it. + */ + workflows?: Array; +} + +type ResourceModuleCode = { imports: string; exports: string }; + +type ResourceModuleEntry = { + bindingName: string; + className: string; + filePath: string; + /** Path relative to the convention directory, for error messages. Defaults to the file name. */ + relativePath?: string; + name?: string; +}; + +/** + * Import each convention module through its namespace so a missing default + * export reaches the guard below instead of failing with a bundler error or a + * generic `Cannot read properties of undefined` at Worker startup. + */ +function compileResourceModules( + entries: ReadonlyArray, + options: { variable: string; directory: string; prefix: string; helpers: string }, +): ResourceModuleCode { + const imports = entries + .map( + ({ filePath }, index) => + `import * as ${options.variable}Module${index} from ${JSON.stringify(filePath)};`, + ) + .join('\n'); + const exports = entries + .map(({ bindingName, className, filePath, relativePath, name }, index) => { + const local = `${options.variable}${index}`; + const file = `${options.directory}/${relativePath ?? filePath.replaceAll('\\', '/').split('/').pop()}`; + const message = `${options.prefix}: ${file} must default-export ${options.helpers}.`; + return [ + `const ${local} = ${options.variable}Module${index}.default;`, + `if (typeof ${local}?.__bind !== "function") { throw new Error(${JSON.stringify(message)}); }`, + `${local}.__bind(${JSON.stringify(bindingName)}${name !== undefined ? `, ${JSON.stringify(name)}` : ''});`, + `export const ${className} = ${local}.class;`, + ].join('\n'); + }) + .join('\n'); + return { imports, exports }; } /** @@ -1239,6 +1282,7 @@ export function compileWorkerEntry(options: WorkerEntryOptions = {}): string { isr, notFound = 'none', durableObjects = [], + workflows = [], } = options; const remotePath = remote?.remotePath; const remoteBindingNames = JSON.stringify(remote?.bindingNames); @@ -1281,17 +1325,23 @@ export function compileWorkerEntry(options: WorkerEntryOptions = {}): string { ? `export { VoidLiveStreamDurableObject };\n__setLiveBindingName(${JSON.stringify(liveBindingName)});\n${liveDevCall}` : `export { VoidLiveStreamDurableObject as ${liveClassName} };\n__setLiveBindingName(${JSON.stringify(liveBindingName)});\n${liveDevCall}` : ''; - const durableObjectImports = durableObjects - .map( - ({ filePath }, index) => - `import __voidDurableObject${index} from ${JSON.stringify(filePath)};`, - ) + const durableObjectModules = compileResourceModules(durableObjects, { + variable: '__voidDurableObject', + directory: 'durable-objects', + prefix: 'durable', + helpers: 'defineDurableState() or defineDurableObject()', + }); + const workflowModules = compileResourceModules(workflows, { + variable: '__voidWorkflow', + directory: 'workflows', + prefix: 'workflows', + helpers: 'defineWorkflow() or defineWorkflowEntrypoint()', + }); + const resourceModuleImports = [durableObjectModules.imports, workflowModules.imports] + .filter(Boolean) .join('\n'); - const durableObjectExports = durableObjects - .map( - ({ bindingName, className, name }, index) => - `__voidDurableObject${index}.__bind(${JSON.stringify(bindingName)}${name !== undefined ? `, ${JSON.stringify(name)}` : ''});\nexport const ${className} = __voidDurableObject${index}.class;`, - ) + const resourceModuleExports = [durableObjectModules.exports, workflowModules.exports] + .filter(Boolean) .join('\n'); const runtimeEnvImport = `import { withRuntimeEnv } from ${JSON.stringify(runtimeEnvPath)};\n`; const remoteImport = remote @@ -1431,7 +1481,7 @@ ${envValidateCall}${remoteEnvSwap}${isrDeploymentStamp} const userEnv = __filte ` : ''; return `${sandboxImport}${entryImport}${liveRuntimeImport}import app, { scheduled, __voidCollectPrerenderPaths, __voidRenderStaticNotFound, __voidHandleInternalRoute, __withRawEnv${queueImport}${emailImport}${webSocketClasses.length > 0 ? `, ${webSocketClasses.join(', ')}` : ''}${liveRouteImport} } from 'virtual:void-routes'; -${durableObjectImports}\n${runtimeEnvImport}${emailProxyImport}${envSchemaImport}${remoteImport}${isrImport}${filterBindingsHelper}${assetHelper} +${resourceModuleImports}\n${runtimeEnvImport}${emailProxyImport}${envSchemaImport}${remoteImport}${isrImport}${filterBindingsHelper}${assetHelper} ${fetchDeclaration} ${scheduledHandler} ${emailHandler} @@ -1439,7 +1489,7 @@ ${emailReceiptHandler} ${queueFunction}${webSocketClasses.map((name) => `export { ${name} };`).join('\n')} ${liveExport} ${sandboxExport} -${durableObjectExports} +${resourceModuleExports} ${entryClass}`; } diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts new file mode 100644 index 0000000000..6aeba30ed0 --- /dev/null +++ b/packages/void/src/runtime/workflows/index.ts @@ -0,0 +1,246 @@ +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; +import { isResourceName } from '../../shared/resource-name.ts'; +import type { StandardSchemaV1 } from '../../standard-schema.ts'; +import { requireRuntimeBinding, withRuntimeEnv } from '../env/runtime.ts'; + +export type { WorkflowEvent, WorkflowStep }; + +type NativeWorkflowClass = new (...args: Array) => { + run(event: never, step: never): Promise; +}; + +/** Params type of a native class, read from its `run(event)` annotation. */ +export type NativeWorkflowParams = + InstanceType extends { + run(event: Readonly>, ...rest: Array): unknown; + } + ? TParams + : unknown; + +/** Context passed to a `defineWorkflow()` run function next to the event and step. */ +export type WorkflowContext = { + readonly env: TEnv; + readonly ctx: ExecutionContext; +}; + +/** Options for starting one Workflow instance. */ +export type WorkflowCreateOptions = Omit & { + params?: TParams; +}; + +export type WorkflowApi = { + class: TClass; + /** @internal Called by Void's generated Worker entry. */ + __bind(bindingName: string, resourceName?: string): void; + /** Start a new instance. Params are validated when the definition has a `params` schema. */ + create(options?: WorkflowCreateOptions): Promise; + create(binding: Workflow, options?: WorkflowCreateOptions): Promise; + /** Start up to 100 instances. Each instance's params are validated first. */ + createBatch( + instances: ReadonlyArray>, + ): Promise; + createBatch( + binding: Workflow, + instances: ReadonlyArray>, + ): Promise; + /** Get a handle to an existing instance. */ + get(id: string): Promise; + get(binding: Workflow, id: string): Promise; +}; + +export type WorkflowRun = ( + event: Readonly>, + step: WorkflowStep, + context: WorkflowContext, +) => Promise; + +export type WorkflowClass = new ( + ctx: ExecutionContext, + env: Record, +) => WorkflowEntrypoint, TParams>; + +/** Error thrown by `create()` and `createBatch()` when params fail the definition's schema. */ +export class WorkflowParamsError extends Error { + readonly issues: ReadonlyArray<{ message: string; path?: string }>; + + constructor(issues: ReadonlyArray) { + const flattened = Array.from(issues, (issue) => ({ + message: issue.message, + ...(issue.path?.length + ? { + path: issue.path + .map((segment) => String(typeof segment === 'object' ? segment.key : segment)) + .join('.'), + } + : {}), + })); + super( + `workflows: invalid params: ${flattened + .map((issue) => (issue.path ? `${issue.path}: ${issue.message}` : issue.message)) + .join('; ')}`, + ); + this.name = 'WorkflowParamsError'; + this.issues = flattened; + } +} + +function isWorkflowBinding(value: Workflow | TOther): value is Workflow { + return ( + typeof value === 'object' && + value !== null && + typeof (value as { create?: unknown }).create === 'function' && + typeof (value as { get?: unknown }).get === 'function' + ); +} + +function createWorkflowApi( + definitionName: string | undefined, + workflowClass: TClass, + schema: StandardSchemaV1 | undefined, +): WorkflowApi { + if (definitionName !== undefined && !isResourceName(definitionName)) { + throw new Error('workflows: name must contain a word starting with a letter.'); + } + let bindingName: string | undefined; + + function boundWorkflow(): Workflow { + if (!bindingName) { + throw new Error( + 'workflows: this definition is not bound. Default-export it from a file in workflows/.', + ); + } + return requireRuntimeBinding(bindingName); + } + + async function prepare( + options: WorkflowCreateOptions | undefined, + ): Promise { + if (!schema) { + return options; + } + const result = await schema['~standard'].validate(options?.params); + if (result.issues) { + throw new WorkflowParamsError(result.issues); + } + return { ...options, params: result.value }; + } + + return { + class: workflowClass, + __bind(name, resourceName) { + if (definitionName !== resourceName) { + throw new Error( + 'workflows: name must be statically discoverable in the workflow definition. Run void info to inspect this definition.', + ); + } + if (bindingName && bindingName !== name) { + throw new Error( + `workflows: definition is already bound to '${bindingName}' and cannot also bind to '${name}'.`, + ); + } + bindingName = name; + }, + async create( + bindingOrOptions?: Workflow | WorkflowCreateOptions, + maybeOptions?: WorkflowCreateOptions, + ) { + const explicit = isWorkflowBinding(bindingOrOptions); + const binding = explicit ? bindingOrOptions : boundWorkflow(); + const options = explicit ? maybeOptions : bindingOrOptions; + return binding.create(await prepare(options)); + }, + async createBatch( + bindingOrInstances: Workflow | ReadonlyArray>, + maybeInstances?: ReadonlyArray>, + ) { + const explicit = isWorkflowBinding(bindingOrInstances); + const binding = explicit ? bindingOrInstances : boundWorkflow(); + const instances = explicit ? (maybeInstances ?? []) : bindingOrInstances; + const prepared = await Promise.all( + Array.from(instances, async (instance) => (await prepare(instance)) ?? {}), + ); + return binding.createBatch({ instances: prepared }); + }, + get(bindingOrId: Workflow | string, maybeId?: string) { + if (typeof bindingOrId === 'string') { + return boundWorkflow().get(bindingOrId); + } + if (maybeId === undefined) { + throw new Error('workflows: get(binding, id) requires an instance id.'); + } + return bindingOrId.get(maybeId); + }, + }; +} + +type WorkflowDefinitionBase = { + /** Optional persistent resource name. Pin the name reported by `void info` before moving this definition. */ + name?: string; +}; + +/** + * Define a Workflow from a run function. Void generates the Cloudflare + * `WorkflowEntrypoint` class. Default-export the result from a file in `workflows/`. + */ +export function defineWorkflow< + TSchema extends StandardSchemaV1, + TEnv extends Record = Record, +>( + definition: WorkflowDefinitionBase & { + /** Standard Schema that validates params in `create()` and `createBatch()`. */ + params: TSchema; + run: WorkflowRun, TEnv>; + }, +): WorkflowApi< + WorkflowClass>, + StandardSchemaV1.InferInput +>; +export function defineWorkflow< + TParams = unknown, + TEnv extends Record = Record, +>( + definition: WorkflowDefinitionBase & { + params?: undefined; + run: WorkflowRun; + }, +): WorkflowApi, TParams>; +export function defineWorkflow( + definition: WorkflowDefinitionBase & { + params?: StandardSchemaV1; + run: WorkflowRun>; + }, +): WorkflowApi, unknown> { + if (typeof definition.run !== 'function') { + throw new Error('workflows: defineWorkflow() requires a run function.'); + } + const run = definition.run; + + class VoidWorkflow extends WorkflowEntrypoint, unknown> { + override run(event: Readonly>, step: WorkflowStep): Promise { + const env = this.env; + const ctx = this.ctx; + return withRuntimeEnv(env, () => run(event, step, { env, ctx })); + } + } + + return createWorkflowApi(definition.name, VoidWorkflow, definition.params); +} + +/** + * Register a native Cloudflare `WorkflowEntrypoint` class without changing it. + * Default-export the result from a file in `workflows/`. + */ +export function defineWorkflowEntrypoint< + TClass extends NativeWorkflowClass, + TParams = NativeWorkflowParams, +>( + definition: WorkflowDefinitionBase & { + class: TClass; + }, +): WorkflowApi { + if (typeof definition.class !== 'function') { + throw new Error('workflows: defineWorkflowEntrypoint() requires a class.'); + } + return createWorkflowApi(definition.name, definition.class, undefined); +} diff --git a/packages/void/src/shared/env.ts b/packages/void/src/shared/env.ts index fdb3322eb1..fdb6380416 100644 --- a/packages/void/src/shared/env.ts +++ b/packages/void/src/shared/env.ts @@ -41,6 +41,12 @@ export const CLOUDFLARE_DEPLOY_BUILD_ENV = 'VOID_CLOUDFLARE_DEPLOY_BUILD'; */ export const CLOUDFLARE_QUEUE_NAMES_BUILD_ENV = 'VOID_CLOUDFLARE_QUEUE_NAMES'; +/** + * The Worker name `void deploy --platform cloudflare` deploys to. Set only for + * its Vite build, which prefixes account-scoped Workflow names with it. + */ +export const CLOUDFLARE_WORKER_NAME_BUILD_ENV = 'VOID_CLOUDFLARE_WORKER_NAME'; + /** * Find legacy Vite dotenv variants. Void intentionally supports only `.env`; * production configuration is project-scoped remote state instead of a file. diff --git a/packages/void/src/shared/resource-definition.ts b/packages/void/src/shared/resource-definition.ts index 2c74460b25..7e85aeb92a 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -63,7 +63,9 @@ export function readResourceDefinition( ? new Set(['defineRoom', 'defineWebSocket']) : source === 'void/durable' ? new Set(['defineDurableState', 'defineDurableObject']) - : new Set(); + : source === 'void/workflows' + ? new Set(['defineWorkflow', 'defineWorkflowEntrypoint']) + : new Set(); for (const specifier of declaration.specifiers ?? []) { const local = specifier.local as AstNode | undefined; recordBindings(local); diff --git a/packages/void/src/workflows/config.ts b/packages/void/src/workflows/config.ts new file mode 100644 index 0000000000..610a6ded1e --- /dev/null +++ b/packages/void/src/workflows/config.ts @@ -0,0 +1,55 @@ +import { cloudflareWorkflowName } from './scan.ts'; +import type { WorkflowModule } from './scan.ts'; + +export type WorkflowConfigEntry = Record & { + name?: unknown; + binding?: unknown; + class_name?: unknown; + script_name?: unknown; +}; + +export function workflowConfigEntries(value: unknown): Array { + if (value === undefined) { + return []; + } + if ( + !Array.isArray(value) || + value.some((entry) => !entry || typeof entry !== 'object' || Array.isArray(entry)) + ) { + throw new Error('Cloudflare workflows configuration must be an array of objects.'); + } + return value as Array; +} + +/** + * The `workflows` entries Void adds for `workflows/` modules, given the entries + * already configured. A module whose binding is already configured for the same + * local class is kept as configured, so an authored entry can pin the name. + */ +export function planWorkflowAdditions( + existing: ReadonlyArray, + modules: ReadonlyArray>, + workerName: string, +): Array<{ name: string; binding: string; class_name: string }> { + const additions: Array<{ name: string; binding: string; class_name: string }> = []; + for (const module of modules) { + const configured = existing.find((entry) => entry.binding === module.bindingName); + if (configured) { + if (configured.class_name !== module.className || configured.script_name !== undefined) { + throw new Error( + `workflows: binding '${module.bindingName}' is already configured for another Workflow, but workflows/ requires class '${module.className}'.`, + ); + } + continue; + } + const name = cloudflareWorkflowName(module.resourceName, workerName); + const owner = [...existing, ...additions].find((entry) => entry.name === name); + if (owner) { + throw new Error( + `workflows: Workflow name '${name}' is already configured for binding '${String(owner.binding)}'.`, + ); + } + additions.push({ name, binding: module.bindingName, class_name: module.className }); + } + return additions; +} diff --git a/packages/void/src/workflows/platform.ts b/packages/void/src/workflows/platform.ts new file mode 100644 index 0000000000..b06544ff3c --- /dev/null +++ b/packages/void/src/workflows/platform.ts @@ -0,0 +1,10 @@ +import { scanWorkflowModules } from './scan.ts'; + +/** Void platform deploys do not provision Cloudflare Workflows yet. */ +export function assertNoWorkflowsForPlatform(root: string): void { + if (scanWorkflowModules(root).length > 0) { + throw new Error( + 'workflows: workflows/ is not supported on Void platforms yet. Deploy this app to your own Cloudflare account with `void deploy --platform cloudflare`.', + ); + } +} diff --git a/packages/void/src/workflows/scan.ts b/packages/void/src/workflows/scan.ts new file mode 100644 index 0000000000..7385175f33 --- /dev/null +++ b/packages/void/src/workflows/scan.ts @@ -0,0 +1,111 @@ +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'pathslash'; +import { globSync } from 'tinyglobby'; +import { readResourceDefinition } from '../shared/resource-definition.ts'; +import { resourceNameWords } from '../shared/resource-name.ts'; + +export type WorkflowModule = { + filePath: string; + /** Path relative to `workflows/`, with `/` separators. */ + relativePath: string; + bindingName: string; + className: string; + /** Kebab-case resource name. Cloudflare Workflow names are derived from it. */ + resourceName: string; + name?: string; +}; + +const MODULE_PATTERN = /\.(?:[cm]?[jt]s)$/; +const MODULE_GLOB = '**/*.{ts,mts,cts,js,mjs,cjs}'; + +const WORKFLOW_HELPERS = new Set(['defineWorkflow', 'defineWorkflowEntrypoint']); + +/** + * The name a module gets without an explicit `name`: its path relative to + * `workflows/` without the extension, with directories joined by `-`, as + * queue names are (`order/notifications.ts` → `order-notifications`). + */ +export function inferWorkflowResourceName(relativePath: string): string { + return relativePath.replaceAll('\\', '/').replace(MODULE_PATTERN, '').replaceAll('/', '-'); +} + +/** Module files under `workflows/`, skipping declarations and `_`-prefixed files or directories. */ +function listWorkflowFiles(directory: string): Array { + return globSync(MODULE_GLOB, { cwd: directory }) + .map((file) => file.replaceAll('\\', '/')) + .filter( + (file) => + !file.endsWith('.d.ts') && + !file.endsWith('.d.mts') && + !file.endsWith('.d.cts') && + file.split('/').every((segment) => !segment.startsWith('_')), + ) + .sort((a, b) => a.localeCompare(b)); +} + +export function deriveWorkflowResourceIdentity(name: string): { + bindingName: string; + className: string; + resourceName: string; +} { + const parts = resourceNameWords(name); + const classBase = parts.map((part) => part[0].toUpperCase() + part.slice(1)).join(''); + return { + bindingName: `WORKFLOW_${parts.join('_').toUpperCase()}`, + className: `${classBase}Workflow`, + resourceName: parts.join('-').toLowerCase(), + }; +} + +/** + * Cloudflare Workflow names are unique per account. Deploys prefix them with the + * Worker name; local development, where names only need to be unique per Worker, + * uses the resource name alone. + */ +export function cloudflareWorkflowName(resourceName: string, workerName?: string): string { + if (!workerName) { + return resourceName; + } + const prefix = workerName.toLowerCase().replaceAll('_', '-'); + return `${prefix}-${resourceName}`.slice(0, 64); +} + +export function scanWorkflowModules(root: string): Array { + const directory = join(root, 'workflows'); + if (!existsSync(directory)) { + return []; + } + + const modules = listWorkflowFiles(directory).map((relativePath) => { + const filePath = join(directory, relativePath); + const definition = readResourceDefinition( + filePath, + readFileSync(filePath, 'utf8'), + WORKFLOW_HELPERS, + ); + const name = definition?.name; + const resourceName = name ?? inferWorkflowResourceName(relativePath); + if (resourceNameWords(resourceName).length === 0) { + throw new Error(`workflows: cannot derive a name from workflows/${relativePath}.`); + } + return { + filePath, + relativePath, + ...deriveWorkflowResourceIdentity(resourceName), + ...(name === undefined ? {} : { name }), + }; + }); + + const bindings = new Set(); + const classes = new Set(); + for (const module of modules) { + if (bindings.has(module.bindingName) || classes.has(module.className)) { + throw new Error( + `workflows: duplicate generated name for 'workflows/${module.relativePath}'. Choose a different resource name or rename one of the workflows files.`, + ); + } + bindings.add(module.bindingName); + classes.add(module.className); + } + return modules; +} diff --git a/packages/void/test/integration/cloudflare-durable-build.test.ts b/packages/void/test/integration/cloudflare-durable-build.test.ts index 571e2f8fa1..c2c01e8b90 100644 --- a/packages/void/test/integration/cloudflare-durable-build.test.ts +++ b/packages/void/test/integration/cloudflare-durable-build.test.ts @@ -9,6 +9,7 @@ import { verifyGeneratedDeployConfig } from '../../src/cli/deploy-artifact-valid import { reconstructExpectedContainers, reconstructExpectedDurableObjectState, + reconstructExpectedWorkflows, snapshotBindingIdentities, snapshotPassthroughIdentities, snapshotPassthroughRawFields, @@ -18,7 +19,10 @@ import { syncWranglerBindings } from '../../src/cli/wrangler.ts'; import { materializeCloudflareConfig } from '../../src/cloudflare-config.ts'; import { renderVoidConfig } from '../../src/config-write.ts'; import { readConfig } from '../../src/config.ts'; -import { CLOUDFLARE_DEPLOY_BUILD_ENV } from '../../src/shared/env.ts'; +import { + CLOUDFLARE_DEPLOY_BUILD_ENV, + CLOUDFLARE_WORKER_NAME_BUILD_ENV, +} from '../../src/shared/env.ts'; const repository = join(import.meta.dirname, '..', '..', '..', '..'); const accountId = '0123456789abcdef0123456789abcdef'; @@ -149,6 +153,13 @@ export default defineDurableState({ initialState: { count: 0 }, methods: { incre ), expectedCrons: signals.expectedCrons, expectedDurableObjectBindings: durable.bindings, + expectedWorkflows: reconstructExpectedWorkflows( + config, + root, + rootConfig, + `durable-merge-${options.name}`, + analysis, + ), expectedMigrations: durable.migrations, }; const build = () => { @@ -172,9 +183,12 @@ export default defineDurableState({ initialState: { count: 0 }, methods: { incre containers?: Array; hyperdrive?: Array; ai?: unknown; + workflows?: Array; }; }; const emitted = build(); + // Workflows are opt-in: an app without workflows/ emits no Workflow config. + expect(emitted.workflows).toBeUndefined(); // Exercise worker/cloudflare overlap through the actual provider plugin, // alongside the existing native build rather than booting another one. if (options.name === 'native') { @@ -215,4 +229,94 @@ export default defineDurableState({ initialState: { count: 0 }, methods: { incre } }, ); + + it('emits Workflow entries named after the deployed Worker and keeps authored ones', () => { + const fixture = createIsolatedPlayground(repository, 'playground/ssr'); + const root = fixture.root; + try { + mkdirSync(join(root, 'workflows'), { recursive: true }); + writeFileSync( + join(root, 'workflows/welcome.ts'), + `import { defineWorkflow } from 'void/workflows'; +export default defineWorkflow({ async run(event, step) { return step.do('greet', async () => 'hi'); } });\n`, + ); + writeFileSync( + join(root, 'workflows/nightly-import.ts'), + `import { WorkflowEntrypoint } from 'cloudflare:workers'; +import { defineWorkflowEntrypoint } from 'void/workflows'; +class Importer extends WorkflowEntrypoint { async run() { return 'imported'; } } +export default defineWorkflowEntrypoint({ class: Importer });\n`, + ); + const pinned = { + name: 'legacy-import', + binding: 'WORKFLOW_NIGHTLY_IMPORT', + class_name: 'NightlyImportWorkflow', + }; + writeFileSync( + join(root, 'void.config.ts'), + renderVoidConfig({ + ...readConfig(root), + cloudflare: { name: 'workflow-merge', account_id: accountId, workflows: [pinned] }, + }), + ); + const config = readConfig(root); + const analysis = analyzeApplicationSync(root, { config }); + const configPath = materializeCloudflareConfig(root); + const rootConfig = parseRootWranglerConfig(configPath); + const expectedWorkflows = reconstructExpectedWorkflows( + config, + root, + rootConfig, + 'deployed-app', + analysis, + ); + expect(expectedWorkflows).toEqual([ + pinned, + { + name: 'deployed-app-welcome', + binding: 'WORKFLOW_WELCOME', + class_name: 'WelcomeWorkflow', + }, + ]); + const result = spawn.sync('vp', ['build'], { + cwd: root, + encoding: 'utf8', + timeout: 60_000, + maxBuffer: 10 * 1024 * 1024, + env: { + ...process.env, + [CLOUDFLARE_DEPLOY_BUILD_ENV]: '1', + [CLOUDFLARE_WORKER_NAME_BUILD_ENV]: 'deployed-app', + CLOUDFLARE_API_TOKEN: '', + CLOUDFLARE_API_KEY: '', + }, + }); + expect(result.status, `${result.stdout ?? ''}${result.stderr ?? ''}`).toBe(0); + const emitted = JSON.parse(readFileSync(join(root, 'dist/ssr/wrangler.json'), 'utf8')) as { + workflows?: Array>; + }; + expect(emitted.workflows).toEqual(expect.arrayContaining(expectedWorkflows)); + expect(emitted.workflows).toHaveLength(expectedWorkflows.length); + const worker = readFileSync(join(root, 'dist/ssr/index.js'), 'utf8'); + expect(worker).toMatch(/WelcomeWorkflow/); + expect(worker).toMatch(/NightlyImportWorkflow/); + expect( + verifyGeneratedDeployConfig(root, { + accountId, + workerName: 'workflow-merge', + passthroughIdentitySnapshot: snapshotPassthroughIdentities(rootConfig), + expectedWorkflows, + }), + ).toEqual({ ok: true }); + expect( + verifyGeneratedDeployConfig(root, { + accountId, + workerName: 'workflow-merge', + expectedWorkflows: [pinned], + }), + ).toMatchObject({ ok: false, reason: expect.stringContaining('workflows differ') }); + } finally { + fixture.cleanup(); + } + }, 120_000); }); diff --git a/packages/void/test/integration/workflow-runtime.test.ts b/packages/void/test/integration/workflow-runtime.test.ts new file mode 100644 index 0000000000..8680a01319 --- /dev/null +++ b/packages/void/test/integration/workflow-runtime.test.ts @@ -0,0 +1,222 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { Miniflare, convertV4MiniflareOptions } from 'miniflare'; +import { build } from 'vite'; +import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; +import { compileWorkerEntry } from '../../src/router/compile.ts'; + +const root = join(import.meta.dirname, '..', '..', '..', '..'); +const runtimePath = join(root, 'packages/void/src/runtime/workflows/index.ts'); +const durablePath = join(root, 'packages/void/src/runtime/durable/index.ts'); +const temporary = mkdtempSync(join(tmpdir(), 'void-workflow-runtime-')); +type Runtime = { dispatchFetch(url: string): Promise; dispose(): Promise }; +let runtime: Runtime; + +const ROUTE_STUBS = ` +export const scheduled = async () => {}; +export const __voidCollectPrerenderPaths = async () => []; +export const __voidRenderStaticNotFound = async () => new Response(null, { status: 204 }); +export const __voidHandleInternalRoute = async () => null; +export const __withRawEnv = (_env, fn) => fn(); +`; + +/** Build a generated Worker entry for `entryOptions` into `name/worker.mjs`. */ +async function buildWorker( + name: string, + routes: string, + entryOptions: Parameters[0], +): Promise { + const directory = join(temporary, name); + const routesPath = join(temporary, `${name}-routes.ts`); + const entryPath = join(temporary, `${name}-entry.ts`); + writeFileSync(routesPath, ROUTE_STUBS + routes); + writeFileSync( + entryPath, + compileWorkerEntry({ + runtimeEnvPath: join(root, 'packages/void/src/runtime/env/runtime.ts'), + ...entryOptions, + }), + ); + await build({ + configFile: false, + logLevel: 'silent', + plugins: [ + { + name: 'workflow-runtime-fixture', + resolveId: (id) => (id === 'virtual:void-routes' ? routesPath : null), + }, + ], + ssr: { noExternal: true }, + build: { + outDir: directory, + emptyOutDir: true, + ssr: entryPath, + target: 'esnext', + rollupOptions: { + external: [/^cloudflare:/, /^node:/], + output: { entryFileNames: 'worker.mjs', codeSplitting: false }, + }, + }, + }); + return directory; +} + +function file(name: string, source: string): string { + const path = join(temporary, name); + writeFileSync(path, source); + return path; +} + +describe('Workflows through the generated Worker and a real Workflows engine', () => { + beforeAll(async () => { + const definition = file( + 'welcome.ts', + ` +import { defineWorkflow } from ${JSON.stringify(runtimePath)}; +const params = { '~standard': { version: 1, vendor: 'test', validate(value) { + return typeof value?.name === 'string' ? { value } : { issues: [{ message: 'name is required', path: ['name'] }] }; +} } }; +export const Welcome = defineWorkflow({ + params, + async run(event, step, { env }) { + const greeting = await step.do('greet', async () => env.GREETING + ', ' + event.payload.name); + return { greeting }; + }, +}); +export default Welcome; +`, + ); + const output = await buildWorker( + 'valid', + ` +import { Welcome } from ${JSON.stringify(definition)}; +export default { async fetch(request) { + const url = new URL(request.url); + if (url.pathname === '/start') { + try { + const instance = await Welcome.create({ id: url.searchParams.get('id'), params: { name: url.searchParams.get('name') ?? undefined } }); + return Response.json({ id: instance.id }); + } catch (error) { + return Response.json({ error: error.message }, { status: 400 }); + } + } + const instance = await Welcome.get(url.searchParams.get('id')); + return Response.json(await instance.status()); +}}; +`, + { + workflows: [ + { + bindingName: 'WORKFLOW_WELCOME', + className: 'WelcomeWorkflow', + filePath: definition, + }, + ], + }, + ); + runtime = new Miniflare( + convertV4MiniflareOptions({ + compatibilityDate: '2026-07-01', + compatibilityFlags: ['nodejs_compat'], + modules: true, + modulesRoot: output, + scriptPath: join(output, 'worker.mjs'), + bindings: { GREETING: 'Hello' }, + workflows: { WORKFLOW_WELCOME: { name: 'welcome', className: 'WelcomeWorkflow' } }, + }), + ) as unknown as Runtime; + }, 30_000); + + afterAll(async () => { + await runtime?.dispose(); + rmSync(temporary, { recursive: true, force: true }); + }); + + it('starts an instance from a route and runs its steps with the Worker env', async () => { + const started = await runtime.dispatchFetch('http://localhost/start?id=first&name=Ada'); + expect(started.status).toBe(200); + expect(await started.json()).toEqual({ id: 'first' }); + + let status: { status: string; output?: unknown } = { status: 'queued' }; + for (let attempt = 0; attempt < 100 && status.status !== 'complete'; attempt++) { + const response = await runtime.dispatchFetch('http://localhost/status?id=first'); + status = await response.json(); + if (status.status === 'errored') { + break; + } + await new Promise((resolve) => { + setTimeout(resolve, 50); + }); + } + expect(status).toMatchObject({ status: 'complete', output: { greeting: 'Hello, Ada' } }); + }); + + it('rejects invalid params before starting an instance', async () => { + const response = await runtime.dispatchFetch('http://localhost/start?id=invalid'); + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ + error: 'workflows: invalid params: name: name is required', + }); + }); +}); + +describe('convention modules without a definition default export', () => { + it.each([ + { + kind: 'workflows', + source: 'export const Welcome = 1;', + message: + 'workflows: workflows/missing.ts must default-export defineWorkflow() or defineWorkflowEntrypoint().', + }, + { + kind: 'workflows', + source: 'export default class Welcome {}', + message: + 'workflows: workflows/missing.ts must default-export defineWorkflow() or defineWorkflowEntrypoint().', + }, + { + kind: 'durable-objects', + source: 'export const Counter = 1;', + message: + 'durable: durable-objects/missing.ts must default-export defineDurableState() or defineDurableObject().', + }, + { + kind: 'durable-objects', + source: `import { defineDurableState } from ${JSON.stringify(durablePath)}; +export const Counter = defineDurableState({ initialState: 0, methods: {} });`, + message: + 'durable: durable-objects/missing.ts must default-export defineDurableState() or defineDurableObject().', + }, + ])( + 'fails Worker startup with a clear error for $kind: $source', + async ({ kind, source, message }) => { + const name = `${kind}-${Math.random().toString(36).slice(2)}`; + const definition = join(temporary, name, kind); + mkdirSync(definition, { recursive: true }); + const filePath = join(definition, 'missing.ts'); + writeFileSync(filePath, source); + const entry = { bindingName: 'MISSING', className: 'Missing', filePath }; + const output = await buildWorker( + name, + 'export default { fetch: () => new Response("ok") };', + kind === 'workflows' ? { workflows: [entry] } : { durableObjects: [entry] }, + ); + const worker = new Miniflare( + convertV4MiniflareOptions({ + compatibilityDate: '2026-07-01', + compatibilityFlags: ['nodejs_compat'], + modules: true, + modulesRoot: output, + scriptPath: join(output, 'worker.mjs'), + }), + ) as unknown as Runtime; + try { + await expect(worker.dispatchFetch('http://localhost/')).rejects.toThrow(message); + } finally { + await worker.dispose().catch(() => {}); + } + }, + 30_000, + ); +}); diff --git a/packages/void/test/unit/compile.test.ts b/packages/void/test/unit/compile.test.ts index 267e6d9bd3..517f63e490 100644 --- a/packages/void/test/unit/compile.test.ts +++ b/packages/void/test/unit/compile.test.ts @@ -857,11 +857,61 @@ describe('compileWorkerEntry', () => { ], }); - expect(code).toContain('import __voidDurableObject0 from "/app/durable-objects/counter.ts";'); + expect(code).toContain( + 'import * as __voidDurableObjectModule0 from "/app/durable-objects/counter.ts";', + ); expect(code).toContain('__voidDurableObject0.__bind("COUNTER");'); expect(code).toContain('export const CounterDurableObject = __voidDurableObject0.class;'); }); + it('re-exports Workflow modules as worker classes with their pinned names', () => { + const code = compileWorkerEntry({ + workflows: [ + { + bindingName: 'WORKFLOW_ONBOARDING', + className: 'OnboardingWorkflow', + filePath: '/app/workflows/onboarding.ts', + name: 'onboarding', + }, + ], + }); + + expect(code).toContain( + 'import * as __voidWorkflowModule0 from "/app/workflows/onboarding.ts";', + ); + expect(code).toContain('__voidWorkflow0.__bind("WORKFLOW_ONBOARDING", "onboarding");'); + expect(code).toContain('export const OnboardingWorkflow = __voidWorkflow0.class;'); + }); + + it('guards convention modules that do not default-export a definition', () => { + const code = compileWorkerEntry({ + durableObjects: [ + { + bindingName: 'COUNTER', + className: 'CounterDurableObject', + filePath: '/app/durable-objects/counter.ts', + }, + ], + workflows: [ + { + bindingName: 'WORKFLOW_ONBOARDING', + className: 'OnboardingWorkflow', + filePath: '/app/workflows/onboarding.ts', + }, + ], + }); + + expect(code).toContain( + 'if (typeof __voidDurableObject0?.__bind !== "function") { throw new Error("durable: durable-objects/counter.ts must default-export defineDurableState() or defineDurableObject()."); }', + ); + expect(code).toContain( + 'if (typeof __voidWorkflow0?.__bind !== "function") { throw new Error("workflows: workflows/onboarding.ts must default-export defineWorkflow() or defineWorkflowEntrypoint()."); }', + ); + expect(code.indexOf('typeof __voidWorkflow0?.__bind')).toBeLessThan( + code.indexOf('__voidWorkflow0.__bind('), + ); + }); + it('re-exports the live Durable Object class when enabled', () => { const code = compileWorkerEntry({ hasQueues: false, diff --git a/packages/void/test/unit/info.test.ts b/packages/void/test/unit/info.test.ts index c1474d0f4d..0a6e13c428 100644 --- a/packages/void/test/unit/info.test.ts +++ b/packages/void/test/unit/info.test.ts @@ -92,6 +92,37 @@ describe('void info', () => { expect(existsSync(join(root, '.void'))).toBe(false); }); + it('reports Workflow identities with inferred and explicit names', () => { + const root = project(); + write(root, 'workflows/send-welcome.ts', 'export default defineWorkflow({ async run() {} });'); + write( + root, + 'workflows/import-v2.ts', + `import { defineWorkflowEntrypoint } from 'void/workflows'; +export default defineWorkflowEntrypoint({ name: 'import', class: Importer });`, + ); + const info = getProjectInfo(root); + expect(info.resources).toEqual([ + { + file: 'workflows/import-v2.ts', + definition: 'defineWorkflow', + name: 'import', + nameSource: 'explicit', + className: 'ImportWorkflow', + bindingName: 'WORKFLOW_IMPORT', + }, + { + file: 'workflows/send-welcome.ts', + definition: 'defineWorkflow', + name: 'send-welcome', + nameSource: 'inferred', + className: 'SendWelcomeWorkflow', + bindingName: 'WORKFLOW_SEND_WELCOME', + }, + ]); + expect(formatProjectInfo(info)).toContain("add this to 'defineWorkflow':"); + }); + it('keeps explicit names visible after moving code and respects configured source paths', () => { const root = project(); write(root, 'void.config.ts', "export default { sourceDir: 'src' };"); diff --git a/packages/void/test/unit/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index f053de23ff..ef8d34d157 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -761,6 +761,17 @@ describe('detectFramework', () => { 'void/durable', ), ).toThrow('void/durable is server-only'); + expect(() => + resolveId.call( + { + environment: { name: 'client' }, + error(message: string): never { + throw new Error(message); + }, + }, + 'void/workflows', + ), + ).toThrow('void/workflows is server-only'); } finally { cwd.mockRestore(); } @@ -830,8 +841,9 @@ describe('detectFramework', () => { try { voidPlugin(); const entry = readFileSync(join(root, '.void', 'entry.ts'), 'utf8'); - expect(entry).toContain('import __voidDurableObject0 from'); + expect(entry).toContain('import * as __voidDurableObjectModule0 from'); expect(entry).toContain('/durable-objects/shopping-cart.ts'); + expect(entry).toContain('const __voidDurableObject0 = __voidDurableObjectModule0.default;'); expect(entry).toContain('__voidDurableObject0.__bind("SHOPPING_CART")'); expect(entry).toContain( 'export const ShoppingCartDurableObject = __voidDurableObject0.class', @@ -841,6 +853,56 @@ describe('detectFramework', () => { } }); + it('exports convention-based Workflows from the worker entry', () => { + const root = createTempRoot(); + mkdirSync(join(root, 'routes'), { recursive: true }); + mkdirSync(join(root, 'workflows'), { recursive: true }); + writeFileSync(join(root, 'routes', 'index.ts'), 'export const GET = () => new Response("ok");'); + writeFileSync( + join(root, 'workflows', 'send-welcome.ts'), + 'export default { class: class SendWelcome {}, __bind() {} }', + ); + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); + + try { + voidPlugin(); + const entry = readFileSync(join(root, '.void', 'entry.ts'), 'utf8'); + expect(entry).toContain('import * as __voidWorkflowModule0 from'); + expect(entry).toContain('/workflows/send-welcome.ts'); + expect(entry).toContain('__voidWorkflow0.__bind("WORKFLOW_SEND_WELCOME")'); + expect(entry).toContain('export const SendWelcomeWorkflow = __voidWorkflow0.class'); + expect(entry).toContain( + 'workflows: workflows/send-welcome.ts must default-export defineWorkflow() or defineWorkflowEntrypoint().', + ); + } finally { + cwd.mockRestore(); + } + }); + + it('rejects Workflow modules in framework adapter mode and on non-Cloudflare targets', () => { + const framework = createTempRoot(); + mkdirSync(join(framework, 'workflows'), { recursive: true }); + writeFileSync( + join(framework, 'package.json'), + JSON.stringify({ dependencies: { '@sveltejs/kit': '^2.0.0' } }), + ); + writeFileSync(join(framework, 'workflows', 'welcome.ts'), 'export default {}'); + const node = createTempRoot(); + mkdirSync(join(node, 'routes'), { recursive: true }); + mkdirSync(join(node, 'workflows'), { recursive: true }); + writeFileSync(join(node, 'void.json'), JSON.stringify({ target: 'node' })); + writeFileSync(join(node, 'workflows', 'welcome.ts'), 'export default {}'); + const cwd = vi.spyOn(process, 'cwd').mockReturnValue(framework); + + try { + expect(() => voidPlugin()).toThrow('workflows/ is currently supported in Void apps only'); + cwd.mockReturnValue(node); + expect(() => voidPlugin()).toThrow('workflows/ requires target: "cloudflare"'); + } finally { + cwd.mockRestore(); + } + }); + it('rejects typed Durable Object modules in framework adapter mode', () => { const root = createTempRoot(); mkdirSync(join(root, 'durable-objects'), { recursive: true }); diff --git a/packages/void/test/unit/workflow-runtime.test.ts b/packages/void/test/unit/workflow-runtime.test.ts new file mode 100644 index 0000000000..7455c6d1b4 --- /dev/null +++ b/packages/void/test/unit/workflow-runtime.test.ts @@ -0,0 +1,151 @@ +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; +import { describe, expect, expectTypeOf, it, vi } from 'vite-plus/test'; +import { getRuntimeEnv, withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; +import { + defineWorkflow, + defineWorkflowEntrypoint, + WorkflowParamsError, +} from '../../src/runtime/workflows/index.ts'; +import type { WorkflowApi } from '../../src/runtime/workflows/index.ts'; +import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; + +vi.mock('cloudflare:workers', () => ({ + WorkflowEntrypoint: class { + protected ctx: unknown; + protected env: unknown; + constructor(ctx: unknown, env: unknown) { + this.ctx = ctx; + this.env = env; + } + }, +})); + +function binding() { + const instance = { id: 'instance' } as unknown as WorkflowInstance; + return { + instance, + workflow: { + create: vi.fn(async (_options?: unknown) => instance), + createBatch: vi.fn(async (_options: unknown) => ({ created: [instance], errors: [] })), + get: vi.fn(async (_id: string) => instance), + }, + }; +} + +/** A minimal Standard Schema for `{ userId: string }` that trims the id. */ +const userSchema: StandardSchemaV1<{ userId: string }, { userId: string }> = { + '~standard': { + version: 1, + vendor: 'test', + validate(value) { + if ( + typeof value === 'object' && + value !== null && + typeof (value as { userId?: unknown }).userId === 'string' + ) { + return { value: { userId: (value as { userId: string }).userId.trim() } }; + } + return { issues: [{ message: 'Expected a string', path: [{ key: 'userId' }] }] }; + }, + }, +}; + +describe('defineWorkflow', () => { + it('generates an entrypoint that runs inside the Worker env', async () => { + const seen: Array = []; + const Welcome = defineWorkflow({ + async run(event: WorkflowEvent<{ userId: string }>, step, context) { + seen.push(event.payload.userId, context.env.GREETING, getRuntimeEnv().GREETING); + return step.do('greet', async () => 'done'); + }, + }); + const step = { do: vi.fn(async (_name: string, fn: () => Promise) => fn()) }; + const instance = new Welcome.class({} as ExecutionContext, { GREETING: 'hello' }); + expect(instance).toBeInstanceOf(WorkflowEntrypoint); + const result = await instance.run( + { payload: { userId: 'u1' } } as WorkflowEvent<{ userId: string }>, + step as unknown as WorkflowStep, + ); + expect(result).toBe('done'); + expect(seen).toEqual(['u1', 'hello', 'hello']); + }); + + it('starts, batches, and gets instances through its convention binding', async () => { + const { workflow, instance } = binding(); + const Welcome = defineWorkflow({ + async run(_event: WorkflowEvent<{ userId: string }>) {}, + }); + await expect(Welcome.create({ params: { userId: 'u1' } })).rejects.toThrow('not bound'); + Welcome.__bind('WORKFLOW_WELCOME'); + await withRuntimeEnv({ WORKFLOW_WELCOME: workflow }, async () => { + expect(await Welcome.create({ id: 'a', params: { userId: 'u1' } })).toBe(instance); + expect(await Welcome.get('a')).toBe(instance); + await Welcome.createBatch([{ params: { userId: 'u2' } }]); + }); + expect(workflow.create).toHaveBeenCalledWith({ id: 'a', params: { userId: 'u1' } }); + expect(workflow.get).toHaveBeenCalledWith('a'); + expect(workflow.createBatch).toHaveBeenCalledWith({ + instances: [{ params: { userId: 'u2' } }], + }); + expect(() => Welcome.__bind('OTHER')).toThrow('already bound'); + }); + + it('accepts an explicit binding', async () => { + const { workflow } = binding(); + const Welcome = defineWorkflow({ async run() {} }); + await Welcome.create(workflow as unknown as Workflow, { id: 'b' }); + await Welcome.get(workflow as unknown as Workflow, 'b'); + expect(workflow.create).toHaveBeenCalledWith({ id: 'b' }); + expect(workflow.get).toHaveBeenCalledWith('b'); + }); + + it('validates and transforms params with its schema before starting', async () => { + const { workflow } = binding(); + const Welcome = defineWorkflow({ + params: userSchema, + async run(event) { + expectTypeOf(event.payload).toEqualTypeOf>(); + }, + }); + Welcome.__bind('WORKFLOW_WELCOME'); + await withRuntimeEnv({ WORKFLOW_WELCOME: workflow }, async () => { + await Welcome.create({ params: { userId: ' u1 ' } }); + const invalid = Welcome.create({ params: { userId: 1 as unknown as string } }); + await expect(invalid).rejects.toBeInstanceOf(WorkflowParamsError); + await expect(invalid).rejects.toThrow('workflows: invalid params: userId: Expected a string'); + await expect(Welcome.create()).rejects.toThrow('invalid params'); + await expect( + Welcome.createBatch([{ params: { userId: 'ok' } }, { params: {} as { userId: string } }]), + ).rejects.toThrow('invalid params'); + }); + expect(workflow.create).toHaveBeenCalledTimes(1); + expect(workflow.create).toHaveBeenCalledWith({ params: { userId: 'u1' } }); + expect(workflow.createBatch).not.toHaveBeenCalled(); + }); + + it('rejects a runtime identity that differs from static analysis and invalid names', () => { + const Welcome = defineWorkflow({ name: 'welcome', async run() {} }); + expect(() => Welcome.__bind('WORKFLOW_WELCOME', 'other')).toThrow('statically discoverable'); + expect(() => defineWorkflow({ name: '123', async run() {} })).toThrow('name must contain'); + }); +}); + +describe('defineWorkflowEntrypoint', () => { + it('keeps the native class and infers params from its run annotation', async () => { + class Importer extends WorkflowEntrypoint, { file: string }> { + override async run(_event: Readonly>, _step: WorkflowStep) { + return 'imported'; + } + } + const { workflow } = binding(); + const Import = defineWorkflowEntrypoint({ name: 'import', class: Importer }); + expect(Import.class).toBe(Importer); + Import.__bind('WORKFLOW_IMPORT', 'import'); + await withRuntimeEnv({ WORKFLOW_IMPORT: workflow }, () => + Import.create({ params: { file: 'a.csv' } }), + ); + expectTypeOf(Import).toEqualTypeOf>(); + expect(workflow.create).toHaveBeenCalledWith({ params: { file: 'a.csv' } }); + }); +}); diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts new file mode 100644 index 0000000000..85da6f867b --- /dev/null +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -0,0 +1,165 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { toSlash } from 'pathslash'; +import { afterEach, describe, expect, it } from 'vite-plus/test'; +import { planWorkflowAdditions } from '../../src/workflows/config.ts'; +import { assertNoWorkflowsForPlatform } from '../../src/workflows/platform.ts'; +import { + cloudflareWorkflowName, + deriveWorkflowResourceIdentity, + scanWorkflowModules, +} from '../../src/workflows/scan.ts'; + +const roots: Array = []; + +function createRoot(files: Record): string { + const root = mkdtempSync(join(tmpdir(), 'void-workflow-scan-')); + roots.push(root); + mkdirSync(join(root, 'workflows')); + for (const [filename, source] of Object.entries(files)) { + mkdirSync(dirname(join(root, 'workflows', filename)), { recursive: true }); + writeFileSync(join(root, 'workflows', filename), source); + } + return root; +} + +afterEach(() => { + for (const root of roots.splice(0)) { + rmSync(root, { recursive: true, force: true }); + } +}); + +describe('scanWorkflowModules', () => { + it('returns nothing without a workflows directory', () => { + const root = mkdtempSync(join(tmpdir(), 'void-workflow-scan-')); + roots.push(root); + expect(scanWorkflowModules(root)).toEqual([]); + expect(() => assertNoWorkflowsForPlatform(root)).not.toThrow(); + }); + + it('derives binding, class, and resource names from filenames', () => { + const root = createRoot({ 'send-welcome.ts': 'export default {}', 'types.d.ts': '' }); + expect(scanWorkflowModules(root)).toEqual([ + { + filePath: toSlash(join(root, 'workflows', 'send-welcome.ts')), + relativePath: 'send-welcome.ts', + bindingName: 'WORKFLOW_SEND_WELCOME', + className: 'SendWelcomeWorkflow', + resourceName: 'send-welcome', + }, + ]); + }); + + it('joins nested directories into the name, as queues do', () => { + const root = createRoot({ 'order/notifications.ts': 'export default {}' }); + expect(scanWorkflowModules(root)).toEqual([ + { + filePath: toSlash(join(root, 'workflows', 'order', 'notifications.ts')), + relativePath: 'order/notifications.ts', + bindingName: 'WORKFLOW_ORDER_NOTIFICATIONS', + className: 'OrderNotificationsWorkflow', + resourceName: 'order-notifications', + }, + ]); + }); + + it('ignores files and directories starting with an underscore', () => { + const root = createRoot({ + 'welcome.ts': 'export default {}', + '_steps.ts': 'export const send = () => {};', + '_lib/email.ts': 'export const send = () => {};', + 'order/_shared.ts': 'export const total = 0;', + }); + expect(scanWorkflowModules(root).map((module) => module.relativePath)).toEqual(['welcome.ts']); + }); + + it('rejects a nested path and a file that produce the same name', () => { + const root = createRoot({ + 'order/notifications.ts': 'export default {}', + 'order-notifications.ts': 'export default {}', + }); + expect(() => scanWorkflowModules(root)).toThrow('duplicate generated name'); + }); + + it('reads a static name through aliased imports without evaluating the module', () => { + const root = createRoot({ + 'renamed.ts': `import { defineWorkflowEntrypoint as workflow } from 'void/workflows'; + const name = 'nightly-import'; + export default workflow({ name, class: Importer });`, + }); + expect(scanWorkflowModules(root)[0]).toMatchObject({ + name: 'nightly-import', + ...deriveWorkflowResourceIdentity('nightly-import'), + }); + }); + + it('rejects files that normalize to the same generated names', () => { + const root = createRoot({ + 'send-welcome.ts': 'export default {}', + 'send_welcome.ts': 'export default {}', + }); + expect(() => scanWorkflowModules(root)).toThrow('duplicate generated name'); + }); + + it('rejects Void platform deploys while workflows exist', () => { + const root = createRoot({ 'welcome.ts': 'export default {}' }); + expect(() => assertNoWorkflowsForPlatform(root)).toThrow('void deploy --platform cloudflare'); + }); +}); + +describe('Cloudflare Workflow names', () => { + it('prefixes the account-scoped name with the Worker name', () => { + expect(cloudflareWorkflowName('welcome', 'My_App')).toBe('my-app-welcome'); + expect(cloudflareWorkflowName('welcome')).toBe('welcome'); + expect(cloudflareWorkflowName('w'.repeat(80), 'app')).toHaveLength(64); + }); + + it('adds only unconfigured modules and keeps an authored entry for the same class', () => { + const modules = [ + deriveWorkflowResourceIdentity('welcome'), + deriveWorkflowResourceIdentity('import'), + ]; + const authored = { + name: 'pinned-welcome', + binding: 'WORKFLOW_WELCOME', + class_name: 'WelcomeWorkflow', + }; + expect(planWorkflowAdditions([authored], modules, 'app')).toEqual([ + { name: 'app-import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, + ]); + expect(planWorkflowAdditions([], [], 'app')).toEqual([]); + }); + + it('rejects a binding retargeted to another class or Worker, and a taken name', () => { + const modules = [deriveWorkflowResourceIdentity('welcome')]; + expect(() => + planWorkflowAdditions( + [{ name: 'x', binding: 'WORKFLOW_WELCOME', class_name: 'Other' }], + modules, + 'app', + ), + ).toThrow("binding 'WORKFLOW_WELCOME' is already configured"); + expect(() => + planWorkflowAdditions( + [ + { + name: 'x', + binding: 'WORKFLOW_WELCOME', + class_name: 'WelcomeWorkflow', + script_name: 'other-worker', + }, + ], + modules, + 'app', + ), + ).toThrow("binding 'WORKFLOW_WELCOME' is already configured"); + expect(() => + planWorkflowAdditions( + [{ name: 'app-welcome', binding: 'MINE', class_name: 'Mine' }], + modules, + 'app', + ), + ).toThrow("Workflow name 'app-welcome' is already configured for binding 'MINE'"); + }); +}); diff --git a/packages/void/vite.config.ts b/packages/void/vite.config.ts index a1773edb58..4d78ef3512 100644 --- a/packages/void/vite.config.ts +++ b/packages/void/vite.config.ts @@ -104,6 +104,7 @@ export default defineConfig({ 'src/runtime/db/postgres.ts', 'src/runtime/db/mysql.ts', 'src/runtime/durable/index.ts', + 'src/runtime/workflows/index.ts', 'src/runtime/db/seed.ts', 'src/runtime/db/validators/drizzle-zod.ts', 'src/runtime/db/validators/drizzle-valibot.ts', From aafcfd64e32a48b4f82d1b6ec5b245fa33e37ffb Mon Sep 17 00:00:00 2001 From: Isak Gustavsen Date: Wed, 25 Nov 2026 01:13:36 +0100 Subject: [PATCH 02/13] fix(void): infer bindings from workflows/ modules Resource imports used only inside workflows/, including _-prefixed step helpers and nested folders, now count toward binding inference, as they already do for durable-objects/. Apps with a sourceDir scan workflows/ too. Co-Authored-By: Claude Opus 5.5 --- docs/reference/resource-inference.md | 2 +- packages/void/src/plugin-inference.ts | 4 +++- .../void/test/unit/plugin-inference.test.ts | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/docs/reference/resource-inference.md b/docs/reference/resource-inference.md index 13407199dc..8cfdaa0967 100644 --- a/docs/reference/resource-inference.md +++ b/docs/reference/resource-inference.md @@ -71,7 +71,7 @@ Regardless of mode, these are always checked: - **SSR entry** such as `src/main.ssr.ts`, for SSR apps that access bindings during rendering - **Application source** in `src/` or your configured `sourceDir`, including resource and auth imports - **`durable-objects/`**, which is scanned for typed Durable Object state modules in native Void apps -- **`workflows/`**, which is scanned for Workflow modules in native Void apps +- **`workflows/`**, which is scanned for Workflow modules and the resources they use in native Void apps ## Custom Scan Directories diff --git a/packages/void/src/plugin-inference.ts b/packages/void/src/plugin-inference.ts index c3ec28f2ca..e6c51e6d81 100644 --- a/packages/void/src/plugin-inference.ts +++ b/packages/void/src/plugin-inference.ts @@ -58,6 +58,7 @@ export const DEFAULT_SCAN_DIRS = [ 'crons', 'email', 'durable-objects', + 'workflows', 'src', ] as const; @@ -152,7 +153,8 @@ export function inferProjectBindings( ): InferredBindings { const paths = options?.paths ?? readProjectPaths(root); const dirs = - scanDirs ?? (paths.sourceDir ? [paths.sourceDir, 'durable-objects'] : DEFAULT_SCAN_DIRS); + scanDirs ?? + (paths.sourceDir ? [paths.sourceDir, 'durable-objects', 'workflows'] : DEFAULT_SCAN_DIRS); const allBindings: Array = []; const scannedFiles = new Set(); const routesPrefix = `${toSlash(paths.routesDir).replace(/\/$/, '')}/`; diff --git a/packages/void/test/unit/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index ef8d34d157..4783d11f9f 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -378,6 +378,24 @@ describe('inferProjectBindings', () => { }); }); + it('infers resources used only by Workflow modules and their helpers', () => { + const root = createTempRoot(); + mkdirSync(join(root, 'workflows', 'order'), { recursive: true }); + writeFileSync( + join(root, 'workflows', '_storage.ts'), + `import { createStorage } from 'void/storage'; + export const files = (env) => createStorage(env.STORAGE);`, + ); + writeFileSync( + join(root, 'workflows', 'order', 'summary.ts'), + `import { createAi } from 'void/ai'; + export const ai = (env) => createAi(env);`, + ); + expect(inferProjectBindings(root)).toMatchObject({ needsAI: true, needsR2: true }); + writeFileSync(join(root, 'void.json'), JSON.stringify({ sourceDir: 'src' })); + expect(inferProjectBindings(root)).toMatchObject({ needsAI: true, needsR2: true }); + }); + it('detects live from a stream module outside the default directories only when scanned', () => { const root = createTempRoot(); mkdirSync(join(root, 'routes'), { recursive: true }); From 1d72f3a8f1be3515b459c78cb7b166d7f1fc4ddd Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 09:17:31 +0900 Subject: [PATCH 03/13] Fix Workflow deployment and payload contracts. --- docs/guide/workflows.md | 6 +- docs/reference/api/workflows.md | 2 + packages/void/src/application-analysis.ts | 11 +++- .../src/cli/cloudflare-deploy/classify.ts | 2 +- .../void/src/cli/deploy-binding-snapshot.ts | 2 +- .../src/cli/deploy-cloudflare-preflight.ts | 14 ++--- .../void/src/cli/deploy-cloudflare-static.ts | 3 +- packages/void/src/cli/preset.ts | 10 +++- packages/void/src/index.ts | 5 +- packages/void/src/plugin-cloudflare-config.ts | 2 +- packages/void/src/plugin-inference.ts | 12 ++-- packages/void/src/runtime/workflows/index.ts | 13 ++-- .../void/src/shared/resource-definition.ts | 10 ++-- packages/void/src/workflows/scan.ts | 49 ++++++++------- .../test/unit/cloudflare-classify.test.ts | 40 +++++++++++++ packages/void/test/unit/info.test.ts | 6 +- .../void/test/unit/plugin-inference.test.ts | 32 ++++++++-- .../void/test/unit/workflow-runtime.test.ts | 1 + .../test/unit/workflow-runtime.typecheck.ts | 29 +++++++++ packages/void/test/unit/workflow-scan.test.ts | 59 +++++++++++++++---- 20 files changed, 239 insertions(+), 69 deletions(-) create mode 100644 packages/void/test/unit/workflow-runtime.typecheck.ts diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md index 90cc4617f5..0b44273231 100644 --- a/docs/guide/workflows.md +++ b/docs/guide/workflows.md @@ -33,7 +33,7 @@ export default Onboarding; Default-export the object returned by `defineWorkflow()`. Named-export it too so routes can import it. -TypeScript and JavaScript files are supported. Subdirectories are scanned too, and files or directories starting with `_` are ignored, so keep shared step helpers in files such as `workflows/_email.ts`. +TypeScript and JavaScript files are supported, including subdirectories. Void discovers default exports created using a helper imported from `void/workflows`. Files and directories starting with `_` are excluded from Workflow discovery. `run` receives: @@ -56,7 +56,7 @@ export const POST = defineHandler(async () => { }); ``` -`create()` accepts the same options as Cloudflare's [`Workflow.create()`](https://developers.cloudflare.com/workflows/build/workers-api/#create), such as `id` and `retention`. Its `params` are typed from your definition. Use `createBatch()` to start up to 100 instances at once. +`create()` accepts the same options as Cloudflare's [`Workflow.create()`](https://developers.cloudflare.com/workflows/build/workers-api/#create), such as `id` and `retention`. Use `createBatch()` to start up to 100 instances at once. Both methods require `params` when your definition requires a payload. Check on an instance with `get()`: @@ -155,6 +155,8 @@ export default defineConfig({ }); ``` +If the generated Cloudflare Workflow name exceeds 64 characters, use this entry to give it a shorter name. + ## Deployment support Workflows are available on the Workers Free plan, within [Cloudflare's Workflows limits](https://developers.cloudflare.com/workflows/reference/limits/). Deploy to your own Cloudflare account with `void deploy --platform cloudflare`. diff --git a/docs/reference/api/workflows.md b/docs/reference/api/workflows.md index e45f14e55c..174765ecce 100644 --- a/docs/reference/api/workflows.md +++ b/docs/reference/api/workflows.md @@ -25,6 +25,8 @@ function defineWorkflow(definition: { With `params`, `run` receives the schema's output type and `create()` accepts its input type. Without it, the params type comes from the `event` annotation. +When the params type requires a payload, pass `params` to `create()` and to every entry in `createBatch()`. + ## `defineWorkflowEntrypoint(definition)` {#defineworkflowentrypoint-definition} Registers a class that extends Cloudflare's `WorkflowEntrypoint` without changing it. The params type is read from the class's `run(event)` annotation. diff --git a/packages/void/src/application-analysis.ts b/packages/void/src/application-analysis.ts index 674f00d335..fbbee8845e 100644 --- a/packages/void/src/application-analysis.ts +++ b/packages/void/src/application-analysis.ts @@ -80,6 +80,7 @@ export async function getNativeWorkerSourceFiles( ...analysis.queues.map(({ filePath }) => join(paths.queuesDir, filePath)), ...emailFiles.map((filePath) => join(paths.emailDir, filePath)), ...analysis.durableObjects.map(({ filePath }) => filePath), + ...analysis.workflows.map(({ filePath }) => filePath), ...(envFile !== null ? [envFile] : []), ]; } @@ -96,10 +97,17 @@ export function analyzeApplicationSync( const { config, environment } = options; const paths = resolveProjectPaths(root, config); const framework = detectFramework(root); + const workflows = scanWorkflowModules(root); const scanDirs = config.inference?.scanDirs ?? (framework ? FRAMEWORK_SCAN_DIRS : undefined); const inferred = inferProjectBindings( root, - { paths, environment, filterPages: !framework, bindings: config.inference?.bindings }, + { + paths, + environment, + filterPages: !framework, + bindings: config.inference?.bindings, + hasWorkflows: workflows.length > 0, + }, scanDirs, ); const authConfigPath = findVoidAuthConfig(root, paths); @@ -119,7 +127,6 @@ export function analyzeApplicationSync( ); // Typed durable modules currently use the root convention on every target. const durableObjects = scanDurableObjectModules(root); - const workflows = scanWorkflowModules(root); const email = scanEmailHandlersSync(paths.sourceRoot); const overrides = config.inference?.bindings; const bindingReason = ( diff --git a/packages/void/src/cli/cloudflare-deploy/classify.ts b/packages/void/src/cli/cloudflare-deploy/classify.ts index 37ed4c1bcf..468c535e4c 100644 --- a/packages/void/src/cli/cloudflare-deploy/classify.ts +++ b/packages/void/src/cli/cloudflare-deploy/classify.ts @@ -78,7 +78,7 @@ export function classifyCloudflareDeployApp( [ 'deploy: --platform cloudflare found no Void backend to deploy.', 'A full Void app has at least one of: routes/, pages/, middleware, crons/, queues/,', - 'email/, or an SSR entry. Add your server code, or use `void deploy` for a static site.', + 'email/, workflows/, or an SSR entry. Add your server code, or use `void deploy` for a static site.', ].join('\n'), ); } diff --git a/packages/void/src/cli/deploy-binding-snapshot.ts b/packages/void/src/cli/deploy-binding-snapshot.ts index c92f1e6039..6d5459bec8 100644 --- a/packages/void/src/cli/deploy-binding-snapshot.ts +++ b/packages/void/src/cli/deploy-binding-snapshot.ts @@ -291,7 +291,6 @@ type DurableObjectSnapshot = { migrations: Array>; }; -/** Reconstruct the Durable Object state emitted after the pre-build root config is synced. */ /** * The exact `workflows` entries the build should emit: the root config's, plus one * per `workflows/` module that the root config does not already bind. @@ -308,6 +307,7 @@ export function reconstructExpectedWorkflows( return [...configured, ...planWorkflowAdditions(configured, modules, workerName)]; } +/** Reconstruct the Durable Object state emitted after the pre-build root config is synced. */ export function reconstructExpectedDurableObjectState( config: VoidConfig, root: string, diff --git a/packages/void/src/cli/deploy-cloudflare-preflight.ts b/packages/void/src/cli/deploy-cloudflare-preflight.ts index 2c7e98f3f4..fb2cc9859d 100644 --- a/packages/void/src/cli/deploy-cloudflare-preflight.ts +++ b/packages/void/src/cli/deploy-cloudflare-preflight.ts @@ -290,6 +290,13 @@ export async function preflightCloudflareWorker(input: { } = connection; rootConfig = connection.rootConfig; const workerName = readWranglerTopLevelString(rootConfig, 'name') ?? deriveWorkerName(root); + const expectedWorkflows = reconstructExpectedWorkflows( + voidConfig, + root, + rootConfig, + workerName, + source.analysis, + ); printDeployContext(workerName, 'Cloudflare'); // Email setup makes credentialed calls, so it runs before the env-schema probe runs any @@ -693,13 +700,6 @@ export async function preflightCloudflareWorker(input: { preBuildRootConfig, { needsSandbox, needsLive, analysis: source.analysis }, ); - const expectedWorkflows = reconstructExpectedWorkflows( - voidConfig, - root, - preBuildRootConfig, - workerName, - source.analysis, - ); return { apiBaseUrl, complianceRegion, diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index c80083a88e..0ffbeeae99 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -257,7 +257,8 @@ export async function resolveCloudflareVoidStaticPreset( hasLive: bindings.needsLive === true, }) || analysis.jobs.length > 0 || - analysis.queues.length > 0; + analysis.queues.length > 0 || + analysis.workflows.length > 0; if (hasRuntimeBackend) { return null; } diff --git a/packages/void/src/cli/preset.ts b/packages/void/src/cli/preset.ts index 5e82b3c7d8..f1d09da8f1 100644 --- a/packages/void/src/cli/preset.ts +++ b/packages/void/src/cli/preset.ts @@ -9,6 +9,7 @@ import { readPackageJson, } from '../shared/package-json.ts'; import { getSsrServerEntryPath, hasSsrEntry } from '../ssr/entry.ts'; +import { scanWorkflowModules } from '../workflows/scan.ts'; import { viteConfigImportsVoidPlugin } from './vite-config-patch.ts'; import { findWorkspaceMemberRoot, parsePackageManagerField } from './workspace.ts'; import type { PackageManager } from './workspace.ts'; @@ -471,6 +472,9 @@ export function findBackendSources(root: string): Array { if (ssrEntry) { found.push(relative(root, ssrEntry)); } + if (scanWorkflowModules(root).length > 0) { + found.push('workflows/'); + } return found; } @@ -479,7 +483,11 @@ export function findBackendSources(root: string): Array { */ export function hasBackendFiles(root: string): boolean { const paths = readProjectPaths(root); - return backendDirs(paths).some((dir) => existsSync(dir)) || hasSsrEntry(root, paths); + return ( + backendDirs(paths).some((dir) => existsSync(dir)) || + hasSsrEntry(root, paths) || + scanWorkflowModules(root).length > 0 + ); } function backendDirs(paths: ProjectPaths): Array { diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index f3e477b189..0f5f8e2a9a 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -608,7 +608,10 @@ export function voidPlugin(options?: { name: 'void:binding-watch', apply: 'serve', configureServer(server) { - const effectiveDirs = scanDirs ?? DEFAULT_SCAN_DIRS; + const effectiveDirs = scanDirs ?? [ + ...DEFAULT_SCAN_DIRS, + ...(workflows.length > 0 ? ['workflows'] : []), + ]; const watchDirs = [...new Set([...effectiveDirs, 'src'])].map((d) => join(root, d)); let hintShown = false; const check = (path: string) => { diff --git a/packages/void/src/plugin-cloudflare-config.ts b/packages/void/src/plugin-cloudflare-config.ts index bf873b7313..01a3e32d17 100644 --- a/packages/void/src/plugin-cloudflare-config.ts +++ b/packages/void/src/plugin-cloudflare-config.ts @@ -94,7 +94,6 @@ export function mergeCloudflareConfig(patch: object, fallback: object): WorkerCo return result; } -/** Translate Void's Wrangler-shaped settings to the configuration that the Cloudflare plugin takes. */ /** The Worker name a Void app gets when its config does not set one: its package or directory name. */ export function defaultCloudflareWorkerName(root: string): string { const packagePath = join(root, 'package.json'); @@ -110,6 +109,7 @@ export function defaultCloudflareWorkerName(root: string): string { ); } +/** Translate Void's Wrangler-shaped settings to the configuration that the Cloudflare plugin takes. */ export function toNativeCloudflareConfig(raw: WorkerConfig, root: string): CloudflareConfig { const name = defaultCloudflareWorkerName(root); const { env, vars, ...base } = raw; diff --git a/packages/void/src/plugin-inference.ts b/packages/void/src/plugin-inference.ts index c856ea513d..c9922cac66 100644 --- a/packages/void/src/plugin-inference.ts +++ b/packages/void/src/plugin-inference.ts @@ -17,6 +17,7 @@ import { isWebSocketPatternFile } from './router/websocket.ts'; import { conventionFileGlobs, isRouteFile } from './shared/convention-files.ts'; import { deriveFromSource } from './shared/source-analysis-cache.ts'; import { getSsrServerEntryPath } from './ssr/entry.ts'; +import { scanWorkflowModules } from './workflows/scan.ts'; const SOURCE_GLOB = '**/*.{ts,tsx,mts,js,jsx,mjs,astro}'; @@ -58,7 +59,6 @@ export const DEFAULT_SCAN_DIRS = [ 'crons', 'email', 'durable-objects', - 'workflows', 'src', ] as const; @@ -119,6 +119,8 @@ export type InferenceOptions = { environment?: RouteEnvironment; /** Also filter Void page files and their `.server` companions by environment. Off for framework apps. */ filterPages?: boolean; + /** Whether the application has a Workflow definition and its convention directory is active. */ + hasWorkflows?: boolean; }; function extractAstroFrontmatter(code: string): string { @@ -152,9 +154,11 @@ export function inferProjectBindings( scanDirs?: ReadonlyArray, ): InferredBindings { const paths = options?.paths ?? readProjectPaths(root); - const dirs = - scanDirs ?? - (paths.sourceDir ? [paths.sourceDir, 'durable-objects', 'workflows'] : DEFAULT_SCAN_DIRS); + const hasWorkflows = options?.hasWorkflows ?? scanWorkflowModules(root).length > 0; + const dirs = scanDirs ?? [ + ...(paths.sourceDir ? [paths.sourceDir, 'durable-objects'] : DEFAULT_SCAN_DIRS), + ...(hasWorkflows ? ['workflows'] : []), + ]; const allBindings: Array = []; const scannedFiles = new Set(); const routesPrefix = `${toSlash(paths.routesDir).replace(/\/$/, '')}/`; diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts index 6aeba30ed0..0bb3896487 100644 --- a/packages/void/src/runtime/workflows/index.ts +++ b/packages/void/src/runtime/workflows/index.ts @@ -25,17 +25,20 @@ export type WorkflowContext = { }; /** Options for starting one Workflow instance. */ -export type WorkflowCreateOptions = Omit & { - params?: TParams; -}; +export type WorkflowCreateOptions = Omit & + (undefined extends TParams ? { params?: TParams } : { params: TParams }); + +type WorkflowCreateArguments = undefined extends TParams + ? [options?: WorkflowCreateOptions] + : [options: WorkflowCreateOptions]; export type WorkflowApi = { class: TClass; /** @internal Called by Void's generated Worker entry. */ __bind(bindingName: string, resourceName?: string): void; /** Start a new instance. Params are validated when the definition has a `params` schema. */ - create(options?: WorkflowCreateOptions): Promise; - create(binding: Workflow, options?: WorkflowCreateOptions): Promise; + create(...args: WorkflowCreateArguments): Promise; + create(binding: Workflow, ...args: WorkflowCreateArguments): Promise; /** Start up to 100 instances. Each instance's params are validated first. */ createBatch( instances: ReadonlyArray>, diff --git a/packages/void/src/shared/resource-definition.ts b/packages/void/src/shared/resource-definition.ts index 7e85aeb92a..b43dbc5bda 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -22,6 +22,7 @@ export function readResourceDefinition( filename: string, source: string, helpers: ReadonlySet, + options?: { requireImportedHelper?: boolean }, ): { helper: string; options?: AstNode; name?: string } | null { let program: AstProgram; try { @@ -176,7 +177,8 @@ export function readResourceDefinition( let helper: string | undefined; if (isIdentifier(callee)) { helper = - importedHelpers.get(callee.name) ?? (helpers.has(callee.name) ? callee.name : undefined); + importedHelpers.get(callee.name) ?? + (!options?.requireImportedHelper && helpers.has(callee.name) ? callee.name : undefined); } else if (isMemberExpression(callee) && isIdentifier(callee.object)) { const property = !callee.computed && isIdentifier(callee.property) @@ -193,7 +195,7 @@ export function readResourceDefinition( if (!helper) { return null; } - const options = resolve(call.arguments?.[0]); - const name = readName(options).value; - return { helper, options, ...(name === undefined ? {} : { name }) }; + const definitionOptions = resolve(call.arguments?.[0]); + const name = readName(definitionOptions).value; + return { helper, options: definitionOptions, ...(name === undefined ? {} : { name }) }; } diff --git a/packages/void/src/workflows/scan.ts b/packages/void/src/workflows/scan.ts index 7385175f33..74cb392448 100644 --- a/packages/void/src/workflows/scan.ts +++ b/packages/void/src/workflows/scan.ts @@ -1,8 +1,9 @@ -import { existsSync, readFileSync } from 'node:fs'; +import { existsSync } from 'node:fs'; import { join } from 'pathslash'; import { globSync } from 'tinyglobby'; import { readResourceDefinition } from '../shared/resource-definition.ts'; import { resourceNameWords } from '../shared/resource-name.ts'; +import { deriveFromSource } from '../shared/source-analysis-cache.ts'; export type WorkflowModule = { filePath: string; @@ -43,11 +44,9 @@ function listWorkflowFiles(directory: string): Array { .sort((a, b) => a.localeCompare(b)); } -export function deriveWorkflowResourceIdentity(name: string): { - bindingName: string; - className: string; - resourceName: string; -} { +export function deriveWorkflowResourceIdentity( + name: string, +): Pick { const parts = resourceNameWords(name); const classBase = parts.map((part) => part[0].toUpperCase() + part.slice(1)).join(''); return { @@ -63,11 +62,14 @@ export function deriveWorkflowResourceIdentity(name: string): { * uses the resource name alone. */ export function cloudflareWorkflowName(resourceName: string, workerName?: string): string { - if (!workerName) { - return resourceName; + const prefix = workerName?.toLowerCase().replaceAll('_', '-'); + const name = prefix ? `${prefix}-${resourceName}` : resourceName; + if (name.length > 64) { + throw new Error( + `workflows: generated Workflow name '${name}' exceeds Cloudflare's limit of 64 characters. Choose a shorter name in cloudflare.workflows.`, + ); } - const prefix = workerName.toLowerCase().replaceAll('_', '-'); - return `${prefix}-${resourceName}`.slice(0, 64); + return name; } export function scanWorkflowModules(root: string): Array { @@ -76,24 +78,27 @@ export function scanWorkflowModules(root: string): Array { return []; } - const modules = listWorkflowFiles(directory).map((relativePath) => { + const modules = listWorkflowFiles(directory).flatMap((relativePath) => { const filePath = join(directory, relativePath); - const definition = readResourceDefinition( - filePath, - readFileSync(filePath, 'utf8'), - WORKFLOW_HELPERS, + const definition = deriveFromSource(filePath, 'workflow-definition', (source) => + readResourceDefinition(filePath, source, WORKFLOW_HELPERS, { requireImportedHelper: true }), ); - const name = definition?.name; + if (!definition) { + return []; + } + const { name } = definition; const resourceName = name ?? inferWorkflowResourceName(relativePath); if (resourceNameWords(resourceName).length === 0) { throw new Error(`workflows: cannot derive a name from workflows/${relativePath}.`); } - return { - filePath, - relativePath, - ...deriveWorkflowResourceIdentity(resourceName), - ...(name === undefined ? {} : { name }), - }; + return [ + { + filePath, + relativePath, + ...deriveWorkflowResourceIdentity(resourceName), + ...(name === undefined ? {} : { name }), + }, + ]; }); const bindings = new Set(); diff --git a/packages/void/test/unit/cloudflare-classify.test.ts b/packages/void/test/unit/cloudflare-classify.test.ts index bdecd37f1b..13bac71d7c 100644 --- a/packages/void/test/unit/cloudflare-classify.test.ts +++ b/packages/void/test/unit/cloudflare-classify.test.ts @@ -5,6 +5,10 @@ import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import { analyzeApplicationSync } from '../../src/application-analysis.ts'; import { classifyCloudflareDeployApp } from '../../src/cli/cloudflare-deploy/classify.ts'; import type { CloudflareDeployAppOptions } from '../../src/cli/cloudflare-deploy/classify.ts'; +import { + resolveCloudflareStaticPreset, + resolveCloudflareVoidStaticPreset, +} from '../../src/cli/deploy-cloudflare-static.ts'; import { syncWranglerDurableObjects } from '../../src/cli/wrangler.ts'; import type { VoidConfig } from '../../src/config.ts'; @@ -29,6 +33,42 @@ afterEach(() => { }); describe('classifyCloudflareDeployApp', () => { + it('selects a Worker for an app whose only backend is a Workflow', () => { + const root = mkdtempSync(join(tmpdir(), 'void-cloudflare-classify-')); + roots.push(root); + writeFileSync(join(root, 'package.json'), JSON.stringify({ devDependencies: { vite: '*' } })); + mkdirSync(join(root, 'workflows')); + writeFileSync( + join(root, 'workflows', 'onboarding.ts'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", + ); + + expect(resolveCloudflareStaticPreset(root, {}, {})).toBeNull(); + expect(classify(root, {})).toEqual({ supported: true }); + expect(classify(root, { inference: { appType: 'void' } })).toEqual({ supported: true }); + }); + + it('keeps the full Worker when Pages are prerendered and a Workflow is declared', async () => { + const root = mkdtempSync(join(tmpdir(), 'void-cloudflare-classify-')); + roots.push(root); + mkdirSync(join(root, 'pages')); + writeFileSync( + join(root, 'pages', 'index.tsx'), + 'export default function Page() { return null; }', + ); + const config = { output: 'static' } satisfies VoidConfig; + expect(await resolveCloudflareVoidStaticPreset(root, config)).toMatchObject({ + appType: 'static', + }); + + mkdirSync(join(root, 'workflows')); + writeFileSync( + join(root, 'workflows', 'onboarding.ts'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", + ); + expect(await resolveCloudflareVoidStaticPreset(root, config)).toBeNull(); + }); + it('accepts a SvelteKit project whose routes live under src/routes', () => { const root = mkdtempSync(join(tmpdir(), 'void-cloudflare-classify-')); roots.push(root); diff --git a/packages/void/test/unit/info.test.ts b/packages/void/test/unit/info.test.ts index 0a6e13c428..108c132434 100644 --- a/packages/void/test/unit/info.test.ts +++ b/packages/void/test/unit/info.test.ts @@ -94,7 +94,11 @@ describe('void info', () => { it('reports Workflow identities with inferred and explicit names', () => { const root = project(); - write(root, 'workflows/send-welcome.ts', 'export default defineWorkflow({ async run() {} });'); + write( + root, + 'workflows/send-welcome.ts', + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", + ); write( root, 'workflows/import-v2.ts', diff --git a/packages/void/test/unit/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index 3766999799..b6ecceb035 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -389,13 +389,29 @@ describe('inferProjectBindings', () => { writeFileSync( join(root, 'workflows', 'order', 'summary.ts'), `import { createAi } from 'void/ai'; - export const ai = (env) => createAi(env);`, + import { defineWorkflow } from 'void/workflows'; + import { files } from '../_storage'; + export default defineWorkflow({ async run(event, step, { env }) { + const storage = files(env); + const ai = createAi(env); + } });`, ); expect(inferProjectBindings(root)).toMatchObject({ needsAI: true, needsR2: true }); writeFileSync(join(root, 'void.json'), JSON.stringify({ sourceDir: 'src' })); expect(inferProjectBindings(root)).toMatchObject({ needsAI: true, needsR2: true }); }); + it('does not infer bindings from an unrelated workflows directory', () => { + const root = createTempRoot(); + mkdirSync(join(root, 'workflows')); + writeFileSync( + join(root, 'workflows', '_maintenance.ts'), + "import { db } from 'void/db'; export const maintenance = () => db;", + ); + + expect(inferProjectBindings(root).needsD1).toBe(false); + }); + it('detects live from a stream module outside the default directories only when scanned', () => { const root = createTempRoot(); mkdirSync(join(root, 'routes'), { recursive: true }); @@ -885,7 +901,7 @@ describe('detectFramework', () => { writeFileSync(join(root, 'routes', 'index.ts'), 'export const GET = () => new Response("ok");'); writeFileSync( join(root, 'workflows', 'send-welcome.ts'), - 'export default { class: class SendWelcome {}, __bind() {} }', + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", ); const cwd = vi.spyOn(process, 'cwd').mockReturnValue(root); @@ -911,15 +927,23 @@ describe('detectFramework', () => { join(framework, 'package.json'), JSON.stringify({ dependencies: { '@sveltejs/kit': '^2.0.0' } }), ); - writeFileSync(join(framework, 'workflows', 'welcome.ts'), 'export default {}'); + const definition = + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });"; const node = createTempRoot(); mkdirSync(join(node, 'routes'), { recursive: true }); mkdirSync(join(node, 'workflows'), { recursive: true }); writeFileSync(join(node, 'void.json'), JSON.stringify({ target: 'node' })); - writeFileSync(join(node, 'workflows', 'welcome.ts'), 'export default {}'); const cwd = vi.spyOn(process, 'cwd').mockReturnValue(framework); try { + for (const root of [framework, node]) { + writeFileSync(join(root, 'workflows', 'maintenance.ts'), 'export const run = () => {};'); + cwd.mockReturnValue(root); + expect(() => voidPlugin()).not.toThrow(); + } + writeFileSync(join(framework, 'workflows', 'welcome.ts'), definition); + writeFileSync(join(node, 'workflows', 'welcome.ts'), definition); + cwd.mockReturnValue(framework); expect(() => voidPlugin()).toThrow('workflows/ is currently supported in Void apps only'); cwd.mockReturnValue(node); expect(() => voidPlugin()).toThrow('workflows/ requires target: "cloudflare"'); diff --git a/packages/void/test/unit/workflow-runtime.test.ts b/packages/void/test/unit/workflow-runtime.test.ts index 7455c6d1b4..314375b96f 100644 --- a/packages/void/test/unit/workflow-runtime.test.ts +++ b/packages/void/test/unit/workflow-runtime.test.ts @@ -114,6 +114,7 @@ describe('defineWorkflow', () => { const invalid = Welcome.create({ params: { userId: 1 as unknown as string } }); await expect(invalid).rejects.toBeInstanceOf(WorkflowParamsError); await expect(invalid).rejects.toThrow('workflows: invalid params: userId: Expected a string'); + // @ts-expect-error JavaScript callers can omit required params, so still validate at runtime. await expect(Welcome.create()).rejects.toThrow('invalid params'); await expect( Welcome.createBatch([{ params: { userId: 'ok' } }, { params: {} as { userId: string } }]), diff --git a/packages/void/test/unit/workflow-runtime.typecheck.ts b/packages/void/test/unit/workflow-runtime.typecheck.ts new file mode 100644 index 0000000000..6d9cc9802f --- /dev/null +++ b/packages/void/test/unit/workflow-runtime.typecheck.ts @@ -0,0 +1,29 @@ +import { defineWorkflow } from '../../src/runtime/workflows/index.ts'; + +declare const binding: Workflow; + +const required = defineWorkflow<{ userId: string }>({ async run() {} }); +void required.create({ params: { userId: 'user' } }); +void required.create(binding, { params: { userId: 'user' } }); +void required.createBatch([{ params: { userId: 'user' } }]); +void required.createBatch(binding, [{ params: { userId: 'user' } }]); + +// @ts-expect-error The handler expects a userId. +void required.create(); +// @ts-expect-error Options without params are incomplete. +void required.create({ id: 'instance' }); +// @ts-expect-error An explicit binding does not make params optional. +void required.create(binding); +// @ts-expect-error Each batch entry needs a payload. +void required.createBatch([{}]); +// @ts-expect-error Each explicit-binding batch entry needs a payload. +void required.createBatch(binding, [{ id: 'instance' }]); + +const optional = defineWorkflow<{ userId: string } | undefined>({ async run() {} }); +void optional.create(); +void optional.create(binding); +void optional.createBatch([{}]); + +const noParams = defineWorkflow({ async run() {} }); +void noParams.create(); +void noParams.createBatch(binding, [{ id: 'instance' }]); diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts index 85da6f867b..ecc3fcf0c0 100644 --- a/packages/void/test/unit/workflow-scan.test.ts +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -12,6 +12,8 @@ import { } from '../../src/workflows/scan.ts'; const roots: Array = []; +const definition = `import { defineWorkflow } from 'void/workflows'; +export default defineWorkflow({ async run() {} });`; function createRoot(files: Record): string { const root = mkdtempSync(join(tmpdir(), 'void-workflow-scan-')); @@ -31,6 +33,16 @@ afterEach(() => { }); describe('scanWorkflowModules', () => { + it('ignores ordinary modules in the workflows directory', () => { + const root = createRoot({ + 'maintenance.ts': 'export default { run() {} }', + 'unrelated.ts': 'const defineWorkflow = (value) => value; export default defineWorkflow({});', + }); + + expect(scanWorkflowModules(root)).toEqual([]); + expect(() => assertNoWorkflowsForPlatform(root)).not.toThrow(); + }); + it('returns nothing without a workflows directory', () => { const root = mkdtempSync(join(tmpdir(), 'void-workflow-scan-')); roots.push(root); @@ -39,7 +51,7 @@ describe('scanWorkflowModules', () => { }); it('derives binding, class, and resource names from filenames', () => { - const root = createRoot({ 'send-welcome.ts': 'export default {}', 'types.d.ts': '' }); + const root = createRoot({ 'send-welcome.ts': definition, 'types.d.ts': '' }); expect(scanWorkflowModules(root)).toEqual([ { filePath: toSlash(join(root, 'workflows', 'send-welcome.ts')), @@ -52,7 +64,7 @@ describe('scanWorkflowModules', () => { }); it('joins nested directories into the name, as queues do', () => { - const root = createRoot({ 'order/notifications.ts': 'export default {}' }); + const root = createRoot({ 'order/notifications.ts': definition }); expect(scanWorkflowModules(root)).toEqual([ { filePath: toSlash(join(root, 'workflows', 'order', 'notifications.ts')), @@ -66,18 +78,19 @@ describe('scanWorkflowModules', () => { it('ignores files and directories starting with an underscore', () => { const root = createRoot({ - 'welcome.ts': 'export default {}', - '_steps.ts': 'export const send = () => {};', - '_lib/email.ts': 'export const send = () => {};', - 'order/_shared.ts': 'export const total = 0;', + 'welcome.ts': definition, + '_steps.ts': definition, + '_lib/email.ts': definition, + 'order/_shared.ts': definition, + 'order/ordinary.ts': 'export const total = 0;', }); expect(scanWorkflowModules(root).map((module) => module.relativePath)).toEqual(['welcome.ts']); }); it('rejects a nested path and a file that produce the same name', () => { const root = createRoot({ - 'order/notifications.ts': 'export default {}', - 'order-notifications.ts': 'export default {}', + 'order/notifications.ts': definition, + 'order-notifications.ts': definition, }); expect(() => scanWorkflowModules(root)).toThrow('duplicate generated name'); }); @@ -96,14 +109,14 @@ describe('scanWorkflowModules', () => { it('rejects files that normalize to the same generated names', () => { const root = createRoot({ - 'send-welcome.ts': 'export default {}', - 'send_welcome.ts': 'export default {}', + 'send-welcome.ts': definition, + 'send_welcome.ts': definition, }); expect(() => scanWorkflowModules(root)).toThrow('duplicate generated name'); }); it('rejects Void platform deploys while workflows exist', () => { - const root = createRoot({ 'welcome.ts': 'export default {}' }); + const root = createRoot({ 'welcome.ts': definition }); expect(() => assertNoWorkflowsForPlatform(root)).toThrow('void deploy --platform cloudflare'); }); }); @@ -112,7 +125,29 @@ describe('Cloudflare Workflow names', () => { it('prefixes the account-scoped name with the Worker name', () => { expect(cloudflareWorkflowName('welcome', 'My_App')).toBe('my-app-welcome'); expect(cloudflareWorkflowName('welcome')).toBe('welcome'); - expect(cloudflareWorkflowName('w'.repeat(80), 'app')).toHaveLength(64); + expect(cloudflareWorkflowName('w'.repeat(60), 'app')).toHaveLength(64); + }); + + it('rejects an overlong generated name and accepts an explicit provider name', () => { + const modules = [ + deriveWorkflowResourceIdentity('welcome'), + deriveWorkflowResourceIdentity('reporting'), + ]; + const worker = 'w'.repeat(63); + expect(() => planWorkflowAdditions([], modules, worker)).toThrow( + /64 characters.*cloudflare\.workflows/, + ); + expect( + planWorkflowAdditions( + modules.map((module) => ({ + binding: module.bindingName, + class_name: module.className, + name: module.resourceName, + })), + modules, + worker, + ), + ).toEqual([]); }); it('adds only unconfigured modules and keeps an authored entry for the same class', () => { From fcd232dc54284d635378649fe77ad61adb577377 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 09:44:52 +0900 Subject: [PATCH 04/13] Fix Workflow deployment, discovery, and runtime contracts. --- docs/guide/workflows.md | 12 ++- docs/integrations/cloudflare.md | 2 +- docs/reference/api/workflows.md | 43 +++------ docs/reference/cli/deploy.md | 4 +- docs/reference/cli/setup.md | 2 +- docs/reference/config.md | 2 +- packages/deploy-cloudflare/src/version.ts | 2 +- packages/void/schema.json | 2 +- .../void/src/cli/deploy-cloudflare-build.ts | 29 ++++-- .../void/src/cli/deploy-cloudflare-helpers.ts | 25 ++++- .../void/src/cli/deploy-cloudflare-publish.ts | 1 + .../void/src/cli/deploy-cloudflare-static.ts | 32 +++++++ packages/void/src/cli/deploy-cloudflare.ts | 6 +- packages/void/src/cli/deploy-types.ts | 2 +- packages/void/src/cli/help.ts | 2 +- packages/void/src/cli/info.ts | 9 +- packages/void/src/plugin-inference.ts | 22 +++-- packages/void/src/plugin-routing.ts | 10 ++ packages/void/src/router/compile.ts | 18 +++- packages/void/src/runtime/workflows/index.ts | 93 +++++++++--------- .../void/src/shared/resource-definition.ts | 35 +++++-- packages/void/src/shared/resource-name.ts | 5 + packages/void/src/workflows/config.ts | 5 +- packages/void/src/workflows/scan.ts | 11 ++- .../test/integration/workflow-dev.test.ts | 45 +++++++++ .../test/integration/workflow-runtime.test.ts | 65 ++++++++++++- .../void/test/unit/cloudflare-deploy.test.ts | 92 +++++++++++++++++- packages/void/test/unit/info.test.ts | 22 ++++- .../void/test/unit/plugin-inference.test.ts | 27 ++++++ .../void/test/unit/workflow-runtime.test.ts | 16 +++- .../test/unit/workflow-runtime.typecheck.ts | 95 ++++++++++++++++++- packages/void/test/unit/workflow-scan.test.ts | 18 ++++ 32 files changed, 623 insertions(+), 131 deletions(-) create mode 100644 packages/void/test/integration/workflow-dev.test.ts diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md index 0b44273231..70807e13f2 100644 --- a/docs/guide/workflows.md +++ b/docs/guide/workflows.md @@ -56,7 +56,7 @@ export const POST = defineHandler(async () => { }); ``` -`create()` accepts the same options as Cloudflare's [`Workflow.create()`](https://developers.cloudflare.com/workflows/build/workers-api/#create), such as `id` and `retention`. Use `createBatch()` to start up to 100 instances at once. Both methods require `params` when your definition requires a payload. +`create()` accepts the same options as Cloudflare's [`Workflow.create()`](https://developers.cloudflare.com/workflows/build/workers-api/#create), such as `id` and `retention`. Use `createBatch()` to start up to 100 instances at once. Both methods require `params` when your definition requires a payload. If you omit optional params, Cloudflare delivers an empty object as `event.payload`. A schema can supply a different default. Check on an instance with `get()`: @@ -99,7 +99,7 @@ Invalid params throw a `WorkflowParamsError`. Its `issues` list each message and ## Native Workflow classes -Use `defineWorkflowEntrypoint()` to keep a class that extends Cloudflare's `WorkflowEntrypoint`. Void binds and exports the class without changing it, and reads the params type from its `run` method: +Use `defineWorkflowEntrypoint()` to keep a class that extends Cloudflare's `WorkflowEntrypoint`. Void reads the params type from the class’s `run` method: ```ts // workflows/report.ts @@ -127,9 +127,9 @@ Void derives the names from the file's path in `workflows/`, joining directories - the exported `SendWelcomeWorkflow` class - a Cloudflare Workflow named `-send-welcome`, since Workflow names must be unique within your Cloudflare account -`workflows/order/notifications.ts` creates `WORKFLOW_ORDER_NOTIFICATIONS`, `OrderNotificationsWorkflow`, and `-order-notifications`. Each Workflow must have a unique name. +`workflows/order/notifications.ts` creates `WORKFLOW_ORDER_NOTIFICATIONS`, `OrderNotificationsWorkflow`, and `-order-notifications`. A path that starts with a digit, such as `2026-report.ts`, exports the class `Workflow2026Report` and uses the binding `WORKFLOW_2026_REPORT`. Each Workflow must have a unique name. -Instances belong to the Workflow name. Renaming the file or the Worker starts a new, empty Workflow, and instances of the old one stop running. To move a file without changing its name, run `void info` first and add the name it suggests: +Instances belong to the Workflow name. Changing the generated Workflow name directs new instances to a different Workflow. To move a file without changing its name, run `void info` first and add the name it suggests: ```ts export const Onboarding = defineWorkflow({ @@ -140,7 +140,7 @@ export const Onboarding = defineWorkflow({ }); ``` -`name` must be a static string containing words that start with a letter. To choose the Cloudflare Workflow name yourself, add an entry for the generated binding and class in `void.config.ts`: +`name` must be a static string containing at least one ASCII letter or digit. To choose the Cloudflare Workflow name yourself, add an entry for the generated binding and class in `void.config.ts`: ```ts // void.config.ts @@ -161,4 +161,6 @@ If the generated Cloudflare Workflow name exceeds 64 characters, use this entry Workflows are available on the Workers Free plan, within [Cloudflare's Workflows limits](https://developers.cloudflare.com/workflows/reference/limits/). Deploy to your own Cloudflare account with `void deploy --platform cloudflare`. +If Cloudflare rejects staging because you added, renamed, or removed a Workflow, run `void deploy --platform cloudflare --atomic` for that deployment. The new version receives traffic before Void checks readiness. + Void platforms do not support Workflows yet: `void deploy` to a Void platform stops with an error while `workflows/` contains modules. Workflows are also unavailable in meta-framework apps and on Node.js, Bun, and Deno. diff --git a/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 9d23adde63..b3963ab103 100644 --- a/docs/integrations/cloudflare.md +++ b/docs/integrations/cloudflare.md @@ -264,7 +264,7 @@ If readiness or trigger updates fail, Void restores the previous deployment. If Finish or cancel gradual rollouts in Cloudflare before deploying through Void. -For an existing Durable Object Worker that Cloudflare cannot stage, review the changes and use: +If Cloudflare cannot stage a change to a Durable Object or Workflow class on an existing Worker, review the changes and run the following command. ```sh void deploy --platform cloudflare --atomic diff --git a/docs/reference/api/workflows.md b/docs/reference/api/workflows.md index 174765ecce..a71f2fc684 100644 --- a/docs/reference/api/workflows.md +++ b/docs/reference/api/workflows.md @@ -11,42 +11,25 @@ Imported from `"void/workflows"`. See [Workflows](../../guide/workflows.md) for Defines a Cloudflare Workflow from a run function. The returned object must be the default export of a module under `workflows/`; named-export the same object to start instances elsewhere in the app. -```ts -function defineWorkflow(definition: { - name?: string; - params?: StandardSchemaV1; - run( - event: Readonly>, - step: WorkflowStep, - context: { env: TEnv; ctx: ExecutionContext }, - ): Promise; -}): WorkflowApi, TParams>; -``` - -With `params`, `run` receives the schema's output type and `create()` accepts its input type. Without it, the params type comes from the `event` annotation. - -When the params type requires a payload, pass `params` to `create()` and to every entry in `createBatch()`. +The definition accepts an optional `name`, an optional Standard Schema for `params`, and an async `run(event, step, { env, ctx })` function. -## `defineWorkflowEntrypoint(definition)` {#defineworkflowentrypoint-definition} +With a schema, `create()` and `createBatch()` accept its input and send its parsed output to Cloudflare. Instances started directly through Cloudflare must supply the payload that `run` expects. Without a schema, the params type comes from the `event` annotation or the type parameter to `defineWorkflow()`. + +Pass `params` to `create()` and to every entry in `createBatch()` when the definition requires a payload. Cloudflare delivers an empty object as `event.payload` if params are omitted or the schema returns `undefined`. When your handler accepts optional params, check the fields it needs. -Registers a class that extends Cloudflare's `WorkflowEntrypoint` without changing it. The params type is read from the class's `run(event)` annotation. +## `defineWorkflowEntrypoint(definition)` {#defineworkflowentrypoint-definition} -```ts -function defineWorkflowEntrypoint(definition: { - name?: string; - class: TClass; -}): WorkflowApi; -``` +Registers a class that extends Cloudflare's `WorkflowEntrypoint`. The params type comes from the class's `run(event)` annotation. You can omit params when the declared payload accepts an empty object. ## `WorkflowApi` {#workflowapi} -| Member | Description | -| ------------------------------ | ----------------------------------------------------------------------------------------------------- | -| `class` | The Workflow class Void exports from the Worker. | -| `create(options?)` | Starts an instance. Options match Cloudflare's `create()`; `params` are typed and validated. | -| `createBatch(instances)` | Starts up to 100 instances and returns Cloudflare's `{ created, errors }` result. | -| `get(id)` | Returns a `WorkflowInstance` for `status()`, `pause()`, `resume()`, `terminate()`, and `sendEvent()`. | -| `create(binding, options?)`, … | Each method also accepts an explicit `Workflow` binding as its first argument. | +| Member | Description | +| ------------------------------ | -------------------------------------------------------------------------------------------------------- | +| `class` | The Workflow entrypoint class for this definition. | +| `create(options?)` | Starts an instance. Options match Cloudflare's `create()`; `params` are typed and validated. | +| `createBatch(instances)` | Starts up to 100 instances and returns Cloudflare's `{ created, errors }` result. | +| `get(id)` | Returns a `WorkflowInstance` for `status()`, `pause()`, `resume()`, `terminate()`, and `sendEvent()`. | +| `create(binding, options?)`, … | Each method accepts an explicit `Workflow` binding for the handler’s payload type as its first argument. | `name` optionally fixes the resource identity instead of deriving it from the filename. Run `void info` and pin the displayed name before moving a deployed definition. diff --git a/docs/reference/cli/deploy.md b/docs/reference/cli/deploy.md index 031eb779e2..651273f9cf 100644 --- a/docs/reference/cli/deploy.md +++ b/docs/reference/cli/deploy.md @@ -39,12 +39,12 @@ For Drizzle projects, deploy performs a read-only schema drift check. If a new m | `--skip-migrations` | Deploy without applying application or authentication SQL migrations; supported on Cloudflare and Void platforms | | `--require-email` | Fail when email cannot be set up instead of deploying without it; requires `--platform cloudflare` | | `--provision` | Run resource provisioning again even when every resource exists; requires `--platform cloudflare` | -| `--atomic` | Publish an existing Durable Object Worker directly; readiness is checked after traffic changes | +| `--atomic` | Publish an existing Worker with Durable Objects or Workflows before checking readiness | | `--preview ` | Deploy a static site or SPA to a Cloudflare Preview; production is unchanged ([more](#void-deploy-preview)) | | `--json` | With `--preview`, print one JSON object on stdout; everything else goes to stderr | | `--debug` | Mirror the structured deploy log to stderr (also written to `~/.void/logs/`) | -`--atomic` applies to one deployment. For an existing Durable Object Worker that consistently cannot stage, set `deploy: { cloudflare: { mode: 'atomic' } }` in `void.config.ts` so plain `void deploy` uses atomic publication. The default is `staged`. +`--atomic` applies to one deployment. For a Worker with Durable Objects or Workflows that consistently cannot stage, set `deploy: { cloudflare: { mode: 'atomic' } }` in `void.config.ts` so plain `void deploy` uses atomic publication. The default is `staged`. Use `--skip-migrations` when you run migrations separately or share a database with a preview. The code must work with the database's current schema. The next deploy without this flag applies pending migrations. diff --git a/docs/reference/cli/setup.md b/docs/reference/cli/setup.md index 4198d53e55..f3257e7dd4 100644 --- a/docs/reference/cli/setup.md +++ b/docs/reference/cli/setup.md @@ -14,7 +14,7 @@ void info --json Shows each Durable State, WebSocket, and Workflow definition's source file, inferred or explicit name, Worker class, and binding. WebSocket entries also include their route in JSON output. It runs locally without authentication, network requests, or file generation. -Before moving a deployed definition, copy the suggested `name` into `defineDurableState()`, `defineRoom()`, `defineWebSocket()`, or `defineWorkflow()`. Keep that name after moving the file to preserve the resource. See [Durable State](../../guide/durable-state.md#rename-a-file-while-keeping-its-state) [WebSockets](../../guide/websockets.md#move-a-route-while-keeping-its-state), and [Workflows](../../guide/workflows.md#names-and-bindings) for migration flows, including WebSocket parameter renames. +Before moving a deployed definition, copy the suggested `name` into the helper shown by `void info`. Keep that name after moving the file to preserve the resource. See [Durable State](../../guide/durable-state.md#rename-a-file-while-keeping-its-state), [WebSockets](../../guide/websockets.md#move-a-route-while-keeping-its-state), and [Workflows](../../guide/workflows.md#names-and-bindings) for migration flows, including WebSocket parameter renames. Resources recorded in `void.lock.json` without a matching definition appear separately. Adopt a suggested name only after identifying the resource you moved. If Void cannot suggest a name, restore its original source and inspect it before moving it again. diff --git a/docs/reference/config.md b/docs/reference/config.md index 5ca4e19125..6e736bface 100644 --- a/docs/reference/config.md +++ b/docs/reference/config.md @@ -372,7 +372,7 @@ If you need to remove a value that Void previously generated, remove it from the ### `deploy.cloudflare.mode` -Direct Cloudflare deploys use `staged` by default: Void checks the new Worker before sending it production traffic. If Cloudflare cannot stage an existing Durable Object Worker, choose `atomic` after reviewing the pending Worker and database changes: +Direct Cloudflare deploys use `staged` by default: Void checks the new Worker before sending it production traffic. If Cloudflare cannot stage a Worker with Durable Objects or Workflows, choose `atomic` after reviewing the pending Worker and database changes: ```ts // Inside defineConfig({ ... }) diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index df051c98d1..7f7d9da7a9 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -894,7 +894,7 @@ export type CloudflareVersionActivationOptions = { activeVersionId: string, bindings: ReadonlyArray<{ name: string; type: 'secret_text' | 'secret_key' }>, ) => Promise | boolean; - /** Explicitly publish an existing Durable Object Worker in one atomic operation. */ + /** Explicitly publish an existing Worker in one atomic operation. */ atomic?: boolean; /** * Plaintext secrets to attach only to the uploaded candidate version. Supplying every remote diff --git a/packages/void/schema.json b/packages/void/schema.json index 486c2043d0..b6848490e4 100644 --- a/packages/void/schema.json +++ b/packages/void/schema.json @@ -406,7 +406,7 @@ "mode": { "type": "string", "enum": ["staged", "atomic"], - "description": "Staged is the default and verifies readiness before traffic. Atomic publishes a Durable Object Worker directly and verifies readiness afterward." + "description": "Staged is the default and verifies readiness before traffic. Atomic publishes a Worker with Durable Objects or Workflows directly and verifies readiness afterward." } }, "additionalProperties": false diff --git a/packages/void/src/cli/deploy-cloudflare-build.ts b/packages/void/src/cli/deploy-cloudflare-build.ts index 81b509c10e..5ea88902a1 100644 --- a/packages/void/src/cli/deploy-cloudflare-build.ts +++ b/packages/void/src/cli/deploy-cloudflare-build.ts @@ -24,6 +24,7 @@ import { resolveGeneratedDeployConfigPathDefault, } from './deploy-artifact-validation.ts'; import { DEPLOY_BINDING_IDENTITY_FIELDS, bindingIdentityKey } from './deploy-binding-snapshot.ts'; +import { activeWorkflowVersionForRemoval } from './deploy-cloudflare-helpers.ts'; import type { CloudflareDeploySource, CloudflarePreflight } from './deploy-cloudflare-preflight.ts'; import { prepareCloudflareFrameworkArtifact } from './deploy-cloudflare-static.ts'; import { log, getExitCode, resolveFullDeployBuildCommand } from './deploy-helpers.ts'; @@ -60,6 +61,7 @@ export async function buildCloudflareWorker(input: { migrations: ReturnType; d1MigrateToken: string | undefined; generatedConfigPath: string; + previousWorkflowVersionId?: string; prepareBuildOutput: () => ReturnType; }> { const { root, voidConfig, deps, exit, atomic, frameworkPreset, detectedFramework } = input; @@ -175,13 +177,20 @@ export async function buildCloudflareWorker(input: { deps.resolveGeneratedConfigPath ?? ((projectRoot) => readGeneratedDeployConfig(projectRoot).path) )(root); - if (atomic && !Array.isArray(parseRootWranglerConfig(lifecycleConfigPath).migrations)) { - log.error( - 'deploy: atomic deployment is only for Workers with Durable Object migration history.', - ); - return exit(1); - } + let previousWorkflowVersionId: string | undefined; try { + if ( + atomic && + !Array.isArray(parseRootWranglerConfig(lifecycleConfigPath).migrations) && + !input.preflight.expectedWorkflows.some( + (workflow) => workflow.script_name === undefined || workflow.script_name === workerName, + ) + ) { + previousWorkflowVersionId = await activeWorkflowVersionForRemoval( + { runWrangler, configPath, workerName, accountId }, + deps.readExistingWorker, + ); + } deduplicateGeneratedCompatibilityFlags(lifecycleConfigPath, configPath); await (deps.assertDurableObjectLifecycle ?? assertCloudflareDurableObjectLifecycleSupported)({ runWrangler, @@ -370,5 +379,11 @@ export async function buildCloudflareWorker(input: { } await preflight.dispose(); } - return { migrations, d1MigrateToken, generatedConfigPath, prepareBuildOutput }; + return { + migrations, + d1MigrateToken, + generatedConfigPath, + previousWorkflowVersionId, + prepareBuildOutput, + }; } diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 999e641c36..00bc02fba4 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -320,6 +320,26 @@ export function createCfActivationRunner(options: { }); } +/** Pin the active version when its local Workflow qualifies a removal for atomic publication. */ +export async function activeWorkflowVersionForRemoval( + options: Parameters[0], + readWorker: typeof readExistingCloudflareWorker = readExistingCloudflareWorker, +): Promise { + const active = await readWorker(options); + const ownsWorkflow = active.bindings.some( + (binding) => + binding.type === 'workflow' && + typeof binding.class_name === 'string' && + (binding.script_name === undefined || binding.script_name === options.workerName), + ); + if (!ownsWorkflow) { + throw new Error( + 'deploy: atomic deployment requires Durable Object migration history or a local Workflow in the new or active Worker.', + ); + } + return active.versionId; +} + /** * Activation options shared by the Worker and static deploys: candidate tracking, the uploaded * binding check, readiness probing and trigger cleanup. @@ -346,6 +366,7 @@ export function cloudflareCandidateActivationOptions(options: { assertUploaderStillPinned: () => boolean; approvedKv: ReadonlyArray; staticAssetsBinding?: string; + previousWorkflowVersionId?: string; queueConsumerCleanup: ReturnType; }): Omit< CloudflareActivationOptions, @@ -364,7 +385,7 @@ export function cloudflareCandidateActivationOptions(options: { accountId, configPath, preserveTriggers: existingWorker !== null, - expectedPreviousVersionId: existingWorker?.versionId, + expectedPreviousVersionId: existingWorker?.versionId ?? options.previousWorkflowVersionId, trustedInheritanceVersionIds: existingWorker ? candidateReceipt?.parentVersionId === existingWorker.versionId ? candidateReceipt.versionIds @@ -832,7 +853,7 @@ function customRouteAccessHint(origin: string): Array { } const ATOMIC_ACCESS_ALTERNATIVE = - 'For a Worker with Durable Object migration history, `void deploy --platform cloudflare --atomic` publishes without the zero-traffic check. The new version receives traffic first, and the command still exits with an error because Void cannot verify readiness through Access.'; + 'For a Worker with Durable Object migration history or a local Workflow, `void deploy --platform cloudflare --atomic` publishes without the zero-traffic check. The new version receives traffic first, and the command still exits with an error because Void cannot verify readiness through Access.'; function formatCloudflareReadinessRestoration( result: Exclude, diff --git a/packages/void/src/cli/deploy-cloudflare-publish.ts b/packages/void/src/cli/deploy-cloudflare-publish.ts index 32de202db0..1e4ed026c8 100644 --- a/packages/void/src/cli/deploy-cloudflare-publish.ts +++ b/packages/void/src/cli/deploy-cloudflare-publish.ts @@ -124,6 +124,7 @@ export async function publishCloudflareWorker(input: { initialCloudflareCandidate, assertUploaderStillPinned, approvedKv: approvedHandoffKv, + previousWorkflowVersionId: input.build.previousWorkflowVersionId, queueConsumerCleanup, }), runWrangler: activationRunner, diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index 0ffbeeae99..cf908615ce 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -27,6 +27,8 @@ import { hasEmailHandlers } from '../router/email.ts'; import { selectNativeVersionMetadataBinding } from '../shared/version-metadata.ts'; import { validateSsrEntry } from '../ssr/entry.ts'; import { prepareCfStaticBuildOutput } from './cf-build-output.ts'; +import { createActiveSecretPinner } from './cf-version-runner.ts'; +import { clearCloudflareCandidate } from './cloudflare-candidate.ts'; import type { CloudflareCandidateReceipt } from './cloudflare-candidate.ts'; import type { CloudflareChildReporter } from './cloudflare-child-report.ts'; import { readCloudflareLink } from './cloudflare-link.ts'; @@ -38,6 +40,7 @@ import { prepareExistingCloudflareDeployWithAuth } from './deploy-cloudflare-aut import { discoverRootWranglerConfig, activateCloudflareVersionWithProgress, + activeWorkflowVersionForRemoval, assertCloudflareDeployTargetUnchanged, cloudflareCandidateActivationOptions, confirmCloudflareDeployAuthentication, @@ -394,6 +397,18 @@ export async function runCloudflareStaticDeploy( } const rootConfig = parseRootWranglerConfig(configPath); const workerName = readWranglerTopLevelString(rootConfig, 'name') ?? deriveWorkerName(root); + let previousWorkflowVersionId: string | undefined; + if (options.atomic) { + try { + previousWorkflowVersionId = await activeWorkflowVersionForRemoval( + { runWrangler, configPath, workerName, accountId }, + deps.readExistingWorker, + ); + } catch (error) { + log.error(getErrorMessage(error)); + return exit(1); + } + } printDeployContext( workerName, options.preview === undefined ? 'Cloudflare' : `Cloudflare Preview ${options.preview}`, @@ -583,6 +598,7 @@ export async function runCloudflareStaticDeploy( assertUploaderStillPinned, approvedKv: [], staticAssetsBinding: 'ASSETS', + previousWorkflowVersionId, queueConsumerCleanup, }), runWrangler: activationRunner, @@ -594,9 +610,25 @@ export async function runCloudflareStaticDeploy( ...(existingWorker ? { preserve: true } : {}), }), assetsDirectoryOverride: stagedAssetsDirectory, + ...(options.atomic + ? { + atomic: true, + pinActiveSecrets: createActiveSecretPinner({ + output: cfOutput, + handoffPending: false, + requiredNames: [], + }), + } + : {}), }, ).finally(() => cfOutput?.dispose()); if (!execution.ok) { + if ( + execution.reason === 'atomic-readiness-failed' || + execution.reason === 'atomic-readiness-access-denied' + ) { + clearCloudflareCandidate(root); + } await reportCloudflareActivationFailure( reporter, formatCloudflareActivationError(execution), diff --git a/packages/void/src/cli/deploy-cloudflare.ts b/packages/void/src/cli/deploy-cloudflare.ts index 26b2ec8df8..6767d0f85b 100644 --- a/packages/void/src/cli/deploy-cloudflare.ts +++ b/packages/void/src/cli/deploy-cloudflare.ts @@ -110,13 +110,13 @@ export async function runCloudflareDeploy( resolveCloudflareStaticPreset(root, voidConfig, options) ?? (await resolveCloudflareVoidStaticPreset(root, voidConfig)); if (staticPreset) { - if (atomic) { - log.error('deploy: atomic deployment is only for Workers with Durable Objects.'); + if (atomic && options.preview !== undefined) { + log.error('deploy: --atomic is unavailable for static previews.'); return exit(1); } return runCloudflareStaticDeploy( root, - options, + { ...options, atomic }, voidConfig, staticPreset, cliLog, diff --git a/packages/void/src/cli/deploy-types.ts b/packages/void/src/cli/deploy-types.ts index fec9064c7f..9c2971f89e 100644 --- a/packages/void/src/cli/deploy-types.ts +++ b/packages/void/src/cli/deploy-types.ts @@ -50,7 +50,7 @@ export type RunDeployOptions = { * (CI / non-TTY, a blocker, a declined prompt). `--platform cloudflare` only. */ requireEmail?: boolean; - /** Publish an existing Durable Object Worker atomically after explicit operator choice. */ + /** Publish an existing Worker with Durable Objects or Workflows atomically after explicit operator choice. */ atomic?: boolean; /** * Create or update this named Cloudflare Preview instead of deploying production. diff --git a/packages/void/src/cli/help.ts b/packages/void/src/cli/help.ts index 78783a256c..69371d7d47 100644 --- a/packages/void/src/cli/help.ts +++ b/packages/void/src/cli/help.ts @@ -192,7 +192,7 @@ const HELP_TREE = { { command: '--atomic', description: - 'Publish a Durable Object Worker without pre-traffic staging (Cloudflare only)', + 'Publish a Worker with Durable Objects or Workflows before checking readiness (Cloudflare only)', }, { command: '--preview ', diff --git a/packages/void/src/cli/info.ts b/packages/void/src/cli/info.ts index e768986a13..6ea1d59559 100644 --- a/packages/void/src/cli/info.ts +++ b/packages/void/src/cli/info.ts @@ -10,11 +10,16 @@ import { inferWebSocketResourceName, } from '../router/websocket.ts'; import { inferWorkflowResourceName } from '../workflows/scan.ts'; +import type { WorkflowModule } from '../workflows/scan.ts'; import type { InfoArgs } from './info-args.ts'; export type PersistentResourceInfo = { file: string; - definition: 'defineDurableState' | 'defineRoom' | 'defineWebSocket' | 'defineWorkflow'; + definition: + | 'defineDurableState' + | 'defineRoom' + | 'defineWebSocket' + | WorkflowModule['definition']; name: string; nameSource: 'inferred' | 'explicit'; className: string; @@ -138,7 +143,7 @@ export function getProjectInfo(root: string): ProjectInfo { })), ...analysis.workflows.map((module) => ({ file: relative(root, module.filePath), - definition: 'defineWorkflow' as const, + definition: module.definition, name: module.name ?? inferWorkflowResourceName(module.relativePath), nameSource: module.name === undefined ? ('inferred' as const) : ('explicit' as const), className: module.className, diff --git a/packages/void/src/plugin-inference.ts b/packages/void/src/plugin-inference.ts index c9922cac66..a246d19198 100644 --- a/packages/void/src/plugin-inference.ts +++ b/packages/void/src/plugin-inference.ts @@ -1,5 +1,5 @@ import { existsSync, readFileSync } from 'node:fs'; -import { join, toSlash } from 'pathslash'; +import { join, relative, toSlash } from 'pathslash'; import { globSync } from 'tinyglobby'; import { applyBindingOverrides } from './application-features.ts'; import { inferBindingsFromSource, mergeBindings } from './inference/walk.ts'; @@ -164,11 +164,21 @@ export function inferProjectBindings( const routesPrefix = `${toSlash(paths.routesDir).replace(/\/$/, '')}/`; const pagesDir = toSlash(paths.pagesDir); const pagesPrefix = pagesDir.endsWith('/') ? pagesDir : `${pagesDir}/`; - const scanSourceFiles = (dirPath: string): Array => - globSync(conventionFileGlobs(dirPath, SOURCE_GLOB, paths.routesDir), { - cwd: dirPath, - absolute: true, - }); + const workflowsDir = join(root, 'workflows'); + const scanSourceFiles = (dirPath: string): Array => { + const patterns = conventionFileGlobs(dirPath, SOURCE_GLOB, paths.routesDir); + if (hasWorkflows) { + // Workflow modules also accept .cts and .cjs. Match step helpers with those + // extensions even when a custom scan directory starts above or inside workflows/. + const prefix = relative(dirPath, workflowsDir); + if (dirPath.startsWith(`${workflowsDir}/`)) { + patterns.push('**/*.{cts,cjs}'); + } else if (prefix !== '..' && !prefix.startsWith('../')) { + patterns.push(join(prefix, '**/*.{cts,cjs}')); + } + } + return globSync(patterns, { cwd: dirPath, absolute: true }); + }; const addFile = (file: string): void => { const normalizedFile = toSlash(file); if (scannedFiles.has(normalizedFile)) { diff --git a/packages/void/src/plugin-routing.ts b/packages/void/src/plugin-routing.ts index a8d406fc14..32bd6a4468 100644 --- a/packages/void/src/plugin-routing.ts +++ b/packages/void/src/plugin-routing.ts @@ -58,6 +58,7 @@ import { SSR_SERVER_ENTRY_RELATIVE_PATHS, SSR_CLIENT_ENTRY_RELATIVE_PATHS, } from './ssr/entry.ts'; +import { scanWorkflowModules } from './workflows/scan.ts'; const VIRTUAL_ROUTES_ID = 'virtual:void-routes'; const VIRTUAL_CLIENT_WORKER_ID = 'virtual:void-client-worker'; @@ -192,6 +193,7 @@ export function routingPlugin( const normalizedMiddlewareDir = normalizePath(middlewareDir); const normalizedJobsDir = normalizePath(jobsDir); const normalizedQueuesDir = normalizePath(queuesDir); + const normalizedWorkflowsDir = normalizePath(join(root, 'workflows')); const normalizedEmailDir = normalizePath(emailDir); const normalizedPagesDir = normalizePath(pagesDir); const ssrEntryAbsPaths = new Set( @@ -1000,7 +1002,10 @@ export function routingPlugin( const authImportCreated = event === 'add' && authConfigStale && compileOptions.auth !== null; + const workflowChanged = + options.workflows && isInDirectory(normalizedPath, normalizedWorkflowsDir); const sourceConventionChanged = + workflowChanged || isInDirectory(normalizedPath, normalizedRoutesDir) || isInDirectory(normalizedPath, normalizedMiddlewareDir) || isInDirectory(normalizedPath, normalizedJobsDir) || @@ -1016,6 +1021,11 @@ export function routingPlugin( const shouldRestart = await regenerateInOrder(async () => { invalidateSourceAnalysis(normalizedPath); + if (workflowChanged) { + // Cloudflare loads bindings and exported classes at startup. Ordinary step edits + // keep the same configuration and can use Vite's module updates. + return !isDeepStrictEqual(options.workflows, scanWorkflowModules(root)); + } // Re-scan and invalidate the virtual module in ALL environments. // The route table virtual module lives in the workerd environment, // not the client — so we must iterate all environments. diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index d6f79fb26c..6f1ca1f49d 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -1226,7 +1226,13 @@ type ResourceModuleEntry = { */ function compileResourceModules( entries: ReadonlyArray, - options: { variable: string; directory: string; prefix: string; helpers: string }, + options: { + variable: string; + directory: string; + prefix: string; + helpers: string; + validateWorkflowEnv?: boolean; + }, ): ResourceModuleCode { const imports = entries .map( @@ -1243,7 +1249,14 @@ function compileResourceModules( `const ${local} = ${options.variable}Module${index}.default;`, `if (typeof ${local}?.__bind !== "function") { throw new Error(${JSON.stringify(message)}); }`, `${local}.__bind(${JSON.stringify(bindingName)}${name !== undefined ? `, ${JSON.stringify(name)}` : ''});`, - `export const ${className} = ${local}.class;`, + options.validateWorkflowEnv + ? `export class ${className} extends ${local}.class { + async run(event, step) { + await _validateEnvOnce(this.env); + return withRuntimeEnv(this.env, () => super.run(event, step)); + } +}` + : `export const ${className} = ${local}.class;`, ].join('\n'); }) .join('\n'); @@ -1337,6 +1350,7 @@ export function compileWorkerEntry(options: WorkerEntryOptions = {}): string { directory: 'workflows', prefix: 'workflows', helpers: 'defineWorkflow() or defineWorkflowEntrypoint()', + validateWorkflowEnv: Boolean(envSchemaModule), }); const resourceModuleImports = [durableObjectModules.imports, workflowModules.imports] .filter(Boolean) diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts index 0bb3896487..0e1d1f3452 100644 --- a/packages/void/src/runtime/workflows/index.ts +++ b/packages/void/src/runtime/workflows/index.ts @@ -1,22 +1,19 @@ import { WorkflowEntrypoint } from 'cloudflare:workers'; import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; -import { isResourceName } from '../../shared/resource-name.ts'; +import { isWorkflowName } from '../../shared/resource-name.ts'; import type { StandardSchemaV1 } from '../../standard-schema.ts'; import { requireRuntimeBinding, withRuntimeEnv } from '../env/runtime.ts'; export type { WorkflowEvent, WorkflowStep }; -type NativeWorkflowClass = new (...args: Array) => { - run(event: never, step: never): Promise; -}; +type NativeWorkflowClass = new (...args: Array) => WorkflowEntrypoint; /** Params type of a native class, read from its `run(event)` annotation. */ -export type NativeWorkflowParams = - InstanceType extends { - run(event: Readonly>, ...rest: Array): unknown; - } - ? TParams - : unknown; +export type NativeWorkflowParams = Parameters< + InstanceType['run'] +>[0] extends { payload: infer TParams } + ? TParams + : unknown; /** Context passed to a `defineWorkflow()` run function next to the event and step. */ export type WorkflowContext = { @@ -32,24 +29,32 @@ type WorkflowCreateArguments = undefined extends TParams ? [options?: WorkflowCreateOptions] : [options: WorkflowCreateOptions]; -export type WorkflowApi = { +// Cloudflare delivers an empty object when create() omits params or a schema returns undefined. +type WorkflowPayload = + | Exclude + | (undefined extends TParams ? Record : never); + +export type WorkflowApi = { class: TClass; /** @internal Called by Void's generated Worker entry. */ __bind(bindingName: string, resourceName?: string): void; /** Start a new instance. Params are validated when the definition has a `params` schema. */ create(...args: WorkflowCreateArguments): Promise; - create(binding: Workflow, ...args: WorkflowCreateArguments): Promise; + create( + binding: Workflow, + ...args: WorkflowCreateArguments + ): Promise; /** Start up to 100 instances. Each instance's params are validated first. */ createBatch( instances: ReadonlyArray>, ): Promise; createBatch( - binding: Workflow, + binding: Workflow, instances: ReadonlyArray>, ): Promise; /** Get a handle to an existing instance. */ get(id: string): Promise; - get(binding: Workflow, id: string): Promise; + get(binding: Workflow, id: string): Promise; }; export type WorkflowRun = ( @@ -58,10 +63,10 @@ export type WorkflowRun = ( context: WorkflowContext, ) => Promise; -export type WorkflowClass = new ( +export type WorkflowClass> = new ( ctx: ExecutionContext, - env: Record, -) => WorkflowEntrypoint, TParams>; + env: TEnv, +) => WorkflowEntrypoint; /** Error thrown by `create()` and `createBatch()` when params fail the definition's schema. */ export class WorkflowParamsError extends Error { @@ -97,13 +102,13 @@ function isWorkflowBinding(value: Workflow | TOther): value is Workflow ); } -function createWorkflowApi( +function createWorkflowApi( definitionName: string | undefined, workflowClass: TClass, schema: StandardSchemaV1 | undefined, -): WorkflowApi { - if (definitionName !== undefined && !isResourceName(definitionName)) { - throw new Error('workflows: name must contain a word starting with a letter.'); +): WorkflowApi { + if (definitionName !== undefined && !isWorkflowName(definitionName)) { + throw new Error('workflows: name must contain a letter or digit.'); } let bindingName: string | undefined; @@ -186,28 +191,23 @@ type WorkflowDefinitionBase = { * Define a Workflow from a run function. Void generates the Cloudflare * `WorkflowEntrypoint` class. Default-export the result from a file in `workflows/`. */ -export function defineWorkflow< - TSchema extends StandardSchemaV1, - TEnv extends Record = Record, ->( +export function defineWorkflow>( definition: WorkflowDefinitionBase & { /** Standard Schema that validates params in `create()` and `createBatch()`. */ params: TSchema; - run: WorkflowRun, TEnv>; + run: WorkflowRun>, TEnv>; }, ): WorkflowApi< - WorkflowClass>, - StandardSchemaV1.InferInput + WorkflowClass>, TEnv>, + StandardSchemaV1.InferInput, + WorkflowPayload> >; -export function defineWorkflow< - TParams = unknown, - TEnv extends Record = Record, ->( +export function defineWorkflow>( definition: WorkflowDefinitionBase & { params?: undefined; - run: WorkflowRun; + run: WorkflowRun, TEnv>; }, -): WorkflowApi, TParams>; +): WorkflowApi, TEnv>, TParams, WorkflowPayload>; export function defineWorkflow( definition: WorkflowDefinitionBase & { params?: StandardSchemaV1; @@ -230,20 +230,25 @@ export function defineWorkflow( return createWorkflowApi(definition.name, VoidWorkflow, definition.params); } +// A native class receives Cloudflare's event as declared in its own run method. +type NativeWorkflowInput = + Record extends TParams ? TParams | undefined : Exclude; + /** * Register a native Cloudflare `WorkflowEntrypoint` class without changing it. * Default-export the result from a file in `workflows/`. */ -export function defineWorkflowEntrypoint< - TClass extends NativeWorkflowClass, - TParams = NativeWorkflowParams, ->( - definition: WorkflowDefinitionBase & { - class: TClass; - }, -): WorkflowApi { - if (typeof definition.class !== 'function') { - throw new Error('workflows: defineWorkflowEntrypoint() requires a class.'); +export function defineWorkflowEntrypoint( + definition: WorkflowDefinitionBase & { class: TClass }, +): WorkflowApi< + TClass, + NativeWorkflowInput>, + NativeWorkflowParams +> { + if (!(definition.class?.prototype instanceof WorkflowEntrypoint)) { + throw new Error( + 'workflows: defineWorkflowEntrypoint() requires a class extending WorkflowEntrypoint.', + ); } return createWorkflowApi(definition.name, definition.class, undefined); } diff --git a/packages/void/src/shared/resource-definition.ts b/packages/void/src/shared/resource-definition.ts index b43dbc5bda..bcfeb1d6d2 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -5,8 +5,10 @@ import { isIdentifier, isMemberExpression, isObjectExpression, + moduleExportName, } from './ast.ts'; import type { + AstExportNamedDeclaration, AstImportDeclaration, AstImportNamespaceSpecifier, AstImportSpecifier, @@ -14,7 +16,7 @@ import type { AstProgram, AstVariableDeclaration, } from './ast.ts'; -import { isResourceName } from './resource-name.ts'; +import { isResourceName, isWorkflowName } from './resource-name.ts'; import { staticLiteral, unwrapStaticExpression } from './static-exports.ts'; /** Inspect default helper definitions without running application code. */ @@ -22,7 +24,7 @@ export function readResourceDefinition( filename: string, source: string, helpers: ReadonlySet, - options?: { requireImportedHelper?: boolean }, + convention?: 'workflows', ): { helper: string; options?: AstNode; name?: string } | null { let program: AstProgram; try { @@ -36,6 +38,7 @@ export function readResourceDefinition( const importedHelpers = new Map(); const namespaces = new Map>(); const bindings = new Set(); + let defaultExport: AstNode | undefined; function recordBindings(node: AstNode | undefined): void { if (isIdentifier(node)) { bindings.add(node.name); @@ -56,6 +59,22 @@ export function readResourceDefinition( } } for (const statement of program.body ?? []) { + if (statement.type === 'ExportDefaultDeclaration') { + defaultExport = statement.declaration as AstNode; + } else if ( + convention === 'workflows' && + statement.type === 'ExportNamedDeclaration' && + !statement.source && + statement.exportKind !== 'type' + ) { + const named = statement as AstExportNamedDeclaration; + const specifier = named.specifiers?.find( + (item) => item.exportKind !== 'type' && moduleExportName(item.exported) === 'default', + ); + if (specifier) { + defaultExport = specifier.local; + } + } if (statement.type === 'ImportDeclaration') { const declaration = statement as AstImportDeclaration; const source = declaration.source.value; @@ -156,9 +175,12 @@ export function readResourceDefinition( continue; } const value = staticLiteral(resolve(valueNode)); - if (!isResourceName(value)) { + const validName = convention === 'workflows' ? isWorkflowName : isResourceName; + if (!validName(value)) { + const requirement = + convention === 'workflows' ? 'a letter or digit' : 'a word starting with a letter'; throw new Error( - `${filename}: resource name must be a static string containing a word starting with a letter.`, + `${filename}: resource name must be a static string containing ${requirement}.`, ); } name = { present: true, value }; @@ -167,8 +189,7 @@ export function readResourceDefinition( return name; } - const statement = program.body?.find((node) => node.type === 'ExportDefaultDeclaration'); - const declaration = unwrapStaticExpression(statement?.declaration as AstNode | undefined); + const declaration = unwrapStaticExpression(defaultExport); const call = resolve(isIdentifier(declaration) ? definitions.get(declaration.name) : declaration); if (!isCallExpression(call)) { return null; @@ -178,7 +199,7 @@ export function readResourceDefinition( if (isIdentifier(callee)) { helper = importedHelpers.get(callee.name) ?? - (!options?.requireImportedHelper && helpers.has(callee.name) ? callee.name : undefined); + (convention !== 'workflows' && helpers.has(callee.name) ? callee.name : undefined); } else if (isMemberExpression(callee) && isIdentifier(callee.object)) { const property = !callee.computed && isIdentifier(callee.property) diff --git a/packages/void/src/shared/resource-name.ts b/packages/void/src/shared/resource-name.ts index 3552ed6601..d5224a749c 100644 --- a/packages/void/src/shared/resource-name.ts +++ b/packages/void/src/shared/resource-name.ts @@ -2,6 +2,11 @@ export function resourceNameWords(value: string): Array { return value.split(/[^a-zA-Z0-9]+/).filter(Boolean); } +/** Workflow resource names can start with a digit because the generated class adds a prefix. */ +export function isWorkflowName(value: unknown): value is string { + return typeof value === 'string' && /[a-zA-Z0-9]/.test(value); +} + export function isResourceName(value: unknown): value is string { if (typeof value !== 'string') { return false; diff --git a/packages/void/src/workflows/config.ts b/packages/void/src/workflows/config.ts index 610a6ded1e..f21379c15b 100644 --- a/packages/void/src/workflows/config.ts +++ b/packages/void/src/workflows/config.ts @@ -35,7 +35,10 @@ export function planWorkflowAdditions( for (const module of modules) { const configured = existing.find((entry) => entry.binding === module.bindingName); if (configured) { - if (configured.class_name !== module.className || configured.script_name !== undefined) { + if ( + configured.class_name !== module.className || + (configured.script_name !== undefined && configured.script_name !== workerName) + ) { throw new Error( `workflows: binding '${module.bindingName}' is already configured for another Workflow, but workflows/ requires class '${module.className}'.`, ); diff --git a/packages/void/src/workflows/scan.ts b/packages/void/src/workflows/scan.ts index 74cb392448..9742040d58 100644 --- a/packages/void/src/workflows/scan.ts +++ b/packages/void/src/workflows/scan.ts @@ -9,6 +9,7 @@ export type WorkflowModule = { filePath: string; /** Path relative to `workflows/`, with `/` separators. */ relativePath: string; + definition: 'defineWorkflow' | 'defineWorkflowEntrypoint'; bindingName: string; className: string; /** Kebab-case resource name. Cloudflare Workflow names are derived from it. */ @@ -51,7 +52,7 @@ export function deriveWorkflowResourceIdentity( const classBase = parts.map((part) => part[0].toUpperCase() + part.slice(1)).join(''); return { bindingName: `WORKFLOW_${parts.join('_').toUpperCase()}`, - className: `${classBase}Workflow`, + className: /^\d/.test(classBase) ? `Workflow${classBase}` : `${classBase}Workflow`, resourceName: parts.join('-').toLowerCase(), }; } @@ -78,10 +79,10 @@ export function scanWorkflowModules(root: string): Array { return []; } - const modules = listWorkflowFiles(directory).flatMap((relativePath) => { + const modules = listWorkflowFiles(directory).flatMap((relativePath) => { const filePath = join(directory, relativePath); const definition = deriveFromSource(filePath, 'workflow-definition', (source) => - readResourceDefinition(filePath, source, WORKFLOW_HELPERS, { requireImportedHelper: true }), + readResourceDefinition(filePath, source, WORKFLOW_HELPERS, 'workflows'), ); if (!definition) { return []; @@ -95,6 +96,10 @@ export function scanWorkflowModules(root: string): Array { { filePath, relativePath, + definition: + definition.helper === 'defineWorkflowEntrypoint' + ? 'defineWorkflowEntrypoint' + : 'defineWorkflow', ...deriveWorkflowResourceIdentity(resourceName), ...(name === undefined ? {} : { name }), }, diff --git a/packages/void/test/integration/workflow-dev.test.ts b/packages/void/test/integration/workflow-dev.test.ts new file mode 100644 index 0000000000..aa0e020e97 --- /dev/null +++ b/packages/void/test/integration/workflow-dev.test.ts @@ -0,0 +1,45 @@ +import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { it, onTestFinished } from 'vite-plus/test'; +import { + createIsolatedPlayground, + killChild, + spawnFixtureServer, + startServer, + waitForServer, +} from '../../../../test/integration-helpers.ts'; + +it('refreshes the Worker when a Workflow is added, renamed, or deleted during dev', async () => { + const fixture = createIsolatedPlayground( + join(import.meta.dirname, '../../../..'), + 'playground/ssr', + ); + onTestFinished(() => fixture.cleanup()); + const route = '/api/workflow-bindings'; + writeFileSync( + join(fixture.root, 'routes', route + '.ts'), + `import { defineHandler } from 'void'; +export const GET = defineHandler(c => Response.json(Object.keys(c.env).filter(key => key.startsWith('WORKFLOW_'))));`, + ); + const server = await startServer((port) => spawnFixtureServer(fixture.root, 'dev', port), 20_000); + onTestFinished(() => killChild(server.child)); + const waitForBindings = (...bindings: Array) => + waitForServer(server.base + route, 10_000, { + expectStatus: 200, + expectBody: JSON.stringify(bindings), + diagnostics: server.output, + }); + await waitForBindings(); + const directory = join(fixture.root, 'workflows'); + mkdirSync(directory); + const file = join(directory, 'welcome.ts'); + const workflow = (name: string) => + `import { defineWorkflow } from 'void/workflows'; +export default defineWorkflow({ name: ${JSON.stringify(name)}, async run(event, step) { return step.do('greet', async () => 'hello'); } });`; + writeFileSync(file, workflow('welcome')); + await waitForBindings('WORKFLOW_WELCOME'); + writeFileSync(file, workflow('onboarding')); + await waitForBindings('WORKFLOW_ONBOARDING'); + rmSync(file); + await waitForBindings(); +}, 60_000); diff --git a/packages/void/test/integration/workflow-runtime.test.ts b/packages/void/test/integration/workflow-runtime.test.ts index 8680a01319..e512b4eca0 100644 --- a/packages/void/test/integration/workflow-runtime.test.ts +++ b/packages/void/test/integration/workflow-runtime.test.ts @@ -13,6 +13,8 @@ const temporary = mkdtempSync(join(tmpdir(), 'void-workflow-runtime-')); type Runtime = { dispatchFetch(url: string): Promise; dispose(): Promise }; let runtime: Runtime; +afterAll(() => rmSync(temporary, { recursive: true, force: true })); + const ROUTE_STUBS = ` export const scheduled = async () => {}; export const __voidCollectPrerenderPaths = async () => []; @@ -130,7 +132,6 @@ export default { async fetch(request) { afterAll(async () => { await runtime?.dispose(); - rmSync(temporary, { recursive: true, force: true }); }); it('starts an instance from a route and runs its steps with the Worker env', async () => { @@ -161,6 +162,68 @@ export default { async fetch(request) { }); }); +describe('Workflow environment validation on a cold Worker', () => { + it.each(['defineWorkflow', 'defineWorkflowEntrypoint'])( + 'prepares async env validators for %s before its first step', + async (helper) => { + const envPath = join(root, 'packages/void/src/runtime/env/public.ts'); + const schema = file( + 'env-' + helper + '.ts', + ` +import { defineEnv } from ${JSON.stringify(envPath)}; +export default defineEnv({ VALUE: { '~standard': { + version: 1, vendor: 'test', async validate(value) { return { value: Number(value) }; } +} } }); +`, + ); + const definition = file( + 'cold-' + helper + '.ts', + ` +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import { env } from ${JSON.stringify(envPath)}; +import { defineWorkflow, defineWorkflowEntrypoint } from ${JSON.stringify(runtimePath)}; +async function run(event, step) { + const value = env.VALUE; + return step.do('read', async () => value + 1); +} +${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'class Cold extends WorkflowEntrypoint { run(event, step) { return run(event, step); } } export default defineWorkflowEntrypoint({ class: Cold });'} +`, + ); + const output = await buildWorker( + 'cold-' + helper, + 'export default { fetch: () => new Response() };', + { + envSchemaModule: { importPath: schema, helperPath: envPath }, + workflows: [{ bindingName: 'COLD', className: 'ColdWorkflow', filePath: definition }], + }, + ); + const worker = new Miniflare( + convertV4MiniflareOptions({ + compatibilityDate: '2026-07-01', + compatibilityFlags: ['nodejs_compat'], + modules: true, + modulesRoot: output, + scriptPath: join(output, 'worker.mjs'), + bindings: { VALUE: '41' }, + workflows: { COLD: { name: 'cold', className: 'ColdWorkflow' } }, + }), + ); + try { + const { COLD } = await worker.getBindings<{ COLD: Workflow }>(); + const instance = await COLD.create(); + await expect + .poll(async () => (await instance.status()).status, { + timeout: 5000, + }) + .toMatch(/^(complete|errored)$/); + expect(await instance.status()).toMatchObject({ status: 'complete', output: 42 }); + } finally { + await worker.dispose(); + } + }, + ); +}); + describe('convention modules without a definition default export', () => { it.each([ { diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 0ac6c802bc..714a6db5d7 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -756,7 +756,7 @@ describe('Cloudflare activation diagnostics', () => { expect(message).toContain('CF_ACCESS_READINESS_ORIGIN=https://dashboard.example.com'); expect(message).toContain('only if you control this hostname and it serves this Worker'); expect(message).toContain( - 'For a Worker with Durable Object migration history, `void deploy --platform cloudflare --atomic`', + 'For a Worker with Durable Object migration history or a local Workflow, `void deploy --platform cloudflare --atomic`', ); expect(message).toContain('still exits with an error'); expect(message).toContain('traffic was restored to the previous version'); @@ -1732,12 +1732,18 @@ describe('existing Cloudflare site handoff', () => { expect(lookups).toEqual([{ ok: true, subdomain: 'team.fed' }]); }); - it('refuses an atomic deploy when the Worker has no Durable Object migration history', async () => { + it('refuses an atomic deploy for a Worker that only binds an external Workflow', async () => { const root = site(); const activateVersion = vi.fn(); const assertDurableObjectLifecycle = vi.fn(); const { deps } = harness({ runBuild: () => build(root), + readExistingWorker: async () => ({ + ...existing, + bindings: [ + { type: 'workflow', name: 'EXTERNAL', workflow_name: 'shared', script_name: 'other' }, + ], + }), activateVersion, assertDurableObjectLifecycle, }); @@ -1747,9 +1753,7 @@ describe('existing Cloudflare site handoff', () => { runCloudflareDeploy(root, { platform: 'cloudflare', atomic: true }, silentCliLog, deps), ).rejects.toBeInstanceOf(ExitError); expect(output).toHaveBeenCalledWith( - expect.stringContaining( - 'atomic deployment is only for Workers with Durable Object migration history', - ), + expect.stringContaining('Durable Object migration history or a local Workflow'), ); expect(activateVersion).not.toHaveBeenCalled(); expect(assertDurableObjectLifecycle).not.toHaveBeenCalled(); @@ -1758,6 +1762,84 @@ describe('existing Cloudflare site handoff', () => { } }); + it.each(['add', 'remove', 'remove to static'] as const)( + 'supports the %s operation for a local Workflow in an atomic deployment', + async (operation) => { + const root = site(); + const configPath = join(root, 'wrangler.jsonc'); + const config = parseRootWranglerConfig(configPath); + config.preview_urls = false; + if (operation === 'add') { + mkdirSync(join(root, 'workflows')); + writeFileSync( + join(root, 'workflows/notify.ts'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", + ); + } + writeFileSync(configPath, JSON.stringify(config)); + if (operation === 'remove to static') { + mkdirSync(join(root, 'dist')); + writeFileSync(join(root, 'dist/index.html'), '

Site

'); + } + const readExistingWorker = vi.fn().mockResolvedValue({ + ...existing, + bindings: [ + { + type: 'workflow', + name: 'WORKFLOW_NOTIFY', + workflow_name: 'site-notify', + class_name: 'NotifyWorkflow', + }, + ], + }); + const activateVersion = vi + .fn>() + .mockResolvedValue({ + ok: true, + versionId: 'new', + previousVersionId: existing.versionId, + previewUrl: 'https://site.example.com', + }); + const { deps } = harness({ + runBuild: () => { + build(root); + if (operation === 'add') { + const path = join(root, 'dist/ssr/wrangler.json'); + writeFileSync( + path, + JSON.stringify({ + ...parseRootWranglerConfig(path), + workflows: [ + { name: 'site-notify', binding: 'WORKFLOW_NOTIFY', class_name: 'NotifyWorkflow' }, + ], + }), + ); + } + }, + readExistingWorker, + verifyDeployConfig: verifyGeneratedDeployConfig, + activateVersion, + }); + await runCloudflareDeploy( + root, + { + platform: 'cloudflare', + atomic: true, + ...(operation === 'remove to static' ? { dir: 'dist' } : {}), + }, + silentCliLog, + deps, + ); + expect(readExistingWorker).toHaveBeenCalledTimes(operation === 'add' ? 0 : 1); + expect(activateVersion).toHaveBeenCalledWith( + expect.objectContaining({ + atomic: true, + expectedPreviousVersionId: operation === 'add' ? undefined : existing.versionId, + }), + ); + }, + ); + it('allows an explicit atomic deploy after the Durable Object migration preflight', async () => { const root = site(); const configPath = join(root, 'wrangler.jsonc'); diff --git a/packages/void/test/unit/info.test.ts b/packages/void/test/unit/info.test.ts index 108c132434..533fedd6a3 100644 --- a/packages/void/test/unit/info.test.ts +++ b/packages/void/test/unit/info.test.ts @@ -109,7 +109,7 @@ export default defineWorkflowEntrypoint({ name: 'import', class: Importer });`, expect(info.resources).toEqual([ { file: 'workflows/import-v2.ts', - definition: 'defineWorkflow', + definition: 'defineWorkflowEntrypoint', name: 'import', nameSource: 'explicit', className: 'ImportWorkflow', @@ -127,6 +127,26 @@ export default defineWorkflowEntrypoint({ name: 'import', class: Importer });`, expect(formatProjectInfo(info)).toContain("add this to 'defineWorkflow':"); }); + it('preserves an inferred numeric-leading Workflow name when pinned and moved', () => { + const root = project(); + const source = (options: string) => `import { defineWorkflowEntrypoint } from 'void/workflows'; +export default defineWorkflowEntrypoint({ ${options} class: Report });`; + write(root, 'workflows/2026-report.ts', source('')); + const info = getProjectInfo(root); + const [initial] = info.resources; + expect(initial).toMatchObject({ + name: '2026-report', + className: 'Workflow2026Report', + bindingName: 'WORKFLOW_2026_REPORT', + }); + expect(formatProjectInfo(info)).toContain("add this to 'defineWorkflowEntrypoint':"); + rmSync(join(root, 'workflows/2026-report.ts')); + write(root, 'workflows/archive/report.ts', source(`name: ${JSON.stringify(initial.name)},`)); + expect(getProjectInfo(root).resources).toEqual([ + { ...initial, file: 'workflows/archive/report.ts', nameSource: 'explicit' }, + ]); + }); + it('keeps explicit names visible after moving code and respects configured source paths', () => { const root = project(); write(root, 'void.config.ts', "export default { sourceDir: 'src' };"); diff --git a/packages/void/test/unit/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index b6ecceb035..0f387d90c3 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -412,6 +412,33 @@ describe('inferProjectBindings', () => { expect(inferProjectBindings(root).needsD1).toBe(false); }); + it('infers bindings in .cts Workflow definitions and .cjs step helpers', () => { + const root = createTempRoot(); + mkdirSync(join(root, 'workflows')); + writeFileSync( + join(root, 'workflows', 'summary.cts'), + `import { defineWorkflow } from 'void/workflows'; +import { kv } from 'void/kv'; +import { read } from './_storage.cjs'; +export default defineWorkflow({ async run(event, step, { env }) { + return step.do('read', async () => [await kv.get('key'), await read(env)]); +} });`, + ); + writeFileSync( + join(root, 'workflows', '_storage.cjs'), + "exports.read = (env) => env.STORAGE.get('key');", + ); + expect(inferProjectBindings(root)).toMatchObject({ needsKV: true, needsR2: true }); + expect(inferProjectBindings(root, undefined, ['.'])).toMatchObject({ + needsKV: true, + needsR2: true, + }); + expect(inferProjectBindings(root, undefined, ['src'])).toMatchObject({ + needsKV: false, + needsR2: false, + }); + }); + it('detects live from a stream module outside the default directories only when scanned', () => { const root = createTempRoot(); mkdirSync(join(root, 'routes'), { recursive: true }); diff --git a/packages/void/test/unit/workflow-runtime.test.ts b/packages/void/test/unit/workflow-runtime.test.ts index 314375b96f..46996c7ade 100644 --- a/packages/void/test/unit/workflow-runtime.test.ts +++ b/packages/void/test/unit/workflow-runtime.test.ts @@ -128,11 +128,23 @@ describe('defineWorkflow', () => { it('rejects a runtime identity that differs from static analysis and invalid names', () => { const Welcome = defineWorkflow({ name: 'welcome', async run() {} }); expect(() => Welcome.__bind('WORKFLOW_WELCOME', 'other')).toThrow('statically discoverable'); - expect(() => defineWorkflow({ name: '123', async run() {} })).toThrow('name must contain'); + expect(() => defineWorkflow({ name: '---', async run() {} })).toThrow('name must contain'); + const Numeric = defineWorkflow({ name: '123', async run() {} }); + expect(() => Numeric.__bind('WORKFLOW_123', '123')).not.toThrow(); }); }); describe('defineWorkflowEntrypoint', () => { + it('rejects a plain class at definition time', () => { + class Plain { + async run() {} + } + // @ts-expect-error JavaScript callers can supply an ordinary class. + expect(() => defineWorkflowEntrypoint({ class: Plain })).toThrow( + 'extending WorkflowEntrypoint', + ); + }); + it('keeps the native class and infers params from its run annotation', async () => { class Importer extends WorkflowEntrypoint, { file: string }> { override async run(_event: Readonly>, _step: WorkflowStep) { @@ -146,7 +158,7 @@ describe('defineWorkflowEntrypoint', () => { await withRuntimeEnv({ WORKFLOW_IMPORT: workflow }, () => Import.create({ params: { file: 'a.csv' } }), ); - expectTypeOf(Import).toEqualTypeOf>(); + expectTypeOf(Import).toEqualTypeOf>>(); expect(workflow.create).toHaveBeenCalledWith({ params: { file: 'a.csv' } }); }); }); diff --git a/packages/void/test/unit/workflow-runtime.typecheck.ts b/packages/void/test/unit/workflow-runtime.typecheck.ts index 6d9cc9802f..5e76908f86 100644 --- a/packages/void/test/unit/workflow-runtime.typecheck.ts +++ b/packages/void/test/unit/workflow-runtime.typecheck.ts @@ -1,4 +1,7 @@ -import { defineWorkflow } from '../../src/runtime/workflows/index.ts'; +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import { defineWorkflow, defineWorkflowEntrypoint } from '../../src/runtime/workflows/index.ts'; +import type { WorkflowEvent } from '../../src/runtime/workflows/index.ts'; +import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; declare const binding: Workflow; @@ -27,3 +30,93 @@ void optional.createBatch([{}]); const noParams = defineWorkflow({ async run() {} }); void noParams.create(); void noParams.createBatch(binding, [{ id: 'instance' }]); + +interface WorkflowEnv { + MAILER: string; +} + +const envWorkflow = defineWorkflow<{ id: number }, WorkflowEnv>({ + async run(_event, _step, { env }) { + env.MAILER.toUpperCase(); + }, +}); +declare const workerEnv: WorkflowEnv, ctx: ExecutionContext; +new envWorkflow.class(ctx, workerEnv); +declare const wrongBinding: Workflow<{ name: string }>; +// @ts-expect-error This binding can't receive the declared payload. +void envWorkflow.create(wrongBinding, { params: { id: 1 } }); +// @ts-expect-error Batch options must agree with the supplied binding. +void envWorkflow.createBatch(wrongBinding, [{ params: { id: 1 } }]); + +const converted = defineWorkflow({ + params: {} as StandardSchemaV1, + async run(event) { + event.payload.id.toFixed(); + }, +}); +declare const convertedBinding: Workflow<{ id: number }>; +void converted.create(convertedBinding, { params: '1' }); +declare const stringBinding: Workflow; +// @ts-expect-error The binding receives the parsed object. +void converted.create(stringBinding, { params: '1' }); + +defineWorkflow<{ userId: string } | undefined>({ + async run(event) { + if (event.payload) { + // @ts-expect-error Cloudflare uses an empty object when the caller omits params. + event.payload.userId.toUpperCase(); + } + event.payload.userId?.toUpperCase(); + }, +}); + +defineWorkflow({ + params: {} as StandardSchemaV1, + async run(event) { + // @ts-expect-error Undefined schema outputs arrive as an empty object. + event.payload.id.toFixed(); + event.payload.id?.toFixed(); + }, +}); + +const narrowHandler = async (_event: WorkflowEvent<{ id: number } | undefined>) => {}; +// @ts-expect-error This handler cannot receive the empty object produced by omitted params. +defineWorkflow<{ id: number } | undefined>({ run: narrowHandler }); +// @ts-expect-error This annotation excludes Cloudflare's empty payload. +defineWorkflow({ run: narrowHandler }); + +const inferred = defineWorkflow({ async run(_event: WorkflowEvent<{ id: number }>) {} }); +// @ts-expect-error The event annotation must still require params. +void inferred.create(); +// @ts-expect-error The event annotation determines the id type. +void inferred.create({ params: { id: 'x' } }); + +class OptionalNative extends WorkflowEntrypoint { + override async run(_event: WorkflowEvent<{ id: number } | undefined>) {} +} +const native = defineWorkflowEntrypoint({ class: OptionalNative }); +void native.create({ params: { id: 1 } }); +// @ts-expect-error This native class can't receive the empty object used for omitted params. +void native.create(); +// @ts-expect-error Passing undefined would deliver an empty object. +void native.create({ params: undefined }); + +class AcceptsEmpty extends WorkflowEntrypoint { + override async run(_event: WorkflowEvent<{ id?: number }>) {} +} +void defineWorkflowEntrypoint({ class: AcceptsEmpty }).create(); + +class VoidNative extends WorkflowEntrypoint { + override async run(_event: WorkflowEvent) {} +} +const voidNative = defineWorkflowEntrypoint({ class: VoidNative }); +// @ts-expect-error This native class expects void but the engine delivers an empty object. +void voidNative.create(); + +const noPayload = defineWorkflow({ + async run(event) { + const empty: Record = event.payload; + return empty; + }, +}); +void noPayload.create(); diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts index ecc3fcf0c0..4cb0d11b94 100644 --- a/packages/void/test/unit/workflow-scan.test.ts +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -56,6 +56,7 @@ describe('scanWorkflowModules', () => { { filePath: toSlash(join(root, 'workflows', 'send-welcome.ts')), relativePath: 'send-welcome.ts', + definition: 'defineWorkflow', bindingName: 'WORKFLOW_SEND_WELCOME', className: 'SendWelcomeWorkflow', resourceName: 'send-welcome', @@ -69,6 +70,7 @@ describe('scanWorkflowModules', () => { { filePath: toSlash(join(root, 'workflows', 'order', 'notifications.ts')), relativePath: 'order/notifications.ts', + definition: 'defineWorkflow', bindingName: 'WORKFLOW_ORDER_NOTIFICATIONS', className: 'OrderNotificationsWorkflow', resourceName: 'order-notifications', @@ -76,6 +78,19 @@ describe('scanWorkflowModules', () => { ]); }); + it('discovers local value exports aliased to default', () => { + const source = `import { defineWorkflow } from 'void/workflows'; +const Job = defineWorkflow({ name: 'daily', async run() {} });`; + const root = createRoot({ + 'digest.ts': `${source}\nexport { Job, Job as default };`, + 'types.ts': `${source}\nexport { type Job as default };`, + 'other.ts': `${source}\nexport { Job as default } from './digest';`, + }); + expect(scanWorkflowModules(root).map(({ relativePath, name }) => [relativePath, name])).toEqual( + [['digest.ts', 'daily']], + ); + }); + it('ignores files and directories starting with an underscore', () => { const root = createRoot({ 'welcome.ts': definition, @@ -163,6 +178,9 @@ describe('Cloudflare Workflow names', () => { expect(planWorkflowAdditions([authored], modules, 'app')).toEqual([ { name: 'app-import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, ]); + expect(planWorkflowAdditions([{ ...authored, script_name: 'app' }], modules, 'app')).toEqual([ + { name: 'app-import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, + ]); expect(planWorkflowAdditions([], [], 'app')).toEqual([]); }); From 914209aeee6abe84e338a0d0aadcfa35969b8ba8 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 10:35:04 +0900 Subject: [PATCH 05/13] Fix Workflow discovery, execution scope, and static deployment. --- .github/scripts/packed-consumer.mjs | 31 ++++++ docs/guide/workflows.md | 4 +- packages/void/package.json | 1 + packages/void/src/cli/deploy-helpers.ts | 2 +- packages/void/src/cli/deploy.ts | 4 +- packages/void/src/cli/preset.ts | 16 ++- packages/void/src/deploy.ts | 2 +- packages/void/src/router/compile.ts | 27 +++--- packages/void/src/runtime/workflows/entry.ts | 97 +++++++++++++++++++ .../void/src/shared/resource-definition.ts | 23 ++++- .../integration/full-deploy-manifest.test.ts | 16 +++ .../test/integration/workflow-runtime.test.ts | 80 ++++++++++++++- packages/void/test/unit/compile.test.ts | 4 +- .../unit/deploy-artifact-preparation.test.ts | 21 ++++ .../void/test/unit/plugin-inference.test.ts | 4 +- .../void/test/unit/workflow-runtime.test.ts | 47 +++++++++ packages/void/test/unit/workflow-scan.test.ts | 9 ++ packages/void/vite.config.ts | 2 + 18 files changed, 363 insertions(+), 27 deletions(-) create mode 100644 packages/void/src/runtime/workflows/entry.ts diff --git a/.github/scripts/packed-consumer.mjs b/.github/scripts/packed-consumer.mjs index 383a57fb34..6072449505 100644 --- a/.github/scripts/packed-consumer.mjs +++ b/.github/scripts/packed-consumer.mjs @@ -326,6 +326,37 @@ try { JSON.parse(readFileSync(join(fixture, 'node_modules/void/package.json'), 'utf8')).version, version, ); + if (framework === 'react') { + // A standalone Workflow can be the only Void import in a worker project. + writeFileSync( + join(fixture, 'workflow.mts'), + `import { defineWorkflow } from 'void/workflows'; +export default defineWorkflow<{ id: string }>({ + async run(event, step) { return step.do('id', async () => event.payload.id); }, +});`, + ); + writeFileSync( + join(fixture, 'tsconfig.workflow.json'), + JSON.stringify({ + compilerOptions: { + module: 'NodeNext', + target: 'ES2022', + lib: ['ES2022'], + types: [], + strict: true, + noEmit: true, + }, + files: ['workflow.mts'], + }), + ); + await run( + process.execPath, + [join(fixture, 'node_modules/typescript/bin/tsc'), '-p', 'tsconfig.workflow.json'], + fixture, + ); + rmSync(join(fixture, 'workflow.mts')); + rmSync(join(fixture, 'tsconfig.workflow.json')); + } await run(process.execPath, [cli, 'prepare'], fixture); await run(manager, manager === 'npm' ? ['ci'] : ['install', '--frozen-lockfile'], fixture); const vite = join( diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md index 70807e13f2..9e1b858df9 100644 --- a/docs/guide/workflows.md +++ b/docs/guide/workflows.md @@ -43,6 +43,8 @@ TypeScript and JavaScript files are supported, including subdirectories. Void di Imports such as `void/env`, `void/db`, and `void/kv` work inside steps. Keep side effects inside `step.do()` so a retry or a resumed instance doesn't repeat them. +Each step attempt has its own D1 session. To start from a bookmark, call `setSession({ bookmark })` inside the step before its first query. + ## Start an instance from a route ```ts @@ -163,4 +165,4 @@ Workflows are available on the Workers Free plan, within [Cloudflare's Workflows If Cloudflare rejects staging because you added, renamed, or removed a Workflow, run `void deploy --platform cloudflare --atomic` for that deployment. The new version receives traffic before Void checks readiness. -Void platforms do not support Workflows yet: `void deploy` to a Void platform stops with an error while `workflows/` contains modules. Workflows are also unavailable in meta-framework apps and on Node.js, Bun, and Deno. +Deploy the Workflow itself to Cloudflare. You can publish the same project's static assets to a Void platform with `void deploy --dir dist` or an explicit `inference.appType` of `static` or `spa`. Meta-framework apps and Node.js, Bun, and Deno targets do not support Workflows. diff --git a/packages/void/package.json b/packages/void/package.json index 5cafe97a4c..0020d58024 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -46,6 +46,7 @@ "#self/runtime/migration-handler-pg": "./dist/runtime/db/migrations/postgres-handler.mjs", "#self/runtime/migration-handler-mysql": "./dist/runtime/db/migrations/mysql-handler.mjs", "#self/runtime/ws-server": "./dist/runtime/ws/server.mjs", + "#self/runtime/workflow-entry": "./dist/runtime/workflows/entry.mjs", "#self/runtime/routing": "./dist/runtime/routing/index.mjs" }, "exports": { diff --git a/packages/void/src/cli/deploy-helpers.ts b/packages/void/src/cli/deploy-helpers.ts index 547cf5c1eb..f3e2dd6cd3 100644 --- a/packages/void/src/cli/deploy-helpers.ts +++ b/packages/void/src/cli/deploy-helpers.ts @@ -386,7 +386,7 @@ export function resolveStaticDeployPreset( }; // Re-detect build command (config stores app type, not command). - const detectedPreset = detectPreset(root, { spa: options?.spa }); + const detectedPreset = detectPreset(root, { spa: options?.spa, skipWorkflowDiscovery: true }); if (detectedPreset) { preset.buildCommand = detectedPreset.buildCommand; if (!outputDir) { diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 413446b7e3..96d464b606 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -304,7 +304,6 @@ async function runManagedDeploy( // Resolve the app type: void.config.ts > CLI flags > auto-detection. const voidConfig = readConfig(root); - assertNoWorkflowsForPlatform(root); cliLog.info('config_resolved', { target: voidConfig.target, appType: voidConfig.inference?.appType, @@ -315,6 +314,9 @@ async function runManagedDeploy( dir: options?.dir, spa: options?.spa, }); + if (!preset) { + assertNoWorkflowsForPlatform(root); + } // Check for known framework after static overrides. const detected = detectFramework(root); diff --git a/packages/void/src/cli/preset.ts b/packages/void/src/cli/preset.ts index f1d09da8f1..522b85bbe6 100644 --- a/packages/void/src/cli/preset.ts +++ b/packages/void/src/cli/preset.ts @@ -245,7 +245,12 @@ export function formatProjectCommand(root: string, command: string): string { */ export function detectPreset( root: string, - options?: { dir?: string; spa?: boolean; strictBackend?: boolean }, + options?: { + dir?: string; + spa?: boolean; + strictBackend?: boolean; + skipWorkflowDiscovery?: boolean; + }, ): StaticPreset | null { // 1. Explicit --dir flag: skip build, use provided directory if (options?.dir) { @@ -281,7 +286,7 @@ export function detectPreset( } // 3. Has backend files → full deploy - if (hasBackendFiles(root)) { + if (hasBackendFiles(root, options)) { return null; } @@ -481,12 +486,15 @@ export function findBackendSources(root: string): Array { /** * Check whether the project has backend files that require a full worker deploy. */ -export function hasBackendFiles(root: string): boolean { +export function hasBackendFiles( + root: string, + options?: { skipWorkflowDiscovery?: boolean }, +): boolean { const paths = readProjectPaths(root); return ( backendDirs(paths).some((dir) => existsSync(dir)) || hasSsrEntry(root, paths) || - scanWorkflowModules(root).length > 0 + (!options?.skipWorkflowDiscovery && scanWorkflowModules(root).length > 0) ); } diff --git a/packages/void/src/deploy.ts b/packages/void/src/deploy.ts index f9a6d9c3e7..c68d9d23ed 100644 --- a/packages/void/src/deploy.ts +++ b/packages/void/src/deploy.ts @@ -84,10 +84,10 @@ export async function prepareDeployArtifact( if (isNodeTarget(config.target) || config.output === 'static') { throw new Error('Artifact preparation requires a Void Cloudflare Worker build.'); } - assertNoWorkflowsForPlatform(root); let preset = resolveStaticDeployPreset(root, config); let analysis: Awaited> | undefined; if (!preset) { + assertNoWorkflowsForPlatform(root); analysis = await analyzeApplication(root, { config, environment: 'prod' }); if ( !config.inference?.appType && diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index 6f1ca1f49d..5646463694 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -1231,7 +1231,7 @@ function compileResourceModules( directory: string; prefix: string; helpers: string; - validateWorkflowEnv?: boolean; + wrapClass?: (classExpression: string) => string; }, ): ResourceModuleCode { const imports = entries @@ -1245,18 +1245,12 @@ function compileResourceModules( const local = `${options.variable}${index}`; const file = `${options.directory}/${relativePath ?? filePath.replaceAll('\\', '/').split('/').pop()}`; const message = `${options.prefix}: ${file} must default-export ${options.helpers}.`; + const resourceClass = `${local}.class`; return [ `const ${local} = ${options.variable}Module${index}.default;`, `if (typeof ${local}?.__bind !== "function") { throw new Error(${JSON.stringify(message)}); }`, `${local}.__bind(${JSON.stringify(bindingName)}${name !== undefined ? `, ${JSON.stringify(name)}` : ''});`, - options.validateWorkflowEnv - ? `export class ${className} extends ${local}.class { - async run(event, step) { - await _validateEnvOnce(this.env); - return withRuntimeEnv(this.env, () => super.run(event, step)); - } -}` - : `export const ${className} = ${local}.class;`, + `export const ${className} = ${options.wrapClass?.(resourceClass) ?? resourceClass};`, ].join('\n'); }) .join('\n'); @@ -1350,9 +1344,20 @@ export function compileWorkerEntry(options: WorkerEntryOptions = {}): string { directory: 'workflows', prefix: 'workflows', helpers: 'defineWorkflow() or defineWorkflowEntrypoint()', - validateWorkflowEnv: Boolean(envSchemaModule), + wrapClass: (workflowClass) => + `__createWorkflowEntrypoint(${workflowClass}, { ${[ + envSchemaModule && 'validateEnv: _validateEnvOnce', + remotePath && `remoteEnv: (env) => ${createRemoteEnvCall}`, + ] + .filter(Boolean) + .join(', ')} })`, }); - const resourceModuleImports = [durableObjectModules.imports, workflowModules.imports] + const resourceModuleImports = [ + durableObjectModules.imports, + workflows.length > 0 && + `import { createWorkflowEntrypoint as __createWorkflowEntrypoint } from ${JSON.stringify(fileURLToPath(import.meta.resolve('#self/runtime/workflow-entry')))};`, + workflowModules.imports, + ] .filter(Boolean) .join('\n'); const resourceModuleExports = [durableObjectModules.exports, workflowModules.exports] diff --git a/packages/void/src/runtime/workflows/entry.ts b/packages/void/src/runtime/workflows/entry.ts new file mode 100644 index 0000000000..50fc554b95 --- /dev/null +++ b/packages/void/src/runtime/workflows/entry.ts @@ -0,0 +1,97 @@ +import type { + WorkflowEntrypoint, + WorkflowEvent, + WorkflowStep, + WorkflowStepConfig, + WorkflowStepContext, + WorkflowStepRollbackOptions, +} from 'cloudflare:workers'; +import { withRuntimeEnv } from '../env/runtime.ts'; +import type { RuntimeEnv } from '../env/runtime.ts'; + +type StepCallback = (context: WorkflowStepContext) => Promise; + +// Workflows invokes these callbacks over RPC. Each invocation needs its own +// request scope: a D1 session belongs to the step attempt that opened it. +function scopedStep(step: WorkflowStep, env: RuntimeEnv): WorkflowStep { + function scoped(callback: (input: Input) => Output) { + return typeof callback === 'function' + ? (input: Input) => withRuntimeEnv(env, () => callback(input)) + : callback; + } + + function scopedConfig(config: WorkflowStepConfig) { + const retries = config?.retries; + return typeof retries?.delay === 'function' + ? { ...config, retries: { ...retries, delay: scoped(retries.delay) } } + : config; + } + + function scopedRollback(options?: WorkflowStepRollbackOptions) { + return typeof options?.rollback === 'function' + ? { + ...options, + rollback: scoped(options.rollback), + ...(options.rollbackConfig && { rollbackConfig: scopedConfig(options.rollbackConfig) }), + } + : options; + } + + function runStep>( + name: string, + configOrCallback: WorkflowStepConfig | StepCallback, + callbackOrRollback?: StepCallback | WorkflowStepRollbackOptions, + rollback?: WorkflowStepRollbackOptions, + ) { + if (typeof configOrCallback === 'function') { + return step.do( + name, + scoped(configOrCallback), + scopedRollback(callbackOrRollback as WorkflowStepRollbackOptions | undefined), + ); + } + return step.do( + name, + scopedConfig(configOrCallback), + scoped(callbackOrRollback as StepCallback), + scopedRollback(rollback), + ); + } + + return { + // The overloads narrow the callback context from retries.delay. The engine + // supplies that context unchanged to each callback. + do: runStep as WorkflowStep['do'], + sleep: (name, duration) => step.sleep(name, duration), + sleepUntil: (name, timestamp) => step.sleepUntil(name, timestamp), + waitForEvent: (name, options) => step.waitForEvent(name, options), + }; +} + +type Entrypoint = new ( + ctx: ExecutionContext, + env: RuntimeEnv, +) => WorkflowEntrypoint; + +/** Create the class exported by the generated Worker for either Workflow definition form. */ +export function createWorkflowEntrypoint( + Workflow: Entrypoint, + options: { + validateEnv?: (env: RuntimeEnv) => Promise; + remoteEnv?: (env: RuntimeEnv) => RuntimeEnv; + }, +): Entrypoint { + return class extends Workflow { + constructor(ctx: ExecutionContext, env: RuntimeEnv) { + super(ctx, env.__VOID_REMOTE === '1' && options.remoteEnv ? options.remoteEnv(env) : env); + } + + override async run(event: Readonly>, step: WorkflowStep) { + const env = this.env; + if (options.validateEnv) { + await options.validateEnv(env); + } + return withRuntimeEnv(env, () => super.run(event, scopedStep(step, env))); + } + }; +} diff --git a/packages/void/src/shared/resource-definition.ts b/packages/void/src/shared/resource-definition.ts index bcfeb1d6d2..6394b5003b 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -13,7 +13,6 @@ import type { AstImportNamespaceSpecifier, AstImportSpecifier, AstNode, - AstProgram, AstVariableDeclaration, } from './ast.ts'; import { isResourceName, isWorkflowName } from './resource-name.ts'; @@ -26,12 +25,28 @@ export function readResourceDefinition( helpers: ReadonlySet, convention?: 'workflows', ): { helper: string; options?: AstNode; name?: string } | null { - let program: AstProgram; + let parsed: ReturnType; try { - program = asAstProgram(parseSync(filename, source).program); - } catch { + parsed = parseSync(filename, source); + } catch (error) { + if (convention === 'workflows' && source.includes('void/workflows')) { + throw new Error(`workflows: could not parse ${filename}`, { cause: error }); + } return null; } + // A fatal parse error can leave the AST empty and even stop before the import. + // Keep unrelated scripts in workflows/ outside the convention. + if ( + convention === 'workflows' && + parsed.errors.length > 0 && + (parsed.module.staticImports.some( + ({ moduleRequest }) => moduleRequest.value === 'void/workflows', + ) || + /\bfrom\s*['"]void\/workflows['"]/.test(source)) + ) { + throw new SyntaxError(`workflows: could not parse ${filename}\n${parsed.errors[0].codeframe}`); + } + const program = asAstProgram(parsed.program); const constants = new Map(); const definitions = new Map(); diff --git a/packages/void/test/integration/full-deploy-manifest.test.ts b/packages/void/test/integration/full-deploy-manifest.test.ts index dc2d853af1..3447b75443 100644 --- a/packages/void/test/integration/full-deploy-manifest.test.ts +++ b/packages/void/test/integration/full-deploy-manifest.test.ts @@ -218,6 +218,22 @@ describe('managed deployment manifests (built Worker)', () => { playground?.cleanup(); }); + it('deploys an explicit static directory alongside Workflow sources', async () => { + const workflows = join(fixture, 'workflows'); + mkdirSync(workflows); + try { + writeFileSync( + join(workflows, 'job.ts'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", + ); + const captured = installPlatformMocks(); + await runDeploy(fixture, { dir: 'dist/client' }); + expect(captured.finalizeBody?.manifest).toMatchObject({ type: 'static', bindings: {} }); + } finally { + rmSync(workflows, { recursive: true, force: true }); + } + }); + beforeEach(() => { mockDetectFramework.mockReset().mockReturnValue(undefined); diff --git a/packages/void/test/integration/workflow-runtime.test.ts b/packages/void/test/integration/workflow-runtime.test.ts index e512b4eca0..a0bc302232 100644 --- a/packages/void/test/integration/workflow-runtime.test.ts +++ b/packages/void/test/integration/workflow-runtime.test.ts @@ -181,10 +181,15 @@ export default defineEnv({ VALUE: { '~standard': { ` import { WorkflowEntrypoint } from 'cloudflare:workers'; import { env } from ${JSON.stringify(envPath)}; +import { db, setSession } from ${JSON.stringify(join(root, 'packages/void/src/runtime/db/index.ts'))}; import { defineWorkflow, defineWorkflowEntrypoint } from ${JSON.stringify(runtimePath)}; async function run(event, step) { const value = env.VALUE; - return step.do('read', async () => value + 1); + setSession('first-primary'); + return step.do('read', { retries: { limit: 0, delay: 0 } }, async () => { + setSession('first-primary'); + return { value: value + 1, sameSession: db.$client === db.$client }; + }); } ${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'class Cold extends WorkflowEntrypoint { run(event, step) { return run(event, step); } } export default defineWorkflowEntrypoint({ class: Cold });'} `, @@ -205,6 +210,7 @@ ${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'cla modulesRoot: output, scriptPath: join(output, 'worker.mjs'), bindings: { VALUE: '41' }, + d1Databases: { DB: 'test' }, workflows: { COLD: { name: 'cold', className: 'ColdWorkflow' } }, }), ); @@ -216,7 +222,10 @@ ${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'cla timeout: 5000, }) .toMatch(/^(complete|errored)$/); - expect(await instance.status()).toMatchObject({ status: 'complete', output: 42 }); + expect(await instance.status()).toMatchObject({ + status: 'complete', + output: { value: 42, sameSession: true }, + }); } finally { await worker.dispose(); } @@ -224,6 +233,73 @@ ${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'cla ); }); +it.each(['defineWorkflow', 'defineWorkflowEntrypoint'])( + 'uses the same remote KV in a route and %s without an env schema', + async (helper) => { + const definition = file( + 'remote-' + helper + '.ts', + ` +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import { getRuntimeBinding } from ${JSON.stringify(join(root, 'packages/void/src/runtime/env/runtime.ts'))}; +import { defineWorkflow, defineWorkflowEntrypoint } from ${JSON.stringify(runtimePath)}; +async function read(step, env) { + return step.do('read', async () => [ + await env.MY_KV.get('key'), await getRuntimeBinding('MY_KV').get('key'), + ]); +} +${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run(event, step, {env}) { return read(step, env); } });' : 'class Job extends WorkflowEntrypoint { run(event, step) { return read(step, this.env); } } export default defineWorkflowEntrypoint({class: Job});'} +`, + ); + const output = await buildWorker( + 'remote-' + helper, + 'export default { async fetch(req, env) { return new Response(await env.MY_KV.get("key")); } };', + { + remote: { + remotePath: join(root, 'packages/void/src/runtime/remote/index.ts'), + bindingNames: { kv: 'MY_KV' }, + }, + workflows: [{ bindingName: 'JOB', className: 'JobWorkflow', filePath: definition }], + }, + ); + const worker = new Miniflare( + convertV4MiniflareOptions({ + compatibilityDate: '2026-07-01', + compatibilityFlags: ['nodejs_compat'], + modules: true, + modulesRoot: output, + scriptPath: join(output, 'worker.mjs'), + bindings: { + __VOID_REMOTE: '1', + __VOID_PROXY_URL: 'https://proxy.test', + __VOID_PROJECT_ID: 'test', + __VOID_TOKEN: 'test', + }, + kvNamespaces: ['MY_KV'], + workflows: { JOB: { name: 'job', className: 'JobWorkflow' } }, + outboundService: (request) => + request.url === 'https://proxy.test/kv/get' + ? Response.json('remote') + : new Response(null, { status: 404 }), + }), + ); + try { + const { JOB, MY_KV } = await worker.getBindings<{ JOB: Workflow; MY_KV: KVNamespace }>(); + await MY_KV.put('key', 'local'); + expect(await (await worker.dispatchFetch('http://localhost/')).text()).toBe('remote'); + const instance = await JOB.create(); + await expect + .poll(async () => (await instance.status()).status) + .toMatch(/^(complete|errored)$/); + expect(await instance.status()).toMatchObject({ + status: 'complete', + output: ['remote', 'remote'], + }); + } finally { + await worker.dispose(); + } + }, +); + describe('convention modules without a definition default export', () => { it.each([ { diff --git a/packages/void/test/unit/compile.test.ts b/packages/void/test/unit/compile.test.ts index 517f63e490..a58549c444 100644 --- a/packages/void/test/unit/compile.test.ts +++ b/packages/void/test/unit/compile.test.ts @@ -880,7 +880,9 @@ describe('compileWorkerEntry', () => { 'import * as __voidWorkflowModule0 from "/app/workflows/onboarding.ts";', ); expect(code).toContain('__voidWorkflow0.__bind("WORKFLOW_ONBOARDING", "onboarding");'); - expect(code).toContain('export const OnboardingWorkflow = __voidWorkflow0.class;'); + expect(code).toContain( + 'export const OnboardingWorkflow = __createWorkflowEntrypoint(__voidWorkflow0.class', + ); }); it('guards convention modules that do not default-export a definition', () => { diff --git a/packages/void/test/unit/deploy-artifact-preparation.test.ts b/packages/void/test/unit/deploy-artifact-preparation.test.ts index dd84832dc6..e1d599ad9a 100644 --- a/packages/void/test/unit/deploy-artifact-preparation.test.ts +++ b/packages/void/test/unit/deploy-artifact-preparation.test.ts @@ -178,6 +178,27 @@ it.each([true, false, undefined])( }, ); +it('allows an explicit asset-only deploy from a project with Workflows', async () => { + mkdirSync(join(root, 'workflows')); + writeFileSync( + join(root, 'workflows/job.ts'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", + ); + await expect(prepareDeployArtifact(root)).rejects.toThrow('not supported on Void platforms'); + // Packaging explicit static output must not even parse the Worker sources. + writeFileSync( + join(root, 'workflows/job.ts'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() { return ); } });", + ); + writeFileSync( + join(root, 'void.config.ts'), + "export default { inference: { appType: 'static', outputDir: 'dist/client' } };", + ); + const result = await prepareDeployArtifact(root); + expect(Object.keys(result.assets)).toEqual(['/index.html']); + expect(result.artifact.workerFiles).toBeUndefined(); +}); + it('keeps SPA plus API apps on the Worker deployment path', async () => { writeFileSync(join(root, 'package.json'), JSON.stringify({ devDependencies: { vite: '*' } })); mkdirSync(join(root, 'routes')); diff --git a/packages/void/test/unit/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index 0f387d90c3..9f9e3a96f1 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -938,7 +938,9 @@ describe('detectFramework', () => { expect(entry).toContain('import * as __voidWorkflowModule0 from'); expect(entry).toContain('/workflows/send-welcome.ts'); expect(entry).toContain('__voidWorkflow0.__bind("WORKFLOW_SEND_WELCOME")'); - expect(entry).toContain('export const SendWelcomeWorkflow = __voidWorkflow0.class'); + expect(entry).toContain( + 'export const SendWelcomeWorkflow = __createWorkflowEntrypoint(__voidWorkflow0.class', + ); expect(entry).toContain( 'workflows: workflows/send-welcome.ts must default-export defineWorkflow() or defineWorkflowEntrypoint().', ); diff --git a/packages/void/test/unit/workflow-runtime.test.ts b/packages/void/test/unit/workflow-runtime.test.ts index 46996c7ade..53f64847f6 100644 --- a/packages/void/test/unit/workflow-runtime.test.ts +++ b/packages/void/test/unit/workflow-runtime.test.ts @@ -2,6 +2,7 @@ import { WorkflowEntrypoint } from 'cloudflare:workers'; import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; import { describe, expect, expectTypeOf, it, vi } from 'vite-plus/test'; import { getRuntimeEnv, withRuntimeEnv } from '../../src/runtime/env/runtime.ts'; +import { createWorkflowEntrypoint } from '../../src/runtime/workflows/entry.ts'; import { defineWorkflow, defineWorkflowEntrypoint, @@ -52,6 +53,52 @@ const userSchema: StandardSchemaV1<{ userId: string }, { userId: string }> = { }; describe('defineWorkflow', () => { + it('restores the Worker env for deferred step, retry and rollback callbacks', async () => { + const seen: Array = []; + const delay = () => { + seen.push(getRuntimeEnv().VALUE); + return 1; + }; + const rollback = async () => { + seen.push(getRuntimeEnv().VALUE); + }; + const Job = defineWorkflow({ + async run(_event, step) { + await step.do('work', { retries: { limit: 1, delay } }, rollback, { + rollback, + rollbackConfig: { retries: { limit: 1, delay } }, + }); + }, + }); + const entry = createWorkflowEntrypoint(Job.class, {}); + const callbacks: Array<() => unknown> = []; + // Invoke the registered callbacks after run() has left its own request scope. + type RetryConfig = { retries: { delay: () => number } }; + const step = { + do( + _name: string, + config: RetryConfig, + run: () => Promise, + options: { rollback: () => Promise; rollbackConfig: RetryConfig }, + ) { + callbacks.push( + run, + config.retries.delay, + options.rollback, + options.rollbackConfig.retries.delay, + ); + }, + }; + await new entry({} as ExecutionContext, { VALUE: 'workflow' }).run( + {} as WorkflowEvent, + step as unknown as WorkflowStep, + ); + for (const callback of callbacks) { + await callback(); + } + expect(seen).toEqual(['workflow', 'workflow', 'workflow', 'workflow']); + }); + it('generates an entrypoint that runs inside the Worker env', async () => { const seen: Array = []; const Welcome = defineWorkflow({ diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts index 4cb0d11b94..824397d2d8 100644 --- a/packages/void/test/unit/workflow-scan.test.ts +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -33,9 +33,18 @@ afterEach(() => { }); describe('scanWorkflowModules', () => { + it.each([ + definition.replace('run() {}', 'run() { return ); }'), + `const broken = );\n${definition}`, + ])('reports a syntax error instead of dropping a Workflow', (source) => { + const root = createRoot({ 'notify.ts': source }); + expect(() => scanWorkflowModules(root)).toThrow(/notify\.ts[\s\S]*Unexpected token/i); + }); + it('ignores ordinary modules in the workflows directory', () => { const root = createRoot({ 'maintenance.ts': 'export default { run() {} }', + 'unfinished.ts': 'export default { run() { return ); } }', 'unrelated.ts': 'const defineWorkflow = (value) => value; export default defineWorkflow({});', }); diff --git a/packages/void/vite.config.ts b/packages/void/vite.config.ts index d0d7ce6f51..9a99f2225b 100644 --- a/packages/void/vite.config.ts +++ b/packages/void/vite.config.ts @@ -34,6 +34,7 @@ function injectWorkersTypesReferencePlugin() { 'runtime/live/server.d.mts', 'runtime/email/index.d.mts', 'runtime/email/testing.d.mts', + 'runtime/workflows/index.d.mts', ]); if (!targets.has(output.fileName)) { continue; @@ -105,6 +106,7 @@ export default defineConfig({ 'src/runtime/db/mysql.ts', 'src/runtime/durable/index.ts', 'src/runtime/workflows/index.ts', + 'src/runtime/workflows/entry.ts', 'src/runtime/db/seed.ts', 'src/runtime/db/validators/drizzle-zod.ts', 'src/runtime/db/validators/drizzle-valibot.ts', From b548e386cf3ceb74d0bf517aa7c96feba6202be6 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 11:08:01 +0900 Subject: [PATCH 06/13] Fix Workflow discovery, deployment, and runtime context. --- docs/guide/workflows.md | 6 +- .../src/cli/cloudflare-deploy/classify.ts | 5 ++ packages/void/src/cli/deploy-helpers.ts | 26 ++++--- packages/void/src/cli/deploy.ts | 13 ++-- packages/void/src/cli/init.ts | 2 +- packages/void/src/cli/preset.ts | 22 +++--- packages/void/src/index.ts | 5 +- packages/void/src/router/compile.ts | 1 + packages/void/src/runtime/workflows/entry.ts | 4 ++ packages/void/src/runtime/workflows/index.ts | 4 +- .../void/src/shared/resource-definition.ts | 71 ++++++++++++------- packages/void/src/workflows/platform.ts | 3 + .../integration/full-deploy-manifest.test.ts | 6 +- .../test/integration/workflow-runtime.test.ts | 17 ++++- .../test/unit/cloudflare-classify.test.ts | 9 +++ .../unit/deploy-artifact-preparation.test.ts | 17 +++++ packages/void/test/unit/init.test.ts | 1 + .../void/test/unit/workflow-runtime.test.ts | 11 ++- packages/void/test/unit/workflow-scan.test.ts | 12 +++- 19 files changed, 168 insertions(+), 67 deletions(-) diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md index 9e1b858df9..cc9a547a7f 100644 --- a/docs/guide/workflows.md +++ b/docs/guide/workflows.md @@ -33,7 +33,7 @@ export default Onboarding; Default-export the object returned by `defineWorkflow()`. Named-export it too so routes can import it. -TypeScript and JavaScript files are supported, including subdirectories. Void discovers default exports created using a helper imported from `void/workflows`. Files and directories starting with `_` are excluded from Workflow discovery. +TypeScript and JavaScript files are supported, including subdirectories. Void discovers default exports created using a helper imported from `void/workflows`. Files and directories starting with `_` are excluded from Workflow discovery. If you maintain an explicit `include` list in `tsconfig.json`, add `workflows` so TypeScript checks definitions started outside your app. `run` receives: @@ -165,4 +165,6 @@ Workflows are available on the Workers Free plan, within [Cloudflare's Workflows If Cloudflare rejects staging because you added, renamed, or removed a Workflow, run `void deploy --platform cloudflare --atomic` for that deployment. The new version receives traffic before Void checks readiness. -Deploy the Workflow itself to Cloudflare. You can publish the same project's static assets to a Void platform with `void deploy --dir dist` or an explicit `inference.appType` of `static` or `spa`. Meta-framework apps and Node.js, Bun, and Deno targets do not support Workflows. +To publish the same project's static assets to a connected Void platform, build the app and run `void deploy --platform void --dir dist/client`. You can also set `inference.appType` to `static` or `spa` and run `void deploy --platform void`. If you customize the build output, set `inference.outputDir` to the directory containing your public assets. + +Workflows require a native Void app targeting Cloudflare Workers. diff --git a/packages/void/src/cli/cloudflare-deploy/classify.ts b/packages/void/src/cli/cloudflare-deploy/classify.ts index 468c535e4c..b78b93a131 100644 --- a/packages/void/src/cli/cloudflare-deploy/classify.ts +++ b/packages/void/src/cli/cloudflare-deploy/classify.ts @@ -11,6 +11,7 @@ import { renderDeploySeedConfig } from '../../config-write.ts'; import type { VoidConfig } from '../../config.ts'; import { assertNoRootSourceConventionConflicts } from '../../project-paths.ts'; import { validateSsrEntry } from '../../ssr/entry.ts'; +import { FRAMEWORK_WORKFLOWS_ERROR } from '../../workflows/platform.ts'; import { CANDIDATE_FILE } from '../cloudflare-candidate.ts'; import { log } from '../deploy-helpers.ts'; import { deriveWorkerName } from '../deploy-resources.ts'; @@ -73,6 +74,10 @@ export function classifyCloudflareDeployApp( ); } + if (framework && application.workflows.length > 0) { + return unsupported(FRAMEWORK_WORKFLOWS_ERROR); + } + if (!framework && !hasBackendFiles(root)) { return unsupported( [ diff --git a/packages/void/src/cli/deploy-helpers.ts b/packages/void/src/cli/deploy-helpers.ts index f3e2dd6cd3..01a5699937 100644 --- a/packages/void/src/cli/deploy-helpers.ts +++ b/packages/void/src/cli/deploy-helpers.ts @@ -23,7 +23,12 @@ import { fetchRemoteSecretNames, formatEnvReport, validateProdEnv } from './env- import { isCancel, log as clackLog, text } from './interactive-prompts.ts'; import type { CliLogger } from './log-file.ts'; import { formatCount, getErrorMessage, pc } from './output.ts'; -import { detectPreset, formatProjectCommand, resolveProjectCommand } from './preset.ts'; +import { + defaultViteClientDir, + detectPreset, + formatProjectCommand, + resolveProjectCommand, +} from './preset.ts'; import type { StaticPreset } from './preset.ts'; import { attachSelectedPlatform, shouldLinkDeployProject, writeProjectConfig } from './project.ts'; import type { ProjectConfig } from './project.ts'; @@ -379,21 +384,14 @@ export function resolveStaticDeployPreset( const appType = voidConfig.inference?.appType; if (appType === 'static' || appType === 'spa') { const outputDir = voidConfig.inference?.outputDir; - const preset: StaticPreset = { - buildCommand: null, - outputDir: outputDir ? resolve(root, outputDir) : join(root, 'dist'), + const detected = detectPreset(root, { spa: options?.spa, skipWorkflowDiscovery: true }); + return { appType, + buildCommand: detected?.buildCommand ?? null, + outputDir: outputDir + ? resolve(root, outputDir) + : (detected?.outputDir ?? defaultViteClientDir(root)), }; - - // Re-detect build command (config stores app type, not command). - const detectedPreset = detectPreset(root, { spa: options?.spa, skipWorkflowDiscovery: true }); - if (detectedPreset) { - preset.buildCommand = detectedPreset.buildCommand; - if (!outputDir) { - preset.outputDir = detectedPreset.outputDir; - } - } - return preset; } return null; diff --git a/packages/void/src/cli/deploy.ts b/packages/void/src/cli/deploy.ts index 96d464b606..56f8d82532 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -172,6 +172,15 @@ async function runManagedDeploy( options: RunDeployOptions, cliLog: CliLogger, ): Promise { + // An explicit static deployment can share a project with a Cloudflare Workflow. + // Reject Worker deploys before looking up or creating a managed project. + if ( + !options.dir && + existsSync(join(root, 'workflows')) && + !resolveStaticDeployPreset(root, readConfig(root), options) + ) { + assertNoWorkflowsForPlatform(root); + } // Resolve the connected recipient before credentials, OIDC, builds, or platform requests. const apiUrl = getApiUrl(root); const requestedProjectSlug = getRequestedProjectSlug(options); @@ -314,10 +323,6 @@ async function runManagedDeploy( dir: options?.dir, spa: options?.spa, }); - if (!preset) { - assertNoWorkflowsForPlatform(root); - } - // Check for known framework after static overrides. const detected = detectFramework(root); // Detect git commit before build (only when not skipping build). Same scrub as diff --git a/packages/void/src/cli/init.ts b/packages/void/src/cli/init.ts index f7c587c019..9d278799ea 100644 --- a/packages/void/src/cli/init.ts +++ b/packages/void/src/cli/init.ts @@ -1089,7 +1089,7 @@ function setupTsconfig( types: ['void/env'], ...getScaffoldTsconfigCompilerOptions(pagesFramework), }, - include: ['src', 'pages', 'routes', 'middleware', 'crons', 'queues', 'db'], + include: ['src', 'pages', 'routes', 'middleware', 'crons', 'queues', 'workflows', 'db'], }; writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, 2) + '\n'); report.created('tsconfig.json'); diff --git a/packages/void/src/cli/preset.ts b/packages/void/src/cli/preset.ts index 522b85bbe6..e820fc6d68 100644 --- a/packages/void/src/cli/preset.ts +++ b/packages/void/src/cli/preset.ts @@ -297,13 +297,11 @@ export function detectPreset( const hasLocalVite = vitePlusRoot === root || hasViteDependency(pkg); if (hasLocalVite || vitePlusRoot !== undefined) { const buildCommand = resolveProjectScriptCommand(root, 'build'); - const viteConfig = VITE_CONFIG_FILES.map((name) => join(root, name)).find((path) => - existsSync(path), - ); + const viteConfig = findViteConfig(root); if (hasLocalVite || buildCommand || viteConfig || existsSync(join(root, 'index.html'))) { return { buildCommand: buildCommand ?? resolveProjectCommand(root, 'vite build'), - outputDir: resolve(root, viteSpaOutputDir(viteConfig)), + outputDir: defaultViteClientDir(root, viteConfig), appType: 'spa', }; } @@ -418,17 +416,23 @@ const VITE_CONFIG_FILES = [ ]; /** - * Where a Vite SPA build puts its browser files. A Vite config that uses + * Where a Vite build puts its browser files. A Vite config that uses * `voidPlugin()` (`void init` adds it) splits the output into `dist/client` * (browser files) and `dist/ssr` (the server bundle, its source map and * `wrangler.json`). Only `dist/client` may be uploaded: uploading `dist` * publishes the server files and leaves `/` without an `index.html`. A * project that installs `void` only for its CLI keeps Vite's plain `dist`. */ -function viteSpaOutputDir(config: string | undefined): string { - return config && viteConfigImportsVoidPlugin(config, readFileSync(config, 'utf8')) - ? 'dist/client' - : 'dist'; +export function defaultViteClientDir( + root: string, + config: string | undefined = findViteConfig(root), +): string { + const usesVoid = config && viteConfigImportsVoidPlugin(config, readFileSync(config, 'utf8')); + return resolve(root, usesVoid ? 'dist/client' : 'dist'); +} + +function findViteConfig(root: string): string | undefined { + return VITE_CONFIG_FILES.map((name) => join(root, name)).find((path) => existsSync(path)); } function hasViteDependency(pkg: Record): boolean { diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index 0f5f8e2a9a..e1a3290c5d 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -90,6 +90,7 @@ import type { RouteEnvironment } from './router/parse-filename.ts'; import { resolveSandboxConfig } from './sandbox/config.ts'; import { CLOUDFLARE_DEPLOY_BUILD_ENV, loadLocalEnv, resolveRemoteMode } from './shared/env.ts'; import { getSsrServerEntryPath, validateSsrEntry } from './ssr/entry.ts'; +import { FRAMEWORK_WORKFLOWS_ERROR } from './workflows/platform.ts'; const scheduledPointerCleanups = new Set(); @@ -268,9 +269,7 @@ export function voidPlugin(options?: { } const workflows = application.workflows; if (detected && workflows.length > 0) { - throw new Error( - 'workflows: workflows/ is currently supported in Void apps only, not framework adapter mode.', - ); + throw new Error(FRAMEWORK_WORKFLOWS_ERROR); } for (const module of workflows) { const owner = diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index 5646463694..a4424b4edf 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -1346,6 +1346,7 @@ export function compileWorkerEntry(options: WorkerEntryOptions = {}): string { helpers: 'defineWorkflow() or defineWorkflowEntrypoint()', wrapClass: (workflowClass) => `__createWorkflowEntrypoint(${workflowClass}, { ${[ + isr && 'isrDeploymentId: __VOID_ISR_DEPLOYMENT_ID', envSchemaModule && 'validateEnv: _validateEnvOnce', remotePath && `remoteEnv: (env) => ${createRemoteEnvCall}`, ] diff --git a/packages/void/src/runtime/workflows/entry.ts b/packages/void/src/runtime/workflows/entry.ts index 50fc554b95..18189a4418 100644 --- a/packages/void/src/runtime/workflows/entry.ts +++ b/packages/void/src/runtime/workflows/entry.ts @@ -77,6 +77,7 @@ type Entrypoint = new ( export function createWorkflowEntrypoint( Workflow: Entrypoint, options: { + isrDeploymentId?: string; validateEnv?: (env: RuntimeEnv) => Promise; remoteEnv?: (env: RuntimeEnv) => RuntimeEnv; }, @@ -88,6 +89,9 @@ export function createWorkflowEntrypoint( override async run(event: Readonly>, step: WorkflowStep) { const env = this.env; + if (options.isrDeploymentId !== undefined) { + env.__VOID_ISR_DEPLOYMENT_ID ??= options.isrDeploymentId; + } if (options.validateEnv) { await options.validateEnv(env); } diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts index 0e1d1f3452..1363ebe008 100644 --- a/packages/void/src/runtime/workflows/index.ts +++ b/packages/void/src/runtime/workflows/index.ts @@ -2,7 +2,7 @@ import { WorkflowEntrypoint } from 'cloudflare:workers'; import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers'; import { isWorkflowName } from '../../shared/resource-name.ts'; import type { StandardSchemaV1 } from '../../standard-schema.ts'; -import { requireRuntimeBinding, withRuntimeEnv } from '../env/runtime.ts'; +import { getRuntimeEnv, requireRuntimeBinding, withRuntimeEnv } from '../env/runtime.ts'; export type { WorkflowEvent, WorkflowStep }; @@ -223,7 +223,7 @@ export function defineWorkflow( override run(event: Readonly>, step: WorkflowStep): Promise { const env = this.env; const ctx = this.ctx; - return withRuntimeEnv(env, () => run(event, step, { env, ctx })); + return withRuntimeEnv(env, () => run(event, step, { env: getRuntimeEnv(), ctx })); } } diff --git a/packages/void/src/shared/resource-definition.ts b/packages/void/src/shared/resource-definition.ts index 6394b5003b..9b1de28315 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -204,34 +204,53 @@ export function readResourceDefinition( return name; } - const declaration = unwrapStaticExpression(defaultExport); - const call = resolve(isIdentifier(declaration) ? definitions.get(declaration.name) : declaration); - if (!isCallExpression(call)) { - return null; - } - const callee = resolve(call.callee); - let helper: string | undefined; - if (isIdentifier(callee)) { - helper = - importedHelpers.get(callee.name) ?? - (convention !== 'workflows' && helpers.has(callee.name) ? callee.name : undefined); - } else if (isMemberExpression(callee) && isIdentifier(callee.object)) { - const property = - !callee.computed && isIdentifier(callee.property) - ? callee.property.name - : staticLiteral(callee.property); - if ( - typeof property === 'string' && - helpers.has(property) && - namespaces.get(callee.object.name)?.has(property) - ) { - helper = property; + function resourceCall(node: AstNode | undefined) { + const call = resolve(node); + if (!isCallExpression(call)) { + return null; + } + const callee = resolve(call.callee); + let helper: string | undefined; + if (isIdentifier(callee)) { + helper = + importedHelpers.get(callee.name) ?? + (convention !== 'workflows' && helpers.has(callee.name) ? callee.name : undefined); + } else if (isMemberExpression(callee) && isIdentifier(callee.object)) { + const property = + !callee.computed && isIdentifier(callee.property) + ? callee.property.name + : staticLiteral(callee.property); + if ( + typeof property === 'string' && + helpers.has(property) && + namespaces.get(callee.object.name)?.has(property) + ) { + helper = property; + } } + if (!helper) { + return null; + } + return { helper, options: resolve(call.arguments?.[0]) }; } - if (!helper) { + + const declaration = unwrapStaticExpression(defaultExport); + const definition = resourceCall( + isIdentifier(declaration) ? definitions.get(declaration.name) : declaration, + ); + if (!definition) { + if (convention === 'workflows') { + const hasWorkflow = + [...definitions.values()].some(resourceCall) || + program.body?.some( + (node) => node.type === 'ExpressionStatement' && resourceCall(node.expression as AstNode), + ); + if (hasWorkflow) { + throw new Error(`workflows: ${filename} must default-export its Workflow definition.`); + } + } return null; } - const definitionOptions = resolve(call.arguments?.[0]); - const name = readName(definitionOptions).value; - return { helper, options: definitionOptions, ...(name === undefined ? {} : { name }) }; + const name = readName(definition.options).value; + return { ...definition, ...(name === undefined ? {} : { name }) }; } diff --git a/packages/void/src/workflows/platform.ts b/packages/void/src/workflows/platform.ts index b06544ff3c..c88b69a14e 100644 --- a/packages/void/src/workflows/platform.ts +++ b/packages/void/src/workflows/platform.ts @@ -1,5 +1,8 @@ import { scanWorkflowModules } from './scan.ts'; +export const FRAMEWORK_WORKFLOWS_ERROR = + 'workflows: workflows/ is currently supported in Void apps only, not framework adapter mode.'; + /** Void platform deploys do not provision Cloudflare Workflows yet. */ export function assertNoWorkflowsForPlatform(root: string): void { if (scanWorkflowModules(root).length > 0) { diff --git a/packages/void/test/integration/full-deploy-manifest.test.ts b/packages/void/test/integration/full-deploy-manifest.test.ts index 3447b75443..eed52fd8b3 100644 --- a/packages/void/test/integration/full-deploy-manifest.test.ts +++ b/packages/void/test/integration/full-deploy-manifest.test.ts @@ -227,7 +227,11 @@ describe('managed deployment manifests (built Worker)', () => { "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", ); const captured = installPlatformMocks(); - await runDeploy(fixture, { dir: 'dist/client' }); + await expect(runDeploy(fixture, { platform: 'void' })).rejects.toThrow( + 'not supported on Void platforms', + ); + expect(fetchMock).not.toHaveBeenCalled(); + await runDeploy(fixture, { platform: 'void', dir: 'dist/client' }); expect(captured.finalizeBody?.manifest).toMatchObject({ type: 'static', bindings: {} }); } finally { rmSync(workflows, { recursive: true, force: true }); diff --git a/packages/void/test/integration/workflow-runtime.test.ts b/packages/void/test/integration/workflow-runtime.test.ts index a0bc302232..feb82e24be 100644 --- a/packages/void/test/integration/workflow-runtime.test.ts +++ b/packages/void/test/integration/workflow-runtime.test.ts @@ -1,6 +1,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { isrKey } from '@void/isr/runtime'; import { Miniflare, convertV4MiniflareOptions } from 'miniflare'; import { build } from 'vite'; import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'; @@ -181,6 +182,7 @@ export default defineEnv({ VALUE: { '~standard': { ` import { WorkflowEntrypoint } from 'cloudflare:workers'; import { env } from ${JSON.stringify(envPath)}; +import { revalidate } from ${JSON.stringify(join(root, 'packages/void/src/runtime/isr/index.ts'))}; import { db, setSession } from ${JSON.stringify(join(root, 'packages/void/src/runtime/db/index.ts'))}; import { defineWorkflow, defineWorkflowEntrypoint } from ${JSON.stringify(runtimePath)}; async function run(event, step) { @@ -188,6 +190,7 @@ async function run(event, step) { setSession('first-primary'); return step.do('read', { retries: { limit: 0, delay: 0 } }, async () => { setSession('first-primary'); + await revalidate({ all: true }); return { value: value + 1, sameSession: db.$client === db.$client }; }); } @@ -196,8 +199,11 @@ ${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'cla ); const output = await buildWorker( 'cold-' + helper, - 'export default { fetch: () => new Response() };', + `export const __VOID_ISR_DEPLOYMENT_ID = 'cold-build'; +export const __VOID_ISR_REVALIDATE = 60, __VOID_ISR_PAGES = [], __VOID_ISR_PATH_REVALIDATE = undefined; +export default { fetch: () => new Response() };`, { + isr: { runtimePath: join(root, 'packages/isr/src/runtime.ts') }, envSchemaModule: { importPath: schema, helperPath: envPath }, workflows: [{ bindingName: 'COLD', className: 'ColdWorkflow', filePath: definition }], }, @@ -211,11 +217,17 @@ ${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'cla scriptPath: join(output, 'worker.mjs'), bindings: { VALUE: '41' }, d1Databases: { DB: 'test' }, + kvNamespaces: ['ISR_CACHE'], workflows: { COLD: { name: 'cold', className: 'ColdWorkflow' } }, }), ); try { - const { COLD } = await worker.getBindings<{ COLD: Workflow }>(); + const { COLD, ISR_CACHE } = await worker.getBindings<{ + COLD: Workflow; + ISR_CACHE: KVNamespace; + }>(); + const cachedPage = isrKey('cold-build', 'example.test', '/news'); + await ISR_CACHE.put(cachedPage, 'cached'); const instance = await COLD.create(); await expect .poll(async () => (await instance.status()).status, { @@ -226,6 +238,7 @@ ${helper === 'defineWorkflow' ? 'export default defineWorkflow({ run });' : 'cla status: 'complete', output: { value: 42, sameSession: true }, }); + expect(await ISR_CACHE.get(cachedPage)).toBeNull(); } finally { await worker.dispose(); } diff --git a/packages/void/test/unit/cloudflare-classify.test.ts b/packages/void/test/unit/cloudflare-classify.test.ts index 13bac71d7c..d4338c0c6a 100644 --- a/packages/void/test/unit/cloudflare-classify.test.ts +++ b/packages/void/test/unit/cloudflare-classify.test.ts @@ -46,6 +46,15 @@ describe('classifyCloudflareDeployApp', () => { expect(resolveCloudflareStaticPreset(root, {}, {})).toBeNull(); expect(classify(root, {})).toEqual({ supported: true }); expect(classify(root, { inference: { appType: 'void' } })).toEqual({ supported: true }); + + writeFileSync( + join(root, 'package.json'), + JSON.stringify({ dependencies: { '@sveltejs/kit': '*' } }), + ); + expect(classify(root, {})).toEqual({ + supported: false, + reason: expect.stringContaining('framework adapter mode'), + }); }); it('keeps the full Worker when Pages are prerendered and a Workflow is declared', async () => { diff --git a/packages/void/test/unit/deploy-artifact-preparation.test.ts b/packages/void/test/unit/deploy-artifact-preparation.test.ts index e1d599ad9a..f01255bfe9 100644 --- a/packages/void/test/unit/deploy-artifact-preparation.test.ts +++ b/packages/void/test/unit/deploy-artifact-preparation.test.ts @@ -199,6 +199,23 @@ it('allows an explicit asset-only deploy from a project with Workflows', async ( expect(result.artifact.workerFiles).toBeUndefined(); }); +it.each(['static', 'spa'])( + 'packages only browser assets for an explicit %s Void app with routes', + async (appType) => { + mkdirSync(join(root, 'routes')); + writeFileSync( + join(root, 'vite.config.ts'), + "import { voidPlugin } from 'void'; export default { plugins: [voidPlugin()] };", + ); + writeFileSync( + join(root, 'void.config.ts'), + `export default { inference: { appType: '${appType}' } };`, + ); + const result = await prepareDeployArtifact(root); + expect(Object.keys(result.assets)).toEqual(['/index.html']); + }, +); + it('keeps SPA plus API apps on the Worker deployment path', async () => { writeFileSync(join(root, 'package.json'), JSON.stringify({ devDependencies: { vite: '*' } })); mkdirSync(join(root, 'routes')); diff --git a/packages/void/test/unit/init.test.ts b/packages/void/test/unit/init.test.ts index ae8bb331b6..5e573be32c 100644 --- a/packages/void/test/unit/init.test.ts +++ b/packages/void/test/unit/init.test.ts @@ -2478,6 +2478,7 @@ describe('isScaffoldableEmptyProject', () => { const tsconfig = JSON.parse(readFileSync(join(root, 'tsconfig.json'), 'utf8')); expect(tsconfig.compilerOptions.jsx).toBe('react-jsx'); expect(tsconfig.include).toContain('pages'); + expect(tsconfig.include).toContain('workflows'); expect(tsconfig.include).toContain('db'); expect(mockLogInfo).toHaveBeenCalledWith('Empty project detected. Creating a Pages starter.'); diff --git a/packages/void/test/unit/workflow-runtime.test.ts b/packages/void/test/unit/workflow-runtime.test.ts index 53f64847f6..f6f705444b 100644 --- a/packages/void/test/unit/workflow-runtime.test.ts +++ b/packages/void/test/unit/workflow-runtime.test.ts @@ -104,11 +104,20 @@ describe('defineWorkflow', () => { const Welcome = defineWorkflow({ async run(event: WorkflowEvent<{ userId: string }>, step, context) { seen.push(event.payload.userId, context.env.GREETING, getRuntimeEnv().GREETING); + expect(Object.keys(context.env)).toEqual(['GREETING']); + expect(context.env.__VOID_MARKER).toBeUndefined(); + expect('ISR_CACHE' in context.env).toBe(false); return step.do('greet', async () => 'done'); }, }); const step = { do: vi.fn(async (_name: string, fn: () => Promise) => fn()) }; - const instance = new Welcome.class({} as ExecutionContext, { GREETING: 'hello' }); + const instance = new Welcome.class({} as ExecutionContext, { + GREETING: 'hello', + __VOID_MARKER: true, + __PROJECT_ID: 'project', + __VOID_ISR_DEPLOYMENT_ID: 'build', + ISR_CACHE: {}, + }); expect(instance).toBeInstanceOf(WorkflowEntrypoint); const result = await instance.run( { payload: { userId: 'u1' } } as WorkflowEvent<{ userId: string }>, diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts index 824397d2d8..460f075d1d 100644 --- a/packages/void/test/unit/workflow-scan.test.ts +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -92,14 +92,22 @@ describe('scanWorkflowModules', () => { const Job = defineWorkflow({ name: 'daily', async run() {} });`; const root = createRoot({ 'digest.ts': `${source}\nexport { Job, Job as default };`, - 'types.ts': `${source}\nexport { type Job as default };`, - 'other.ts': `${source}\nexport { Job as default } from './digest';`, + 'types.ts': "export { type Job as default } from './digest';", + 'other.ts': "export { Job as default } from './digest';", }); expect(scanWorkflowModules(root).map(({ relativePath, name }) => [relativePath, name])).toEqual( [['digest.ts', 'daily']], ); }); + it.each([ + "import { defineWorkflow as job } from 'void/workflows'; export const Nightly = job({ async run() {} });", + "import * as wf from 'void/workflows'; const Nightly = wf.defineWorkflowEntrypoint({ class: Job }); export default {};", + ])('reports a Workflow definition missing its default export', (source) => { + const root = createRoot({ 'nested/nightly.ts': source }); + expect(() => scanWorkflowModules(root)).toThrow(/nightly\.ts.*default.export/i); + }); + it('ignores files and directories starting with an underscore', () => { const root = createRoot({ 'welcome.ts': definition, From c225a3e1555c2d1042ec263bdd0ae0b502a781ba Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 12:06:33 +0900 Subject: [PATCH 07/13] Fix Workflow schedule recovery, discovery, and deployment contracts. --- .github/scripts/packed-consumer.mjs | 8 +- docs/guide/workflows.md | 6 +- docs/reference/config.md | 2 +- docs/reference/structure.md | 2 +- packages/deploy-cloudflare/src/existing.ts | 5 + packages/deploy-cloudflare/src/operations.ts | 14 ++ packages/deploy-cloudflare/src/version.ts | 134 ++++++++++++++---- .../test/unit/version.test.ts | 133 ++++++++++++++--- packages/void/AGENTS.md | 2 +- packages/void/src/cli/cf-version-runner.ts | 7 + .../src/cli/cloudflare-operation-process.ts | 79 ++++++++++- .../void/src/cli/deploy-cloudflare-helpers.ts | 36 ++++- packages/void/src/cli/deploy-helpers.ts | 2 +- packages/void/src/cli/preset.ts | 28 +++- packages/void/src/runtime/workflows/index.ts | 19 ++- .../void/src/shared/resource-definition.ts | 45 +++++- packages/void/src/workflows/scan.ts | 5 +- .../cloudflare-durable-build.test.ts | 2 +- .../void/test/unit/cf-version-runner.test.ts | 49 ++++--- .../void/test/unit/cloudflare-deploy.test.ts | 38 ++++- .../unit/cloudflare-operation-process.test.ts | 79 +++++++++++ .../void/test/unit/deploy-project.test.ts | 36 +++++ .../test/unit/workflow-runtime.typecheck.ts | 12 ++ packages/void/test/unit/workflow-scan.test.ts | 32 ++++- 24 files changed, 683 insertions(+), 92 deletions(-) diff --git a/.github/scripts/packed-consumer.mjs b/.github/scripts/packed-consumer.mjs index 6072449505..ba71cac2da 100644 --- a/.github/scripts/packed-consumer.mjs +++ b/.github/scripts/packed-consumer.mjs @@ -331,9 +331,13 @@ try { writeFileSync( join(fixture, 'workflow.mts'), `import { defineWorkflow } from 'void/workflows'; -export default defineWorkflow<{ id: string }>({ +const job = defineWorkflow<{ id: string }>({ async run(event, step) { return step.do('id', async () => event.payload.id); }, -});`, +}); +declare const receiver: Workflow<{ id: string; recipient: string }>; +// @ts-expect-error The receiver also requires a recipient. +void job.create(receiver, { params: { id: '1' } }); +export default job;`, ); writeFileSync( join(fixture, 'tsconfig.workflow.json'), diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md index cc9a547a7f..3a1b16404f 100644 --- a/docs/guide/workflows.md +++ b/docs/guide/workflows.md @@ -33,7 +33,7 @@ export default Onboarding; Default-export the object returned by `defineWorkflow()`. Named-export it too so routes can import it. -TypeScript and JavaScript files are supported, including subdirectories. Void discovers default exports created using a helper imported from `void/workflows`. Files and directories starting with `_` are excluded from Workflow discovery. If you maintain an explicit `include` list in `tsconfig.json`, add `workflows` so TypeScript checks definitions started outside your app. +Keep `workflows/` at the project root, including when `sourceDir` is set. Write Workflow definitions as TypeScript or JavaScript ES modules with an import from `void/workflows` and a default export. In CommonJS projects, use `.mjs` or `.mts` for definitions. Subdirectories are supported. Files and directories starting with `_` are excluded from Workflow discovery. If you maintain an explicit `include` list in `tsconfig.json`, add `workflows` so TypeScript checks definitions started outside your app. `run` receives: @@ -127,9 +127,9 @@ Void derives the names from the file's path in `workflows/`, joining directories - the `WORKFLOW_SEND_WELCOME` binding - the exported `SendWelcomeWorkflow` class -- a Cloudflare Workflow named `-send-welcome`, since Workflow names must be unique within your Cloudflare account +- a Cloudflare Workflow named `_send-welcome`, since Workflow names must be unique within your Cloudflare account -`workflows/order/notifications.ts` creates `WORKFLOW_ORDER_NOTIFICATIONS`, `OrderNotificationsWorkflow`, and `-order-notifications`. A path that starts with a digit, such as `2026-report.ts`, exports the class `Workflow2026Report` and uses the binding `WORKFLOW_2026_REPORT`. Each Workflow must have a unique name. +`workflows/order/notifications.ts` creates `WORKFLOW_ORDER_NOTIFICATIONS`, `OrderNotificationsWorkflow`, and `_order-notifications`. A path that starts with a digit, such as `2026-report.ts`, exports the class `Workflow2026Report` and uses the binding `WORKFLOW_2026_REPORT`. Each Workflow must have a unique name. Instances belong to the Workflow name. Changing the generated Workflow name directs new instances to a different Workflow. To move a file without changing its name, run `void info` first and add the name it suggests: diff --git a/docs/reference/config.md b/docs/reference/config.md index 6e736bface..1bd9bcde68 100644 --- a/docs/reference/config.md +++ b/docs/reference/config.md @@ -62,7 +62,7 @@ When set, those conventions move under the configured directory: { "sourceDir": "src" } ``` -With that config, Void reads `src/pages`, `src/routes`, `src/db/schema.ts`, `src/db/migrations`, `src/auth.ts`, and `src/env.ts`. Project files such as `void.config.ts`, `vite.config.ts`, `package.json`, `tsconfig.json`, `public/`, and the local-only `.env` stay at the project root. Keep source files in the configured directory. Duplicate conventions at the root and under `sourceDir` cause a build error. +With that config, Void reads `src/pages`, `src/routes`, `src/db/schema.ts`, `src/db/migrations`, `src/auth.ts`, and `src/env.ts`. Project files such as `void.config.ts`, `vite.config.ts`, `package.json`, `tsconfig.json`, `public/`, and the local-only `.env` stay at the project root. Keep those source files in the configured directory. Workflow definitions stay in `workflows/` at the project root. Duplicate conventions at the root and under `sourceDir` cause a build error. ### `ai` diff --git a/docs/reference/structure.md b/docs/reference/structure.md index 59b9ecb7d4..e78b0fb39f 100644 --- a/docs/reference/structure.md +++ b/docs/reference/structure.md @@ -129,7 +129,7 @@ Generate schema with `void gen model` or write it by hand. Generate migrations w ## `workflows/` -[Workflow](/guide/workflows) modules. Each file default-exports a `defineWorkflow()` or `defineWorkflowEntrypoint()` definition. +[Workflow](/guide/workflows) modules. This directory stays at the project root when `sourceDir` is configured. Each Workflow module default-exports a `defineWorkflow()` or `defineWorkflowEntrypoint()` definition. ## `src/` diff --git a/packages/deploy-cloudflare/src/existing.ts b/packages/deploy-cloudflare/src/existing.ts index 202d3fa419..4a53a81107 100644 --- a/packages/deploy-cloudflare/src/existing.ts +++ b/packages/deploy-cloudflare/src/existing.ts @@ -13,6 +13,7 @@ import { cloudflareStagingPairGuidance } from './staging-guidance.ts'; export type ExistingCloudflareWorker = { versionId: string; + versionMessage?: string; bindings: Array>; runtime: Record; script: Record; @@ -145,6 +146,10 @@ async function readCloudflareWorker( return { snapshot: { versionId, + ...(isRecord(version.annotations) && + typeof version.annotations['workers/message'] === 'string' + ? { versionMessage: version.annotations['workers/message'] } + : {}), bindings: resources.bindings, runtime: resources.script_runtime, script: resources.script, diff --git a/packages/deploy-cloudflare/src/operations.ts b/packages/deploy-cloudflare/src/operations.ts index 4ce4930534..6bd7cc8a82 100644 --- a/packages/deploy-cloudflare/src/operations.ts +++ b/packages/deploy-cloudflare/src/operations.ts @@ -4,6 +4,14 @@ import type { R2LocationHint } from '@void/deploy-core'; type ConfigTarget = { configPath?: string }; type WorkerTarget = ConfigTarget & { workerName?: string }; +export type WorkflowScheduleCleanup = { + workflowName: string; + className: string; + limits?: unknown; + concurrency?: unknown; + default_retention?: unknown; +}; + export type CloudflareOperation = | ({ type: 'auth.whoami' | 'auth.login' | 'auth.logout' | 'auth.token' } & ConfigTarget) | ({ @@ -79,6 +87,12 @@ export type CloudflareOperation = | ({ type: 'previews.delete'; previewName: string } & WorkerTarget) | ({ type: 'triggers.deploy'; assets?: boolean } & WorkerTarget) | ({ type: 'triggers.clear-crons' | 'triggers.clear-domains' } & WorkerTarget) + | ({ + type: 'triggers.clear-workflow-schedules'; + workerName: string; + inspectOnly?: boolean; + } & WorkflowScheduleCleanup & + ConfigTarget) | ({ type: 'tail'; search?: string; versionId?: string; status?: 'error' } & WorkerTarget); export type CloudflareUploadResult = { diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 7f7d9da7a9..4fd4908bc8 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -14,7 +14,7 @@ import { isWorkerNotFound, } from './execute.ts'; import type { CloudflareCommandResult, CloudflareCommandRunner } from './execute.ts'; -import type { CloudflareUploadResult } from './operations.ts'; +import type { CloudflareUploadResult, WorkflowScheduleCleanup } from './operations.ts'; import { isVoidSecretDraftHeader, isVoidSecretOnlyDraft, @@ -58,6 +58,8 @@ export type CloudflareTriggerConfig = Readonly<{ crons: ReadonlyArray; queueConsumers: ReadonlyArray; workflows: ReadonlyArray; + /** Replay a previous name's schedule removal until the provider confirms it is clear. */ + workflowScheduleCleanup?: ReadonlyArray; /** * Email Routing addresses (`addresses` in Wrangler config). The Cloudflare CLI applies its * Email Routing plan inside `triggers deploy` — `undefined` skips the plan entirely, while @@ -282,15 +284,7 @@ export async function deployCloudflareVersionTriggers(options: { // config so an ephemeral assets directory (or another bundle-only field) cannot break the // post-activation reconciliation after `versions upload` has already consumed it. const base = pickWranglerTriggerContext(source); - const config = triggerWranglerConfig( - base, - triggerConfigWithRemovedWorkflowSchedules( - options.workerName, - options.triggerConfig, - options.previousTriggerConfig, - ), - options.manageRoutes, - ); + const config = triggerWranglerConfig(base, options.triggerConfig, options.manageRoutes); const directory = mkdtempSync(join(tmpdir(), 'void-version-triggers-')); const configPath = join(directory, 'wrangler.json'); try { @@ -302,6 +296,29 @@ export async function deployCloudflareVersionTriggers(options: { if (!isCleanCommandExit(deployed)) { return deployed; } + for (const workflow of workflowsToClear( + options.workerName, + options.triggerConfig, + options.previousTriggerConfig?.workflows, + [ + ...(options.previousTriggerConfig?.workflowScheduleCleanup ?? []), + ...(options.triggerConfig.workflowScheduleCleanup ?? []), + ], + )) { + const cleared = await options.runWrangler( + { + ...workflow, + type: 'triggers.clear-workflow-schedules', + workerName: options.workerName, + configPath, + inspectOnly: false, + }, + { capture: true }, + ); + if (!isCleanCommandExit(cleared)) { + return cleared; + } + } if (options.triggerConfig.crons.length === 0 && options.publishEmptyCrons) { const published = await options.publishEmptyCrons(); if (!isCleanCommandExit(published)) { @@ -511,6 +528,7 @@ function mergeTriggerCleanupBaselines( crons: unique(present.flatMap((config) => config.crons)), queueConsumers: unique(present.flatMap((config) => config.queueConsumers)), workflows: unique(present.flatMap((config) => config.workflows)), + workflowScheduleCleanup: present.flatMap((config) => config.workflowScheduleCleanup ?? []), ...(withAddresses.length === 0 ? {} : { addresses: [...new Set(withAddresses.flatMap((config) => config.addresses ?? []))] }), @@ -568,34 +586,79 @@ function triggerConfigWithQueueConsumerCleanup( }; } -function triggerConfigWithRemovedWorkflowSchedules( +function workflowsToClear( workerName: string, desired: CloudflareTriggerConfig, - previous: CloudflareTriggerConfig | undefined, -): CloudflareTriggerConfig { - if (!previous) { - return desired; - } + previous: ReadonlyArray = [], + outstanding: ReadonlyArray = [], +): Array { const desiredNames = new Set( desired.workflows.flatMap((workflow) => isRecord(workflow) && typeof workflow.name === 'string' ? [workflow.name] : [], ), ); - const removed = previous.workflows.flatMap((workflow) => { + const pending = new Map(); + for (const cleanup of outstanding) { + if (!desiredNames.has(cleanup.workflowName)) { + pending.set(cleanup.workflowName, cleanup); + } + } + for (const workflow of previous) { if ( !isRecord(workflow) || typeof workflow.name !== 'string' || typeof workflow.class_name !== 'string' || + !Array.isArray(workflow.schedules) || + workflow.schedules.length === 0 || desiredNames.has(workflow.name) || (typeof workflow.script_name === 'string' && workflow.script_name !== workerName) ) { - return []; + continue; } - return [{ ...workflow, schedules: [] }]; - }); - return removed.length === 0 - ? desired - : { ...desired, workflows: [...desired.workflows, ...removed] }; + pending.set(workflow.name, { + workflowName: workflow.name, + className: workflow.class_name, + limits: workflow.limits, + concurrency: workflow.concurrency, + default_retention: workflow.default_retention, + }); + } + return [...pending.values()]; +} + +// After an atomic publication the version can stay live even if trigger sync fails. +// Carry unconfirmed removals into its successor; a successful read retires the record. +async function recordWorkflowScheduleCleanup( + options: CloudflareVersionActivationOptions, + desired: CloudflareTriggerConfig, + previous: CloudflareTriggerConfig, +): Promise { + const removed = workflowsToClear(options.workerName, desired, previous.workflows); + const candidates = workflowsToClear( + options.workerName, + desired, + [], + previous.workflowScheduleCleanup, + ); + for (const candidate of candidates) { + if (removed.some(({ workflowName }) => workflowName === candidate.workflowName)) { + continue; + } + const inspected = await options.runWrangler( + { + ...candidate, + type: 'triggers.clear-workflow-schedules', + workerName: options.workerName, + configPath: options.configPath, + inspectOnly: true, + }, + { capture: true }, + ); + if (!isCleanCommandExit(inspected) || inspected.data !== false) { + removed.push(candidate); + } + } + return removed.length ? { ...desired, workflowScheduleCleanup: removed } : desired; } function hasCustomDomains(routes: ReadonlyArray | undefined): boolean { @@ -691,6 +754,7 @@ function parseTriggerConfig(value: unknown): CloudflareTriggerConfig | null { return null; } const addresses = readEmailAddresses(value.addresses); + const cleanup = value.workflowScheduleCleanup; if ( ['preserve', 'preserveRoutes', 'preserveWorkersDev', 'preservePreviewUrls', 'logpush'].some( (key) => value[key] !== undefined && typeof value[key] !== 'boolean', @@ -703,6 +767,14 @@ function parseTriggerConfig(value: unknown): CloudflareTriggerConfig | null { !Array.isArray(value.crons) || !Array.isArray(value.queueConsumers) || !Array.isArray(value.workflows) || + (cleanup !== undefined && + (!Array.isArray(cleanup) || + !cleanup.every( + (entry): entry is WorkflowScheduleCleanup => + isRecord(entry) && + typeof entry.workflowName === 'string' && + typeof entry.className === 'string', + ))) || (value.addresses !== undefined && addresses === undefined) ) { return null; @@ -721,6 +793,7 @@ function parseTriggerConfig(value: unknown): CloudflareTriggerConfig | null { crons: value.crons, queueConsumers: value.queueConsumers, workflows: value.workflows, + ...(cleanup && { workflowScheduleCleanup: cleanup }), ...(addresses === undefined ? {} : { addresses }), }; } @@ -1199,12 +1272,23 @@ async function activateCloudflareVersionWithSecretsFile( } desiredTriggerConfig = resolved; } + const versionedPreviousTriggerConfig = + previousMetadata?.schema === 2 ? previousMetadata.triggerConfig : undefined; + if ( + versionedPreviousTriggerConfig && + !desiredTriggerConfig.preserve && + !options.preserveTriggers + ) { + desiredTriggerConfig = await recordWorkflowScheduleCleanup( + options, + desiredTriggerConfig, + versionedPreviousTriggerConfig, + ); + } const message = desiredMetadata?.schema === 2 ? encodeCloudflareVersionMessage(desiredMetadata.migrations, desiredTriggerConfig) : options.message; - const versionedPreviousTriggerConfig = - previousMetadata?.schema === 2 ? previousMetadata.triggerConfig : undefined; const versionedPreviousTriggerConfigWithTraffic = versionedPreviousTriggerConfig && previousTrafficConfig ? { ...versionedPreviousTriggerConfig, ...previousTrafficConfig } diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index 50966c92ea..67955e65b2 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -18,7 +18,10 @@ import type { CloudflareOperation, CloudflareTriggerConfig, } from '../../src/index.ts'; -import { STALE_VERSION_HISTORY_DELAYS_MS } from '../../src/version.ts'; +import { + stabilizeCloudflareVersionTriggers, + STALE_VERSION_HISTORY_DELAYS_MS, +} from '../../src/version.ts'; import { operationFixture } from '../operation-fixture.ts'; import { apiSecretDraftVersion, voidSecretDraftVersion } from '../secret-draft-fixture.ts'; @@ -2759,24 +2762,120 @@ describe('Cloudflare version activation', () => { ]); }); - it('clears schedules without deleting removed workflow state', async () => { - let applied: Record | undefined; - await deployCloudflareVersionTriggers({ - runWrangler: operationFixture(async (args) => { - applied = readConfigArg(args); - return ok(); - }), + it('retains failed schedule cleanup across atomic deploy retries and retires it after success', async () => { + const old = { + name: 'nightly', + binding: 'JOB', + class_name: 'Job', + schedules: ['0 0 * * *'], + concurrency: { limit: 2 }, + }; + const desired = encodeCloudflareVersionMessage( + [], + triggersWith({ workflows: [{ ...old, name: 'pinned' }] }), + ); + let activeMessage = encodeCloudflareVersionMessage([], triggersWith({ workflows: [old] })); + let scheduled = true; + const operations: Array = []; + for (const attempt of [1, 2, 3]) { + const fixture = recoveryActivation({ + atomic: true, + previous: { id: CURRENT, number: 1, annotations: { 'workers/message': activeMessage } }, + }); + const outcome = await activateCloudflareVersion({ + ...fixture.options, + message: desired, + runWrangler: async (operation) => { + if (operation.type === 'worker.deploy') { + activeMessage = operation.message ?? ''; + } + if (operation.type === 'triggers.clear-workflow-schedules') { + expect(operation).toMatchObject({ + workflowName: 'nightly', + className: 'Job', + concurrency: { limit: 2 }, + }); + operations.push(operation.inspectOnly ? 'inspect' : 'clear'); + if (operation.inspectOnly) { + return { ...ok(), data: scheduled }; + } + if (attempt === 1) { + return { status: 1, stdout: '', stderr: '503' }; + } + scheduled = false; + return ok(); + } + return fixture.options.runWrangler(operation); + }, + }); + expect(outcome.ok, JSON.stringify(outcome)).toBe(attempt !== 1); + expect(activeMessage.includes('workflowScheduleCleanup')).toBe(attempt < 3); + } + expect(operations).toEqual(['clear', 'inspect', 'clear', 'inspect', 'clear']); + }); + + it('finishes pending schedule cleanup when rolling back to a version from before the Workflow', async () => { + const cleanup = { workflowName: 'nightly', className: 'Job' }; + const cleared: Array = []; + const result = await stabilizeCloudflareVersionTriggers({ workerName: 'app', - triggerConfig: triggersWith(), - previousTriggerConfig: triggersWith({ - workflows: [{ name: 'nightly', class_name: 'NightlyWorkflow', schedules: ['0 0 * * *'] }], - }), + targetVersionId: CURRENT, + targetTriggerConfig: triggersWith(), + previousTriggerConfig: triggersWith({ workflowScheduleCleanup: [cleanup] }), + runWrangler: async (operation) => { + if (operation.type === 'deployments.status') { + return { ...ok(), data: { versions: [{ version_id: CURRENT, percentage: 100 }] } }; + } + if (operation.type === 'triggers.clear-workflow-schedules') { + cleared.push(operation.workflowName); + } + return ok(); + }, }); - - expect(applied?.workflows).toEqual([ - { name: 'nightly', class_name: 'NightlyWorkflow', schedules: [] }, - ]); - }); + expect(result.ok).toBe(true); + expect(cleared).toEqual(['nightly']); + }); + + it.each([0, 1])( + 'clears a renamed Workflow schedule separately and returns its exit status %s', + async (status) => { + const old = { name: 'nightly', binding: 'JOB', class_name: 'Job', schedules: ['0 0 * * *'] }; + const current = { ...old, name: 'pinned' }; + const cleared: Array = []; + const result = await deployCloudflareVersionTriggers({ + runWrangler: async (operation) => { + if (operation.type === 'triggers.deploy' && operation.configPath) { + expect(JSON.parse(readFileSync(operation.configPath, 'utf8')).workflows).toEqual([ + current, + ]); + return ok(); + } + expect(operation).toMatchObject({ + type: 'triggers.clear-workflow-schedules', + workerName: 'app', + className: 'Job', + }); + if (operation.type === 'triggers.clear-workflow-schedules') { + cleared.push(operation.workflowName); + } + return { status, stdout: '', stderr: '' }; + }, + workerName: 'app', + triggerConfig: triggersWith({ workflows: [current] }), + previousTriggerConfig: triggersWith({ + workflows: [ + old, + old, + current, + { ...old, name: 'external', script_name: 'elsewhere' }, + { ...old, name: 'unscheduled', schedules: [] }, + ], + }), + }); + expect(cleared).toEqual(['nightly']); + expect(result.status).toBe(status); + }, + ); it('publishes an explicit empty set when removing the final custom domain', async () => { const publishEmptyCustomDomains = vi.fn(async () => ok()); diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index 57a6aefaa3..3628273991 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -148,7 +148,7 @@ generated entries must preserve the module-boundary rules below. - **Framework env schema**: `env` has no schema in a Worker whose own modules have not loaded `env.ts`, whatever the Vite plugin loaded in its process, so it returns raw values. The Class A wrapper (TanStack Start, React Router, vinext) imports `env.ts` ahead of the framework entry and awaits `_prepareEnv(env)` on every request, in dev and build. Unlike `_validateEnvOnce`, it never rejects: a read of a key that failed throws that key's error, async validators included, so requests that do not read it and a build-time prerender without production secrets still run. Both keep one result per key, reuse a validation for the same raw values, and keep the results with the env object they received. Reads through another object (the `cloudflare:workers` env that a D1 app's framework reads outside a request scope, the remote dev copy) get the latest validation's result while they hold the raw value it came from; never copy results to that object, which can come to hold other values. A validation in which a validator threw serves its reads but runs again on the next call. Results live on the process-global registry because `void deploy` bundles cron and queue jobs apart from the app, with a copy of `void/env` of their own: the jobs call `registry.prepare`, the `_prepareEnv` of the copy that registered the schema (key in `shared/env-registry.ts`). SvelteKit, Nuxt, Analog and Astro Workers do not load `env.ts` yet. - **Reserved `__VOID_*` names**: `envSchemaPlugin.config` (every mode, with or without `env.ts`) and `void env check` reject `__VOID_*` names in the root `.env` or declared in `env.ts`. Do not try to strip them from dev `vars` instead: Wrangler reads `.env` itself and writes it over `vars`, so a strip cannot be enforced. Manual trigger auth is a compile-time literal (`__VOID_SERVE` from `CompileOptions.dev`, false in builds and `vite preview`): dev accepts only `x-void-dev-trigger`, builds use the proxy token or build key. Never key it on `import.meta.env.DEV`, which is true in a `NODE_ENV=development` build. - **Typed Durable State convention**: each default-exported `defineDurableState()` definition in `durable-objects/*.ts` becomes a filename-derived binding and worker class (`shopping-cart.ts` → `SHOPPING_CART` / `ShoppingCartDurableObject`). The generated entry calls the internal `__bind()` hook so named imports can use `State.get(name)` without touching `c.env`, exports `State.class`, and emits a stable `new_sqlite_classes` migration. `syncWranglerDurableObjects()` persists bindings and append-only class migration history in `void.lock.json` through the generated Cloudflare config; never regenerate migration order solely from the current sorted files. The generated class extends `DurableObject` from `cloudflare:workers` so namespace stubs expose real RPC methods; runtime state and helpers use JavaScript private fields and methods. Runtime operations are serialized and persisted after successful typed RPC, `fetch`, or `alarm` handlers; versioned value migrations run on load. This is native-Void + Cloudflare only and is supported by direct Cloudflare deploys. Typed `*.ws.ts` routes likewise use SQLite-backed classes; their root-config sync uses the comment-preserving writer, retains legacy `new_classes` histories, and appends a new migration tag only for new classes. -- **Workflows convention**: each default-exported `defineWorkflow()` / `defineWorkflowEntrypoint()` under `workflows/` becomes `WORKFLOW_` / `Workflow` (`send-welcome.ts` → `WORKFLOW_SEND_WELCOME` / `SendWelcomeWorkflow`), bound through the same `__bind()` hook as Durable State. The binding prefix matches `QUEUE_*`. Discovery follows `queues/` rather than `durable-objects/`: subdirectories are joined with `-` (`order/notifications.ts` → `order-notifications`) and `_`-prefixed path segments are skipped. Workflows need no class migrations, so they are not written to `void.lock.json`; `mergeWorkerBindings()` emits only the additions (the Cloudflare plugin concatenates arrays) via `planWorkflowAdditions()`, naming each `-` because Workflow names are account-scoped. `void deploy --platform cloudflare` passes its Worker name to the build as `VOID_CLOUDFLARE_WORKER_NAME`, and `reconstructExpectedWorkflows()` pins the exact emitted set for `verifyGeneratedDeployConfig()`. An authored entry with the same binding and class keeps its name. Void platform deploys, framework mode and Node targets reject `workflows/` until platform provisioning exists. The generated entry imports convention modules through their namespace and fails Worker startup with a named error when the default export is not a definition; this guard also covers `durable-objects/`. +- **Workflows convention**: each default-exported `defineWorkflow()` / `defineWorkflowEntrypoint()` under `workflows/` becomes `WORKFLOW_` / `Workflow` (`send-welcome.ts` → `WORKFLOW_SEND_WELCOME` / `SendWelcomeWorkflow`), bound through the same `__bind()` hook as Durable State. The binding prefix matches `QUEUE_*`. Discovery follows `queues/` rather than `durable-objects/`: subdirectories are joined with `-` (`order/notifications.ts` → `order-notifications`) and `_`-prefixed path segments are skipped. Workflows need no class migrations, so they are not written to `void.lock.json`; `mergeWorkerBindings()` emits only the additions (the Cloudflare plugin concatenates arrays) via `planWorkflowAdditions()`, naming each `_` because Workflow names are account-scoped. `void deploy --platform cloudflare` passes its Worker name to the build as `VOID_CLOUDFLARE_WORKER_NAME`, and `reconstructExpectedWorkflows()` pins the exact emitted set for `verifyGeneratedDeployConfig()`. An authored entry with the same binding and class keeps its name. Void platform deploys, framework mode and Node targets reject `workflows/` until platform provisioning exists. The generated entry imports convention modules through their namespace and fails Worker startup with a named error when the default export is not a definition; this guard also covers `durable-objects/`. - **Persistent resource names**: optional static `name` on Durable State, WebSocket, and Workflow definitions uses the same identity derivation as unnamed filenames/routes. Preserve unnamed defaults exactly. `void info` reports names and verified unmatched lock identities without executing source or writing files. Scanners use the shared AST reader; runtime validation imports only the Worker-safe `shared/resource-name.ts` leaf. Carry explicit names through generated metadata and `__bind()`; runtime mismatches fail instead of selecting an inferred replacement. WebSocket `key({ params })` is shared by namespace selection and hook `ctx.id`; absent keys keep the existing ordered `param=value` format. - **Server room actions**: `defineRoom({ actions })` keeps each action's declared parameters and return type (`RoomActions` accepts any annotated parameter list, so unannotated parameters become `never`). Codegen adds `actions` to `WebSocketRouteMap` for room routes only, and `getRoom()` from `void/ws/server` resolves the same `bindingName` plus `buildWebSocketInstanceId()` key as `forwardWebSocketRequest()`. The generated route table registers route metadata once, after attaching `key`, through `__registerWebSocketRoutes`; the map lives on `globalThis` because dev can evaluate the module twice. Dispatch is Durable Object RPC (`__voidRoomAction`), so the WebSocket DO class extends `DurableObject` from `cloudflare:workers`; its own helpers are `#` methods so they stay off that RPC surface, and actions are never reachable from `fetch`, `webSocketMessage`, or client HTTP. - **Journal coherence invariant**: `db/migrations/*.sql` and `db/migrations/meta/_journal.json` must stay in sync — every `.sql` file has a matching journal entry (by `tag`) and vice versa. `assertJournalCoherence` in `src/migrations/validate.ts` is the gate, called from `deploy`, `db status`, `db migrate`, and `db reset`. The two CLI commands that mutate migration state — `void gen migration` and `void db rename-migrations` — are responsible for keeping the journal coherent themselves: when the journal has entries, the first delegates to `drizzle-kit generate --custom --name `, which writes the empty `.sql`, appends the journal entry, and writes a snapshot of the current schema (it refuses if the last entry's snapshot is missing and byte-restores the journal if drizzle-kit fails); with no journal entries it writes a plain timestamped `.sql`. The second rewrites `tag` values alongside the file renames and also renames the matching `meta/_snapshot.json` (with byte-level rollback on failure). Drift will fail loudly before touching any remote DB. This prevents an orphan scaffolded `.sql` file from half-applying against D1 and blocking later deploys. diff --git a/packages/void/src/cli/cf-version-runner.ts b/packages/void/src/cli/cf-version-runner.ts index 72982c92eb..03ebff32af 100644 --- a/packages/void/src/cli/cf-version-runner.ts +++ b/packages/void/src/cli/cf-version-runner.ts @@ -423,6 +423,7 @@ export function createCfVersionRunner(options: { workerName: string; runCf: CfCommand; verifyResources: (directory: string) => Promise; + clearWorkflowSchedules?: CloudflareCommandRunner; pinnedUpload?: { accountId: string; apiBaseUrl: string; @@ -556,6 +557,12 @@ export function createCfVersionRunner(options: { }; return async (operation, command) => { + if (operation.type === 'triggers.clear-workflow-schedules') { + if (operation.workerName !== workerName || !options.clearWorkflowSchedules) { + return failed('The Cloudflare Workflow schedule publisher is unavailable for this Worker.'); + } + return options.clearWorkflowSchedules(operation, command); + } if (operation.type === 'deployments.status') { const result = await run(['workers', 'deployments', 'list', '--worker', workerName], true); if (!isCleanCloudflareExit(result)) { diff --git a/packages/void/src/cli/cloudflare-operation-process.ts b/packages/void/src/cli/cloudflare-operation-process.ts index 0021394a4c..802455b761 100644 --- a/packages/void/src/cli/cloudflare-operation-process.ts +++ b/packages/void/src/cli/cloudflare-operation-process.ts @@ -384,6 +384,76 @@ async function clearWorkerCronSchedules(worker: string): Promise { return result(0); } +async function clearWorkflowSchedules( + request: Extract, +): Promise { + const { workerName: worker, workflowName: workflow, className } = request; + if (!/^[A-Za-z0-9_][A-Za-z0-9_-]{0,63}$/.test(workflow)) { + throw new Error('Invalid Cloudflare Workflow name.'); + } + const endpoint = `${apiBaseUrl()}/accounts/${encodeURIComponent(accountId())}/workflows/${encodeURIComponent(workflow)}`; + const headers = await apiHeaders(); + const current = await fetch(endpoint, { + headers, + redirect: 'error', + signal: AbortSignal.timeout(30_000), + }); + const body = object(await current.json()); + if ( + current.status === 404 && + Array.isArray(body.errors) && + body.errors.some((error) => object(error).code === 10_200) + ) { + return result(0, '', '', false); + } + if (!current.ok || body.success !== true) { + throw new Error(`Could not inspect Cloudflare Workflow ${workflow} (HTTP ${current.status}).`); + } + const active = object(body.result); + if ( + active.name !== workflow || + typeof active.script_name !== 'string' || + typeof active.class_name !== 'string' + ) { + throw new Error(`Cloudflare returned an invalid owner for Workflow ${workflow}.`); + } + // The old name can have moved to another Worker or class since this version ran. + if ( + active.script_name !== worker || + active.class_name !== className || + active.schedules === undefined || + (Array.isArray(active.schedules) && active.schedules.length === 0) + ) { + return result(0, '', '', false); + } + if (!Array.isArray(active.schedules)) { + throw new Error(`Cloudflare returned invalid schedules for Workflow ${workflow}.`); + } + if (request.inspectOnly) { + return result(0, '', '', true); + } + const cleared = await fetch(endpoint, { + method: 'PUT', + headers: { ...headers, 'Content-Type': 'application/json' }, + body: JSON.stringify({ + script_name: worker, + class_name: className, + schedules: [], + limits: request.limits, + concurrency: request.concurrency, + default_retention: request.default_retention, + }), + redirect: 'error', + signal: AbortSignal.timeout(30_000), + }); + if (!cleared.ok || object(await cleared.json()).success !== true) { + throw new Error( + `Could not clear schedules for Cloudflare Workflow ${workflow} (HTTP ${cleared.status}).`, + ); + } + return result(0); +} + async function clearWorkerCustomDomains(worker: string): Promise { const endpoint = `${apiBaseUrl()}/accounts/${encodeURIComponent(accountId())}/workers/scripts/${encodeURIComponent(worker)}/domains/records`; const response = await fetch(endpoint, { @@ -1281,10 +1351,17 @@ async function workerChanges(): Promise { if (raw.name !== name) { throw new Error('Cloudflare Worker target changed.'); } - if (operation.type === 'triggers.clear-crons' || operation.type === 'triggers.clear-domains') { + if ( + operation.type === 'triggers.clear-crons' || + operation.type === 'triggers.clear-domains' || + operation.type === 'triggers.clear-workflow-schedules' + ) { if (raw.account_id !== undefined && raw.account_id !== accountId()) { throw new Error('Cloudflare trigger target changed.'); } + if (operation.type === 'triggers.clear-workflow-schedules') { + return clearWorkflowSchedules(operation); + } return operation.type === 'triggers.clear-crons' ? clearWorkerCronSchedules(name) : clearWorkerCustomDomains(name); diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index 00bc02fba4..f987fa4b23 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -1,6 +1,7 @@ import { existsSync } from 'node:fs'; import { assertCloudflareBindingsPreserved, + parseCloudflareVersionMessage, parseRootWranglerConfig, readExistingCloudflareWorker, readWranglerTopLevelString, @@ -42,6 +43,7 @@ import { createCloudflareEmptyCronPublisher, createCloudflareEmptyDomainPublisher, } from './cloudflare-operations.ts'; +import { isCleanCloudflareExit } from './cloudflare-process.ts'; import { readCloudflareWorkersDevSubdomain, rememberCloudflareWorkersDevSubdomain, @@ -305,6 +307,7 @@ export function createCfActivationRunner(options: { output: cfOutput, workerName: options.workerName, runCf, + clearWorkflowSchedules: runWrangler, pinnedUpload: { accountId, apiBaseUrl, @@ -332,12 +335,35 @@ export async function activeWorkflowVersionForRemoval( typeof binding.class_name === 'string' && (binding.script_name === undefined || binding.script_name === options.workerName), ); - if (!ownsWorkflow) { - throw new Error( - 'deploy: atomic deployment requires Durable Object migration history or a local Workflow in the new or active Worker.', - ); + if (ownsWorkflow) { + return active.versionId; + } + const metadata = parseCloudflareVersionMessage(active.versionMessage); + if (metadata?.schema === 2) { + for (const cleanup of metadata.triggerConfig.workflowScheduleCleanup ?? []) { + const checked = await options.runWrangler( + { + ...cleanup, + type: 'triggers.clear-workflow-schedules', + workerName: options.workerName, + configPath: options.configPath, + inspectOnly: true, + }, + { capture: true }, + ); + if (!isCleanCloudflareExit(checked) || typeof checked.data !== 'boolean') { + throw new Error( + 'deploy: could not verify outstanding Workflow schedule cleanup before atomic publication.', + ); + } + if (checked.data) { + return active.versionId; + } + } } - return active.versionId; + throw new Error( + 'deploy: atomic deployment requires Durable Object migration history or a local Workflow in the new or active Worker.', + ); } /** diff --git a/packages/void/src/cli/deploy-helpers.ts b/packages/void/src/cli/deploy-helpers.ts index 01a5699937..2108ed07e4 100644 --- a/packages/void/src/cli/deploy-helpers.ts +++ b/packages/void/src/cli/deploy-helpers.ts @@ -384,7 +384,7 @@ export function resolveStaticDeployPreset( const appType = voidConfig.inference?.appType; if (appType === 'static' || appType === 'spa') { const outputDir = voidConfig.inference?.outputDir; - const detected = detectPreset(root, { spa: options?.spa, skipWorkflowDiscovery: true }); + const detected = detectPreset(root, { spa: options?.spa, explicitStatic: { outputDir } }); return { appType, buildCommand: detected?.buildCommand ?? null, diff --git a/packages/void/src/cli/preset.ts b/packages/void/src/cli/preset.ts index e820fc6d68..73a4778d42 100644 --- a/packages/void/src/cli/preset.ts +++ b/packages/void/src/cli/preset.ts @@ -249,7 +249,7 @@ export function detectPreset( dir?: string; spa?: boolean; strictBackend?: boolean; - skipWorkflowDiscovery?: boolean; + explicitStatic?: { outputDir?: string }; }, ): StaticPreset | null { // 1. Explicit --dir flag: skip build, use provided directory @@ -286,7 +286,10 @@ export function detectPreset( } // 3. Has backend files → full deploy - if (hasBackendFiles(root, options)) { + const hasBackend = hasBackendFiles(root, { + skipWorkflowDiscovery: Boolean(options?.explicitStatic), + }); + if (hasBackend && !options?.explicitStatic) { return null; } @@ -309,6 +312,18 @@ export function detectPreset( } // 5. No build tool — look for pre-built output + if ( + options?.explicitStatic && + (hasBackend || options.explicitStatic.outputDir || !canServeStaticProjectRoot(root)) + ) { + // A mixed project can have an index.html beside server source. Use its configured + // output directory (or dist) and never select the project root as public assets. + return { + appType: 'static', + buildCommand: resolveProjectScriptCommand(root, 'build'), + outputDir: defaultViteClientDir(root), + }; + } if (existsSync(join(root, 'dist/index.html'))) { return { buildCommand: null, @@ -328,6 +343,15 @@ export function detectPreset( return null; } +function canServeStaticProjectRoot(root: string): boolean { + try { + return scanWorkflowModules(root).length === 0; + } catch { + // Explicit static deployments can use built assets while the Worker sources are incomplete. + return false; + } +} + /** * The refusal shown when an SSG project also carries backend sources and no * `inference.appType` says which one to deploy. Names the exact directories diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts index 1363ebe008..2e5e0fed09 100644 --- a/packages/void/src/runtime/workflows/index.ts +++ b/packages/void/src/runtime/workflows/index.ts @@ -34,22 +34,33 @@ type WorkflowPayload = | Exclude | (undefined extends TParams ? Record : never); +// Workflow.create is a method, so its parameter is bivariant. Compare the +// delivered payload directly with what the concrete binding accepts. +type AcceptsPayload = TBinding extends Workflow + ? [TPayload] extends [NonNullable[0]>['params']] + ? true + : false + : never; + +type CompatibleBinding = TBinding & + (false extends AcceptsPayload ? never : unknown); + export type WorkflowApi = { class: TClass; /** @internal Called by Void's generated Worker entry. */ __bind(bindingName: string, resourceName?: string): void; /** Start a new instance. Params are validated when the definition has a `params` schema. */ create(...args: WorkflowCreateArguments): Promise; - create( - binding: Workflow, + create( + binding: CompatibleBinding, ...args: WorkflowCreateArguments ): Promise; /** Start up to 100 instances. Each instance's params are validated first. */ createBatch( instances: ReadonlyArray>, ): Promise; - createBatch( - binding: Workflow, + createBatch( + binding: CompatibleBinding, instances: ReadonlyArray>, ): Promise; /** Get a handle to an existing instance. */ diff --git a/packages/void/src/shared/resource-definition.ts b/packages/void/src/shared/resource-definition.ts index 9b1de28315..5aa8b4eef9 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -44,7 +44,10 @@ export function readResourceDefinition( ) || /\bfrom\s*['"]void\/workflows['"]/.test(source)) ) { - throw new SyntaxError(`workflows: could not parse ${filename}\n${parsed.errors[0].codeframe}`); + const hint = filename.endsWith('.cjs') ? ' Use .mjs for ES module syntax.' : ''; + throw new SyntaxError( + `workflows: could not parse ${filename}.${hint}\n${parsed.errors[0].codeframe}`, + ); } const program = asAstProgram(parsed.program); @@ -54,6 +57,13 @@ export function readResourceDefinition( const namespaces = new Map>(); const bindings = new Set(); let defaultExport: AstNode | undefined; + let commonJsExport: AstNode | undefined; + const isWorkflowRequire = (node: AstNode | undefined) => + convention === 'workflows' && + isCallExpression(node) && + isIdentifier(node.callee) && + node.callee.name === 'require' && + staticLiteral(node.arguments?.[0]) === 'void/workflows'; function recordBindings(node: AstNode | undefined): void { if (isIdentifier(node)) { bindings.add(node.name); @@ -74,6 +84,20 @@ export function readResourceDefinition( } } for (const statement of program.body ?? []) { + if (convention === 'workflows' && statement.type === 'ExpressionStatement') { + const assignment = statement.expression as AstNode; + const left = assignment.left as AstNode | undefined; + if ( + assignment.type === 'AssignmentExpression' && + assignment.operator === '=' && + isMemberExpression(left) && + isIdentifier(left.object) && + ((left.object.name === 'module' && moduleExportName(left.property) === 'exports') || + (left.object.name === 'exports' && moduleExportName(left.property) === 'default')) + ) { + commonJsExport = assignment.right as AstNode; + } + } if (statement.type === 'ExportDefaultDeclaration') { defaultExport = statement.declaration as AstNode; } else if ( @@ -128,6 +152,15 @@ export function readResourceDefinition( } for (const variable of (declaration as AstVariableDeclaration).declarations ?? []) { recordBindings(variable.id); + if (isWorkflowRequire(variable.init) && variable.id?.type === 'ObjectPattern') { + for (const property of variable.id.properties as Array) { + const helper = moduleExportName(property.key as AstNode | undefined); + const local = property.value as AstNode | undefined; + if (helper && helpers.has(helper) && isIdentifier(local)) { + importedHelpers.set(local.name, helper); + } + } + } if (isIdentifier(variable.id) && variable.init) { definitions.set(variable.id.name, variable.init); if (declaration.kind === 'const') { @@ -215,7 +248,7 @@ export function readResourceDefinition( helper = importedHelpers.get(callee.name) ?? (convention !== 'workflows' && helpers.has(callee.name) ? callee.name : undefined); - } else if (isMemberExpression(callee) && isIdentifier(callee.object)) { + } else if (isMemberExpression(callee)) { const property = !callee.computed && isIdentifier(callee.property) ? callee.property.name @@ -223,7 +256,8 @@ export function readResourceDefinition( if ( typeof property === 'string' && helpers.has(property) && - namespaces.get(callee.object.name)?.has(property) + ((isIdentifier(callee.object) && namespaces.get(callee.object.name)?.has(property)) || + isWorkflowRequire(resolve(callee.object))) ) { helper = property; } @@ -240,6 +274,11 @@ export function readResourceDefinition( ); if (!definition) { if (convention === 'workflows') { + if (resourceCall(commonJsExport)) { + throw new Error( + `workflows: ${filename} uses CommonJS. Use an ES module such as .mjs with import and export default for this Workflow definition.`, + ); + } const hasWorkflow = [...definitions.values()].some(resourceCall) || program.body?.some( diff --git a/packages/void/src/workflows/scan.ts b/packages/void/src/workflows/scan.ts index 9742040d58..ce57ca647f 100644 --- a/packages/void/src/workflows/scan.ts +++ b/packages/void/src/workflows/scan.ts @@ -63,8 +63,9 @@ export function deriveWorkflowResourceIdentity( * uses the resource name alone. */ export function cloudflareWorkflowName(resourceName: string, workerName?: string): string { - const prefix = workerName?.toLowerCase().replaceAll('_', '-'); - const name = prefix ? `${prefix}-${resourceName}` : resourceName; + // Resource names contain only letters, digits and hyphens. The last underscore + // always separates the original Worker name from its resource. + const name = workerName ? `${workerName}_${resourceName}` : resourceName; if (name.length > 64) { throw new Error( `workflows: generated Workflow name '${name}' exceeds Cloudflare's limit of 64 characters. Choose a shorter name in cloudflare.workflows.`, diff --git a/packages/void/test/integration/cloudflare-durable-build.test.ts b/packages/void/test/integration/cloudflare-durable-build.test.ts index c2c01e8b90..5b05aa570a 100644 --- a/packages/void/test/integration/cloudflare-durable-build.test.ts +++ b/packages/void/test/integration/cloudflare-durable-build.test.ts @@ -273,7 +273,7 @@ export default defineWorkflowEntrypoint({ class: Importer });\n`, expect(expectedWorkflows).toEqual([ pinned, { - name: 'deployed-app-welcome', + name: 'deployed-app_welcome', binding: 'WORKFLOW_WELCOME', class_name: 'WelcomeWorkflow', }, diff --git a/packages/void/test/unit/cf-version-runner.test.ts b/packages/void/test/unit/cf-version-runner.test.ts index ce68d5bedd..1c17aebd93 100644 --- a/packages/void/test/unit/cf-version-runner.test.ts +++ b/packages/void/test/unit/cf-version-runner.test.ts @@ -2555,7 +2555,7 @@ it('applies the immutable trigger snapshot through a private cf output copy', as } }); -it.each(['restore', 'remove'] as const)( +it.each(['restore', 'remove', 'rename'] as const)( 'replays workflow exports and schedules when triggers %s the previous workflow state', async (operation) => { const workflow = { @@ -2570,29 +2570,45 @@ it.each(['restore', 'remove'] as const)( migrations: [{ tag: 'v1', new_sqlite_classes: ['State'] }], workflows: operation === 'restore' ? [workflow] : [], }); - const desiredWorkflow = { ...workflow, schedules: ['30 * * * *'], concurrency: { limit: 2 } }; + const desiredWorkflow = { + ...workflow, + name: operation === 'rename' ? 'renamed-job' : workflow.name, + schedules: ['30 * * * *'], + concurrency: { limit: 2 }, + }; + const removedNames: Array = []; try { const calls: Array> = []; const runner = createCfVersionRunner({ output: prepared, workerName: 'void-test', verifyResources: async () => ({ status: 0, stdout: '', stderr: '' }), + clearWorkflowSchedules: async (request) => { + if (request.type === 'triggers.clear-workflow-schedules') { + removedNames.push(request.workflowName); + } + return { status: 0, stdout: '', stderr: '' }; + }, runCf: (args, { cwd }) => { calls.push(args); const worker = JSON.parse(readFileSync(getWorkerConfigPath(cwd), 'utf8')); - expect(worker.exports.Job).toEqual({ - type: 'workflow', - name: 'void-job', - ...(operation === 'restore' - ? { schedules: ['30 * * * *'], concurrency: { limit: 2 } } - : {}), - }); - expect(worker.env.JOB).toMatchObject({ - type: 'workflow', - name: 'void-job', - worker: 'void-test', - exportName: 'Job', - }); + if (operation === 'remove') { + expect(worker.exports.Job).toBeUndefined(); + expect(worker.env.JOB).toBeUndefined(); + } else { + expect(worker.exports.Job).toEqual({ + type: 'workflow', + name: desiredWorkflow.name, + schedules: ['30 * * * *'], + concurrency: { limit: 2 }, + }); + expect(worker.env.JOB).toMatchObject({ + type: 'workflow', + name: desiredWorkflow.name, + worker: 'void-test', + exportName: 'Job', + }); + } expect(worker.exports.State).toMatchObject({ type: 'durable-object', storage: 'sqlite' }); expect(worker.env.STATE).toMatchObject({ type: 'durable-object' }); expect(worker.env.FIXED).toEqual({ type: 'text', value: 'value' }); @@ -2612,12 +2628,13 @@ it.each(['restore', 'remove'] as const)( runWrangler: runner, triggerConfig: { ...base, - workflows: operation === 'restore' ? [desiredWorkflow] : [], + workflows: operation === 'remove' ? [] : [desiredWorkflow], }, previousTriggerConfig: { ...base, workflows: [workflow] }, }); expect(result.status).toBe(0); expect(calls).toEqual([['workers', 'triggers', 'deploy', '--prebuilt']]); + expect(removedNames).toEqual(operation === 'restore' ? [] : ['void-job']); const original = JSON.parse(readFileSync(getWorkerConfigPath(prepared.directory), 'utf8')); expect(original.exports.Job?.schedules).toEqual( operation === 'restore' ? ['0 * * * *'] : undefined, diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 714a6db5d7..bd55d040cb 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -1762,7 +1762,7 @@ describe('existing Cloudflare site handoff', () => { } }); - it.each(['add', 'remove', 'remove to static'] as const)( + it.each(['add', 'remove', 'remove to static', 'retry cleanup', 'completed cleanup'] as const)( 'supports the %s operation for a local Workflow in an atomic deployment', async (operation) => { const root = site(); @@ -1791,6 +1791,26 @@ describe('existing Cloudflare site handoff', () => { class_name: 'NotifyWorkflow', }, ], + ...((operation === 'retry cleanup' || operation === 'completed cleanup') && { + bindings: [], + versionMessage: + 'void:' + + JSON.stringify({ + schema: 2, + migrations: [], + triggerConfig: { + workers_dev: true, + preview_urls: false, + crons: [], + routes: [], + queueConsumers: [], + workflows: [], + workflowScheduleCleanup: [ + { workflowName: 'site-notify', className: 'NotifyWorkflow' }, + ], + }, + }), + }), }); const activateVersion = vi .fn>() @@ -1810,7 +1830,7 @@ describe('existing Cloudflare site handoff', () => { JSON.stringify({ ...parseRootWranglerConfig(path), workflows: [ - { name: 'site-notify', binding: 'WORKFLOW_NOTIFY', class_name: 'NotifyWorkflow' }, + { name: 'site_notify', binding: 'WORKFLOW_NOTIFY', class_name: 'NotifyWorkflow' }, ], }), ); @@ -1820,6 +1840,20 @@ describe('existing Cloudflare site handoff', () => { verifyDeployConfig: verifyGeneratedDeployConfig, activateVersion, }); + const defaultRunner = deps.runWrangler; + if (defaultRunner) { + deps.runWrangler = (request, command) => + request.type === 'triggers.clear-workflow-schedules' && request.inspectOnly + ? { ...cleanExit, data: operation === 'retry cleanup' } + : defaultRunner(request, command); + } + if (operation === 'completed cleanup') { + await expect( + runCloudflareDeploy(root, { platform: 'cloudflare', atomic: true }, silentCliLog, deps), + ).rejects.toBeInstanceOf(ExitError); + expect(activateVersion).not.toHaveBeenCalled(); + return; + } await runCloudflareDeploy( root, { diff --git a/packages/void/test/unit/cloudflare-operation-process.test.ts b/packages/void/test/unit/cloudflare-operation-process.test.ts index 6f65f63081..2c32198fba 100644 --- a/packages/void/test/unit/cloudflare-operation-process.test.ts +++ b/packages/void/test/unit/cloudflare-operation-process.test.ts @@ -319,6 +319,85 @@ registerHooks({ 30_000, ); +it.each(['scheduled', 'already cleared', 'inspect', 'moved', 'missing', 'denied'] as const)( + 'clears schedules of a removed Workflow by its provider name: %s', + async (state) => { + const directory = temporaryDirectory('void-workflow-schedules-'); + const requests: Array<{ method: string | undefined; url: string | undefined; body: unknown }> = + []; + const api = await listen( + createServer(async (request, response) => { + let data = ''; + for await (const chunk of request) { + data += chunk; + } + requests.push({ + method: request.method, + url: request.url, + body: data ? JSON.parse(data) : undefined, + }); + const missing = state === 'missing'; + const denied = state === 'denied' && request.method === 'PUT'; + response.writeHead(missing ? 404 : denied ? 403 : 200, { + 'Content-Type': 'application/json', + }); + response.end( + JSON.stringify({ + success: !missing && !denied, + errors: missing ? [{ code: 10_200 }] : [], + result: { + name: 'previous-name', + script_name: state === 'moved' ? 'another-worker' : 'test-worker', + class_name: 'Job', + schedules: + state === 'already cleared' || request.method === 'PUT' + ? [] + : [{ cron: '0 0 * * *' }], + }, + }), + ); + }), + ); + const configPath = join(directory, 'wrangler.json'); + writeFileSync(configPath, JSON.stringify({ name: 'test-worker', account_id: 'test-account' })); + const settings = { + concurrency: { limit: 2 }, + limits: { steps: 10 }, + default_retention: { success_retention: '7 days' }, + }; + const output = await runOperation( + directory, + { + type: 'triggers.clear-workflow-schedules', + workerName: 'test-worker', + workflowName: 'previous-name', + className: 'Job', + configPath, + inspectOnly: state === 'inspect', + ...settings, + }, + tokenEnv(api), + ); + expect(output.status, output.stderr).toBe(state === 'denied' ? 1 : 0); + if (state === 'inspect') { + expect(decodeCloudflareOperationResult(output).data).toBe(true); + } + const url = '/client/v4/accounts/test-account/workflows/previous-name'; + expect(requests).toEqual([ + { method: 'GET', url, body: undefined }, + ...(state === 'scheduled' || state === 'denied' + ? [ + { + method: 'PUT', + url, + body: { script_name: 'test-worker', class_name: 'Job', schedules: [], ...settings }, + }, + ] + : []), + ]); + }, +); + it.each(['clear-crons', 'clear-domains'])( 'clears %s through the pinned account API', async (operation) => { diff --git a/packages/void/test/unit/deploy-project.test.ts b/packages/void/test/unit/deploy-project.test.ts index 6c8f2b95ce..7033aeed71 100644 --- a/packages/void/test/unit/deploy-project.test.ts +++ b/packages/void/test/unit/deploy-project.test.ts @@ -425,6 +425,42 @@ describe('resolveFullDeployBuildCommand', () => { }); describe('resolveStaticDeployPreset', () => { + it('keeps root static assets when workflows/ only contains illustrations', () => { + const root = mkdtempSync(join(tmpdir(), 'void-static-assets-')); + tempDirs.push(root); + mkdirSync(join(root, 'workflows')); + writeFileSync(join(root, 'workflows', 'chart.svg'), ''); + writeFileSync(join(root, 'index.html'), '
'); + expect(resolveStaticDeployPreset(root, { inference: { appType: 'static' } })?.outputDir).toBe( + toSlash(root), + ); + writeFileSync( + join(root, 'workflows/job.ts'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({async run() {}})", + ); + expect(resolveStaticDeployPreset(root, { inference: { appType: 'static' } })?.outputDir).toBe( + toSlash(join(root, 'dist')), + ); + }); + it('builds the client of an explicitly static Vite app with routes and Workflows', () => { + const root = mkdtempSync(join(tmpdir(), 'void-static-workflows-')); + tempDirs.push(root); + mkdirSync(join(root, 'routes')); + mkdirSync(join(root, 'workflows')); + writeFileSync( + join(root, 'vite.config.ts'), + "import { voidPlugin } from 'void'; export default { plugins: [voidPlugin()] };", + ); + writeFileSync( + join(root, 'package.json'), + JSON.stringify({ scripts: { build: 'vite build' }, devDependencies: { vite: 'latest' } }), + ); + expect(resolveStaticDeployPreset(root, { inference: { appType: 'spa' } })).toEqual({ + appType: 'spa', + buildCommand: 'npm run build', + outputDir: toSlash(join(root, 'dist/client')), + }); + }); it('treats --dir as a static deploy override even in framework-shaped projects', () => { const root = mkdtempSync(join(tmpdir(), 'void-test-')); tempDirs.push(root); diff --git a/packages/void/test/unit/workflow-runtime.typecheck.ts b/packages/void/test/unit/workflow-runtime.typecheck.ts index 5e76908f86..eca1b10443 100644 --- a/packages/void/test/unit/workflow-runtime.typecheck.ts +++ b/packages/void/test/unit/workflow-runtime.typecheck.ts @@ -43,6 +43,16 @@ const envWorkflow = defineWorkflow<{ id: number }, WorkflowEnv>({ declare const workerEnv: WorkflowEnv, ctx: ExecutionContext; new envWorkflow.class(ctx, workerEnv); declare const wrongBinding: Workflow<{ name: string }>; +declare const narrowerBinding: Workflow<{ id: number; recipient: string }>; +// @ts-expect-error The definition cannot supply the recipient required by this binding. +void envWorkflow.create(narrowerBinding, { params: { id: 1 } }); +// @ts-expect-error The batch also sends only the definition's payload. +void envWorkflow.createBatch(narrowerBinding, [{ params: { id: 1 } }]); +declare const broaderBinding: Workflow<{ id: number | string }>; +void envWorkflow.create(broaderBinding, { params: { id: 1 } }); +declare const oneOfTwoBindings: typeof broaderBinding | typeof narrowerBinding; +// @ts-expect-error The receiver could be the binding requiring a recipient. +void envWorkflow.create(oneOfTwoBindings, { params: { id: 1 } }); // @ts-expect-error This binding can't receive the declared payload. void envWorkflow.create(wrongBinding, { params: { id: 1 } }); // @ts-expect-error Batch options must agree with the supplied binding. @@ -56,6 +66,8 @@ const converted = defineWorkflow({ }); declare const convertedBinding: Workflow<{ id: number }>; void converted.create(convertedBinding, { params: '1' }); +// @ts-expect-error The schema's output is missing recipient. +void converted.create(narrowerBinding, { params: '1' }); declare const stringBinding: Workflow; // @ts-expect-error The binding receives the parsed object. void converted.create(stringBinding, { params: '1' }); diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts index 460f075d1d..5e315d8e59 100644 --- a/packages/void/test/unit/workflow-scan.test.ts +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -59,6 +59,25 @@ describe('scanWorkflowModules', () => { expect(() => assertNoWorkflowsForPlatform(root)).not.toThrow(); }); + it('reports CommonJS Workflow definitions and leaves ordinary CommonJS helpers alone', () => { + const root = createRoot({ + 'tools.cjs': + "const { defineWorkflow } = require('void/workflows'); module.exports = { defineWorkflow };", + }); + expect(scanWorkflowModules(root)).toEqual([]); + writeFileSync( + join(root, 'workflows', 'job.cjs'), + `const { defineWorkflow } = require('void/workflows'); +module.exports = defineWorkflow({ async run() {} });`, + ); + expect(() => scanWorkflowModules(root)).toThrow(/job\.cjs.*\.mjs/); + writeFileSync( + join(root, 'workflows', 'job.cjs'), + "module.exports = require('void/workflows')['defineWorkflow']({ async run() {} });", + ); + expect(() => scanWorkflowModules(root)).toThrow(/job\.cjs.*\.mjs/); + }); + it('derives binding, class, and resource names from filenames', () => { const root = createRoot({ 'send-welcome.ts': definition, 'types.d.ts': '' }); expect(scanWorkflowModules(root)).toEqual([ @@ -155,7 +174,10 @@ const Job = defineWorkflow({ name: 'daily', async run() {} });`; describe('Cloudflare Workflow names', () => { it('prefixes the account-scoped name with the Worker name', () => { - expect(cloudflareWorkflowName('welcome', 'My_App')).toBe('my-app-welcome'); + expect(cloudflareWorkflowName('welcome', 'My_App')).toBe('My_App_welcome'); + expect(cloudflareWorkflowName('eu-charge', 'billing')).not.toBe( + cloudflareWorkflowName('charge', 'billing-eu'), + ); expect(cloudflareWorkflowName('welcome')).toBe('welcome'); expect(cloudflareWorkflowName('w'.repeat(60), 'app')).toHaveLength(64); }); @@ -193,10 +215,10 @@ describe('Cloudflare Workflow names', () => { class_name: 'WelcomeWorkflow', }; expect(planWorkflowAdditions([authored], modules, 'app')).toEqual([ - { name: 'app-import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, + { name: 'app_import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, ]); expect(planWorkflowAdditions([{ ...authored, script_name: 'app' }], modules, 'app')).toEqual([ - { name: 'app-import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, + { name: 'app_import', binding: 'WORKFLOW_IMPORT', class_name: 'ImportWorkflow' }, ]); expect(planWorkflowAdditions([], [], 'app')).toEqual([]); }); @@ -226,10 +248,10 @@ describe('Cloudflare Workflow names', () => { ).toThrow("binding 'WORKFLOW_WELCOME' is already configured"); expect(() => planWorkflowAdditions( - [{ name: 'app-welcome', binding: 'MINE', class_name: 'Mine' }], + [{ name: 'app_welcome', binding: 'MINE', class_name: 'Mine' }], modules, 'app', ), - ).toThrow("Workflow name 'app-welcome' is already configured for binding 'MINE'"); + ).toThrow("Workflow name 'app_welcome' is already configured for binding 'MINE'"); }); }); From f3fb7457d096aabeac921af8cc4570df4b84fa2b Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 13:59:17 +0900 Subject: [PATCH 08/13] Fix Workflow scheduling, binding types, and development reloads. --- docs/guide/workflows.md | 4 + docs/reference/api/workflows.md | 2 + docs/reference/resource-inference.md | 4 +- packages/deploy-cloudflare/src/index.ts | 1 + packages/deploy-cloudflare/src/operations.ts | 1 + packages/deploy-cloudflare/src/version.ts | 7 +- .../test/unit/version.test.ts | 2 +- .../src/cli/cloudflare-operation-process.ts | 41 +++++++ .../src/cli/deploy-cloudflare-preflight.ts | 32 +++++ packages/void/src/cli/deploy-resources.ts | 3 +- packages/void/src/codegen/binding-types.ts | 20 ++- packages/void/src/codegen/prepare.ts | 2 +- packages/void/src/index.ts | 2 +- packages/void/src/plugin-routing.ts | 39 ++++-- .../void/src/plugin-worker-environment.ts | 8 ++ .../test/integration/workflow-dev.test.ts | 115 +++++++++++++++++- .../void/test/unit/cloudflare-deploy.test.ts | 52 ++++++++ .../unit/cloudflare-operation-process.test.ts | 67 ++++++++++ 18 files changed, 378 insertions(+), 24 deletions(-) diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md index 3a1b16404f..164e6c94be 100644 --- a/docs/guide/workflows.md +++ b/docs/guide/workflows.md @@ -35,6 +35,8 @@ Default-export the object returned by `defineWorkflow()`. Named-export it too so Keep `workflows/` at the project root, including when `sourceDir` is set. Write Workflow definitions as TypeScript or JavaScript ES modules with an import from `void/workflows` and a default export. In CommonJS projects, use `.mjs` or `.mts` for definitions. Subdirectories are supported. Files and directories starting with `_` are excluded from Workflow discovery. If you maintain an explicit `include` list in `tsconfig.json`, add `workflows` so TypeScript checks definitions started outside your app. +Use ES modules for local step helpers too. For example, export a helper from `workflows/_read.mjs` and import it from the Workflow. The development Worker loads these files as ES modules. + `run` receives: - `event`, with the `payload` passed to `create()`, the `instanceId`, and a `timestamp` @@ -163,6 +165,8 @@ If the generated Cloudflare Workflow name exceeds 64 characters, use this entry Workflows are available on the Workers Free plan, within [Cloudflare's Workflows limits](https://developers.cloudflare.com/workflows/reference/limits/). Deploy to your own Cloudflare account with `void deploy --platform cloudflare`. +To start instances on a cron schedule through `cloudflare.workflows[].schedules`, [enable Workers Paid](https://dash.cloudflare.com/?to=/:account/workers/plans). For scheduled Workflows, give your deployment API token **Account Settings: Read** to check the account's entitlements and **Workers Scripts: Edit** to publish. Omit `schedules` to start instances from application code on Workers Free. + If Cloudflare rejects staging because you added, renamed, or removed a Workflow, run `void deploy --platform cloudflare --atomic` for that deployment. The new version receives traffic before Void checks readiness. To publish the same project's static assets to a connected Void platform, build the app and run `void deploy --platform void --dir dist/client`. You can also set `inference.appType` to `static` or `spa` and run `void deploy --platform void`. If you customize the build output, set `inference.outputDir` to the directory containing your public assets. diff --git a/docs/reference/api/workflows.md b/docs/reference/api/workflows.md index a71f2fc684..8fa931507d 100644 --- a/docs/reference/api/workflows.md +++ b/docs/reference/api/workflows.md @@ -33,6 +33,8 @@ Registers a class that extends Cloudflare's `WorkflowEntrypoint`. The params typ `name` optionally fixes the resource identity instead of deriving it from the filename. Run `void info` and pin the displayed name before moving a deployed definition. +Run `void prepare` to type the generated binding on a route's `c.env`. For example, `Onboarding.create(c.env.WORKFLOW_ONBOARDING, { params: { userId } })` checks the params against the definition. + ## `WorkflowParamsError` {#workflowparamserror} Thrown by `create()` and `createBatch()` when params fail the definition's schema. `issues` is an array of `{ message, path? }`. diff --git a/docs/reference/resource-inference.md b/docs/reference/resource-inference.md index 78c91e8592..e341447a7b 100644 --- a/docs/reference/resource-inference.md +++ b/docs/reference/resource-inference.md @@ -71,7 +71,7 @@ Regardless of mode, these are always checked: - **SSR entry** such as `src/main.ssr.ts`, for SSR apps that access bindings during rendering - **Application source** in `src/` or your configured `sourceDir`, including resource and auth imports - **`durable-objects/`**, which is scanned for typed Durable Object state modules in native Void apps -- **`workflows/`**, which is scanned for Workflow modules and the resources they use in native Void apps +- **`workflows/`**, where native Void apps discover Workflow definitions ## Custom Scan Directories @@ -87,6 +87,8 @@ If your project organizes code in non-standard directories, you can override whi Paths are relative to the project root. When `inference.scanDirs` is set, it replaces the default directories entirely. The SSR entry and application source scan still apply. +Include `"workflows"` in a custom `scanDirs` list to infer bindings used by Workflow definitions and their step helpers. + ## Explicit Binding Overrides Use [`inference.bindings`](./config.md#inference-bindings) to enable, disable, or rename a binding when inference does not match your setup. It overrides only the bindings you name; the rest are still inferred. diff --git a/packages/deploy-cloudflare/src/index.ts b/packages/deploy-cloudflare/src/index.ts index a62c9e4805..434ed08c4a 100644 --- a/packages/deploy-cloudflare/src/index.ts +++ b/packages/deploy-cloudflare/src/index.ts @@ -41,6 +41,7 @@ export { deployCloudflareVersionTraffic, encodeCloudflareVersionMessage, extractWorkersDevSubdomain, + hasWorkflowSchedules, normalizeReadinessAccessOrigin, normalizeWorkersDevSubdomain, parseCloudflareVersionMessage, diff --git a/packages/deploy-cloudflare/src/operations.ts b/packages/deploy-cloudflare/src/operations.ts index 6bd7cc8a82..bd35d77e16 100644 --- a/packages/deploy-cloudflare/src/operations.ts +++ b/packages/deploy-cloudflare/src/operations.ts @@ -18,6 +18,7 @@ export type CloudflareOperation = type: 'd1.list' | 'kv.namespace.list' | 'containers.list' | 'workers.subdomain.get'; } & ConfigTarget) | ({ type: 'd1.info'; name: string } & ConfigTarget) + | ({ type: 'workflows.schedules.entitlement'; fedramp: boolean } & ConfigTarget) | { type: 'd1.create'; name: string; binding: string; configPath: string } | ({ type: 'd1.execute'; database: string; configPath: string } & ( | { sql: string; file?: never } diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 4fd4908bc8..c245026ae4 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -586,6 +586,10 @@ function triggerConfigWithQueueConsumerCleanup( }; } +export function hasWorkflowSchedules(schedules: unknown): boolean { + return (typeof schedules === 'string' || Array.isArray(schedules)) && schedules.length > 0; +} + function workflowsToClear( workerName: string, desired: CloudflareTriggerConfig, @@ -608,8 +612,7 @@ function workflowsToClear( !isRecord(workflow) || typeof workflow.name !== 'string' || typeof workflow.class_name !== 'string' || - !Array.isArray(workflow.schedules) || - workflow.schedules.length === 0 || + !hasWorkflowSchedules(workflow.schedules) || desiredNames.has(workflow.name) || (typeof workflow.script_name === 'string' && workflow.script_name !== workerName) ) { diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index 67955e65b2..e316b5bfba 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -2767,7 +2767,7 @@ describe('Cloudflare version activation', () => { name: 'nightly', binding: 'JOB', class_name: 'Job', - schedules: ['0 0 * * *'], + schedules: '0 0 * * *', concurrency: { limit: 2 }, }; const desired = encodeCloudflareVersionMessage( diff --git a/packages/void/src/cli/cloudflare-operation-process.ts b/packages/void/src/cli/cloudflare-operation-process.ts index 802455b761..f226531593 100644 --- a/packages/void/src/cli/cloudflare-operation-process.ts +++ b/packages/void/src/cli/cloudflare-operation-process.ts @@ -790,8 +790,49 @@ async function readAllQueues(): Promise> { throw new Error('Cloudflare Queue list exceeded the supported page limit.'); } +async function checkWorkflowSchedulesEntitlement(fedramp: boolean): Promise { + const body = await cloudflareApiGet( + `/accounts/${encodeURIComponent(accountId())}/entitlements`, + 'Could not read account entitlements for scheduled Workflows.', + ); + if (!Array.isArray(body.result)) { + throw new Error('Cloudflare returned an invalid account entitlement list.'); + } + const active = body.result.map(object).filter((entry) => !entry.deleted_date); + function allocation(id: string) { + const entry = active.find((item) => item.id === id); + return entry && object(entry.allocation); + } + function count(id: string): number | undefined { + const limit = allocation(id); + if (!limit) { + return undefined; + } + if ( + limit.type !== 'max_count' || + typeof limit.value !== 'number' || + !Number.isSafeInteger(limit.value) || + limit.value < 0 + ) { + throw new Error(`Cloudflare returned an invalid allocation for ${id}.`); + } + return limit.value; + } + const concurrency = count('workflows.max_concurrent_instances'); + // A paid concurrency allocation also enables the paid step limit. + if (concurrency !== undefined) { + return result(0, '', '', concurrency >= 10_000); + } + const plan = allocation('workers.enabled'); + const paid = fedramp || (plan?.type === 'bool' && plan.value === true); + const steps = count('workflows.max_step_count'); + return result(0, '', '', paid && (steps === undefined || steps >= 25_000)); +} + async function resources(): Promise { switch (operation.type) { + case 'workflows.schedules.entitlement': + return checkWorkflowSchedulesEntitlement(operation.fedramp); case 'd1.import': { const database = d1Database(operation.database); await importD1SqlFile({ diff --git a/packages/void/src/cli/deploy-cloudflare-preflight.ts b/packages/void/src/cli/deploy-cloudflare-preflight.ts index fb2cc9859d..055706e112 100644 --- a/packages/void/src/cli/deploy-cloudflare-preflight.ts +++ b/packages/void/src/cli/deploy-cloudflare-preflight.ts @@ -5,6 +5,7 @@ import { readStoredResourceName, readWranglerTopLevelString, assertExistingCloudflareConfig, + hasWorkflowSchedules, } from '@void/deploy-cloudflare'; import type { ExistingCloudflareWorker, @@ -55,6 +56,7 @@ import { deriveWorkerName, formatCloudflareSandboxUnavailable, CLOUDFLARE_RESOURCE_LABELS, + CLOUDFLARE_WORKERS_PAID_URL, } from './deploy-resources.ts'; import { printDeployContext } from './deploy-summary.ts'; import { buildSchemaProbeEnv } from './deploy-transport.ts'; @@ -299,6 +301,36 @@ export async function preflightCloudflareWorker(input: { ); printDeployContext(workerName, 'Cloudflare'); + if ( + expectedWorkflows.some( + (workflow) => + (workflow.script_name === undefined || workflow.script_name === workerName) && + hasWorkflowSchedules(workflow.schedules), + ) + ) { + if (!assertUploaderStillPinned()) { + return exit(1); + } + const checked = await runWrangler( + { + type: 'workflows.schedules.entitlement', + configPath, + fedramp: complianceRegion === 'fedramp_high', + }, + { capture: true }, + ); + if (!isCleanCloudflareExit(checked) || checked.data !== true) { + log.error( + [ + `deploy: could not confirm scheduled Workflow access for Cloudflare account ${accountId}.`, + `Workflow schedules require Workers Paid. Enable the plan at ${CLOUDFLARE_WORKERS_PAID_URL} or remove schedules to use Workers Free.`, + 'The deploy token needs Account Settings: Read to check entitlements and Workers Scripts: Edit to publish.', + ].join('\n'), + ); + return exit(1); + } + } + // Email setup makes credentialed calls, so it runs before the env-schema probe runs any // project code. Its config writes become part of the baseline the probe check compares. let emailMap: EmailAddressMapInput | null = null; diff --git a/packages/void/src/cli/deploy-resources.ts b/packages/void/src/cli/deploy-resources.ts index 39cec54909..c631b6f956 100644 --- a/packages/void/src/cli/deploy-resources.ts +++ b/packages/void/src/cli/deploy-resources.ts @@ -39,7 +39,8 @@ export class CloudflareAuthSecretError extends Error { } } -const CLOUDFLARE_WORKERS_PAID_URL = 'https://dash.cloudflare.com/?to=/:account/workers/plans'; +export const CLOUDFLARE_WORKERS_PAID_URL = + 'https://dash.cloudflare.com/?to=/:account/workers/plans'; const CLOUDFLARE_CONTAINERS_PRICING_URL = 'https://developers.cloudflare.com/containers/pricing/'; diff --git a/packages/void/src/codegen/binding-types.ts b/packages/void/src/codegen/binding-types.ts index 2157bad838..1f64c5ac9a 100644 --- a/packages/void/src/codegen/binding-types.ts +++ b/packages/void/src/codegen/binding-types.ts @@ -1,6 +1,7 @@ import { rmSync } from 'node:fs'; import { join } from 'pathslash'; import type { VoidConfig } from '../config.ts'; +import type { WorkflowModule } from '../workflows/scan.ts'; import { writeFileIfChanged } from './write-if-changed.ts'; // Standard runtime types, as emitted by Cloudflare's type generator. RPC classes @@ -50,8 +51,11 @@ const bindingTypes: Array<[path: string, name: string, type: string]> = [ ]; const managedBindings = new Set(['DB', 'KV', 'STORAGE', 'AI', 'SANDBOX', 'ASSETS']); -/** Generate types for explicitly configured bindings without changing managed types. */ -export function generateBindingTypes(config: VoidConfig): string | null { +/** Generate types for configured bindings and local Workflow entrypoints. */ +export function generateBindingTypes( + config: VoidConfig, + workflows: ReadonlyArray = [], +): string | null { if (config.target && config.target !== 'cloudflare') { return null; } @@ -72,6 +76,10 @@ export function generateBindingTypes(config: VoidConfig): string | null { } } } + for (const { bindingName } of workflows) { + // A definition may use its own binding. Keep c.env independent of the definition's type. + bindings.set(bindingName, 'Workflow'); + } if (bindings.size === 0) { return null; } @@ -89,9 +97,13 @@ export function generateBindingTypes(config: VoidConfig): string | null { ].join('\n'); } -export function syncBindingTypes(root: string, config: VoidConfig): void { +export function syncBindingTypes( + root: string, + config: VoidConfig, + workflows: ReadonlyArray = [], +): void { const path = join(root, '.void', 'bindings.d.ts'); - const dts = generateBindingTypes(config); + const dts = generateBindingTypes(config, workflows); if (dts) { writeFileIfChanged(path, dts); } else { diff --git a/packages/void/src/codegen/prepare.ts b/packages/void/src/codegen/prepare.ts index 84ce159f57..cdceeaa047 100644 --- a/packages/void/src/codegen/prepare.ts +++ b/packages/void/src/codegen/prepare.ts @@ -49,7 +49,7 @@ export async function prepareProject(root: string): Promise = []; const removed: Array = []; - const bindingTypes = generateBindingTypes(config); + const bindingTypes = generateBindingTypes(config, analysis.workflows); if (bindingTypes) { writeGeneratedFile(outDir, 'bindings.d.ts', bindingTypes, written); } else { diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index e1a3290c5d..ab7e4da89a 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -117,7 +117,6 @@ export function voidPlugin(options?: { ? crypto.randomUUID() : getOrCreateDevTriggerToken(root); const config = readConfig(root); - syncBindingTypes(root, config); const projectCloudflareConfigPath = !isNodeTarget(config.target) ? materializeCloudflareConfig(root) : undefined; @@ -171,6 +170,7 @@ export function voidPlugin(options?: { }, }; let application = analyzeApplicationSync(root, { config }); + syncBindingTypes(root, config, application.workflows); const { paths, dialect, bindingNames, authConfigPath } = application; const analyses = new Map(); const getApplicationAnalysis = (environment: RouteEnvironment, refresh = false) => { diff --git a/packages/void/src/plugin-routing.ts b/packages/void/src/plugin-routing.ts index 32bd6a4468..9b79f21633 100644 --- a/packages/void/src/plugin-routing.ts +++ b/packages/void/src/plugin-routing.ts @@ -3,7 +3,12 @@ import { homedir } from 'node:os'; import { fileURLToPath } from 'node:url'; import { isDeepStrictEqual } from 'node:util'; import { dirname, join, relative, resolve } from 'pathslash'; -import { createRunnableDevEnvironment, isRunnableDevEnvironment, normalizePath } from 'vite'; +import { + createRunnableDevEnvironment, + isRunnableDevEnvironment, + normalizePath, + parseSync, +} from 'vite'; import type { Plugin, ResolvedConfig, RunnableDevEnvironment } from 'vite'; import type { ApplicationAnalysis } from './application-analysis.ts'; import { completeApplicationAnalysis } from './application-routing.ts'; @@ -908,6 +913,24 @@ export function routingPlugin( invalidateSourceAnalysis(id); }, + transform: { + filter: { id: /\.c[jt]s$/, code: /\b(?:exports|require)\b/ }, + handler(code, id) { + if ( + options.workflows?.length && + this.environment.mode === 'dev' && + this.environment.config.resolve.conditions.includes('workerd') && + isInDirectory(id, normalizedWorkflowsDir) && + !relative(normalizedWorkflowsDir, id).split('/').includes('node_modules') && + !parseSync(id, code).module.hasModuleSyntax + ) { + this.error( + `workflows: ${relative(root, id)} is a CommonJS helper. Use an ES module (.mjs or .mts) with import and export for local Workflow development.`, + ); + } + }, + }, + resolveId: { filter: { id: RESOLVE_ID_FILTER }, handler(id) { @@ -1005,7 +1028,6 @@ export function routingPlugin( const workflowChanged = options.workflows && isInDirectory(normalizedPath, normalizedWorkflowsDir); const sourceConventionChanged = - workflowChanged || isInDirectory(normalizedPath, normalizedRoutesDir) || isInDirectory(normalizedPath, normalizedMiddlewareDir) || isInDirectory(normalizedPath, normalizedJobsDir) || @@ -1015,16 +1037,19 @@ export function routingPlugin( authConfigChanged || authImportCreated || isPotentialEnvFilePath(normalizedPath); - if (!sourceConventionChanged && !ssrEntryAbsPaths.has(normalizedPath)) { + const rescanRoutes = sourceConventionChanged || ssrEntryAbsPaths.has(normalizedPath); + if (!workflowChanged && !rescanRoutes) { return; } const shouldRestart = await regenerateInOrder(async () => { invalidateSourceAnalysis(normalizedPath); - if (workflowChanged) { - // Cloudflare loads bindings and exported classes at startup. Ordinary step edits - // keep the same configuration and can use Vite's module updates. - return !isDeepStrictEqual(options.workflows, scanWorkflowModules(root)); + if (workflowChanged && !isDeepStrictEqual(options.workflows, scanWorkflowModules(root))) { + return true; + } + // A custom sourceDir can put routes inside workflows/. Step-only edits use Vite HMR. + if (!rescanRoutes) { + return; } // Re-scan and invalidate the virtual module in ALL environments. // The route table virtual module lives in the workerd environment, diff --git a/packages/void/src/plugin-worker-environment.ts b/packages/void/src/plugin-worker-environment.ts index ef02720350..ecf6158c38 100644 --- a/packages/void/src/plugin-worker-environment.ts +++ b/packages/void/src/plugin-worker-environment.ts @@ -112,6 +112,14 @@ export function createHonoCompressionPlugin( export function createDefaultWorkerEnvironmentPlugin(): Plugin { return { name: 'void:default-worker-environment', + configureServer: { + order: 'pre', + async handler(server) { + // Cloudflare can resolve Worker imports while Vite is still restoring optimized + // dependency filenames. Finish loading the cache before the Worker starts or restarts. + await server.environments[DEFAULT_WORKER_ENVIRONMENT_NAME]?.depsOptimizer?.init(); + }, + }, config(config) { const currentEnvironment = config.environments?.[DEFAULT_WORKER_ENVIRONMENT_NAME]; return { diff --git a/packages/void/test/integration/workflow-dev.test.ts b/packages/void/test/integration/workflow-dev.test.ts index aa0e020e97..c191b2dee7 100644 --- a/packages/void/test/integration/workflow-dev.test.ts +++ b/packages/void/test/integration/workflow-dev.test.ts @@ -1,6 +1,7 @@ -import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { execFileSync } from 'node:child_process'; +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { it, onTestFinished } from 'vite-plus/test'; +import { expect, it, onTestFinished } from 'vite-plus/test'; import { createIsolatedPlayground, killChild, @@ -9,11 +10,10 @@ import { waitForServer, } from '../../../../test/integration-helpers.ts'; +const repository = join(import.meta.dirname, '../../../..'); + it('refreshes the Worker when a Workflow is added, renamed, or deleted during dev', async () => { - const fixture = createIsolatedPlayground( - join(import.meta.dirname, '../../../..'), - 'playground/ssr', - ); + const fixture = createIsolatedPlayground(repository, 'playground/ssr'); onTestFinished(() => fixture.cleanup()); const route = '/api/workflow-bindings'; writeFileSync( @@ -38,8 +38,111 @@ export const GET = defineHandler(c => Response.json(Object.keys(c.env).filter(ke export default defineWorkflow({ name: ${JSON.stringify(name)}, async run(event, step) { return step.do('greet', async () => 'hello'); } });`; writeFileSync(file, workflow('welcome')); await waitForBindings('WORKFLOW_WELCOME'); + const declaration = join(fixture.root, '.void', 'bindings.d.ts'); + expect(readFileSync(declaration, 'utf8')).toContain('"WORKFLOW_WELCOME": Workflow'); writeFileSync(file, workflow('onboarding')); await waitForBindings('WORKFLOW_ONBOARDING'); + expect(readFileSync(declaration, 'utf8')).not.toContain('WORKFLOW_WELCOME'); rmSync(file); await waitForBindings(); + expect(existsSync(declaration)).toBe(false); }, 60_000); + +it('discovers new routes when sourceDir is inside workflows/', async () => { + const fixture = createIsolatedPlayground(repository, 'playground/ssr'); + onTestFinished(() => fixture.cleanup()); + const directory = join(fixture.root, 'workflows'); + rmSync(join(fixture.root, 'routes'), { recursive: true }); + mkdirSync(join(directory, 'routes'), { recursive: true }); + writeFileSync( + join(directory, 'routes', 'index.ts'), + "export const GET = () => new Response('home');", + ); + writeFileSync(join(fixture.root, 'void.config.ts'), "export default { sourceDir: 'workflows' };"); + const server = await startServer((port) => spawnFixtureServer(fixture.root, 'dev', port), 20_000); + onTestFinished(() => killChild(server.child)); + writeFileSync( + join(directory, 'routes', 'added.ts'), + "export const GET = () => new Response('new route');", + ); + await waitForServer(server.base + '/added', 10_000, { + expectBody: 'new route', + expectStatus: 200, + diagnostics: server.output, + }); +}); + +it('types the explicit binding and its payload in a prepared consumer', async () => { + const fixture = createIsolatedPlayground(repository, 'playground/ssr'); + onTestFinished(() => fixture.cleanup()); + const directory = join(fixture.root, 'workflows'); + mkdirSync(directory); + writeFileSync( + join(directory, 'notify.ts'), + `import type { CloudBindings } from 'void/handler'; +import { defineWorkflow } from 'void/workflows'; +export default defineWorkflow<{ id: string }, CloudBindings>({ + async run(event, step, { env }) { + if (event.payload.id === 'first') { + return step.do('start next', async () => (await env.WORKFLOW_NOTIFY.create({ params: { id: 'next' } })).id); + } + }, +});`, + ); + const { prepareProject } = await import('../../src/codegen/prepare.ts'); + await prepareProject(fixture.root); + const declaration = join(fixture.root, '.void', 'bindings.d.ts'); + expect(readFileSync(declaration, 'utf8')).toContain('"WORKFLOW_NOTIFY": Workflow'); + writeFileSync( + join(fixture.root, 'binding.ts'), + `import { defineHandler } from 'void'; +import Notify from './workflows/notify'; +export const GET = defineHandler(async c => { + await Notify.create(c.env.WORKFLOW_NOTIFY, { params: { id: 'hello' } }); + // @ts-expect-error The Workflow requires a string id. + await Notify.create(c.env.WORKFLOW_NOTIFY, { params: { id: 42 } }); + return 'ok'; +});`, + ); + writeFileSync( + join(fixture.root, 'tsconfig.binding.json'), + JSON.stringify({ + extends: './.void/tsconfig.json', + compilerOptions: { + strict: true, + noEmit: true, + module: 'ESNext', + moduleResolution: 'Bundler', + target: 'ES2022', + types: ['void/env'], + skipLibCheck: true, + }, + include: ['binding.ts'], + }), + ); + execFileSync( + process.execPath, + [join(repository, 'node_modules/typescript/bin/tsc'), '-p', 'tsconfig.binding.json'], + { cwd: fixture.root }, + ); +}); + +it.each(['cjs', 'cts'])( + 'identifies a CommonJS .%s helper that the development Worker cannot load', + async (extension) => { + const fixture = createIsolatedPlayground(repository, 'playground/ssr'); + onTestFinished(() => fixture.cleanup()); + const directory = join(fixture.root, 'workflows'); + mkdirSync(directory); + writeFileSync(join(directory, `_reader.${extension}`), 'exports.read = () => "result";'); + writeFileSync( + join(directory, 'read.ts'), + `import { defineWorkflow } from 'void/workflows'; +import { read } from './_reader.${extension}'; +export default defineWorkflow({ async run(event, step) { return step.do('read', async () => read()); } });`, + ); + await expect( + startServer((port) => spawnFixtureServer(fixture.root, 'dev', port), 10_000), + ).rejects.toThrow(/workflows\/_reader\.c[jt]s.*ES module/); + }, +); diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index bd55d040cb..1df0574796 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -4487,6 +4487,58 @@ describe('runCloudflareDeploy — preflight', () => { expect(trace.indexOf('wrangler:containers')).toBeLessThan(trace.indexOf('build')); }); + it.each([ + { schedules: '0 * * * *', paid: false, shouldProbe: true }, + { schedules: ['0 * * * *'], paid: true, shouldProbe: true }, + { schedules: [], paid: false, shouldProbe: false }, + { schedules: undefined, paid: false, shouldProbe: false }, + ])( + 'checks Workers Paid only for scheduled Workflows ($schedules, paid=$paid)', + async ({ schedules, paid, shouldProbe }) => { + const root = d1Project( + { + ...PROVISIONED_D1, + workflows: [ + { binding: 'WORKFLOW_NOTIFY', name: 'notify', class_name: 'NotifyWorkflow', schedules }, + ], + }, + { + 'workflows/notify.ts': + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({async run(){}});", + }, + ); + const { deps, trace } = harness(); + const run = deps.runWrangler!; + deps.runWrangler = (operation, options) => { + if (operation.type === 'workflows.schedules.entitlement') { + trace.push('check-schedules'); + return { ...cleanExit, data: paid }; + } + return run(operation, options); + }; + const deploy = runCloudflareDeploy( + root, + { platform: 'cloudflare', provision: true }, + silentCliLog, + deps, + ); + if (shouldProbe && !paid) { + await expect(deploy).rejects.toBeInstanceOf(ExitError); + expect(trace).toContain('check-schedules'); + expect(trace).not.toContain('provision'); + expect(trace).not.toContain('build'); + } else { + await deploy; + expect(trace.includes('check-schedules')).toBe(shouldProbe); + expect(trace).toContain('provision'); + if (shouldProbe) { + expect(trace.indexOf('check-schedules')).toBeLessThan(trace.indexOf('provision')); + } + expect(trace).toContain('build'); + } + }, + ); + it('fails before provisioning or building when Sandbox Containers are unavailable', async () => { const root = sandboxProject(); const errors: Array = []; diff --git a/packages/void/test/unit/cloudflare-operation-process.test.ts b/packages/void/test/unit/cloudflare-operation-process.test.ts index 2c32198fba..14e2f600b4 100644 --- a/packages/void/test/unit/cloudflare-operation-process.test.ts +++ b/packages/void/test/unit/cloudflare-operation-process.test.ts @@ -1867,6 +1867,73 @@ syncBuiltinESMExports();`, 30_000, ); +it.each([ + { + name: 'Workers Paid', + entitlements: [{ id: 'workers.enabled', allocation: { type: 'bool', value: true } }], + eligible: true, + }, + { + name: 'paid Workflow allocation', + entitlements: [ + { + id: 'workflows.max_concurrent_instances', + allocation: { type: 'max_count', value: 10_000 }, + }, + ], + eligible: true, + }, + { + name: 'Free Workflow allocation', + entitlements: [ + { id: 'workflows.max_concurrent_instances', allocation: { type: 'max_count', value: 100 } }, + ], + eligible: false, + }, + { name: 'absent entitlements', entitlements: [], eligible: false }, + { name: 'FedRAMP default allocation', entitlements: [], fedramp: true, eligible: true }, + { + name: 'lower step allocation on FedRAMP', + fedramp: true, + entitlements: [ + { id: 'workflows.max_step_count', allocation: { type: 'max_count', value: 1024 } }, + ], + eligible: false, + }, + { + name: 'expired Workers entitlement', + entitlements: [ + { + id: 'workers.enabled', + deleted_date: '2025-01-01', + allocation: { type: 'bool', value: true }, + }, + ], + eligible: false, + }, + { name: 'missing token permission', entitlements: [], status: 403 }, +])( + 'reads scheduled Workflow eligibility using the pinned account: $name', + async ({ entitlements, eligible, status, fedramp = false }) => { + const requests: Array = []; + const api = await listen( + createServer((request, response) => { + requests.push(`${request.method} ${request.url}`); + response.writeHead(status ?? 200, { 'Content-Type': 'application/json' }); + response.end(JSON.stringify({ success: !status, result: entitlements })); + }), + ); + const output = await runOperation( + temporaryDirectory('void-workflow-plan-'), + { type: 'workflows.schedules.entitlement', fedramp }, + tokenEnv(api), + ); + expect(requests).toEqual(['GET /client/v4/accounts/test-account/entitlements']); + expect(output.status).toBe(status ? 1 : 0); + expect(decodeCloudflareOperationResult(output).data).toBe(eligible); + }, +); + it.each(['canonical', 'alias', 'bearer'] as const)( 'reads the account workers.dev subdomain with %s credentials', async (credentials) => { From 75bd8a1e7d5abb9531f022c0a460965e0d1540cd Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 14:04:41 +0900 Subject: [PATCH 09/13] Consume the routing asset response before dispatching more requests. --- packages/void/test/integration/typed-routing-runtime.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/void/test/integration/typed-routing-runtime.test.ts b/packages/void/test/integration/typed-routing-runtime.test.ts index cf41a10825..9ff434984e 100644 --- a/packages/void/test/integration/typed-routing-runtime.test.ts +++ b/packages/void/test/integration/typed-routing-runtime.test.ts @@ -251,7 +251,6 @@ renderPage.preambleScript = ${JSON.stringify(preambleScript)};`; method: 'POST', body: { message: 'destructured handler' }, }); - const asset = await runtime.dispatchFetch('https://app.test/static/client-abcdefgh.js'); expect(await (await runtime.dispatchFetch('https://app.test/quoted')).json()).toEqual({ method: 'GET', }); @@ -266,6 +265,7 @@ renderPage.preambleScript = ${JSON.stringify(preambleScript)};`; }); expect(quotedAction.status).toBe(200); expect(await quotedAction.text()).toBe('quoted action'); + const asset = await runtime.dispatchFetch('https://app.test/static/client-abcdefgh.js'); expect(asset.headers.get('x-user-middleware')).toBe('ran'); expect(asset.headers.get('x-edge-rule')).toBe('ran'); expect(asset.headers.get('cache-control')).toBe('public, max-age=31536000, immutable'); From ad77fbf1a92df1efb10a3cd57609adad0a416b2d Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 14:37:17 +0900 Subject: [PATCH 10/13] Fix Workflow discovery, binding types, and deployment recovery. --- docs/guide/workflows.md | 2 +- packages/deploy-cloudflare/src/operations.ts | 8 +- packages/deploy-cloudflare/src/version.ts | 32 +++++++- .../test/unit/version.test.ts | 30 ++++++++ .../src/cli/cloudflare-operation-process.ts | 32 +++++--- .../src/cli/deploy-cloudflare-preflight.ts | 43 ++++++++--- .../void/src/cli/deploy-cloudflare-publish.ts | 9 ++- .../void/src/cli/deploy-cloudflare-static.ts | 12 ++- packages/void/src/codegen/binding-types.ts | 16 +++- packages/void/src/plugin-inference.ts | 11 ++- packages/void/src/runtime/workflows/index.ts | 28 +++++-- packages/void/src/shared/static-exports.ts | 1 + packages/void/src/workflows/scan.ts | 2 +- .../test/integration/workflow-dev.test.ts | 73 ++++++++++++++++++- .../void/test/unit/cloudflare-deploy.test.ts | 22 +++++- .../unit/cloudflare-operation-process.test.ts | 43 ++++++++++- .../void/test/unit/plugin-inference.test.ts | 6 ++ packages/void/test/unit/workflow-scan.test.ts | 15 ++++ 18 files changed, 327 insertions(+), 58 deletions(-) diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md index 164e6c94be..c843c2d83d 100644 --- a/docs/guide/workflows.md +++ b/docs/guide/workflows.md @@ -165,7 +165,7 @@ If the generated Cloudflare Workflow name exceeds 64 characters, use this entry Workflows are available on the Workers Free plan, within [Cloudflare's Workflows limits](https://developers.cloudflare.com/workflows/reference/limits/). Deploy to your own Cloudflare account with `void deploy --platform cloudflare`. -To start instances on a cron schedule through `cloudflare.workflows[].schedules`, [enable Workers Paid](https://dash.cloudflare.com/?to=/:account/workers/plans). For scheduled Workflows, give your deployment API token **Account Settings: Read** to check the account's entitlements and **Workers Scripts: Edit** to publish. Omit `schedules` to start instances from application code on Workers Free. +To start instances on a cron schedule through `cloudflare.workflows[].schedules`, set `limits.steps` above 1,024, or set `concurrency.limit` above 100, [enable Workers Paid](https://dash.cloudflare.com/?to=/:account/workers/plans). Workers Paid supports up to 25,000 steps per instance. For these settings, give your deployment API token **Account Settings: Read** to check your account's allocation and **Workers Scripts: Edit** to publish. If Cloudflare rejects staging because you added, renamed, or removed a Workflow, run `void deploy --platform cloudflare --atomic` for that deployment. The new version receives traffic before Void checks readiness. diff --git a/packages/deploy-cloudflare/src/operations.ts b/packages/deploy-cloudflare/src/operations.ts index bd35d77e16..521905af84 100644 --- a/packages/deploy-cloudflare/src/operations.ts +++ b/packages/deploy-cloudflare/src/operations.ts @@ -18,7 +18,13 @@ export type CloudflareOperation = type: 'd1.list' | 'kv.namespace.list' | 'containers.list' | 'workers.subdomain.get'; } & ConfigTarget) | ({ type: 'd1.info'; name: string } & ConfigTarget) - | ({ type: 'workflows.schedules.entitlement'; fedramp: boolean } & ConfigTarget) + | ({ + type: 'workflows.entitlement'; + fedramp: boolean; + schedules: boolean; + steps: number; + concurrency: number; + } & ConfigTarget) | { type: 'd1.create'; name: string; binding: string; configPath: string } | ({ type: 'd1.execute'; database: string; configPath: string } & ( | { sql: string; file?: never } diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index c245026ae4..3b84867a0b 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -1,8 +1,10 @@ +import { Buffer as NodeBuffer } from 'node:buffer'; import { createHash } from 'node:crypto'; import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { setTimeout as delay } from 'node:timers/promises'; import { isDeepStrictEqual } from 'node:util'; +import { deflateRawSync, inflateRawSync } from 'node:zlib'; import { canonicalJson, isRecord } from '@void/deploy-core'; import { join } from 'pathslash'; import { parseRootWranglerConfig } from './config.ts'; @@ -179,6 +181,10 @@ type RecentCloudflareVersion = Readonly<{ inspection: Record; }>; +// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- workers-types declares Buffer as any in this Node package. +const Buffer = NodeBuffer as BufferConstructor; +const MAX_VERSION_MESSAGE_BYTES = 1000; + /** Encode migration state into Cloudflare's version annotation for safe rollback diagnostics. */ export function encodeCloudflareVersionMessage( migrations: ReadonlyArray | null, @@ -188,7 +194,20 @@ export function encodeCloudflareVersionMessage( const metadata: CloudflareVersionMetadata = triggerConfig ? { schema: 2, migrations, triggerConfig, ...(contentHash ? { contentHash } : {}) } : { schema: 1, migrations }; - return `void:${JSON.stringify(metadata)}`; + const json = JSON.stringify(metadata); + const message = 'void:' + json; + // Cloudflare truncates workers/message at 1000 bytes. Keep the existing format + // when it fits, and compress larger recovery snapshots before publication. + if (Buffer.byteLength(message) <= MAX_VERSION_MESSAGE_BYTES) { + return message; + } + const compressed = 'void:z:' + deflateRawSync(json).toString('base64url'); + if (compressed.length > MAX_VERSION_MESSAGE_BYTES) { + throw new Error( + "deploy: Worker recovery metadata exceeds Cloudflare's 1000-byte version message limit even after compression. Reduce the deployment's trigger or migration configuration before retrying.", + ); + } + return compressed; } /** Read migration state written by {@link encodeCloudflareVersionMessage}. */ @@ -199,7 +218,16 @@ export function parseCloudflareVersionMessage( return null; } try { - const value: unknown = JSON.parse(message.slice(5)); + const compressed = message.startsWith('void:z:'); + if (compressed && message.length > MAX_VERSION_MESSAGE_BYTES) { + return null; + } + const json = compressed + ? inflateRawSync(Buffer.from(message.slice(7), 'base64url'), { + maxOutputLength: 1024 * 1024, + }).toString('utf8') + : message.slice(5); + const value: unknown = JSON.parse(json); if ( !isRecord(value) || (value.schema !== 1 && value.schema !== 2) || diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index e316b5bfba..badc8f3539 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -1,3 +1,4 @@ +import { createHash } from 'node:crypto'; import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -2762,6 +2763,35 @@ describe('Cloudflare version activation', () => { ]); }); + it('round-trips schedule cleanup within the 1000-byte version annotation', () => { + const workflows = Array.from({ length: 5 }, (_, i) => ({ + name: 'app_modified-batch-' + i, + binding: 'WORKFLOW_BATCH_' + i, + class_name: 'Batch' + i + 'Workflow', + schedules: ['0 * * * *'], + })); + const triggers = triggersWith({ + workflows, + workflowScheduleCleanup: workflows.map((workflow, i) => ({ + workflowName: 'app_previous-batch-' + i, + className: workflow.class_name, + })), + }); + const message = encodeCloudflareVersionMessage([], triggers); + expect(new TextEncoder().encode(message).byteLength).toBeLessThanOrEqual(1000); + expect(parseCloudflareVersionMessage(message)).toMatchObject({ triggerConfig: triggers }); + }); + + it('refuses recovery metadata that cannot fit even when compressed', () => { + const history = Array.from({ length: 64 }, (_, i) => + createHash('sha256').update(String(i)).digest('hex'), + ); + expect(() => encodeCloudflareVersionMessage(history)).toThrow( + '1000-byte version message limit', + ); + expect(parseCloudflareVersionMessage('void:z:invalid')).toBeNull(); + }); + it('retains failed schedule cleanup across atomic deploy retries and retires it after success', async () => { const old = { name: 'nightly', diff --git a/packages/void/src/cli/cloudflare-operation-process.ts b/packages/void/src/cli/cloudflare-operation-process.ts index f226531593..5f805498f0 100644 --- a/packages/void/src/cli/cloudflare-operation-process.ts +++ b/packages/void/src/cli/cloudflare-operation-process.ts @@ -790,10 +790,12 @@ async function readAllQueues(): Promise> { throw new Error('Cloudflare Queue list exceeded the supported page limit.'); } -async function checkWorkflowSchedulesEntitlement(fedramp: boolean): Promise { +async function checkWorkflowEntitlement( + request: Extract, +): Promise { const body = await cloudflareApiGet( `/accounts/${encodeURIComponent(accountId())}/entitlements`, - 'Could not read account entitlements for scheduled Workflows.', + 'Could not read account entitlements for Workflows.', ); if (!Array.isArray(body.result)) { throw new Error('Cloudflare returned an invalid account entitlement list.'); @@ -819,20 +821,28 @@ async function checkWorkflowSchedulesEntitlement(fedramp: boolean): Promise= 10_000); - } const plan = allocation('workers.enabled'); - const paid = fedramp || (plan?.type === 'bool' && plan.value === true); - const steps = count('workflows.max_step_count'); - return result(0, '', '', paid && (steps === undefined || steps >= 25_000)); + const paid = + concurrency !== undefined + ? concurrency >= 10_000 + : request.fedramp || (plan?.type === 'bool' && plan.value === true); + const stepLimit = count('workflows.max_step_count') ?? (paid ? 25_000 : 1024); + const schedulesAllowed = paid && (concurrency !== undefined || stepLimit >= 25_000); + const concurrencyLimit = concurrency ?? (paid ? 50_000 : 100); + return result( + 0, + '', + '', + request.steps <= stepLimit && + request.concurrency <= concurrencyLimit && + (!request.schedules || schedulesAllowed), + ); } async function resources(): Promise { switch (operation.type) { - case 'workflows.schedules.entitlement': - return checkWorkflowSchedulesEntitlement(operation.fedramp); + case 'workflows.entitlement': + return checkWorkflowEntitlement(operation); case 'd1.import': { const database = d1Database(operation.database); await importD1SqlFile({ diff --git a/packages/void/src/cli/deploy-cloudflare-preflight.ts b/packages/void/src/cli/deploy-cloudflare-preflight.ts index 055706e112..d1e628901f 100644 --- a/packages/void/src/cli/deploy-cloudflare-preflight.ts +++ b/packages/void/src/cli/deploy-cloudflare-preflight.ts @@ -11,6 +11,7 @@ import type { ExistingCloudflareWorker, ApprovedCloudflareKvBinding, } from '@void/deploy-cloudflare'; +import { isRecord } from '@void/deploy-core'; import { basename, dirname, relative } from 'pathslash'; import { analyzeApplicationSync } from '../application-analysis.ts'; import type { ApplicationAnalysis } from '../application-analysis.ts'; @@ -301,19 +302,32 @@ export async function preflightCloudflareWorker(input: { ); printDeployContext(workerName, 'Cloudflare'); - if ( - expectedWorkflows.some( - (workflow) => - (workflow.script_name === undefined || workflow.script_name === workerName) && - hasWorkflowSchedules(workflow.schedules), - ) - ) { + const localWorkflows = expectedWorkflows.filter( + (workflow) => workflow.script_name === undefined || workflow.script_name === workerName, + ); + const schedules = localWorkflows.some((workflow) => hasWorkflowSchedules(workflow.schedules)); + const steps = Math.max( + 0, + ...localWorkflows.map(({ limits }) => + isRecord(limits) && typeof limits.steps === 'number' ? limits.steps : 0, + ), + ); + const concurrency = Math.max( + 0, + ...localWorkflows.map(({ concurrency }) => + isRecord(concurrency) && typeof concurrency.limit === 'number' ? concurrency.limit : 0, + ), + ); + if (schedules || steps > 1024 || concurrency > 100) { if (!assertUploaderStillPinned()) { return exit(1); } const checked = await runWrangler( { - type: 'workflows.schedules.entitlement', + type: 'workflows.entitlement', + schedules, + steps, + concurrency, configPath, fedramp: complianceRegion === 'fedramp_high', }, @@ -322,8 +336,17 @@ export async function preflightCloudflareWorker(input: { if (!isCleanCloudflareExit(checked) || checked.data !== true) { log.error( [ - `deploy: could not confirm scheduled Workflow access for Cloudflare account ${accountId}.`, - `Workflow schedules require Workers Paid. Enable the plan at ${CLOUDFLARE_WORKERS_PAID_URL} or remove schedules to use Workers Free.`, + `deploy: could not confirm the requested Workflow settings for Cloudflare account ${accountId}.`, + ...(schedules ? ['Remove Workflow schedules to use Workers Free.'] : []), + ...(steps > 1024 + ? [ + `Requested ${steps} steps per Workflow. Workers Free allows 1,024; Workers Paid allows up to 25,000.`, + ] + : []), + ...(concurrency > 100 + ? [`Requested ${concurrency} concurrent instances. Workers Free allows 100.`] + : []), + `Enable Workers Paid at ${CLOUDFLARE_WORKERS_PAID_URL} or use settings within your account limits.`, 'The deploy token needs Account Settings: Read to check entitlements and Workers Scripts: Edit to publish.', ].join('\n'), ); diff --git a/packages/void/src/cli/deploy-cloudflare-publish.ts b/packages/void/src/cli/deploy-cloudflare-publish.ts index 1e4ed026c8..9bad45a691 100644 --- a/packages/void/src/cli/deploy-cloudflare-publish.ts +++ b/packages/void/src/cli/deploy-cloudflare-publish.ts @@ -80,6 +80,10 @@ export async function publishCloudflareWorker(input: { if (usesCf && !cfUploaderIsPinned()) { return exit(1); } + const message = encodeCloudflareVersionMessage(input.migration.migrationHistory, { + ...readCloudflareTriggerConfig(generatedConfigPath, configPath), + ...(existingWorker ? { preserve: true } : {}), + }); const cfOutput = usesCf ? await prepareBuildOutput() : null; if (!cfOutput && usesCf) { log.error('deploy: cf could not prepare the built Worker for deployment.'); @@ -131,10 +135,7 @@ export async function publishCloudflareWorker(input: { verifyUploader: cfOutput ? cfUploaderIsPinned : assertUploaderStillPinned, requireVersionMetadata: existingWorker === null || hasVersionMetadata, requirePreviewForReadiness: existingWorker !== null && !hasVersionMetadata, - message: encodeCloudflareVersionMessage(input.migration.migrationHistory, { - ...readCloudflareTriggerConfig(generatedConfigPath, configPath), - ...(existingWorker ? { preserve: true } : {}), - }), + message, allowFirstDeploymentBootstrap: workerWasMissingBeforeSecretProvisioning, ...(pinActiveSecrets ? { pinActiveSecrets } : {}), atomic, diff --git a/packages/void/src/cli/deploy-cloudflare-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index cf908615ce..ea5b7677e3 100644 --- a/packages/void/src/cli/deploy-cloudflare-static.ts +++ b/packages/void/src/cli/deploy-cloudflare-static.ts @@ -535,6 +535,13 @@ export async function runCloudflareStaticDeploy( if (usesCf && !cfUploaderIsPinned()) { return exit(1); } + const message = + options.preview === undefined + ? encodeCloudflareVersionMessage([], { + ...readCloudflareTriggerConfig(staticConfigPath, configPath), + ...(existingWorker ? { preserve: true } : {}), + }) + : ''; const cfOutput = usesCf ? await prepareCfStaticBuildOutput({ projectRoot: root, @@ -605,10 +612,7 @@ export async function runCloudflareStaticDeploy( verifyUploader: cfOutput ? cfUploaderIsPinned : assertUploaderStillPinned, requireVersionMetadata: existingWorker === null || versionMetadataBinding !== undefined, requirePreviewForReadiness: existingWorker !== null && versionMetadataBinding === undefined, - message: encodeCloudflareVersionMessage([], { - ...readCloudflareTriggerConfig(staticConfigPath, configPath), - ...(existingWorker ? { preserve: true } : {}), - }), + message, assetsDirectoryOverride: stagedAssetsDirectory, ...(options.atomic ? { diff --git a/packages/void/src/codegen/binding-types.ts b/packages/void/src/codegen/binding-types.ts index 1f64c5ac9a..e4d79ebb89 100644 --- a/packages/void/src/codegen/binding-types.ts +++ b/packages/void/src/codegen/binding-types.ts @@ -76,9 +76,18 @@ export function generateBindingTypes( } } } - for (const { bindingName } of workflows) { - // A definition may use its own binding. Keep c.env independent of the definition's type. - bindings.set(bindingName, 'Workflow'); + const workflowTypes: Array = []; + for (const { bindingName, relativePath } of workflows) { + const module = JSON.stringify('../workflows/' + relativePath); + if (/\.[cm]?js$/.test(relativePath)) { + workflowTypes.push( + '// @ts-ignore A JavaScript workflow can lack declarations when allowJs is disabled.', + ); + } + workflowTypes.push( + `type ${bindingName}Params = import("void/workflows").NativeWorkflowParams;`, + ); + bindings.set(bindingName, `Workflow<${bindingName}Params>`); } if (bindings.size === 0) { return null; @@ -86,6 +95,7 @@ export function generateBindingTypes( return [ '// Auto-generated by void — do not edit', 'export {};', + ...workflowTypes, 'declare global {', ' interface VoidGeneratedEnvBindings {', ...[...bindings] diff --git a/packages/void/src/plugin-inference.ts b/packages/void/src/plugin-inference.ts index a246d19198..dc18a01dc9 100644 --- a/packages/void/src/plugin-inference.ts +++ b/packages/void/src/plugin-inference.ts @@ -167,17 +167,22 @@ export function inferProjectBindings( const workflowsDir = join(root, 'workflows'); const scanSourceFiles = (dirPath: string): Array => { const patterns = conventionFileGlobs(dirPath, SOURCE_GLOB, paths.routesDir); + const prefix = relative(dirPath, workflowsDir); + const insideWorkflows = dirPath === workflowsDir || dirPath.startsWith(`${workflowsDir}/`); if (hasWorkflows) { // Workflow modules also accept .cts and .cjs. Match step helpers with those // extensions even when a custom scan directory starts above or inside workflows/. - const prefix = relative(dirPath, workflowsDir); - if (dirPath.startsWith(`${workflowsDir}/`)) { + if (insideWorkflows) { patterns.push('**/*.{cts,cjs}'); } else if (prefix !== '..' && !prefix.startsWith('../')) { patterns.push(join(prefix, '**/*.{cts,cjs}')); } } - return globSync(patterns, { cwd: dirPath, absolute: true }); + return globSync(patterns, { + cwd: dirPath, + absolute: true, + ignore: [join(insideWorkflows ? '' : prefix, '**/node_modules/**')], + }); }; const addFile = (file: string): void => { const normalizedFile = toSlash(file); diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts index 2e5e0fed09..5348cdcb13 100644 --- a/packages/void/src/runtime/workflows/index.ts +++ b/packages/void/src/runtime/workflows/index.ts @@ -6,7 +6,11 @@ import { getRuntimeEnv, requireRuntimeBinding, withRuntimeEnv } from '../env/run export type { WorkflowEvent, WorkflowStep }; -type NativeWorkflowClass = new (...args: Array) => WorkflowEntrypoint; +// Inferring a binding needs the event parameter. Inspecting the return type here would +// make a class that starts its own Workflow depend on its own inferred result. +type NativeWorkflowClass = new (...args: Array) => Rpc.WorkflowEntrypointBranded & { + run(...args: Array): void; +}; /** Params type of a native class, read from its `run(event)` annotation. */ export type NativeWorkflowParams = Parameters< @@ -68,11 +72,13 @@ export type WorkflowApi = { get(binding: Workflow, id: string): Promise; }; -export type WorkflowRun = ( +type WorkflowCallback = ( event: Readonly>, step: WorkflowStep, context: WorkflowContext, -) => Promise; +) => TResult; + +export type WorkflowRun = WorkflowCallback>; export type WorkflowClass> = new ( ctx: ExecutionContext, @@ -198,6 +204,11 @@ type WorkflowDefinitionBase = { name?: string; }; +// TypeScript must be able to resolve the binding before checking a step that starts its own +// Workflow. The callback result is forwarded by the entrypoint and never inferred by the API. +// oxlint-disable-next-line typescript/no-explicit-any -- An unconstrained contextual return prevents recursive inference. +type DefinitionRun = WorkflowCallback; + /** * Define a Workflow from a run function. Void generates the Cloudflare * `WorkflowEntrypoint` class. Default-export the result from a file in `workflows/`. @@ -206,7 +217,7 @@ export function defineWorkflow>, TEnv>; + run: DefinitionRun>, TEnv>; }, ): WorkflowApi< WorkflowClass>, TEnv>, @@ -216,13 +227,13 @@ export function defineWorkflow>( definition: WorkflowDefinitionBase & { params?: undefined; - run: WorkflowRun, TEnv>; + run: DefinitionRun, TEnv>; }, ): WorkflowApi, TEnv>, TParams, WorkflowPayload>; export function defineWorkflow( definition: WorkflowDefinitionBase & { params?: StandardSchemaV1; - run: WorkflowRun>; + run: WorkflowCallback, unknown>; }, ): WorkflowApi, unknown> { if (typeof definition.run !== 'function') { @@ -231,7 +242,10 @@ export function defineWorkflow( const run = definition.run; class VoidWorkflow extends WorkflowEntrypoint, unknown> { - override run(event: Readonly>, step: WorkflowStep): Promise { + override async run( + event: Readonly>, + step: WorkflowStep, + ): Promise { const env = this.env; const ctx = this.ctx; return withRuntimeEnv(env, () => run(event, step, { env: getRuntimeEnv(), ctx })); diff --git a/packages/void/src/shared/static-exports.ts b/packages/void/src/shared/static-exports.ts index 1b8f06d894..da814c8b3f 100644 --- a/packages/void/src/shared/static-exports.ts +++ b/packages/void/src/shared/static-exports.ts @@ -140,6 +140,7 @@ export function unwrapStaticExpression(node: AstNode | undefined): AstNode | und [ 'ParenthesizedExpression', 'TSAsExpression', + 'TSInstantiationExpression', 'TSSatisfiesExpression', 'TSTypeAssertion', ].includes(node.type) diff --git a/packages/void/src/workflows/scan.ts b/packages/void/src/workflows/scan.ts index ce57ca647f..d8dc0b547e 100644 --- a/packages/void/src/workflows/scan.ts +++ b/packages/void/src/workflows/scan.ts @@ -33,7 +33,7 @@ export function inferWorkflowResourceName(relativePath: string): string { /** Module files under `workflows/`, skipping declarations and `_`-prefixed files or directories. */ function listWorkflowFiles(directory: string): Array { - return globSync(MODULE_GLOB, { cwd: directory }) + return globSync(MODULE_GLOB, { cwd: directory, ignore: ['**/node_modules/**'] }) .map((file) => file.replaceAll('\\', '/')) .filter( (file) => diff --git a/packages/void/test/integration/workflow-dev.test.ts b/packages/void/test/integration/workflow-dev.test.ts index c191b2dee7..1e61f92615 100644 --- a/packages/void/test/integration/workflow-dev.test.ts +++ b/packages/void/test/integration/workflow-dev.test.ts @@ -1,4 +1,4 @@ -import { execFileSync } from 'node:child_process'; +import { spawnSync } from 'node:child_process'; import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { expect, it, onTestFinished } from 'vite-plus/test'; @@ -88,6 +88,18 @@ export default defineWorkflow<{ id: string }, CloudBindings>({ } }, });`, + ); + writeFileSync( + join(directory, 'bill.mts'), + `import { WorkflowEntrypoint, type WorkflowEvent } from 'cloudflare:workers'; +import type { CloudBindings } from 'void/handler'; +import { defineWorkflowEntrypoint } from 'void/workflows'; +class Bill extends WorkflowEntrypoint { + async run(event: WorkflowEvent<{ invoice: number }>) { + if (event.payload.invoice === 1) return (await this.env.WORKFLOW_BILL.create({ params: { invoice: 2 } })).id; + } +} +export default defineWorkflowEntrypoint({ class: Bill });`, ); const { prepareProject } = await import('../../src/codegen/prepare.ts'); await prepareProject(fixture.root); @@ -99,6 +111,10 @@ export default defineWorkflow<{ id: string }, CloudBindings>({ import Notify from './workflows/notify'; export const GET = defineHandler(async c => { await Notify.create(c.env.WORKFLOW_NOTIFY, { params: { id: 'hello' } }); + // @ts-expect-error Bill requires an invoice, so it cannot receive Notify's payload. + await Notify.create(c.env.WORKFLOW_BILL, { params: { id: 'hello' } }); + // @ts-expect-error Raw creation on a local binding checks its payload too. + await c.env.WORKFLOW_NOTIFY.create({ params: { invoice: 123 } }); // @ts-expect-error The Workflow requires a string id. await Notify.create(c.env.WORKFLOW_NOTIFY, { params: { id: 42 } }); return 'ok'; @@ -115,16 +131,67 @@ export const GET = defineHandler(async c => { moduleResolution: 'Bundler', target: 'ES2022', types: ['void/env'], + lib: ['ES2022'], skipLibCheck: true, }, include: ['binding.ts'], }), ); - execFileSync( + const tsc = spawnSync( process.execPath, [join(repository, 'node_modules/typescript/bin/tsc'), '-p', 'tsconfig.binding.json'], - { cwd: fixture.root }, + { cwd: fixture.root, encoding: 'utf8' }, ); + expect(tsc.status, tsc.stdout + tsc.stderr).toBe(0); +}); + +it('types JavaScript Workflow bindings with and without allowJs', async () => { + const fixture = createIsolatedPlayground(repository, 'playground/ssr'); + onTestFinished(() => fixture.cleanup()); + mkdirSync(join(fixture.root, 'workflows')); + writeFileSync( + join(fixture.root, 'workflows', 'archive.mjs'), + ` +import { defineWorkflow } from 'void/workflows'; +export default defineWorkflow({ + /** @param {import('void/workflows').WorkflowEvent<{ days: number }>} event */ + async run(event) { return event.payload.days; }, +});`, + ); + const { prepareProject } = await import('../../src/codegen/prepare.ts'); + await prepareProject(fixture.root); + for (const allowJs of [false, true]) { + writeFileSync( + join(fixture.root, 'binding.mts'), + ` +import type {} from 'void/workflows'; +declare const env: VoidGeneratedEnvBindings; +void env.WORKFLOW_ARCHIVE.create({ params: { days: 3 } }); +${allowJs ? '// @ts-expect-error Checked JavaScript requires a numeric days field.' : ''} +void env.WORKFLOW_ARCHIVE.create({ params: { days: "three" } });`, + ); + writeFileSync( + join(fixture.root, 'tsconfig.binding.json'), + JSON.stringify({ + compilerOptions: { + allowJs, + strict: true, + noEmit: true, + module: 'NodeNext', + target: 'ES2022', + lib: ['ES2022'], + types: [], + }, + files: ['binding.mts', '.void/bindings.d.ts'], + }), + ); + const tsc = spawnSync( + process.execPath, + [join(repository, 'node_modules/typescript/bin/tsc'), '-p', 'tsconfig.binding.json'], + { cwd: fixture.root, encoding: 'utf8' }, + ); + expect(tsc.status, tsc.stdout + tsc.stderr).toBe(0); + } }); it.each(['cjs', 'cts'])( diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 1df0574796..b75d5f334b 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -4490,16 +4490,27 @@ describe('runCloudflareDeploy — preflight', () => { it.each([ { schedules: '0 * * * *', paid: false, shouldProbe: true }, { schedules: ['0 * * * *'], paid: true, shouldProbe: true }, + { schedules: undefined, concurrency: 101, paid: false, shouldProbe: true }, + { schedules: undefined, concurrency: 100, paid: false, shouldProbe: false }, + { schedules: undefined, steps: 25_000, paid: false, shouldProbe: true }, + { schedules: undefined, steps: 1024, paid: false, shouldProbe: false }, { schedules: [], paid: false, shouldProbe: false }, { schedules: undefined, paid: false, shouldProbe: false }, ])( - 'checks Workers Paid only for scheduled Workflows ($schedules, paid=$paid)', - async ({ schedules, paid, shouldProbe }) => { + 'checks Workflow entitlements when required ($schedules, $steps steps, paid=$paid)', + async ({ schedules, steps, concurrency, paid, shouldProbe }) => { const root = d1Project( { ...PROVISIONED_D1, workflows: [ - { binding: 'WORKFLOW_NOTIFY', name: 'notify', class_name: 'NotifyWorkflow', schedules }, + { + binding: 'WORKFLOW_NOTIFY', + name: 'notify', + class_name: 'NotifyWorkflow', + schedules, + ...(steps && { limits: { steps } }), + ...(concurrency && { concurrency: { limit: concurrency } }), + }, ], }, { @@ -4510,7 +4521,10 @@ describe('runCloudflareDeploy — preflight', () => { const { deps, trace } = harness(); const run = deps.runWrangler!; deps.runWrangler = (operation, options) => { - if (operation.type === 'workflows.schedules.entitlement') { + if (operation.type === 'workflows.entitlement') { + expect(operation.steps).toBe(steps ?? 0); + expect(operation.concurrency).toBe(concurrency ?? 0); + expect(operation.schedules).toBe(Boolean(schedules?.length)); trace.push('check-schedules'); return { ...cleanExit, data: paid }; } diff --git a/packages/void/test/unit/cloudflare-operation-process.test.ts b/packages/void/test/unit/cloudflare-operation-process.test.ts index 14e2f600b4..da1d0ce01d 100644 --- a/packages/void/test/unit/cloudflare-operation-process.test.ts +++ b/packages/void/test/unit/cloudflare-operation-process.test.ts @@ -1867,7 +1867,16 @@ syncBuiltinESMExports();`, 30_000, ); -it.each([ +const workflowEntitlementCases: Array<{ + name: string; + entitlements: Array; + eligible?: boolean; + status?: number; + fedramp?: boolean; + schedules?: boolean; + steps?: number; + concurrency?: number; +}> = [ { name: 'Workers Paid', entitlements: [{ id: 'workers.enabled', allocation: { type: 'bool', value: true } }], @@ -1890,6 +1899,22 @@ it.each([ ], eligible: false, }, + ...[2000, 2001].map((steps) => ({ + name: `requested ${steps} steps against a custom 2000-step allocation`, + entitlements: [ + { id: 'workflows.max_step_count', allocation: { type: 'max_count', value: 2000 } }, + ], + schedules: false, + steps, + eligible: steps === 2000, + })), + ...[100, 101].map((concurrency) => ({ + name: `requested concurrency of ${concurrency} on Free`, + entitlements: [], + concurrency, + schedules: false, + eligible: concurrency <= 100, + })), { name: 'absent entitlements', entitlements: [], eligible: false }, { name: 'FedRAMP default allocation', entitlements: [], fedramp: true, eligible: true }, { @@ -1912,9 +1937,19 @@ it.each([ eligible: false, }, { name: 'missing token permission', entitlements: [], status: 403 }, -])( +]; + +it.each(workflowEntitlementCases)( 'reads scheduled Workflow eligibility using the pinned account: $name', - async ({ entitlements, eligible, status, fedramp = false }) => { + async ({ + entitlements, + eligible, + status, + fedramp = false, + schedules = true, + steps = 0, + concurrency = 0, + }) => { const requests: Array = []; const api = await listen( createServer((request, response) => { @@ -1925,7 +1960,7 @@ it.each([ ); const output = await runOperation( temporaryDirectory('void-workflow-plan-'), - { type: 'workflows.schedules.entitlement', fedramp }, + { type: 'workflows.entitlement', fedramp, schedules, steps, concurrency }, tokenEnv(api), ); expect(requests).toEqual(['GET /client/v4/accounts/test-account/entitlements']); diff --git a/packages/void/test/unit/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index 9f9e3a96f1..09995ff161 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -396,6 +396,12 @@ describe('inferProjectBindings', () => { const ai = createAi(env); } });`, ); + const installed = join(root, 'workflows', 'order', 'node_modules', 'mailer'); + mkdirSync(installed, { recursive: true }); + writeFileSync(join(installed, 'unused.js'), "import { db } from 'void/db'; export default db;"); + for (const dirs of [undefined, ['.'], ['workflows/order']]) { + expect(inferProjectBindings(root, undefined, dirs).needsD1).toBe(false); + } expect(inferProjectBindings(root)).toMatchObject({ needsAI: true, needsR2: true }); writeFileSync(join(root, 'void.json'), JSON.stringify({ sourceDir: 'src' })); expect(inferProjectBindings(root)).toMatchObject({ needsAI: true, needsR2: true }); diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts index 5e315d8e59..78314e5df0 100644 --- a/packages/void/test/unit/workflow-scan.test.ts +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -52,6 +52,21 @@ describe('scanWorkflowModules', () => { expect(() => assertNoWorkflowsForPlatform(root)).not.toThrow(); }); + it('ignores definitions in installed packages', () => { + const root = createRoot({ 'team/node_modules/mailer/send.js': definition }); + expect(scanWorkflowModules(root)).toEqual([]); + expect(() => assertNoWorkflowsForPlatform(root)).not.toThrow(); + }); + + it('resolves a specialized TypeScript helper alias', () => { + const root = createRoot({ + 'digest.ts': `import { defineWorkflow } from 'void/workflows'; +const defineDigest = defineWorkflow<{ id: string }>; +export default defineDigest({ name: 'daily', async run() {} });`, + }); + expect(scanWorkflowModules(root)).toMatchObject([{ bindingName: 'WORKFLOW_DAILY' }]); + }); + it('returns nothing without a workflows directory', () => { const root = mkdtempSync(join(tmpdir(), 'void-workflow-scan-')); roots.push(root); From b138d5d37fe2e512c7c753c21264864c3ba7f5b3 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 15:03:50 +0900 Subject: [PATCH 11/13] Fix Workflow deployment, migration recovery, and binding inference. --- docs/guide/workflows.md | 4 +- docs/reference/cli/project.md | 2 +- packages/deploy-cloudflare/src/index.ts | 3 + packages/deploy-cloudflare/src/operations.ts | 1 + packages/deploy-cloudflare/src/version.ts | 104 +++++++++-- packages/deploy-cloudflare/src/workflows.ts | 35 ++++ .../test/unit/version.test.ts | 130 +++++++++++++- packages/void/src/cli/cf-config-migrate.ts | 28 ++- .../src/cli/cloudflare-operation-process.ts | 2 + .../void/src/cli/cloudflare-operations.ts | 5 +- .../src/cli/deploy-artifact-validation.ts | 7 + .../void/src/cli/deploy-binding-snapshot.ts | 6 +- .../void/src/cli/deploy-cloudflare-migrate.ts | 146 +++++++++------- .../src/cli/deploy-cloudflare-preflight.ts | 46 ++++- .../void/src/cli/deploy-cloudflare-publish.ts | 27 +-- packages/void/src/cli/deploy-cloudflare.ts | 30 ++-- packages/void/src/cli/list.ts | 4 +- packages/void/src/cli/rollback.ts | 39 +++-- packages/void/src/codegen/binding-types.ts | 3 +- packages/void/src/plugin-worker-bindings.ts | 3 +- packages/void/src/runtime/workflows/index.ts | 19 ++ .../void/src/shared/resource-definition.ts | 38 ++-- packages/void/src/workflows/config.ts | 8 +- packages/void/src/workflows/retention.ts | 36 ++++ .../cloudflare-durable-build.test.ts | 44 ++++- .../test/integration/workflow-dev.test.ts | 56 +++++- .../void/test/unit/cloudflare-deploy.test.ts | 163 +++++++++++++++--- .../unit/cloudflare-operation-process.test.ts | 18 +- .../void/test/unit/rollback-platform.test.ts | 34 ++++ packages/void/test/unit/workflow-scan.test.ts | 23 +++ 30 files changed, 890 insertions(+), 174 deletions(-) create mode 100644 packages/deploy-cloudflare/src/workflows.ts create mode 100644 packages/void/src/workflows/retention.ts diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md index c843c2d83d..3679626f9a 100644 --- a/docs/guide/workflows.md +++ b/docs/guide/workflows.md @@ -161,11 +161,13 @@ export default defineConfig({ If the generated Cloudflare Workflow name exceeds 64 characters, use this entry to give it a shorter name. +If you already declare the Workflow in `cloudflare.exports`, use the generated class name as the export key. Void uses that export's Workflow name and settings for the generated binding. + ## Deployment support Workflows are available on the Workers Free plan, within [Cloudflare's Workflows limits](https://developers.cloudflare.com/workflows/reference/limits/). Deploy to your own Cloudflare account with `void deploy --platform cloudflare`. -To start instances on a cron schedule through `cloudflare.workflows[].schedules`, set `limits.steps` above 1,024, or set `concurrency.limit` above 100, [enable Workers Paid](https://dash.cloudflare.com/?to=/:account/workers/plans). Workers Paid supports up to 25,000 steps per instance. For these settings, give your deployment API token **Account Settings: Read** to check your account's allocation and **Workers Scripts: Edit** to publish. +Scheduled Workflows, more than 1,024 steps, concurrency above 100, and default retention longer than 3 days require [Workers Paid](https://dash.cloudflare.com/?to=/:account/workers/plans). Paid supports up to 25,000 steps per instance and up to 30 days of retention. Set `default_retention.success_retention` or `default_retention.error_retention` to a duration such as `"7 days"` or a whole number of milliseconds. For paid settings, give your deployment API token **Account Settings: Read** to check your account's allocation and **Workers Scripts: Edit** to publish. If Cloudflare rejects staging because you added, renamed, or removed a Workflow, run `void deploy --platform cloudflare --atomic` for that deployment. The new version receives traffic before Void checks readiness. diff --git a/docs/reference/cli/project.md b/docs/reference/cli/project.md index 699ba10b53..760ebe51de 100644 --- a/docs/reference/cli/project.md +++ b/docs/reference/cli/project.md @@ -267,7 +267,7 @@ On a Void platform, you can select a retained deployment. On Cloudflare, use a c Pass `--platform cloudflare` to roll back a one-off Cloudflare deployment. -Database recovery is separate from code rollback. Void asks for confirmation when the earlier code may be incompatible with the current schema. For D1 on Cloudflare, use [`void db restore`](./database.md#void-db-restore) with the restore point printed during deployment. +Database recovery is separate from code rollback. Void asks for confirmation when the earlier code may be incompatible with the current schema. For long Cloudflare migration histories, the rollback prompt can report a change and the migration counts without listing individual filenames. For D1 on Cloudflare, use [`void db restore`](./database.md#void-db-restore) with the restore point printed during deployment. ## `void project preview delete ` {#void-project-preview-delete-name} diff --git a/packages/deploy-cloudflare/src/index.ts b/packages/deploy-cloudflare/src/index.ts index 434ed08c4a..971591302c 100644 --- a/packages/deploy-cloudflare/src/index.ts +++ b/packages/deploy-cloudflare/src/index.ts @@ -40,6 +40,7 @@ export { deployCloudflareVersionTriggers, deployCloudflareVersionTraffic, encodeCloudflareVersionMessage, + summarizeCloudflareMigrations, extractWorkersDevSubdomain, hasWorkflowSchedules, normalizeReadinessAccessOrigin, @@ -74,3 +75,5 @@ export type { CloudflareUploadResult, CloudflareProviderError, } from './operations.ts'; + +export { readWorkflowDeclarations, workflowExports } from './workflows.ts'; diff --git a/packages/deploy-cloudflare/src/operations.ts b/packages/deploy-cloudflare/src/operations.ts index 521905af84..cf6585cd17 100644 --- a/packages/deploy-cloudflare/src/operations.ts +++ b/packages/deploy-cloudflare/src/operations.ts @@ -24,6 +24,7 @@ export type CloudflareOperation = schedules: boolean; steps: number; concurrency: number; + retentionMs: number; } & ConfigTarget) | { type: 'd1.create'; name: string; binding: string; configPath: string } | ({ type: 'd1.execute'; database: string; configPath: string } & ( diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 3b84867a0b..238e119614 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -25,18 +25,30 @@ import { VOID_SECRET_DRAFT_SOURCE, } from './secret-draft.ts'; import { cloudflareStagingPairGuidance } from './staging-guidance.ts'; +import { readWorkflowDeclarations } from './workflows.ts'; const DURABLE_MIGRATION_VERSION_ERROR = 10_211; const CLOUDFLARE_SECRET_CHANGED_ERROR = 10_220; +type MigrationSummary = Readonly<{ count: number; digest: string }>; + +export function summarizeCloudflareMigrations(names: ReadonlyArray): MigrationSummary { + return { + count: names.length, + digest: createHash('sha256').update(JSON.stringify(names)).digest('hex'), + }; +} + export type CloudflareVersionMetadata = | Readonly<{ schema: 1; migrations: ReadonlyArray | null; + migrationSummary?: MigrationSummary; }> | Readonly<{ schema: 2; migrations: ReadonlyArray | null; + migrationSummary?: MigrationSummary; triggerConfig: CloudflareTriggerConfig; /** Digest of the complete Worker upload input, when supplied by the caller. */ contentHash?: string; @@ -187,13 +199,17 @@ const MAX_VERSION_MESSAGE_BYTES = 1000; /** Encode migration state into Cloudflare's version annotation for safe rollback diagnostics. */ export function encodeCloudflareVersionMessage( - migrations: ReadonlyArray | null, + history: ReadonlyArray | MigrationSummary | null, triggerConfig?: CloudflareTriggerConfig, contentHash?: string, ): string { + const migrationState = + history && 'digest' in history + ? { migrations: null, migrationSummary: history } + : { migrations: history }; const metadata: CloudflareVersionMetadata = triggerConfig - ? { schema: 2, migrations, triggerConfig, ...(contentHash ? { contentHash } : {}) } - : { schema: 1, migrations }; + ? { schema: 2, ...migrationState, triggerConfig, ...(contentHash ? { contentHash } : {}) } + : { schema: 1, ...migrationState }; const json = JSON.stringify(metadata); const message = 'void:' + json; // Cloudflare truncates workers/message at 1000 bytes. Keep the existing format @@ -203,8 +219,21 @@ export function encodeCloudflareVersionMessage( } const compressed = 'void:z:' + deflateRawSync(json).toString('base64url'); if (compressed.length > MAX_VERSION_MESSAGE_BYTES) { + // Keep trigger recovery lossless. The digest still lets rollback distinguish + // identical migration histories when the individual filenames do not fit. + if (migrationState.migrations?.length) { + return encodeCloudflareVersionMessage( + summarizeCloudflareMigrations(migrationState.migrations), + triggerConfig, + contentHash, + ); + } + if (migrationState.migrationSummary) { + // Rollback asks for confirmation when even the digest cannot fit alongside the triggers. + return encodeCloudflareVersionMessage(null, triggerConfig, contentHash); + } throw new Error( - "deploy: Worker recovery metadata exceeds Cloudflare's 1000-byte version message limit even after compression. Reduce the deployment's trigger or migration configuration before retrying.", + "deploy: Worker recovery metadata exceeds Cloudflare's 1000-byte version message limit even after compression. Reduce the deployment's trigger configuration before retrying.", ); } return compressed; @@ -239,11 +268,28 @@ export function parseCloudflareVersionMessage( ) { return null; } + const summary = value.migrationSummary; + let migrationSummary: MigrationSummary | undefined; + if ( + value.migrations === null && + isRecord(summary) && + typeof summary.count === 'number' && + Number.isSafeInteger(summary.count) && + summary.count >= 0 && + typeof summary.digest === 'string' && + /^[a-f0-9]{64}$/.test(summary.digest) + ) { + migrationSummary = { count: summary.count, digest: summary.digest }; + } + const migrationState = { + migrations: value.migrations, + ...(migrationSummary && { migrationSummary }), + }; if (value.schema === 1) { // Schema 1 did not capture preview_urls and represented an omitted // workers_dev ambiguously. Keep its migration history, but never expose // its incomplete trigger state to rollback. - return { schema: 1, migrations: value.migrations }; + return { schema: 1, ...migrationState }; } const triggerConfig = parseTriggerConfig(value.triggerConfig); if (!triggerConfig) { @@ -251,7 +297,7 @@ export function parseCloudflareVersionMessage( } return { schema: 2, - migrations: value.migrations, + ...migrationState, triggerConfig, ...(typeof value.contentHash === 'string' && /^[a-f0-9]{64}$/.test(value.contentHash) ? { contentHash: value.contentHash } @@ -748,7 +794,7 @@ function triggerConfigFromWrangler(config: Record): CloudflareT routes, crons: Array.isArray(triggers.crons) ? triggers.crons : [], queueConsumers: Array.isArray(queues.consumers) ? queues.consumers : [], - workflows: Array.isArray(config.workflows) ? config.workflows : [], + workflows: readWorkflowDeclarations(config), ...(addresses === undefined ? {} : { addresses }), }; } @@ -845,6 +891,21 @@ function triggerWranglerConfig( const queues = isRecord(base.queues) ? { ...base.queues } : {}; triggers.crons = [...triggerConfig.crons]; queues.consumers = [...triggerConfig.queueConsumers]; + const workflowExports = new Map(); + const workflows: Array = []; + for (const entry of triggerConfig.workflows) { + if ( + isRecord(entry) && + entry.type === 'workflow' && + typeof entry.class_name === 'string' && + entry.binding === undefined + ) { + const { class_name: className, ...declaration } = entry; + workflowExports.set(className, declaration); + } else { + workflows.push(entry); + } + } const config: WranglerTriggerConfig = { ...base, ...(triggerConfig.observability === undefined @@ -853,7 +914,8 @@ function triggerWranglerConfig( ...(triggerConfig.logpush === undefined ? {} : { logpush: triggerConfig.logpush }), triggers, queues, - workflows: [...triggerConfig.workflows], + workflows, + ...(workflowExports.size ? { exports: Object.fromEntries(workflowExports) } : {}), workers_dev: triggerConfig.workers_dev, preview_urls: triggerConfig.preview_urls, }; @@ -966,6 +1028,8 @@ export type CloudflareVersionActivationOptions = { */ readinessHeadersOrigin?: string; message: string; + /** Run database migrations once the effective recovery annotation fits, before either upload path. */ + beforeUpload?: () => Promise; /** Direct empty-domain publisher for the Wrangler reconciliation gap. */ publishEmptyCustomDomains?: () => Promise; publishEmptyCrons?: () => Promise; @@ -1318,8 +1382,18 @@ async function activateCloudflareVersionWithSecretsFile( } const message = desiredMetadata?.schema === 2 - ? encodeCloudflareVersionMessage(desiredMetadata.migrations, desiredTriggerConfig) + ? encodeCloudflareVersionMessage( + desiredMetadata.migrations ?? desiredMetadata.migrationSummary ?? null, + desiredTriggerConfig, + desiredMetadata.contentHash, + ) : options.message; + if (options.beforeUpload) { + await options.beforeUpload(); + if (!options.verifyUploader()) { + return { ok: false, reason: 'uploader-changed' }; + } + } const versionedPreviousTriggerConfigWithTraffic = versionedPreviousTriggerConfig && previousTrafficConfig ? { ...versionedPreviousTriggerConfig, ...previousTrafficConfig } @@ -1430,7 +1504,7 @@ async function activateCloudflareVersionWithSecretsFile( pinnedActiveSecrets = activeSecrets; } } - if (pinnedActiveSecrets) { + if (pinnedActiveSecrets || options.beforeUpload) { if (!options.verifyUploader()) { return { ok: false, reason: 'uploader-changed' }; } @@ -1440,11 +1514,13 @@ async function activateCloudflareVersionWithSecretsFile( } if ( owner.kind !== 'ok' || - previousVersionId === null || owner.versionId !== previous.versionId || - !productionVersionPercentagesEqual(owner.versions, [ - { versionId: previousVersionId, percentage: 100 }, - ]) + !productionVersionPercentagesEqual( + owner.versions, + pinnedActiveSecrets && previousVersionId + ? [{ versionId: previousVersionId, percentage: 100 }] + : previous.versions, + ) ) { return { ok: false, diff --git a/packages/deploy-cloudflare/src/workflows.ts b/packages/deploy-cloudflare/src/workflows.ts new file mode 100644 index 0000000000..cd134871ae --- /dev/null +++ b/packages/deploy-cloudflare/src/workflows.ts @@ -0,0 +1,35 @@ +import { isRecord } from '@void/deploy-core'; + +export function workflowExports(value: unknown): Record> { + return Object.fromEntries( + Object.entries(isRecord(value) ? value : {}).filter( + (entry): entry is [string, Record] => + isRecord(entry[1]) && entry[1].type === 'workflow', + ), + ); +} + +/** Capture bindings with their export settings and retain declarations that expose only ctx.exports. */ +export function readWorkflowDeclarations(config: Record): Array { + const bindings: ReadonlyArray = Array.isArray(config.workflows) ? config.workflows : []; + const workflows = [...bindings]; + for (const [className, declaration] of Object.entries(workflowExports(config.exports))) { + const { type, ...settings } = declaration; + let bound = false; + for (const [index, binding] of workflows.entries()) { + if ( + isRecord(binding) && + binding.class_name === className && + binding.name === settings.name && + (binding.script_name === undefined || binding.script_name === config.name) + ) { + workflows[index] = { ...settings, ...binding }; + bound = true; + } + } + if (!bound) { + workflows.push({ ...settings, type, class_name: className }); + } + } + return workflows; +} diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index badc8f3539..45fde0039a 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -2782,16 +2782,140 @@ describe('Cloudflare version activation', () => { expect(parseCloudflareVersionMessage(message)).toMatchObject({ triggerConfig: triggers }); }); + it('replays bound and export-only Workflow settings from version metadata', async () => { + const directory = mkdtempSync(join(tmpdir(), 'void-workflow-exports-')); + const configPath = join(directory, 'wrangler.json'); + const bound = { binding: 'JOB', class_name: 'Job', name: 'app_job' }; + const settings = { schedules: ['0 0 * * *'], default_retention: { error_retention: '7 days' } }; + const daily = { type: 'workflow', name: 'daily', limits: { steps: 2000 } }; + try { + writeFileSync( + configPath, + JSON.stringify({ + name: 'app', + workflows: [bound], + exports: { + Job: { type: 'workflow', name: bound.name, ...settings }, + Daily: daily, + }, + }), + ); + const metadata = parseCloudflareVersionMessage( + encodeCloudflareVersionMessage([], readCloudflareTriggerConfig(configPath)), + ); + if (metadata?.schema !== 2) { + throw new Error('Missing trigger snapshot'); + } + const runWrangler = vi.fn( + operationFixture((args) => { + expect(readConfigArg(args)).toMatchObject({ + workflows: [{ ...bound, ...settings }], + exports: { Daily: daily }, + }); + return ok(); + }), + ); + await deployCloudflareVersionTriggers({ + runWrangler, + workerName: 'app', + configPath, + triggerConfig: metadata.triggerConfig, + }); + expect(runWrangler).toHaveBeenCalledOnce(); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); + it('refuses recovery metadata that cannot fit even when compressed', () => { - const history = Array.from({ length: 64 }, (_, i) => - createHash('sha256').update(String(i)).digest('hex'), + const routes = Array.from( + { length: 64 }, + (_, i) => + createHash('sha256').update(String(i)).digest('hex').slice(0, 32) + '.example.com/*', ); - expect(() => encodeCloudflareVersionMessage(history)).toThrow( + const triggers = triggersWith({ routes }); + expect(() => encodeCloudflareVersionMessage([], triggers)).toThrow( '1000-byte version message limit', ); expect(parseCloudflareVersionMessage('void:z:invalid')).toBeNull(); }); + it('keeps the full trigger snapshot when even a migration digest would exceed the limit', () => { + const routes = Array.from( + { length: 28 }, + (_, i) => + createHash('sha256').update(String(i)).digest('hex').slice(0, 32) + '.example.com/*', + ); + const triggers = triggersWith({ routes }); + const history = Array.from({ length: 180 }, (_, i) => i + '_migration.sql'); + expect( + parseCloudflareVersionMessage(encodeCloudflareVersionMessage(history, triggers)), + ).toEqual({ + schema: 2, + migrations: null, + triggerConfig: triggers, + }); + }); + + it.each([false, true])( + 'rechecks the uploader after preparing migrations (atomic=%s)', + async (atomic) => { + const fixture = recoveryActivation({ previous: VOID_SCHEMA_2_PREVIOUS, atomic }); + let pinned = true; + const beforeUpload = vi.fn(async () => { + await Promise.resolve(); + pinned = false; + }); + const result = await activateCloudflareVersion({ + ...fixture.options, + verifyUploader: () => pinned, + beforeUpload, + }); + expect(beforeUpload).toHaveBeenCalledOnce(); + expect(result).toMatchObject({ ok: false, reason: 'uploader-changed' }); + expect( + fixture.options.runWrangler.mock.calls.map(([operation]) => operation.type), + ).not.toContain(atomic ? 'worker.deploy' : 'versions.upload'); + }, + ); + + it('checks the combined size of new routes and removed Workflow schedules before migrations', async () => { + const tenants = Array.from({ length: 16 }, (_, i) => + createHash('sha256').update(String(i)).digest('hex'), + ); + const previous = triggersWith({ + workflows: tenants.map((tenant, i) => ({ + name: 'job_' + tenant.slice(0, 32), + binding: 'JOB_' + i, + class_name: 'Job' + i, + schedules: ['0 * * * *'], + })), + }); + const desired = triggersWith({ + routes: tenants.map((tenant) => tenant.slice(-32) + '.example.com/*'), + }); + const fixture = recoveryActivation({ + previous: { + id: CURRENT, + number: 1, + annotations: { 'workers/message': encodeCloudflareVersionMessage([], previous) }, + }, + atomic: true, + }); + const beforeUpload = vi.fn(async () => {}); + await expect( + activateCloudflareVersion({ + ...fixture.options, + message: encodeCloudflareVersionMessage([], desired), + beforeUpload, + }), + ).rejects.toThrow('1000-byte version message limit'); + expect(beforeUpload).not.toHaveBeenCalled(); + expect( + fixture.options.runWrangler.mock.calls.map(([operation]) => operation.type), + ).not.toContain('worker.deploy'); + }); + it('retains failed schedule cleanup across atomic deploy retries and retires it after success', async () => { const old = { name: 'nightly', diff --git a/packages/void/src/cli/cf-config-migrate.ts b/packages/void/src/cli/cf-config-migrate.ts index b023dd61d3..78f031027c 100644 --- a/packages/void/src/cli/cf-config-migrate.ts +++ b/packages/void/src/cli/cf-config-migrate.ts @@ -154,6 +154,7 @@ function applyWorkflows(raw: JsonObject, worker: JsonObject): void { 'concurrency', 'schedules', 'default_retention', + 'jurisdiction', ]); for (const key of Object.keys(workflow)) { if (!allowed.has(key)) { @@ -170,19 +171,26 @@ function applyWorkflows(raw: JsonObject, worker: JsonObject): void { exportName: workflow.class_name, }; if (workflow.script_name !== undefined && workflow.script_name !== worker.name) { + if ( + Object.values(exports).some( + (value) => isRecord(value) && value.type === 'workflow' && value.name === workflow.name, + ) + ) { + throw new Error( + `External Workflow ${workflow.name} conflicts with a local Workflow export.`, + ); + } continue; } const retention = record(workflow.default_retention); - if (Object.hasOwn(exports, workflow.class_name)) { - throw new Error(`Duplicate Worker export ${workflow.class_name}.`); - } const schedules = Array.isArray(workflow.schedules) && workflow.schedules.length === 0 ? undefined : workflow.schedules; - exports[workflow.class_name] = { + const declaration = { type: 'workflow', name: workflow.name, + ...(workflow.jurisdiction !== undefined ? { jurisdiction: workflow.jurisdiction } : {}), ...(workflow.limits !== undefined ? { limits: workflow.limits } : {}), ...(workflow.concurrency !== undefined ? { concurrency: workflow.concurrency } : {}), ...(schedules !== undefined ? { schedules } : {}), @@ -199,6 +207,18 @@ function applyWorkflows(raw: JsonObject, worker: JsonObject): void { } : {}), }; + const existing = record(exports[workflow.class_name]); + if ( + existing && + Object.entries(declaration).some( + ([key, value]) => Object.hasOwn(existing, key) && !isDeepStrictEqual(existing[key], value), + ) + ) { + throw new Error( + `Conflicting Worker export ${workflow.class_name} for Workflow ${workflow.name}.`, + ); + } + exports[workflow.class_name] = { ...existing, ...declaration }; } worker.env = env; worker.exports = exports; diff --git a/packages/void/src/cli/cloudflare-operation-process.ts b/packages/void/src/cli/cloudflare-operation-process.ts index 5f805498f0..aa91298036 100644 --- a/packages/void/src/cli/cloudflare-operation-process.ts +++ b/packages/void/src/cli/cloudflare-operation-process.ts @@ -14,6 +14,7 @@ import type { } from '@void/deploy-cloudflare'; import { parse } from 'jsonc-parser'; import { dirname, join, resolve } from 'pathslash'; +import { FREE_WORKFLOW_RETENTION_MS, PAID_WORKFLOW_RETENTION_MS } from '../workflows/retention.ts'; import { CF_VERSION_SOURCE_MAX_OUTPUT_BYTES, isD1Bookmark, @@ -835,6 +836,7 @@ async function checkWorkflowEntitlement( '', request.steps <= stepLimit && request.concurrency <= concurrencyLimit && + request.retentionMs <= (paid ? PAID_WORKFLOW_RETENTION_MS : FREE_WORKFLOW_RETENTION_MS) && (!request.schedules || schedulesAllowed), ); } diff --git a/packages/void/src/cli/cloudflare-operations.ts b/packages/void/src/cli/cloudflare-operations.ts index d4b120275c..02052177e7 100644 --- a/packages/void/src/cli/cloudflare-operations.ts +++ b/packages/void/src/cli/cloudflare-operations.ts @@ -506,7 +506,10 @@ export async function activateCloudflareExistingVersion( const currentTriggerConfig = publishedTraffic ? { ...current.metadata.triggerConfig, ...publishedTraffic } : current.metadata.triggerConfig; - const message = encodeCloudflareVersionMessage(target.metadata.migrations, targetTriggerConfig); + const message = encodeCloudflareVersionMessage( + target.metadata.migrations ?? target.metadata.migrationSummary ?? null, + targetTriggerConfig, + ); const ownerBeforeActivation = await readActiveCloudflareVersionId(context); if (ownerBeforeActivation !== current.id) { throw new Error( diff --git a/packages/void/src/cli/deploy-artifact-validation.ts b/packages/void/src/cli/deploy-artifact-validation.ts index 32edad8958..85483948d3 100644 --- a/packages/void/src/cli/deploy-artifact-validation.ts +++ b/packages/void/src/cli/deploy-artifact-validation.ts @@ -5,6 +5,7 @@ import { readConfigEntryString as readD1EntryString, readStoredResourceName, assertExistingCloudflareConfig, + workflowExports, } from '@void/deploy-cloudflare'; import type { ExistingCloudflareWorker, @@ -374,6 +375,12 @@ export function verifyGeneratedDeployConfig( // `[]` deletes every email routing rule the Worker owns, so it must match exactly. if (expected.passthroughRawFields) { const raw = expected.passthroughRawFields; + if (!deepEqual(workflowExports(generated.exports), workflowExports(raw.get('exports')))) { + return { + ok: false, + reason: 'generated Workflow exports differ from the pre-build configuration.', + }; + } for (const field of DEPLOY_WHOLE_OBJECT_PINNED_FIELDS) { const emitted = generated[field]; const rootValue = raw.get(field); diff --git a/packages/void/src/cli/deploy-binding-snapshot.ts b/packages/void/src/cli/deploy-binding-snapshot.ts index 6d5459bec8..7b5031ab14 100644 --- a/packages/void/src/cli/deploy-binding-snapshot.ts +++ b/packages/void/src/cli/deploy-binding-snapshot.ts @@ -171,6 +171,7 @@ export const DEPLOY_WHOLE_OBJECT_PINNED_FIELDS: ReadonlyArray = [ */ const DEPLOY_RAW_SNAPSHOT_FIELDS: ReadonlyArray = [ ...DEPLOY_WHOLE_OBJECT_PINNED_FIELDS, + 'exports', 'durable_objects', 'ai', 'migrations', @@ -304,7 +305,10 @@ export function reconstructExpectedWorkflows( ): Array> { const configured = workflowConfigEntries(rootConfig.workflows); const modules = (analysis ?? analyzeApplicationSync(root, { config })).workflows; - return [...configured, ...planWorkflowAdditions(configured, modules, workerName)]; + return [ + ...configured, + ...planWorkflowAdditions(configured, modules, workerName, rootConfig.exports), + ]; } /** Reconstruct the Durable Object state emitted after the pre-build root config is synced. */ diff --git a/packages/void/src/cli/deploy-cloudflare-migrate.ts b/packages/void/src/cli/deploy-cloudflare-migrate.ts index f5fadef6c1..336e0aaa60 100644 --- a/packages/void/src/cli/deploy-cloudflare-migrate.ts +++ b/packages/void/src/cli/deploy-cloudflare-migrate.ts @@ -1,3 +1,7 @@ +import { + encodeCloudflareVersionMessage, + readCloudflareTriggerConfig, +} from '@void/deploy-cloudflare'; import { runMySqlMigrations } from '../migrations/runner-mysql.ts'; import { runPgMigrations } from '../migrations/runner-pg.ts'; import { @@ -8,20 +12,17 @@ import { ensureCloudflareAuthSecret } from './deploy-cloudflare-auth.ts'; import type { CloudflareBuild } from './deploy-cloudflare-build.ts'; import type { CloudflareDeploySource, CloudflarePreflight } from './deploy-cloudflare-preflight.ts'; import { log } from './deploy-helpers.ts'; -import { - applyAndVerifyRemoteD1Migrations, - logD1RestoreAfterDeployFailure, -} from './deploy-migrations.ts'; +import { applyAndVerifyRemoteD1Migrations } from './deploy-migrations.ts'; import { CloudflareAuthSecretError } from './deploy-resources.ts'; import type { CloudflareDeployDeps } from './deploy-types.ts'; import type { CliLogger } from './log-file.ts'; import { getErrorMessage } from './output.ts'; import { readDeploymentPlatform } from './project.ts'; -export type CloudflareMigration = Awaited>; +export type CloudflareMigration = Awaited>; -/** Provision the auth secret and apply database migrations, then verify the artifact. */ -export async function migrateCloudflareWorker(input: { +/** Verify the build and prepare migrations for the deploy's pre-upload check. */ +export async function prepareCloudflareWorkerMigrations(input: { readonly root: string; readonly deps: CloudflareDeployDeps; readonly exit: (code: number) => never; @@ -30,14 +31,14 @@ export async function migrateCloudflareWorker(input: { readonly preflight: CloudflarePreflight; readonly build: CloudflareBuild; readonly skipMigrations?: boolean; + readonly onD1Restore: (command: string) => void; }): Promise<{ workerWasMissingBeforeSecretProvisioning: boolean; initialAuthSecret: string | undefined; - appliedMigrations: number; + applyMigrations: (() => Promise) | undefined; + message: string; /** Null when SQL execution was skipped and applied history was not verified. */ migrationHistory: ReadonlyArray | null; - /** Restores the D1 state from before this deploy's migrations, when it applied any. */ - d1RestoreCommand: string | undefined; }> { const { root, deps, exit, cliLog } = input; const { @@ -84,6 +85,14 @@ export async function migrateCloudflareWorker(input: { expectedCrons, }; + const migrationHistory = input.skipMigrations + ? null + : migrations.map((migration) => migration.name); + const message = encodeCloudflareVersionMessage(migrationHistory, { + ...readCloudflareTriggerConfig(input.build.generatedConfigPath, configPath), + ...(input.preflight.existingWorker ? { preserve: true } : {}), + }); + // Persistent Better Auth secret: adopted when present, otherwise generated once and verified, // before the first remote migration or upload. if (authEnabled) { @@ -127,72 +136,81 @@ export async function migrateCloudflareWorker(input: { } } - let appliedMigrations = 0; + const verifyArtifact = () => + verifyCloudflareDeployArtifact(root, deps, { + ...verifyOptions, + requiredSecretNames: schemaFacts.requiredKeys, + }); + if (!verifyArtifact()) { + return exit(1); + } + if (input.skipMigrations) { log.info('Skipping database migrations.'); cliLog.info('cloudflare_migrations_skipped'); } - // Cloudflare never returns the Hyperdrive password, so the deploy environment provides the - // production URL. A rerun skips migrations already recorded as finished. A failed PostgreSQL - // file rolls back. A failed MySQL file rolls back its data changes, but MySQL commits DDL on - // its own, so earlier statements of that file can stay applied. - if (!input.skipMigrations && dialect !== 'sqlite' && migrations.length > 0) { - const mysql = dialect === 'mysql'; - const label = mysql ? 'MySQL' : 'PostgreSQL'; - const databaseUrl = process.env.DATABASE_URL; - if (!databaseUrl) { - log.error(`deploy: DATABASE_URL disappeared before ${label} migrations could run.`); - return exit(1); - } - try { - const applyMigrations = mysql - ? (deps.applyMySqlMigrations ?? runMySqlMigrations) - : (deps.applyPostgresMigrations ?? runPgMigrations); - const applied = await applyMigrations(migrationsDir, databaseUrl); - appliedMigrations = applied.length; - cliLog.info(mysql ? 'cloudflare_mysql_migrations' : 'cloudflare_postgres_migrations', { - applied: applied.length, - }); - if (applied.length > 0) { - log.step(`Applied ${applied.length} ${label} migration${applied.length === 1 ? '' : 's'}.`); + async function applyMigrations(): Promise { + let appliedMigrations = 0; + + // Cloudflare never returns the Hyperdrive password, so the deploy environment provides the + // production URL. A rerun skips migrations already recorded as finished. A failed PostgreSQL + // file rolls back. A failed MySQL file rolls back its data changes, but MySQL commits DDL on + // its own, so earlier statements of that file can stay applied. + if (dialect !== 'sqlite' && migrations.length > 0) { + const mysql = dialect === 'mysql'; + const label = mysql ? 'MySQL' : 'PostgreSQL'; + const databaseUrl = process.env.DATABASE_URL; + if (!databaseUrl) { + log.error(`deploy: DATABASE_URL disappeared before ${label} migrations could run.`); + return exit(1); + } + try { + const migrate = mysql + ? (deps.applyMySqlMigrations ?? runMySqlMigrations) + : (deps.applyPostgresMigrations ?? runPgMigrations); + const applied = await migrate(migrationsDir, databaseUrl); + appliedMigrations = applied.length; + cliLog.info(mysql ? 'cloudflare_mysql_migrations' : 'cloudflare_postgres_migrations', { + applied: applied.length, + }); + if (applied.length > 0) { + log.step( + `Applied ${applied.length} ${label} migration${applied.length === 1 ? '' : 's'}.`, + ); + } + } catch (err) { + log.error(`deploy: ${label} migrations failed — ${getErrorMessage(err)}`); + return exit(1); } - } catch (err) { - log.error(`deploy: ${label} migrations failed — ${getErrorMessage(err)}`); - return exit(1); } - } - - const d1 = input.skipMigrations - ? { restoreCommand: undefined } - : await applyAndVerifyRemoteD1Migrations( - d1MigrateToken, - configPath, - runWrangler, - assertUploaderStillPinned, - readDeploymentPlatform(root) !== 'cloudflare', - ); - if (!d1) { - return exit(1); - } - const d1RestoreCommand = d1.restoreCommand; - if ( - !verifyCloudflareDeployArtifact(root, deps, { - ...verifyOptions, - requiredSecretNames: schemaFacts.requiredKeys, - }) - ) { - if (d1RestoreCommand) { - logD1RestoreAfterDeployFailure(d1RestoreCommand); + const d1 = await applyAndVerifyRemoteD1Migrations( + d1MigrateToken, + configPath, + runWrangler, + assertUploaderStillPinned, + readDeploymentPlatform(root) !== 'cloudflare', + ); + if (!d1) { + return exit(1); } - return exit(1); + if (d1.restoreCommand) { + input.onD1Restore(d1.restoreCommand); + } + if (!verifyArtifact()) { + return exit(1); + } + return appliedMigrations; } return { - migrationHistory: input.skipMigrations ? null : migrations.map((migration) => migration.name), + migrationHistory, workerWasMissingBeforeSecretProvisioning, initialAuthSecret, - appliedMigrations, - d1RestoreCommand, + applyMigrations: + !input.skipMigrations && (d1MigrateToken || (dialect !== 'sqlite' && migrations.length > 0)) + ? applyMigrations + : undefined, + message, }; } diff --git a/packages/void/src/cli/deploy-cloudflare-preflight.ts b/packages/void/src/cli/deploy-cloudflare-preflight.ts index d1e628901f..8ac3a1330d 100644 --- a/packages/void/src/cli/deploy-cloudflare-preflight.ts +++ b/packages/void/src/cli/deploy-cloudflare-preflight.ts @@ -6,6 +6,7 @@ import { readWranglerTopLevelString, assertExistingCloudflareConfig, hasWorkflowSchedules, + readWorkflowDeclarations, } from '@void/deploy-cloudflare'; import type { ExistingCloudflareWorker, @@ -21,6 +22,7 @@ import type { VoidConfig } from '../config.ts'; import type { detectFramework } from '../plugin-inference.ts'; import { cloudflareQueueName } from '../queues/cloudflare-names.ts'; import { assertSandboxNamespaceConfig, resolveSandboxConfig } from '../sandbox/config.ts'; +import { FREE_WORKFLOW_RETENTION_MS, workflowRetentionMs } from '../workflows/retention.ts'; import type { CloudflareChildReporter } from './cloudflare-child-report.ts'; import { classifyCloudflareDeployApp } from './cloudflare-deploy/classify.ts'; import { approvedCloudflareIsrBinding, chooseCloudflareIsr } from './cloudflare-isr.ts'; @@ -302,9 +304,15 @@ export async function preflightCloudflareWorker(input: { ); printDeployContext(workerName, 'Cloudflare'); - const localWorkflows = expectedWorkflows.filter( - (workflow) => workflow.script_name === undefined || workflow.script_name === workerName, - ); + const localWorkflows = readWorkflowDeclarations({ + ...rootConfig, + name: workerName, + workflows: expectedWorkflows, + }) + .filter(isRecord) + .filter( + (workflow) => workflow.script_name === undefined || workflow.script_name === workerName, + ); const schedules = localWorkflows.some((workflow) => hasWorkflowSchedules(workflow.schedules)); const steps = Math.max( 0, @@ -318,8 +326,24 @@ export async function preflightCloudflareWorker(input: { isRecord(concurrency) && typeof concurrency.limit === 'number' ? concurrency.limit : 0, ), ); - if (schedules || steps > 1024 || concurrency > 100) { - if (!assertUploaderStillPinned()) { + const retentionMs = Math.max( + 0, + ...localWorkflows.map(({ default_retention }) => + isRecord(default_retention) + ? Math.max( + workflowRetentionMs(default_retention.success_retention), + workflowRetentionMs(default_retention.error_retention), + ) + : 0, + ), + ); + const checkWorkflowPlan = + schedules || steps > 1024 || concurrency > 100 || retentionMs > FREE_WORKFLOW_RETENTION_MS; + if (checkWorkflowPlan) { + if ( + !(await confirmCloudflareDeployAuthentication(connection, configPath)) || + !assertUploaderStillPinned() + ) { return exit(1); } const checked = await runWrangler( @@ -328,6 +352,7 @@ export async function preflightCloudflareWorker(input: { schedules, steps, concurrency, + retentionMs, configPath, fedramp: complianceRegion === 'fedramp_high', }, @@ -346,6 +371,11 @@ export async function preflightCloudflareWorker(input: { ...(concurrency > 100 ? [`Requested ${concurrency} concurrent instances. Workers Free allows 100.`] : []), + ...(retentionMs > FREE_WORKFLOW_RETENTION_MS + ? [ + 'Workflow retention is limited to 3 days on Workers Free and 30 days on Workers Paid.', + ] + : []), `Enable Workers Paid at ${CLOUDFLARE_WORKERS_PAID_URL} or use settings within your account limits.`, 'The deploy token needs Account Settings: Read to check entitlements and Workers Scripts: Edit to publish.', ].join('\n'), @@ -452,7 +482,11 @@ export async function preflightCloudflareWorker(input: { } // The probe ran project code, so the uploader is re-checked before this credentialed run. - if (!(await confirmCloudflareDeployAuthentication(connection, configPath))) { + if ( + checkWorkflowPlan + ? !assertUploaderStillPinned() + : !(await confirmCloudflareDeployAuthentication(connection, configPath)) + ) { return exit(1); } diff --git a/packages/void/src/cli/deploy-cloudflare-publish.ts b/packages/void/src/cli/deploy-cloudflare-publish.ts index 9bad45a691..e7250cae44 100644 --- a/packages/void/src/cli/deploy-cloudflare-publish.ts +++ b/packages/void/src/cli/deploy-cloudflare-publish.ts @@ -1,9 +1,4 @@ -import { - activateCloudflareVersion, - encodeCloudflareVersionMessage, - parseRootWranglerConfig, - readCloudflareTriggerConfig, -} from '@void/deploy-cloudflare'; +import { activateCloudflareVersion, parseRootWranglerConfig } from '@void/deploy-cloudflare'; import type { detectFramework } from '../plugin-inference.ts'; import { readVersionMetadataBinding } from '../shared/version-metadata.ts'; import { createActiveSecretPinner } from './cf-version-runner.ts'; @@ -65,7 +60,7 @@ export async function publishCloudflareWorker(input: { readinessAccessOrigin, } = input.preflight; const { d1MigrateToken, generatedConfigPath, prepareBuildOutput } = input.build; - const { workerWasMissingBeforeSecretProvisioning, initialAuthSecret, appliedMigrations } = + const { workerWasMissingBeforeSecretProvisioning, initialAuthSecret, message, applyMigrations } = input.migration; const queueConsumerCleanup = readWranglerManagedQueueCleanupCandidates(configPath); @@ -80,10 +75,7 @@ export async function publishCloudflareWorker(input: { if (usesCf && !cfUploaderIsPinned()) { return exit(1); } - const message = encodeCloudflareVersionMessage(input.migration.migrationHistory, { - ...readCloudflareTriggerConfig(generatedConfigPath, configPath), - ...(existingWorker ? { preserve: true } : {}), - }); + let appliedMigrations = 0; const cfOutput = usesCf ? await prepareBuildOutput() : null; if (!cfOutput && usesCf) { log.error('deploy: cf could not prepare the built Worker for deployment.'); @@ -136,6 +128,19 @@ export async function publishCloudflareWorker(input: { requireVersionMetadata: existingWorker === null || hasVersionMetadata, requirePreviewForReadiness: existingWorker !== null && !hasVersionMetadata, message, + beforeUpload: + applyMigrations && + (async () => { + appliedMigrations = await applyMigrations(); + assertCloudflareDeployTargetUnchanged({ + root, + existingWorker, + pinnedHandoffLink, + initialCloudflareCandidate, + accountId, + workerName, + }); + }), allowFirstDeploymentBootstrap: workerWasMissingBeforeSecretProvisioning, ...(pinActiveSecrets ? { pinActiveSecrets } : {}), atomic, diff --git a/packages/void/src/cli/deploy-cloudflare.ts b/packages/void/src/cli/deploy-cloudflare.ts index 6767d0f85b..2ca84f2e19 100644 --- a/packages/void/src/cli/deploy-cloudflare.ts +++ b/packages/void/src/cli/deploy-cloudflare.ts @@ -11,7 +11,7 @@ import { removeDeployPointer, } from './deploy-artifact-validation.ts'; import { buildCloudflareWorker } from './deploy-cloudflare-build.ts'; -import { migrateCloudflareWorker } from './deploy-cloudflare-migrate.ts'; +import { prepareCloudflareWorkerMigrations } from './deploy-cloudflare-migrate.ts'; import { prepareCloudflareDeploySource, preflightCloudflareWorker, @@ -187,22 +187,13 @@ export async function runCloudflareDeploy( source, preflight, }); - const migration = await migrateCloudflareWorker({ - root, - deps, - exit, - cliLog, - source, - preflight, - build, - skipMigrations: options.skipMigrations, - }); + let d1RestoreCommand: string | undefined; // When migrations were applied, every later failure names the restore point again. let restoreReported = false; const reportRestore = () => { - if (migration.d1RestoreCommand && !restoreReported) { + if (d1RestoreCommand && !restoreReported) { restoreReported = true; - logD1RestoreAfterDeployFailure(migration.d1RestoreCommand); + logD1RestoreAfterDeployFailure(d1RestoreCommand); } }; const exitAfterMigrations = (code: number): never => { @@ -211,6 +202,19 @@ export async function runCloudflareDeploy( } return exit(code); }; + const migration = await prepareCloudflareWorkerMigrations({ + root, + deps, + exit: exitAfterMigrations, + onD1Restore: (command) => { + d1RestoreCommand = command; + }, + cliLog, + source, + preflight, + build, + skipMigrations: options.skipMigrations, + }); try { await publishCloudflareWorker({ root, diff --git a/packages/void/src/cli/list.ts b/packages/void/src/cli/list.ts index deba4fcf37..7450965185 100644 --- a/packages/void/src/cli/list.ts +++ b/packages/void/src/cli/list.ts @@ -78,7 +78,9 @@ async function showCloudflareDeployments(root: string, slug?: string): Promise ({ id: version.id, status: version.id === status.activeVersionId ? 'live' : 'available', - migrations: version.metadata?.migrations ? String(version.metadata.migrations.length) : '-', + migrations: String( + version.metadata?.migrations?.length ?? version.metadata?.migrationSummary?.count ?? '-', + ), deployed: version.createdAt ? formatRelativeTime(version.createdAt) : '-', })); const idWidth = Math.max('id'.length, ...rows.map((row) => row.id.length)); diff --git a/packages/void/src/cli/rollback.ts b/packages/void/src/cli/rollback.ts index 8a999546c4..ced38678d0 100644 --- a/packages/void/src/cli/rollback.ts +++ b/packages/void/src/cli/rollback.ts @@ -154,13 +154,15 @@ async function runCloudflareRollback( if (!target) { const result = await select({ message: 'Select a version to roll back to:', - options: candidates.map((version) => ({ - value: version.id, - label: `${version.id} ${dim(version.createdAt ? formatRelativeTime(version.createdAt) : '')}`, - hint: version.metadata?.migrations - ? formatCount(version.metadata.migrations.length, 'migration') - : 'migration state unknown', - })), + options: candidates.map((version) => { + const count = + version.metadata?.migrations?.length ?? version.metadata?.migrationSummary?.count; + return { + value: version.id, + label: `${version.id} ${dim(version.createdAt ? formatRelativeTime(version.createdAt) : '')}`, + hint: count !== undefined ? formatCount(count, 'migration') : 'migration state unknown', + }; + }), }); if (isCancel(result)) { cancel('Rollback cancelled.'); @@ -185,17 +187,28 @@ async function runCloudflareRollback( 'This rollback keeps the current domains, routes, and schedules. The selected version has no complete trigger snapshot.', ); } - if (!current?.metadata?.migrations || !target.metadata?.migrations) { - log.warn( - 'Void migration metadata is unavailable for one of these versions. Database migrations are forward-only and will not be reverted.', - ); - await confirmRollbackOrExit(); - } else { + if (current?.metadata?.migrations && target.metadata?.migrations) { const targetSet = new Set(target.metadata.migrations); const migrationDiff = current.metadata.migrations.filter( (migration) => !targetSet.has(migration), ); await confirmUnrevertedMigrations(migrationDiff, 'version', restorePlatformFlag); + } else { + const { summarizeCloudflareMigrations } = await import('@void/deploy-cloudflare'); + const currentHistory = current?.metadata?.migrations + ? summarizeCloudflareMigrations(current.metadata.migrations) + : current?.metadata?.migrationSummary; + const targetHistory = target.metadata?.migrations + ? summarizeCloudflareMigrations(target.metadata.migrations) + : target.metadata?.migrationSummary; + if (!currentHistory || !targetHistory || currentHistory.digest !== targetHistory.digest) { + log.warn( + currentHistory && targetHistory + ? `The versions have different migration histories (current: ${currentHistory.count}, selected: ${targetHistory.count}). The older code will run against the current database schema.` + : 'Void migration metadata is unavailable for one of these versions. Database migrations are forward-only and will not be reverted.', + ); + await confirmRollbackOrExit(); + } } const spinner = createSpinner(); diff --git a/packages/void/src/codegen/binding-types.ts b/packages/void/src/codegen/binding-types.ts index e4d79ebb89..d3f35ac9de 100644 --- a/packages/void/src/codegen/binding-types.ts +++ b/packages/void/src/codegen/binding-types.ts @@ -87,7 +87,7 @@ export function generateBindingTypes( workflowTypes.push( `type ${bindingName}Params = import("void/workflows").NativeWorkflowParams;`, ); - bindings.set(bindingName, `Workflow<${bindingName}Params>`); + bindings.set(bindingName, `WorkflowBinding<${bindingName}Params>`); } if (bindings.size === 0) { return null; @@ -95,6 +95,7 @@ export function generateBindingTypes( return [ '// Auto-generated by void — do not edit', 'export {};', + ...(workflows.length ? ['import type { WorkflowBinding } from "void/workflows";'] : []), ...workflowTypes, 'declare global {', ' interface VoidGeneratedEnvBindings {', diff --git a/packages/void/src/plugin-worker-bindings.ts b/packages/void/src/plugin-worker-bindings.ts index 560cc9997e..c6787a52b3 100644 --- a/packages/void/src/plugin-worker-bindings.ts +++ b/packages/void/src/plugin-worker-bindings.ts @@ -1,4 +1,4 @@ -import { appendSqliteClassMigration } from '@void/deploy-core'; +import { appendSqliteClassMigration, isRecord } from '@void/deploy-core'; import type { ApplicationAnalysis } from './application-analysis.ts'; import { SEND_EMAIL_BINDING } from './cli/email-cloudflare.ts'; import type { resolveLiveBindingConfig } from './cli/wrangler.ts'; @@ -87,6 +87,7 @@ function mergeWorkflowBindings( [...patchEntries, ...workflowConfigEntries((resolved as Record).workflows)], workflows, deployWorkerName || ((resolved as { name?: string }).name ?? defaultCloudflareWorkerName(root)), + { ...resolved.exports, ...(isRecord(result.exports) ? result.exports : {}) }, ); if (additions.length > 0) { result.workflows = [...patchEntries, ...additions]; diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts index 5348cdcb13..0828131ebf 100644 --- a/packages/void/src/runtime/workflows/index.ts +++ b/packages/void/src/runtime/workflows/index.ts @@ -33,6 +33,25 @@ type WorkflowCreateArguments = undefined extends TParams ? [options?: WorkflowCreateOptions] : [options: WorkflowCreateOptions]; +/** Native binding for a local Workflow. Omitted params are delivered as an empty object. */ +export type WorkflowBinding = + Record extends TParams + ? Workflow> + : Omit, 'create' | 'createBatch'> & { + create(options: WorkflowCreateOptions>): Promise; + createBatch( + options: WorkflowBatchCreateOptions & + ( + | { count: number; params: Exclude } + | { instances: Array>> } + ), + ): Promise; + /** @deprecated Use the object form to receive per-instance errors. */ + createBatch( + instances: Array>>, + ): Promise>; + }; + // Cloudflare delivers an empty object when create() omits params or a schema returns undefined. type WorkflowPayload = | Exclude diff --git a/packages/void/src/shared/resource-definition.ts b/packages/void/src/shared/resource-definition.ts index 5aa8b4eef9..b98e81902f 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -55,6 +55,7 @@ export function readResourceDefinition( const definitions = new Map(); const importedHelpers = new Map(); const namespaces = new Map>(); + const destructured: Array<{ pattern: AstNode; source: AstNode }> = []; const bindings = new Set(); let defaultExport: AstNode | undefined; let commonJsExport: AstNode | undefined; @@ -152,14 +153,8 @@ export function readResourceDefinition( } for (const variable of (declaration as AstVariableDeclaration).declarations ?? []) { recordBindings(variable.id); - if (isWorkflowRequire(variable.init) && variable.id?.type === 'ObjectPattern') { - for (const property of variable.id.properties as Array) { - const helper = moduleExportName(property.key as AstNode | undefined); - const local = property.value as AstNode | undefined; - if (helper && helpers.has(helper) && isIdentifier(local)) { - importedHelpers.set(local.name, helper); - } - } + if (convention === 'workflows' && variable.init && variable.id?.type === 'ObjectPattern') { + destructured.push({ pattern: variable.id, source: variable.init }); } if (isIdentifier(variable.id) && variable.init) { definitions.set(variable.id.name, variable.init); @@ -179,6 +174,28 @@ export function readResourceDefinition( return resolve(constants.get(node.name), seen); } + // Imports are hoisted. Resolve namespace aliases once all top-level declarations are known. + for (const { pattern, source } of destructured) { + const namespace = resolve(source); + const supported = isIdentifier(namespace) ? namespaces.get(namespace.name) : undefined; + if (!supported && !isWorkflowRequire(namespace)) { + continue; + } + for (const property of pattern.properties as Array) { + const key = property.key as AstNode | undefined; + const name = property.computed ? staticLiteral(resolve(key)) : moduleExportName(key); + const local = property.value as AstNode | undefined; + if ( + typeof name === 'string' && + helpers.has(name) && + (!supported || supported.has(name)) && + isIdentifier(local) + ) { + importedHelpers.set(local.name, name); + } + } + } + type StaticName = { present: boolean; value?: string }; function isStaticUndefined(node: AstNode | undefined): boolean { @@ -249,6 +266,7 @@ export function readResourceDefinition( importedHelpers.get(callee.name) ?? (convention !== 'workflows' && helpers.has(callee.name) ? callee.name : undefined); } else if (isMemberExpression(callee)) { + const namespace = resolve(callee.object); const property = !callee.computed && isIdentifier(callee.property) ? callee.property.name @@ -256,8 +274,8 @@ export function readResourceDefinition( if ( typeof property === 'string' && helpers.has(property) && - ((isIdentifier(callee.object) && namespaces.get(callee.object.name)?.has(property)) || - isWorkflowRequire(resolve(callee.object))) + ((isIdentifier(namespace) && namespaces.get(namespace.name)?.has(property)) || + isWorkflowRequire(namespace)) ) { helper = property; } diff --git a/packages/void/src/workflows/config.ts b/packages/void/src/workflows/config.ts index f21379c15b..b9b123eb6c 100644 --- a/packages/void/src/workflows/config.ts +++ b/packages/void/src/workflows/config.ts @@ -1,3 +1,4 @@ +import { isRecord } from '@void/deploy-core'; import { cloudflareWorkflowName } from './scan.ts'; import type { WorkflowModule } from './scan.ts'; @@ -30,6 +31,7 @@ export function planWorkflowAdditions( existing: ReadonlyArray, modules: ReadonlyArray>, workerName: string, + workerExports?: unknown, ): Array<{ name: string; binding: string; class_name: string }> { const additions: Array<{ name: string; binding: string; class_name: string }> = []; for (const module of modules) { @@ -45,7 +47,11 @@ export function planWorkflowAdditions( } continue; } - const name = cloudflareWorkflowName(module.resourceName, workerName); + const declared = isRecord(workerExports) ? workerExports[module.className] : undefined; + const name = + isRecord(declared) && declared.type === 'workflow' && typeof declared.name === 'string' + ? declared.name + : cloudflareWorkflowName(module.resourceName, workerName); const owner = [...existing, ...additions].find((entry) => entry.name === name); if (owner) { throw new Error( diff --git a/packages/void/src/workflows/retention.ts b/packages/void/src/workflows/retention.ts new file mode 100644 index 0000000000..b9df7684e2 --- /dev/null +++ b/packages/void/src/workflows/retention.ts @@ -0,0 +1,36 @@ +const DAY = 86_400_000; +export const FREE_WORKFLOW_RETENTION_MS: number = 3 * DAY; +export const PAID_WORKFLOW_RETENTION_MS: number = 30 * DAY; + +const durationUnits = new Map([ + ['second', 1000], + ['minute', 60_000], + ['hour', 3_600_000], + ['day', DAY], + ['week', 7 * DAY], + ['month', 30 * DAY], + ['year', 365.25 * DAY], +]); + +/** Workflow durations accept milliseconds or a number followed by a duration unit. */ +export function workflowRetentionMs(value: unknown): number { + if (value === undefined) { + return 0; + } + let milliseconds = value; + if (typeof value === 'string') { + const parts = /^(\S+)\s+([a-z]+?)s?$/.exec(value.trim()); + const unit = parts && durationUnits.get(parts[2]); + milliseconds = parts && unit ? Number(parts[1]) * unit : Number(value); + } + if ( + typeof milliseconds !== 'number' || + !Number.isSafeInteger(milliseconds) || + milliseconds <= 0 + ) { + throw new Error( + 'deploy: Workflow default_retention must be a duration such as "3 days" or a whole number of milliseconds.', + ); + } + return milliseconds; +} diff --git a/packages/void/test/integration/cloudflare-durable-build.test.ts b/packages/void/test/integration/cloudflare-durable-build.test.ts index 5b05aa570a..cb405fe2f5 100644 --- a/packages/void/test/integration/cloudflare-durable-build.test.ts +++ b/packages/void/test/integration/cloudflare-durable-build.test.ts @@ -1,5 +1,6 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; +import { readBuildOutput } from '@cloudflare/build-output-utils'; import { parseRootWranglerConfig } from '@void/deploy-cloudflare'; import spawn from 'cross-spawn'; import { describe, expect, it } from 'vite-plus/test'; @@ -230,7 +231,7 @@ export default defineDurableState({ initialState: { count: 0 }, methods: { incre }, ); - it('emits Workflow entries named after the deployed Worker and keeps authored ones', () => { + it('emits Workflow entries named after the deployed Worker and keeps authored ones', async () => { const fixture = createIsolatedPlayground(repository, 'playground/ssr'); const root = fixture.root; try { @@ -246,17 +247,35 @@ export default defineWorkflow({ async run(event, step) { return step.do('greet', import { defineWorkflowEntrypoint } from 'void/workflows'; class Importer extends WorkflowEntrypoint { async run() { return 'imported'; } } export default defineWorkflowEntrypoint({ class: Importer });\n`, + ); + writeFileSync( + join(root, 'workflows/daily.ts'), + `import { defineWorkflow } from 'void/workflows'; +export default defineWorkflow({ async run() { return 'done'; } });\n`, ); const pinned = { name: 'legacy-import', binding: 'WORKFLOW_NIGHTLY_IMPORT', class_name: 'NightlyImportWorkflow', }; + const workflowExport = { + type: 'workflow', + name: pinned.name, + schedules: ['0 2 * * *'], + limits: { steps: 3000 }, + default_retention: { success_retention: '7 days' }, + }; + const exportOnly = { type: 'workflow', name: 'existing-daily', concurrency: { limit: 9 } }; writeFileSync( join(root, 'void.config.ts'), renderVoidConfig({ ...readConfig(root), - cloudflare: { name: 'workflow-merge', account_id: accountId, workflows: [pinned] }, + cloudflare: { + name: 'workflow-merge', + account_id: accountId, + workflows: [pinned], + exports: { NightlyImportWorkflow: workflowExport, DailyWorkflow: exportOnly }, + }, }), ); const config = readConfig(root); @@ -272,6 +291,11 @@ export default defineWorkflowEntrypoint({ class: Importer });\n`, ); expect(expectedWorkflows).toEqual([ pinned, + { + name: exportOnly.name, + binding: 'WORKFLOW_DAILY', + class_name: 'DailyWorkflow', + }, { name: 'deployed-app_welcome', binding: 'WORKFLOW_WELCOME', @@ -297,6 +321,22 @@ export default defineWorkflowEntrypoint({ class: Importer });\n`, }; expect(emitted.workflows).toEqual(expect.arrayContaining(expectedWorkflows)); expect(emitted.workflows).toHaveLength(expectedWorkflows.length); + const built = await readBuildOutput(root); + expect(built.workers.default.config.exports?.DailyWorkflow).toMatchObject(exportOnly); + expect( + verifyGeneratedDeployConfig(root, { + accountId, + workerName: 'workflow-merge', + passthroughRawFields: snapshotPassthroughRawFields({ ...rootConfig, exports: {} }), + }), + ).toMatchObject({ ok: false, reason: expect.stringContaining('Workflow exports') }); + expect(built.workers.default.config.exports?.NightlyImportWorkflow).toMatchObject({ + type: 'workflow', + name: pinned.name, + schedules: workflowExport.schedules, + limits: workflowExport.limits, + defaultRetention: { successRetention: '7 days' }, + }); const worker = readFileSync(join(root, 'dist/ssr/index.js'), 'utf8'); expect(worker).toMatch(/WelcomeWorkflow/); expect(worker).toMatch(/NightlyImportWorkflow/); diff --git a/packages/void/test/integration/workflow-dev.test.ts b/packages/void/test/integration/workflow-dev.test.ts index 1e61f92615..bd59140ed8 100644 --- a/packages/void/test/integration/workflow-dev.test.ts +++ b/packages/void/test/integration/workflow-dev.test.ts @@ -39,7 +39,7 @@ export default defineWorkflow({ name: ${JSON.stringify(name)}, async run(event, writeFileSync(file, workflow('welcome')); await waitForBindings('WORKFLOW_WELCOME'); const declaration = join(fixture.root, '.void', 'bindings.d.ts'); - expect(readFileSync(declaration, 'utf8')).toContain('"WORKFLOW_WELCOME": Workflow'); + expect(readFileSync(declaration, 'utf8')).toContain('"WORKFLOW_WELCOME"'); writeFileSync(file, workflow('onboarding')); await waitForBindings('WORKFLOW_ONBOARDING'); expect(readFileSync(declaration, 'utf8')).not.toContain('WORKFLOW_WELCOME'); @@ -101,23 +101,71 @@ class Bill extends WorkflowEntrypoint { } export default defineWorkflowEntrypoint({ class: Bill });`, ); + for (const [filename, payload] of [ + ['digest', '{ day?: string }'], + ['report', '{ month: string } | undefined'], + ]) { + writeFileSync( + join(directory, filename + '.ts'), + `import { WorkflowEntrypoint, type WorkflowEvent } from 'cloudflare:workers'; +import { defineWorkflowEntrypoint } from 'void/workflows'; +type Payload = ${payload}; +class Job extends WorkflowEntrypoint { + async run(event: WorkflowEvent) { return event.payload; } +} +export default defineWorkflowEntrypoint({ class: Job });`, + ); + } const { prepareProject } = await import('../../src/codegen/prepare.ts'); await prepareProject(fixture.root); const declaration = join(fixture.root, '.void', 'bindings.d.ts'); - expect(readFileSync(declaration, 'utf8')).toContain('"WORKFLOW_NOTIFY": Workflow'); + expect(readFileSync(declaration, 'utf8')).toContain('"WORKFLOW_NOTIFY"'); writeFileSync( join(fixture.root, 'binding.ts'), `import { defineHandler } from 'void'; import Notify from './workflows/notify'; export const GET = defineHandler(async c => { - await Notify.create(c.env.WORKFLOW_NOTIFY, { params: { id: 'hello' } }); + const notify = c.env.WORKFLOW_NOTIFY; + const options = { params: { id: 'hello' } }; + await Notify.create(notify, options); + await Notify.createBatch(notify, [options]); + await Notify.get(notify, 'hello'); + const instance: WorkflowInstance = await notify.create(options); + const legacy: WorkflowInstance[] = await notify.createBatch([options]); + const list: WorkflowBatchCreateResult = await notify.createBatch({ instances: [options] }); + const shared: WorkflowBatchCreateResult = await notify.createBatch({ count: 2, ...options }); + await notify.deleteBatch([instance.id]); + // @ts-expect-error An omitted payload would deliver an empty object with no id. + await notify.create(); + // @ts-expect-error Supplying an instance id doesn't supply the payload. + await notify.create({ id: 'instance-id' }); + // @ts-expect-error Each legacy batch entry needs params. + await notify.createBatch([options, {}]); + // @ts-expect-error Each object-form batch entry needs params. + await notify.createBatch({ instances: [{}] }); + // @ts-expect-error Count-form batches need the shared payload. + await notify.createBatch({ count: 2 }); + // @ts-expect-error The shared payload must also match the handler. + await notify.createBatch({ count: 2, params: { id: 42 } }); + + await c.env.WORKFLOW_DIGEST.create(); + await c.env.WORKFLOW_DIGEST.create({ params: undefined }); + await c.env.WORKFLOW_DIGEST.createBatch({ count: 2 }); + await c.env.WORKFLOW_DIGEST.createBatch({ instances: [{}] }); + await c.env.WORKFLOW_REPORT.create({ params: { month: 'June' } }); + // @ts-expect-error The native handler's union excludes the empty object. + await c.env.WORKFLOW_REPORT.create(); + // @ts-expect-error Explicit undefined also delivers an empty object. + await c.env.WORKFLOW_REPORT.create({ params: undefined }); + // @ts-expect-error A native handler with a required invoice also needs params. + await c.env.WORKFLOW_BILL.create(); // @ts-expect-error Bill requires an invoice, so it cannot receive Notify's payload. await Notify.create(c.env.WORKFLOW_BILL, { params: { id: 'hello' } }); // @ts-expect-error Raw creation on a local binding checks its payload too. await c.env.WORKFLOW_NOTIFY.create({ params: { invoice: 123 } }); // @ts-expect-error The Workflow requires a string id. await Notify.create(c.env.WORKFLOW_NOTIFY, { params: { id: 42 } }); - return 'ok'; + return [legacy.length, list.created.length, shared.created.length]; });`, ); writeFileSync( diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index b75d5f334b..9c574c00e8 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -1,3 +1,4 @@ +import { createHash } from 'node:crypto'; import { existsSync, mkdirSync, @@ -1118,6 +1119,7 @@ function harness(overrides: Partial = {}): { // One `deploy` call through the runner the deploy passed in, so a test that swaps the runner // still sees whether the upload happened. packages/deploy-cloudflare tests the real activation. activateVersion: async (options) => { + await options.beforeUpload?.(); if (!options.verifyUploader()) { return { ok: false, reason: 'uploader-changed' }; } @@ -3096,6 +3098,74 @@ describe('runCloudflareDeploy — PostgreSQL checked-in migrations', () => { expect(output).not.toContain('D1 migrations up to date'); }); + it('publishes a long migration history while keeping its trigger snapshot', async () => { + vi.stubEnv('DATABASE_URL', 'postgresql://prod.example/app'); + const files = Array.from({ length: 180 }, (_, i) => { + const month = new Date(Date.UTC(2010, i, 1)).toISOString().slice(0, 7); + const name = String(i).padStart(4, '0') + '_create_events_partition_' + month + '.sql'; + return ['db/migrations/' + name, 'CREATE TABLE partition_' + i + ' (id integer);']; + }); + const root = pgProject(Object.fromEntries(files)); + const { deps, trace } = harness(); + const activate = vi.fn(deps.activateVersion); + deps.activateVersion = activate; + await runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps); + expect(trace).toContain('postgres-migrate'); + expect(trace).toContain('wrangler:deploy'); + expect(parseCloudflareVersionMessage(activate.mock.calls[0][0].message)).toMatchObject({ + schema: 2, + migrations: null, + migrationSummary: { count: files.length, digest: expect.stringMatching(/^[a-f0-9]{64}$/) }, + triggerConfig: { workflows: [], crons: [], queueConsumers: [] }, + }); + }); + + it.each(['authored', 'preserved'] as const)( + 'refuses an oversized %s trigger snapshot before applying pending migrations', + async (source) => { + vi.stubEnv('DATABASE_URL', 'postgresql://prod.example/app'); + const routes = Array.from({ length: 40 }, (_, i) => { + const tenant = createHash('sha256').update(String(i)).digest('hex').slice(0, 32); + return tenant + '.example.com/*'; + }); + const root = pgProject(INIT_MIGRATION); + const path = join(root, 'wrangler.jsonc'); + if (source === 'authored') { + writeFileSync(path, JSON.stringify({ ...parseRootWranglerConfig(path), routes })); + } else { + writeWranglerPublishedTrafficSnapshot(path, { + workers_dev: true, + preview_urls: true, + routes, + }); + } + const apply = vi.fn(async () => ['0000_init.sql']); + const { deps } = harness({ + runBuild: () => { + mkdirSync(join(root, 'dist/ssr'), { recursive: true }); + writeFileSync(join(root, 'dist/ssr/wrangler.json'), readFileSync(path)); + }, + applyPostgresMigrations: apply, + activateVersion: activateCloudflareVersionPrimitive, + }); + const runner = deps.runWrangler!; + const active = '11111111-1111-4111-8111-111111111111'; + deps.runWrangler = (operation, options) => { + if (operation.type === 'deployments.status') { + return { ...cleanExit, data: { versions: [{ version_id: active, percentage: 100 }] } }; + } + if (operation.type === 'versions.list') { + return { ...cleanExit, data: [{ id: active, number: 1 }] }; + } + return runner(operation, options); + }; + await expect( + runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps), + ).rejects.toThrow('1000-byte version message limit'); + expect(apply).not.toHaveBeenCalled(); + }, + ); + it('still deploys a pg app WITHOUT checked-in migrations (external schema — no false-reject)', async () => { const root = pgProject(); const { deps, wranglerArgs, exitCalls } = harness(); @@ -4494,24 +4564,54 @@ describe('runCloudflareDeploy — preflight', () => { { schedules: undefined, concurrency: 100, paid: false, shouldProbe: false }, { schedules: undefined, steps: 25_000, paid: false, shouldProbe: true }, { schedules: undefined, steps: 1024, paid: false, shouldProbe: false }, + { retention: { error_retention: '72 hours' }, paid: false, shouldProbe: false }, + { + retention: { success_retention: 259_200_001, error_retention: '1 day' }, + retentionMs: 259_200_001, + paid: false, + shouldProbe: true, + }, + { + exportOnly: true, + retention: { error_retention: '7 days' }, + retentionMs: 604_800_000, + paid: true, + shouldProbe: true, + }, + { exportOnly: true, steps: 2500, schedules: '0 * * * *', paid: false, shouldProbe: true }, { schedules: [], paid: false, shouldProbe: false }, { schedules: undefined, paid: false, shouldProbe: false }, ])( - 'checks Workflow entitlements when required ($schedules, $steps steps, paid=$paid)', - async ({ schedules, steps, concurrency, paid, shouldProbe }) => { + 'checks Workflow entitlements for %j', + async ({ + schedules, + steps, + concurrency, + retention, + retentionMs, + exportOnly, + paid, + shouldProbe, + }) => { + vi.stubEnv('CLOUDFLARE_API_TOKEN', undefined); + vi.stubEnv('CF_API_TOKEN', undefined); + const workflowSettings = { + name: 'myapp_notify', + schedules, + ...(steps && { limits: { steps } }), + ...(concurrency && { concurrency: { limit: concurrency } }), + ...(retention && { default_retention: retention }), + }; const root = d1Project( { ...PROVISIONED_D1, - workflows: [ - { - binding: 'WORKFLOW_NOTIFY', - name: 'notify', - class_name: 'NotifyWorkflow', - schedules, - ...(steps && { limits: { steps } }), - ...(concurrency && { concurrency: { limit: concurrency } }), - }, - ], + ...(exportOnly + ? { exports: { NotifyWorkflow: { type: 'workflow', ...workflowSettings } } } + : { + workflows: [ + { binding: 'WORKFLOW_NOTIFY', class_name: 'NotifyWorkflow', ...workflowSettings }, + ], + }), }, { 'workflows/notify.ts': @@ -4525,7 +4625,8 @@ describe('runCloudflareDeploy — preflight', () => { expect(operation.steps).toBe(steps ?? 0); expect(operation.concurrency).toBe(concurrency ?? 0); expect(operation.schedules).toBe(Boolean(schedules?.length)); - trace.push('check-schedules'); + expect(operation.retentionMs ?? 0).toBe(retentionMs ?? 0); + trace.push('check-workflows'); return { ...cleanExit, data: paid }; } return run(operation, options); @@ -4538,18 +4639,22 @@ describe('runCloudflareDeploy — preflight', () => { ); if (shouldProbe && !paid) { await expect(deploy).rejects.toBeInstanceOf(ExitError); - expect(trace).toContain('check-schedules'); + expect(trace).toContain('check-workflows'); expect(trace).not.toContain('provision'); expect(trace).not.toContain('build'); } else { await deploy; - expect(trace.includes('check-schedules')).toBe(shouldProbe); + expect(trace.includes('check-workflows')).toBe(shouldProbe); expect(trace).toContain('provision'); if (shouldProbe) { - expect(trace.indexOf('check-schedules')).toBeLessThan(trace.indexOf('provision')); + expect(trace.indexOf('check-workflows')).toBeLessThan(trace.indexOf('provision')); } expect(trace).toContain('build'); } + if (shouldProbe) { + expect(trace).toContain('wrangler:whoami'); + expect(trace.indexOf('wrangler:whoami')).toBeLessThan(trace.indexOf('check-workflows')); + } }, ); @@ -10050,7 +10155,10 @@ describe('runCloudflareDeploy — remote migration gates', () => { }); const { deps } = harness({ runWrangler: migratingWrangler(true), - activateVersion: async () => ({ ok: false, reason: 'upload-failed', status: 1 }), + activateVersion: async (options) => { + await options.beforeUpload?.(); + return { ok: false, reason: 'upload-failed', status: 1 }; + }, // process.exit never returns, so the restore point must be named before it. exit: (code) => { order.push('exit'); @@ -10077,9 +10185,18 @@ describe('runCloudflareDeploy — remote migration gates', () => { it('names the restore point again when the built config fails its check', async () => { const root = d1Project(PROVISIONED_D1, INIT_MIGRATION); const output = vi.spyOn(log, 'error').mockImplementation(() => {}); + const run = migratingWrangler(true); + let applied = false; const { deps } = harness({ - runWrangler: migratingWrangler(true), - verifyDeployConfig: () => ({ ok: false, reason: 'different account' }), + runWrangler: async (operation, options) => { + const result = await run(operation, options); + if (operation.type === 'd1.migrations.apply') { + applied = true; + } + return result; + }, + verifyDeployConfig: () => + applied ? { ok: false, reason: 'different account' } : { ok: true }, }); try { await expect( @@ -10096,7 +10213,8 @@ describe('runCloudflareDeploy — remote migration gates', () => { const output = vi.spyOn(log, 'error').mockImplementation(() => {}); const { deps } = harness({ runWrangler: migratingWrangler(true), - activateVersion: async () => { + activateVersion: async (options) => { + await options.beforeUpload?.(); throw new Error('connection reset'); }, }); @@ -10115,7 +10233,10 @@ describe('runCloudflareDeploy — remote migration gates', () => { const output = vi.spyOn(log, 'error').mockImplementation(() => {}); const { deps } = harness({ runWrangler: migratingWrangler(false), - activateVersion: async () => ({ ok: false, reason: 'upload-failed', status: 1 }), + activateVersion: async (options) => { + await options.beforeUpload?.(); + return { ok: false, reason: 'upload-failed', status: 1 }; + }, }); try { await expect( diff --git a/packages/void/test/unit/cloudflare-operation-process.test.ts b/packages/void/test/unit/cloudflare-operation-process.test.ts index da1d0ce01d..fa8bc0650e 100644 --- a/packages/void/test/unit/cloudflare-operation-process.test.ts +++ b/packages/void/test/unit/cloudflare-operation-process.test.ts @@ -1876,6 +1876,7 @@ const workflowEntitlementCases: Array<{ schedules?: boolean; steps?: number; concurrency?: number; + retentionMs?: number; }> = [ { name: 'Workers Paid', @@ -1915,6 +1916,20 @@ const workflowEntitlementCases: Array<{ schedules: false, eligible: concurrency <= 100, })), + ...[259_200_000, 259_200_001].map((retentionMs) => ({ + name: `requested retention of ${retentionMs} ms on Free`, + entitlements: [], + schedules: false, + retentionMs, + eligible: retentionMs === 259_200_000, + })), + ...[2_592_000_000, 2_592_000_001].map((retentionMs) => ({ + name: `requested retention of ${retentionMs} ms on Paid`, + entitlements: [{ id: 'workers.enabled', allocation: { type: 'bool', value: true } }], + schedules: false, + retentionMs, + eligible: retentionMs === 2_592_000_000, + })), { name: 'absent entitlements', entitlements: [], eligible: false }, { name: 'FedRAMP default allocation', entitlements: [], fedramp: true, eligible: true }, { @@ -1949,6 +1964,7 @@ it.each(workflowEntitlementCases)( schedules = true, steps = 0, concurrency = 0, + retentionMs = 0, }) => { const requests: Array = []; const api = await listen( @@ -1960,7 +1976,7 @@ it.each(workflowEntitlementCases)( ); const output = await runOperation( temporaryDirectory('void-workflow-plan-'), - { type: 'workflows.entitlement', fedramp, schedules, steps, concurrency }, + { type: 'workflows.entitlement', fedramp, schedules, steps, concurrency, retentionMs }, tokenEnv(api), ); expect(requests).toEqual(['GET /client/v4/accounts/test-account/entitlements']); diff --git a/packages/void/test/unit/rollback-platform.test.ts b/packages/void/test/unit/rollback-platform.test.ts index 209063da9b..b5c74c6297 100644 --- a/packages/void/test/unit/rollback-platform.test.ts +++ b/packages/void/test/unit/rollback-platform.test.ts @@ -60,6 +60,40 @@ beforeEach(() => { }); describe('void project rollback --platform cloudflare', () => { + it.each([true, false])( + 'compares compact migration history with a named history (equal=%s)', + async (equal) => { + const { summarizeCloudflareMigrations } = await import('@void/deploy-cloudflare'); + const current = ['001_init.sql', '002_add_email.sql']; + mockReadDeploymentPlatform.mockReturnValue('cloudflare'); + mockReadCloudflareWorkerStatus.mockResolvedValue({ + workerName: 'app', + activeVersionId: 'new-version', + deployedVersionIds: ['old-version', 'new-version'], + versions: [ + { + id: 'new-version', + metadata: { + ...metadata(null), + migrationSummary: summarizeCloudflareMigrations(current), + }, + }, + { + id: 'old-version', + metadata: metadata(equal ? current : ['001_init.sql', '002_add_name.sql']), + }, + ], + }); + await runRollbackCommand('/app', 'old-version'); + expect(log.warn).toHaveBeenCalledTimes(equal ? 0 : 1); + if (!equal) { + expect(log.warn).toHaveBeenCalledWith( + expect.stringContaining('different migration histories'), + ); + } + expect(mockActivateCloudflareExistingVersion).toHaveBeenCalledOnce(); + }, + ); it('warns about unknown SQL history after a deploy that skipped migrations', async () => { mockReadDeploymentPlatform.mockReturnValue('cloudflare'); mockReadCloudflareWorkerStatus.mockResolvedValue({ diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts index 78314e5df0..dddeb73162 100644 --- a/packages/void/test/unit/workflow-scan.test.ts +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -67,6 +67,29 @@ export default defineDigest({ name: 'daily', async run() {} });`, expect(scanWorkflowModules(root)).toMatchObject([{ bindingName: 'WORKFLOW_DAILY' }]); }); + it('discovers helpers through local aliases of an imported Workflow namespace', () => { + const root = createRoot({ + 'digest.ts': `import * as Workflows from 'void/workflows'; +const api = Workflows; +const { defineWorkflow: job } = api; +export default job({ name: 'daily', async run() {} });`, + 'report.ts': `import * as Workflows from 'void/workflows'; +const api = Workflows; +export default api.defineWorkflowEntrypoint({ name: 'monthly', class: Report });`, + 'ordinary.ts': `import * as Workflows from './_helpers'; +const { defineWorkflow: job } = Workflows; +export default job({});`, + }); + expect(scanWorkflowModules(root)).toMatchObject([ + { relativePath: 'digest.ts', definition: 'defineWorkflow', bindingName: 'WORKFLOW_DAILY' }, + { + relativePath: 'report.ts', + definition: 'defineWorkflowEntrypoint', + bindingName: 'WORKFLOW_MONTHLY', + }, + ]); + }); + it('returns nothing without a workflows directory', () => { const root = mkdtempSync(join(tmpdir(), 'void-workflow-scan-')); roots.push(root); From ffd04d2d8a1e76cdf9bfb5c709ce644e6e3db9bf Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 16:36:57 +0900 Subject: [PATCH 12/13] Discover JSX Workflows and their helper bindings, and fix native receiver types. --- docs/guide/workflows.md | 2 +- packages/void/src/codegen/binding-types.ts | 2 +- packages/void/src/inference/client-auth.ts | 19 +++++++--- packages/void/src/inference/walk.ts | 35 +++++++++++++++++-- packages/void/src/runtime/workflows/index.ts | 2 +- packages/void/src/workflows/scan.ts | 4 +-- .../test/integration/workflow-dev.test.ts | 16 ++++++--- .../void/test/unit/plugin-inference.test.ts | 18 ++++++++-- .../test/unit/workflow-runtime.typecheck.ts | 15 +++++++- packages/void/test/unit/workflow-scan.test.ts | 16 +++++++++ 10 files changed, 109 insertions(+), 20 deletions(-) diff --git a/docs/guide/workflows.md b/docs/guide/workflows.md index 3679626f9a..bd05588896 100644 --- a/docs/guide/workflows.md +++ b/docs/guide/workflows.md @@ -33,7 +33,7 @@ export default Onboarding; Default-export the object returned by `defineWorkflow()`. Named-export it too so routes can import it. -Keep `workflows/` at the project root, including when `sourceDir` is set. Write Workflow definitions as TypeScript or JavaScript ES modules with an import from `void/workflows` and a default export. In CommonJS projects, use `.mjs` or `.mts` for definitions. Subdirectories are supported. Files and directories starting with `_` are excluded from Workflow discovery. If you maintain an explicit `include` list in `tsconfig.json`, add `workflows` so TypeScript checks definitions started outside your app. +Keep `workflows/` at the project root, including when `sourceDir` is set. Write Workflow definitions as TypeScript or JavaScript ES modules with an import from `void/workflows` and a default export. Use `.tsx` or `.jsx` for definitions containing JSX. In CommonJS projects, use `.mjs` or `.mts` for definitions. Subdirectories are supported. Files and directories starting with `_` are excluded from Workflow discovery. If you maintain an explicit `include` list in `tsconfig.json`, add `workflows` so TypeScript checks definitions started outside your app. Use ES modules for local step helpers too. For example, export a helper from `workflows/_read.mjs` and import it from the Workflow. The development Worker loads these files as ES modules. diff --git a/packages/void/src/codegen/binding-types.ts b/packages/void/src/codegen/binding-types.ts index d3f35ac9de..c6c7562908 100644 --- a/packages/void/src/codegen/binding-types.ts +++ b/packages/void/src/codegen/binding-types.ts @@ -79,7 +79,7 @@ export function generateBindingTypes( const workflowTypes: Array = []; for (const { bindingName, relativePath } of workflows) { const module = JSON.stringify('../workflows/' + relativePath); - if (/\.[cm]?js$/.test(relativePath)) { + if (/\.(?:[cm]?js|jsx)$/.test(relativePath)) { workflowTypes.push( '// @ts-ignore A JavaScript workflow can lack declarations when allowJs is disabled.', ); diff --git a/packages/void/src/inference/client-auth.ts b/packages/void/src/inference/client-auth.ts index c2e830b45b..0d3cb6b359 100644 --- a/packages/void/src/inference/client-auth.ts +++ b/packages/void/src/inference/client-auth.ts @@ -22,8 +22,12 @@ function propertyName(node: AstNode) { } /** Detect runtime auth imports and namespace reads without confusing aliases or type names. */ -export function inferClientAuth(parsed: ReturnType, code: string): boolean { - let hasNamespace = false; +export function inferClientAuth( + parsed: ReturnType, + code: string, + requiredNamespaces: ReadonlySet, +): boolean { + let hasNamespace = requiredNamespaces.size > 0; for (const statement of parsed.module.staticImports) { if (!CLIENT_MODULES.has(statement.moduleRequest.value)) { continue; @@ -60,10 +64,13 @@ export function inferClientAuth(parsed: ReturnType, code: stri ) { return false; } - return inferNamespaceAuth(asAstProgram(parsed.program)); + return inferNamespaceAuth(asAstProgram(parsed.program), requiredNamespaces); } -function inferNamespaceAuth(program: AstProgram): boolean { +function inferNamespaceAuth( + program: AstProgram, + requiredNamespaces: ReadonlySet, +): boolean { const namespaces = new Set(); for (const statement of program.body ?? []) { const source = staticLiteral(statement.source as AstNode | undefined); @@ -123,6 +130,10 @@ function inferNamespaceAuth(program: AstProgram): boolean { const aliases: Array = []; let found = false; while ((node = unwrapStaticExpression(node))) { + if (requiredNamespaces.has(node)) { + found = true; + break; + } if (node.type === 'AwaitExpression') { node = node.argument as AstNode; continue; diff --git a/packages/void/src/inference/walk.ts b/packages/void/src/inference/walk.ts index 95a8b3f0dc..f42badf053 100644 --- a/packages/void/src/inference/walk.ts +++ b/packages/void/src/inference/walk.ts @@ -1,6 +1,7 @@ import { walk } from 'estree-walker'; import { parseSync } from 'vite'; -import { isIdentifier, isMemberExpression } from '../shared/ast.ts'; +import { bindingResolver } from '../shared/ast-bindings.ts'; +import { asAstProgram, isCallExpression, isIdentifier, isMemberExpression } from '../shared/ast.ts'; import type { AstNode } from '../shared/ast.ts'; import { staticModuleReferences } from '../shared/module-references.ts'; import { staticLiteral, unwrapStaticExpression } from '../shared/static-exports.ts'; @@ -47,7 +48,7 @@ function isEnv(node: AstNode | undefined): boolean { /** * Infer which Cloudflare bindings a source file uses. * - * Read Vite's module metadata, then walk the AST only for potential env bindings. + * Read Vite's module metadata, then walk the AST for CommonJS imports or env bindings. */ export function inferBindingsFromSource(code: string, filename: string): InferredBindings { const result: InferredBindings = { @@ -73,6 +74,7 @@ export function inferBindingsFromSource(code: string, filename: string): Inferre } let hasClientModule = false; + const requiredClientNamespaces = new Set(); function recordModuleReference(source: string): void { if (CLIENT_MODULES.has(source)) { hasClientModule = true; @@ -112,6 +114,33 @@ export function inferBindingsFromSource(code: string, filename: string): Inferre recordModuleReference(reference.source); } + // The parser's module metadata omits CommonJS imports. Resolve the callee so a local + // function named require cannot cause a project to provision unrelated resources. + if (/\brequire\b|\\u/.test(code)) { + const imports = new Map(); + const resolve = bindingResolver(asAstProgram(parsed.program), { + names: new Set(['require']), + visit(node) { + if (isCallExpression(node) && isIdentifier(node.callee) && node.callee.name === 'require') { + const source = staticLiteral(node.arguments?.[0]); + if (typeof source === 'string' && source.startsWith('void/')) { + imports.set(node, source); + return true; + } + } + return false; + }, + }); + for (const [node, source] of imports) { + if (!resolve(node, 'require')) { + recordModuleReference(source); + if (CLIENT_MODULES.has(source)) { + requiredClientNamespaces.add(node); + } + } + } + } + for (const reference of parsed.module.dynamicImports) { // Parse just the argument so literal decoding does not materialize the whole file's AST. const argument = code.slice(reference.moduleRequest.start, reference.moduleRequest.end); @@ -126,7 +155,7 @@ export function inferBindingsFromSource(code: string, filename: string): Inferre } if (hasClientModule) { - result.needsAuth ||= inferClientAuth(parsed, code); + result.needsAuth ||= inferClientAuth(parsed, code, requiredClientNamespaces); } if (!ENV_BINDING_RE.test(code) || !RESOURCE_BINDING_RE.test(code)) { diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts index 0828131ebf..774a2d817f 100644 --- a/packages/void/src/runtime/workflows/index.ts +++ b/packages/void/src/runtime/workflows/index.ts @@ -287,7 +287,7 @@ export function defineWorkflowEntrypoint( ): WorkflowApi< TClass, NativeWorkflowInput>, - NativeWorkflowParams + Exclude, void> > { if (!(definition.class?.prototype instanceof WorkflowEntrypoint)) { throw new Error( diff --git a/packages/void/src/workflows/scan.ts b/packages/void/src/workflows/scan.ts index d8dc0b547e..5fd25bee08 100644 --- a/packages/void/src/workflows/scan.ts +++ b/packages/void/src/workflows/scan.ts @@ -17,8 +17,8 @@ export type WorkflowModule = { name?: string; }; -const MODULE_PATTERN = /\.(?:[cm]?[jt]s)$/; -const MODULE_GLOB = '**/*.{ts,mts,cts,js,mjs,cjs}'; +const MODULE_PATTERN = /\.(?:[cm]?[jt]s|[jt]sx)$/; +const MODULE_GLOB = '**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}'; const WORKFLOW_HELPERS = new Set(['defineWorkflow', 'defineWorkflowEntrypoint']); diff --git a/packages/void/test/integration/workflow-dev.test.ts b/packages/void/test/integration/workflow-dev.test.ts index bd59140ed8..84c6a37ef5 100644 --- a/packages/void/test/integration/workflow-dev.test.ts +++ b/packages/void/test/integration/workflow-dev.test.ts @@ -197,15 +197,17 @@ it('types JavaScript Workflow bindings with and without allowJs', async () => { const fixture = createIsolatedPlayground(repository, 'playground/ssr'); onTestFinished(() => fixture.cleanup()); mkdirSync(join(fixture.root, 'workflows')); - writeFileSync( - join(fixture.root, 'workflows', 'archive.mjs'), - ` + for (const file of ['archive.mjs', 'mail.jsx']) { + writeFileSync( + join(fixture.root, 'workflows', file), + ` import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ /** @param {import('void/workflows').WorkflowEvent<{ days: number }>} event */ async run(event) { return event.payload.days; }, });`, - ); + ); + } const { prepareProject } = await import('../../src/codegen/prepare.ts'); await prepareProject(fixture.root); for (const allowJs of [false, true]) { @@ -216,13 +218,17 @@ import type {} from 'void/workflows'; declare const env: VoidGeneratedEnvBindings; void env.WORKFLOW_ARCHIVE.create({ params: { days: 3 } }); ${allowJs ? '// @ts-expect-error Checked JavaScript requires a numeric days field.' : ''} -void env.WORKFLOW_ARCHIVE.create({ params: { days: "three" } });`, +void env.WORKFLOW_ARCHIVE.create({ params: { days: "three" } }); +void env.WORKFLOW_MAIL.create({ params: { days: 3 } }); +${allowJs ? '// @ts-expect-error Checked JSX also requires a numeric days field.' : ''} +void env.WORKFLOW_MAIL.create({ params: { days: "three" } });`, ); writeFileSync( join(fixture.root, 'tsconfig.binding.json'), JSON.stringify({ compilerOptions: { allowJs, + jsx: 'preserve', strict: true, noEmit: true, module: 'NodeNext', diff --git a/packages/void/test/unit/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index 09995ff161..02aef9109f 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -432,9 +432,18 @@ export default defineWorkflow({ async run(event, step, { env }) { ); writeFileSync( join(root, 'workflows', '_storage.cjs'), - "exports.read = (env) => env.STORAGE.get('key');", + `const { db } = require('void/db'); + const { fetch } = require('void/client'); + exports.read = (env) => [db, env.STORAGE.get('key')]; + exports.test = (require) => require('void/ai');`, ); - expect(inferProjectBindings(root)).toMatchObject({ needsKV: true, needsR2: true }); + expect(inferProjectBindings(root)).toMatchObject({ + needsKV: true, + needsR2: true, + needsD1: true, + needsAI: false, + needsAuth: false, + }); expect(inferProjectBindings(root, undefined, ['.'])).toMatchObject({ needsKV: true, needsR2: true, @@ -443,6 +452,11 @@ export default defineWorkflow({ async run(event, step, { env }) { needsKV: false, needsR2: false, }); + writeFileSync( + join(root, 'workflows', '_auth.cjs'), + "exports.auth = require('void/client').auth;", + ); + expect(inferProjectBindings(root).needsAuth).toBe(true); }); it('detects live from a stream module outside the default directories only when scanned', () => { diff --git a/packages/void/test/unit/workflow-runtime.typecheck.ts b/packages/void/test/unit/workflow-runtime.typecheck.ts index eca1b10443..708f3b3990 100644 --- a/packages/void/test/unit/workflow-runtime.typecheck.ts +++ b/packages/void/test/unit/workflow-runtime.typecheck.ts @@ -1,6 +1,10 @@ import { WorkflowEntrypoint } from 'cloudflare:workers'; import { defineWorkflow, defineWorkflowEntrypoint } from '../../src/runtime/workflows/index.ts'; -import type { WorkflowEvent } from '../../src/runtime/workflows/index.ts'; +import type { + NativeWorkflowParams, + WorkflowBinding, + WorkflowEvent, +} from '../../src/runtime/workflows/index.ts'; import type { StandardSchemaV1 } from '../../src/standard-schema.ts'; declare const binding: Workflow; @@ -107,7 +111,16 @@ class OptionalNative extends WorkflowEntrypoint) {} } const native = defineWorkflowEntrypoint({ class: OptionalNative }); +declare const nativeBinding: WorkflowBinding>; void native.create({ params: { id: 1 } }); +void native.create(nativeBinding, { params: { id: 1 } }); +void native.createBatch(nativeBinding, [{ params: { id: 1 } }]); +// @ts-expect-error This native Workflow does not supply the recipient required by the receiver. +void native.create(narrowerBinding, { params: { id: 1 } }); +// @ts-expect-error Each instance would be missing the receiver's required recipient. +void native.createBatch(narrowerBinding, [{ params: { id: 1 } }]); +// @ts-expect-error The generated binding also requires params. +void native.create(nativeBinding); // @ts-expect-error This native class can't receive the empty object used for omitted params. void native.create(); // @ts-expect-error Passing undefined would deliver an empty object. diff --git a/packages/void/test/unit/workflow-scan.test.ts b/packages/void/test/unit/workflow-scan.test.ts index dddeb73162..61311c8a28 100644 --- a/packages/void/test/unit/workflow-scan.test.ts +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -130,6 +130,22 @@ module.exports = defineWorkflow({ async run() {} });`, ]); }); + it.each(['tsx', 'jsx'])('discovers JSX Workflow definitions in .%s files', (extension) => { + const root = createRoot({ + ['mail/welcome.' + extension]: definition.replace( + 'run() {}', + 'run() { return

Hello

; }', + ), + }); + expect(scanWorkflowModules(root)).toMatchObject([ + { + bindingName: 'WORKFLOW_MAIL_WELCOME', + className: 'MailWelcomeWorkflow', + resourceName: 'mail-welcome', + }, + ]); + }); + it('joins nested directories into the name, as queues do', () => { const root = createRoot({ 'order/notifications.ts': definition }); expect(scanWorkflowModules(root)).toEqual([ From e310f32fd3333357de7ad4b21f9b4f09648fc9a9 Mon Sep 17 00:00:00 2001 From: Christoph Nakazawa Date: Tue, 1 Dec 2026 16:36:59 +0900 Subject: [PATCH 13/13] Preserve Workflow schedules and recover large deployments across version changes. --- packages/deploy-cloudflare/src/existing.ts | 12 +- packages/deploy-cloudflare/src/index.ts | 3 + packages/deploy-cloudflare/src/operations.ts | 2 + packages/deploy-cloudflare/src/static.ts | 20 +- packages/deploy-cloudflare/src/version.ts | 171 +++++++++++++++--- .../test/unit/version.test.ts | 124 +++++++++++-- packages/void/src/cli/cf-version-message.ts | 95 ++++++++++ packages/void/src/cli/cf-version-runner.ts | 137 +++++++------- .../src/cli/cloudflare-operation-process.ts | 68 ++++--- .../void/src/cli/cloudflare-operations.ts | 21 +++ packages/void/src/cli/cloudflare-process.ts | 79 ++++++-- .../void/src/cli/deploy-cloudflare-build.ts | 4 +- .../void/src/cli/deploy-cloudflare-helpers.ts | 3 +- .../src/cli/deploy-cloudflare-preflight.ts | 2 + .../src/cli/platform-installer-inspection.ts | 23 ++- packages/void/src/cli/provision.ts | 14 +- packages/void/src/cli/rollback.ts | 5 +- .../void/test/unit/cf-version-message.test.ts | 169 +++++++++++++++++ .../void/test/unit/cf-version-runner.test.ts | 102 +++++++++++ .../void/test/unit/cloudflare-deploy.test.ts | 55 +++++- .../unit/cloudflare-operation-process.test.ts | 81 ++++++++- .../test/unit/cloudflare-operations.test.ts | 47 ++++- .../void/test/unit/rollback-platform.test.ts | 1 + 23 files changed, 1051 insertions(+), 187 deletions(-) create mode 100644 packages/void/src/cli/cf-version-message.ts create mode 100644 packages/void/test/unit/cf-version-message.test.ts diff --git a/packages/deploy-cloudflare/src/existing.ts b/packages/deploy-cloudflare/src/existing.ts index 4a53a81107..a53bdc1ddd 100644 --- a/packages/deploy-cloudflare/src/existing.ts +++ b/packages/deploy-cloudflare/src/existing.ts @@ -10,6 +10,7 @@ import { isWranglerSecretOnlyDraft, } from './secret-draft.ts'; import { cloudflareStagingPairGuidance } from './staging-guidance.ts'; +import { resolveCloudflareVersionMessage } from './version.ts'; export type ExistingCloudflareWorker = { versionId: string; @@ -134,6 +135,12 @@ async function readCloudflareWorker( isSecretOnlyDraft = isVoidSecretOnlyDraft(source); } } + const annotation = isRecord(version.annotations) ? version.annotations['workers/message'] : null; + const versionMessage = await resolveCloudflareVersionMessage( + typeof annotation === 'string' ? annotation : null, + versionId, + () => read({ type: 'versions.view', versionId, includeSource: true, ...target }), + ); const after = options.versionId ? deployment : await read({ type: 'deployments.status', ...target }); @@ -146,10 +153,7 @@ async function readCloudflareWorker( return { snapshot: { versionId, - ...(isRecord(version.annotations) && - typeof version.annotations['workers/message'] === 'string' - ? { versionMessage: version.annotations['workers/message'] } - : {}), + ...(versionMessage === null ? {} : { versionMessage }), bindings: resources.bindings, runtime: resources.script_runtime, script: resources.script, diff --git a/packages/deploy-cloudflare/src/index.ts b/packages/deploy-cloudflare/src/index.ts index 971591302c..a2eeda4889 100644 --- a/packages/deploy-cloudflare/src/index.ts +++ b/packages/deploy-cloudflare/src/index.ts @@ -40,6 +40,9 @@ export { deployCloudflareVersionTriggers, deployCloudflareVersionTraffic, encodeCloudflareVersionMessage, + cloudflareVersionMessageReference, + cloudflareVersionMessageModule, + resolveCloudflareVersionMessage, summarizeCloudflareMigrations, extractWorkersDevSubdomain, hasWorkflowSchedules, diff --git a/packages/deploy-cloudflare/src/operations.ts b/packages/deploy-cloudflare/src/operations.ts index cf6585cd17..ae32278ff1 100644 --- a/packages/deploy-cloudflare/src/operations.ts +++ b/packages/deploy-cloudflare/src/operations.ts @@ -77,6 +77,8 @@ export type CloudflareOperation = secretsFilePath?: string; assetsDirectory?: string; previewAlias?: string; + /** Install these schedules after removed schedules have released their account slots. */ + deferWorkflowSchedules?: ReadonlyArray; noBundle?: boolean; /** * Attach the Cloudflare CLI to this terminal so that it can ask the diff --git a/packages/deploy-cloudflare/src/static.ts b/packages/deploy-cloudflare/src/static.ts index 6ac9709717..7588d4daa0 100644 --- a/packages/deploy-cloudflare/src/static.ts +++ b/packages/deploy-cloudflare/src/static.ts @@ -1,9 +1,11 @@ import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { isRecord } from '@void/deploy-core'; import type { AssetConfig, HeaderRule, RedirectRule } from '@void/deploy-core'; import { createScanner, parse, parseTree, SyntaxKind } from 'jsonc-parser'; import type { Node, ParseError } from 'jsonc-parser'; import { dirname, join, relative, resolve } from 'pathslash'; import { setJsoncValue } from './config.ts'; +import { workflowExports } from './workflows.ts'; export type CloudflareStaticDeployConfig = Readonly<{ configPath: string; @@ -96,7 +98,7 @@ export function writeCloudflareStaticDeployConfig(options: CloudflareStaticDeplo : '{}\n'; const hasBom = initial.startsWith('\uFEFF'); const source = hasBom ? initial.slice(1) : initial; - assertValidStaticConfig(source, options.configPath); + const original = readValidStaticConfig(source, options.configPath); const originalComments = extractCommentTokens(source); let content = source; const upsert = (path: Array, value: unknown): void => { @@ -122,8 +124,11 @@ export function writeCloudflareStaticDeployConfig(options: CloudflareStaticDeplo upsert(['triggers', 'crons'], []); upsert(['containers'], []); upsert(['workflows'], []); + for (const name of Object.keys(workflowExports(original.exports))) { + upsert(['exports', name], undefined); + } - assertValidStaticConfig(content, options.configPath); + readValidStaticConfig(content, options.configPath); const droppedComment = findDroppedComment(originalComments, extractCommentTokens(content)); if (droppedComment !== undefined) { throw new Error( @@ -141,17 +146,11 @@ export function writeCloudflareStaticDeployConfig(options: CloudflareStaticDeplo return false; } -function assertValidStaticConfig(text: string, configPath: string): void { +function readValidStaticConfig(text: string, configPath: string): Record { const errors: Array = []; const parsed: unknown = parse(text, errors, { allowTrailingComma: true }); const root = parseTree(text, undefined, { allowTrailingComma: true }); - if ( - errors.length > 0 || - !root || - typeof parsed !== 'object' || - parsed === null || - Array.isArray(parsed) - ) { + if (errors.length > 0 || !root || !isRecord(parsed)) { throw new Error( `deploy: cannot update "${configPath}" — it is not valid JSON/JSONC. Fix the file and retry.`, ); @@ -176,6 +175,7 @@ function assertValidStaticConfig(text: string, configPath: string): void { node.children?.forEach(walk); }; walk(root); + return parsed; } function extractCommentTokens(text: string): Array { diff --git a/packages/deploy-cloudflare/src/version.ts b/packages/deploy-cloudflare/src/version.ts index 238e119614..52e0e8aee2 100644 --- a/packages/deploy-cloudflare/src/version.ts +++ b/packages/deploy-cloudflare/src/version.ts @@ -74,6 +74,8 @@ export type CloudflareTriggerConfig = Readonly<{ workflows: ReadonlyArray; /** Replay a previous name's schedule removal until the provider confirms it is clear. */ workflowScheduleCleanup?: ReadonlyArray; + /** Scheduled names waiting for the old names to release capacity, including on an atomic retry. */ + deferredWorkflowSchedules?: ReadonlyArray; /** * Email Routing addresses (`addresses` in Wrangler config). The Cloudflare CLI applies its * Email Routing plan inside `triggers deploy` — `undefined` skips the plan entirely, while @@ -222,21 +224,83 @@ export function encodeCloudflareVersionMessage( // Keep trigger recovery lossless. The digest still lets rollback distinguish // identical migration histories when the individual filenames do not fit. if (migrationState.migrations?.length) { - return encodeCloudflareVersionMessage( + const summary = encodeCloudflareVersionMessage( summarizeCloudflareMigrations(migrationState.migrations), triggerConfig, contentHash, ); + if (Buffer.byteLength(summary) <= MAX_VERSION_MESSAGE_BYTES) { + return summary; + } } - if (migrationState.migrationSummary) { - // Rollback asks for confirmation when even the digest cannot fit alongside the triggers. - return encodeCloudflareVersionMessage(null, triggerConfig, contentHash); + // The uploader places the full snapshot in an immutable Worker module and + // records its digest in the annotation when even the trigger state alone is too large. + return message; + } + return compressed; +} + +const VERSION_REFERENCE = /^void:ref:([a-f0-9]{64})$/; + +/** The provider annotation for a recovery record that needs its own Worker module. */ +export function cloudflareVersionMessageReference(message: string): string | undefined { + if ( + Buffer.byteLength(message) <= MAX_VERSION_MESSAGE_BYTES || + !parseCloudflareVersionMessage(message) + ) { + return undefined; + } + return 'void:ref:' + createHash('sha256').update(message).digest('hex'); +} + +export function cloudflareVersionMessageModule(reference: string): string { + const match = VERSION_REFERENCE.exec(reference); + if (!match) { + throw new Error('Invalid Cloudflare recovery metadata reference.'); + } + return '__void_recovery_' + match[1] + '.txt'; +} + +class CloudflareVersionRecoveryError extends Error {} + +/** Resolve only references written by Void, using the exact immutable Worker's modules. */ +export async function resolveCloudflareVersionMessage( + message: string | null, + versionId: string, + // oxlint-disable-next-line quality/no-unknown-returns -- Validate the provider response before reading module bytes. + readVersionSource: () => Promise, +): Promise { + if (!message || !VERSION_REFERENCE.test(message)) { + return message; + } + try { + const name = cloudflareVersionMessageModule(message); + const version = await readVersionSource(); + if (isRecord(version) && version.id === versionId && Array.isArray(version.modules)) { + const modules: Array = version.modules; + const matching = modules.filter((module) => isRecord(module) && module.name === name); + const module = matching[0]; + if ( + matching.length === 1 && + isRecord(module) && + module.content_type === 'text/plain' && + typeof module.content_base64 === 'string' + ) { + const value = Buffer.from(module.content_base64, 'base64').toString('utf8'); + if (cloudflareVersionMessageReference(value) === message) { + return value; + } + } } - throw new Error( - "deploy: Worker recovery metadata exceeds Cloudflare's 1000-byte version message limit even after compression. Reduce the deployment's trigger configuration before retrying.", + } catch (cause) { + throw new CloudflareVersionRecoveryError( + `Could not read the recovery metadata for Cloudflare Worker version ${versionId}.`, + { cause }, ); } - return compressed; + throw new CloudflareVersionRecoveryError( + `Could not verify the recovery metadata for Cloudflare Worker version ${versionId}.`, + ); } /** Read migration state written by {@link encodeCloudflareVersionMessage}. */ @@ -363,13 +427,7 @@ export async function deployCloudflareVersionTriggers(options: { const configPath = join(directory, 'wrangler.json'); try { writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 }); - const deployed = await options.runWrangler( - { type: 'triggers.deploy', configPath, workerName: options.workerName }, - { capture: false }, - ); - if (!isCleanCommandExit(deployed)) { - return deployed; - } + // Workflow schedules share an account quota. Release the retired names before registering replacements. for (const workflow of workflowsToClear( options.workerName, options.triggerConfig, @@ -393,6 +451,13 @@ export async function deployCloudflareVersionTriggers(options: { return cleared; } } + const deployed = await options.runWrangler( + { type: 'triggers.deploy', configPath, workerName: options.workerName }, + { capture: false }, + ); + if (!isCleanCommandExit(deployed)) { + return deployed; + } if (options.triggerConfig.crons.length === 0 && options.publishEmptyCrons) { const published = await options.publishEmptyCrons(); if (!isCleanCommandExit(published)) { @@ -703,6 +768,21 @@ function workflowsToClear( return [...pending.values()]; } +function localWorkflowScheduleCounts(workerName: string, workflows: ReadonlyArray) { + const counts = new Map(); + for (const workflow of workflows) { + if ( + isRecord(workflow) && + typeof workflow.name === 'string' && + (workflow.script_name === undefined || workflow.script_name === workerName) && + hasWorkflowSchedules(workflow.schedules) + ) { + counts.set(workflow.name, Array.isArray(workflow.schedules) ? workflow.schedules.length : 1); + } + } + return counts; +} + // After an atomic publication the version can stay live even if trigger sync fails. // Carry unconfirmed removals into its successor; a successful read retires the record. async function recordWorkflowScheduleCleanup( @@ -735,7 +815,24 @@ async function recordWorkflowScheduleCleanup( removed.push(candidate); } } - return removed.length ? { ...desired, workflowScheduleCleanup: removed } : desired; + if (!removed.length) { + return desired; + } + const previousCounts = localWorkflowScheduleCounts(options.workerName, previous.workflows); + const desiredCounts = localWorkflowScheduleCounts(options.workerName, desired.workflows); + // An earlier atomic publish may have gone live before any replacement was registered. + // Older annotations listed the outstanding removals but could not identify those replacements. + const deferredWorkflowSchedules: Array = []; + for (const [name, count] of desiredCounts) { + if ( + count > (previousCounts.get(name) ?? 0) || + (previous.deferredWorkflowSchedules?.includes(name) ?? + Boolean(previous.workflowScheduleCleanup?.length)) + ) { + deferredWorkflowSchedules.push(name); + } + } + return { ...desired, workflowScheduleCleanup: removed, deferredWorkflowSchedules }; } function hasCustomDomains(routes: ReadonlyArray | undefined): boolean { @@ -781,7 +878,7 @@ function triggerConfigFromWrangler(config: Record): CloudflareT // rollback do not accidentally reopen the public workers.dev hostname. const workersDev = typeof config.workers_dev === 'boolean' ? config.workers_dev : routes.length === 0; - const addresses = readEmailAddresses(config.addresses); + const addresses = readStringArray(config.addresses); return { ...(config.routes === undefined && config.route === undefined ? { preserveRoutes: true } : {}), ...(config.workers_dev === undefined ? { preserveWorkersDev: true } : {}), @@ -810,8 +907,8 @@ function desiredTriggerConfigFor( return configPath ? readCloudflareTriggerConfig(configPath) : triggerConfigFromWrangler({}); } -/** A well-formed `addresses` array, or `undefined` when the field is absent or malformed. */ -function readEmailAddresses(value: unknown): ReadonlyArray | undefined { +/** A string array, or undefined when the field is absent or malformed. */ +function readStringArray(value: unknown): ReadonlyArray | undefined { return Array.isArray(value) && value.every((entry) => typeof entry === 'string') ? value : undefined; @@ -830,8 +927,9 @@ function parseTriggerConfig(value: unknown): CloudflareTriggerConfig | null { if (!isRecord(value)) { return null; } - const addresses = readEmailAddresses(value.addresses); + const addresses = readStringArray(value.addresses); const cleanup = value.workflowScheduleCleanup; + const deferred = readStringArray(value.deferredWorkflowSchedules); if ( ['preserve', 'preserveRoutes', 'preserveWorkersDev', 'preservePreviewUrls', 'logpush'].some( (key) => value[key] !== undefined && typeof value[key] !== 'boolean', @@ -844,6 +942,7 @@ function parseTriggerConfig(value: unknown): CloudflareTriggerConfig | null { !Array.isArray(value.crons) || !Array.isArray(value.queueConsumers) || !Array.isArray(value.workflows) || + (value.deferredWorkflowSchedules !== undefined && deferred === undefined) || (cleanup !== undefined && (!Array.isArray(cleanup) || !cleanup.every( @@ -871,6 +970,7 @@ function parseTriggerConfig(value: unknown): CloudflareTriggerConfig | null { queueConsumers: value.queueConsumers, workflows: value.workflows, ...(cleanup && { workflowScheduleCleanup: cleanup }), + ...(deferred && { deferredWorkflowSchedules: deferred }), ...(addresses === undefined ? {} : { addresses }), }; } @@ -2296,11 +2396,28 @@ async function readCloudflareVersionInspection( } } } + const resolvedMessage = await resolveCloudflareVersionMessage( + typeof message === 'string' ? message : null, + versionId, + async () => { + const source = await options.runWrangler( + { + type: 'versions.view', + versionId, + configPath: options.configPath, + workerName: options.workerName, + includeSource: true, + }, + { capture: true }, + ); + return isCleanCommandExit(source) ? source.data : null; + }, + ); const inspectedDraft = draft; const isVoidDraft = isVoidSecretOnlyDraft(inspectedDraft); return { - metadata: typeof message === 'string' ? parseCloudflareVersionMessage(message) : null, - message: typeof message === 'string' ? message : null, + metadata: parseCloudflareVersionMessage(resolvedMessage), + message: resolvedMessage, isSecretOnlyDraft: isWranglerSecretOnlyDraft(draft) || isVoidDraft, isVoidSecretOnlyDraft: isVoidDraft, voidDraftSecretNames: isVoidDraft @@ -2309,7 +2426,10 @@ async function readCloudflareVersionInspection( draftUnknown, }; } - } catch { + } catch (error) { + if (error instanceof CloudflareVersionRecoveryError) { + throw error; + } return null; } return null; @@ -2573,12 +2693,17 @@ async function bootstrapFirstDeployment( options.onProgress?.( atomic ? 'Publishing the Worker atomically...' : 'Publishing the first Worker deployment...', ); + const desiredMetadata = parseCloudflareVersionMessage(options.message); + const desiredTriggerConfig = desiredTriggerConfigFor(desiredMetadata, options.configPath); const bootstrap = await options.runWrangler( { type: 'worker.deploy', configPath: options.configPath, workerName: options.workerName, message: options.message, + ...(desiredTriggerConfig.deferredWorkflowSchedules?.length && { + deferWorkflowSchedules: desiredTriggerConfig.deferredWorkflowSchedules, + }), secretsFilePath: options.candidateSecretsFilePath, assetsDirectory: options.assetsDirectoryOverride, }, @@ -2597,8 +2722,6 @@ async function bootstrapFirstDeployment( } const published = readUploadResult(bootstrap); const versionId = published?.versionId; - const desiredMetadata = parseCloudflareVersionMessage(options.message); - const desiredTriggerConfig = desiredTriggerConfigFor(desiredMetadata, options.configPath); const reportedUrl = published?.previewUrl ?? published?.workersDevUrl; let reportedOrConfiguredUrl = reportedUrl ?? diff --git a/packages/deploy-cloudflare/test/unit/version.test.ts b/packages/deploy-cloudflare/test/unit/version.test.ts index 45fde0039a..5aa6f7f66f 100644 --- a/packages/deploy-cloudflare/test/unit/version.test.ts +++ b/packages/deploy-cloudflare/test/unit/version.test.ts @@ -8,6 +8,9 @@ import { assertCloudflareDurableObjectLifecycleSupported, deployCloudflareVersionTriggers, encodeCloudflareVersionMessage, + cloudflareVersionMessageReference, + cloudflareVersionMessageModule, + resolveCloudflareVersionMessage, extractWorkersDevSubdomain, normalizeReadinessAccessOrigin, normalizeWorkersDevSubdomain, @@ -388,6 +391,8 @@ function recoveryActivation(setup: { return { ...ok(), data: setup.previousSource }; } return { stdout: '', stderr: 'Version view is unavailable.', status: 1 }; + case 'triggers.clear-workflow-schedules': + return { ...ok(), data: true }; case 'versions.upload': uploaded = true; return { @@ -2827,20 +2832,54 @@ describe('Cloudflare version activation', () => { } }); - it('refuses recovery metadata that cannot fit even when compressed', () => { + it('authenticates a large recovery module from the exact Worker version', async () => { const routes = Array.from( { length: 64 }, (_, i) => createHash('sha256').update(String(i)).digest('hex').slice(0, 32) + '.example.com/*', ); const triggers = triggersWith({ routes }); - expect(() => encodeCloudflareVersionMessage([], triggers)).toThrow( - '1000-byte version message limit', - ); + const message = encodeCloudflareVersionMessage([], triggers); + const reference = cloudflareVersionMessageReference(message)!; + const module = { + name: cloudflareVersionMessageModule(reference), + content_type: 'text/plain', + content_base64: btoa(message), + }; + const source = { id: CURRENT, modules: [module] }; + const read = vi.fn(async () => source); + expect(reference).toMatch(/^void:ref:[a-f0-9]{64}$/); + expect(await resolveCloudflareVersionMessage(message, CURRENT, read)).toBe(message); + expect(read).not.toHaveBeenCalled(); + expect( + parseCloudflareVersionMessage( + await resolveCloudflareVersionMessage(reference, CURRENT, read), + ), + ).toMatchObject({ triggerConfig: triggers }); + for (const bad of [ + { ...source, id: NEXT }, + { ...source, modules: [] }, + { ...source, modules: [module, module] }, + { ...source, modules: [{ ...module, content_base64: btoa(message + ' ') }] }, + ]) { + await expect( + resolveCloudflareVersionMessage(reference, CURRENT, async () => bad), + ).rejects.toThrow('verify the recovery metadata'); + } + const recovery = recoveryActivation({ + previous: { id: CURRENT, number: 1, annotations: { 'workers/message': reference } }, + previousSource: source, + triggers: [TRIGGER_FAILURE], + }); + expect(await activateCloudflareVersion(recovery.options)).toMatchObject({ + ok: false, + rollback: 'succeeded', + triggersRestored: 'yes', + }); expect(parseCloudflareVersionMessage('void:z:invalid')).toBeNull(); }); - it('keeps the full trigger snapshot when even a migration digest would exceed the limit', () => { + it('keeps the migration filenames with a trigger snapshot that requires a module', () => { const routes = Array.from( { length: 28 }, (_, i) => @@ -2852,7 +2891,7 @@ describe('Cloudflare version activation', () => { parseCloudflareVersionMessage(encodeCloudflareVersionMessage(history, triggers)), ).toEqual({ schema: 2, - migrations: null, + migrations: history, triggerConfig: triggers, }); }); @@ -2879,7 +2918,7 @@ describe('Cloudflare version activation', () => { }, ); - it('checks the combined size of new routes and removed Workflow schedules before migrations', async () => { + it('keeps new routes and removed Workflow schedules together across an atomic publish', async () => { const tenants = Array.from({ length: 16 }, (_, i) => createHash('sha256').update(String(i)).digest('hex'), ); @@ -2909,11 +2948,73 @@ describe('Cloudflare version activation', () => { message: encodeCloudflareVersionMessage([], desired), beforeUpload, }), - ).rejects.toThrow('1000-byte version message limit'); - expect(beforeUpload).not.toHaveBeenCalled(); + ).resolves.toMatchObject({ ok: true }); + expect(beforeUpload).toHaveBeenCalledOnce(); + const publish = fixture.options.runWrangler.mock.calls + .map(([operation]) => operation) + .find((operation) => operation.type === 'worker.deploy'); + const message = (publish?.type === 'worker.deploy' && publish.message) || ''; + expect(cloudflareVersionMessageReference(message)).toMatch(/^void:ref:/); + const metadata = parseCloudflareVersionMessage(message); + expect(metadata).toMatchObject({ triggerConfig: { routes: desired.routes } }); expect( - fixture.options.runWrangler.mock.calls.map(([operation]) => operation.type), - ).not.toContain('worker.deploy'); + metadata?.schema === 2 && + metadata.triggerConfig.workflowScheduleCleanup?.map((entry) => entry.workflowName), + ).toEqual(tenants.map((tenant) => 'job_' + tenant.slice(0, 32))); + }); + + it('replaces a scheduled Workflow at the account quota during atomic publication', async () => { + const job = { name: 'old', binding: 'JOB', class_name: 'Job', schedules: ['0 0 * * *'] }; + const steady = { ...job, name: 'steady', binding: 'STEADY', class_name: 'Steady' }; + const next = { ...job, name: 'new' }; + const previous = triggersWith({ workflows: [job, steady] }); + const desired = triggersWith({ workflows: [next, steady] }); + const fixture = recoveryActivation({ + atomic: true, + previous: { + id: CURRENT, + number: 1, + annotations: { 'workers/message': encodeCloudflareVersionMessage([], previous) }, + }, + }); + const installed = new Set(['old', 'steady']); + const publishNew = () => { + // Another 98 schedules belong to other Workers in this account. + if (!installed.has('new') && installed.size === 2) { + return { ...ok(), status: 1, stderr: 'Account schedule limit exceeded' }; + } + installed.add('new'); + return ok(); + }; + const result = await activateCloudflareVersion({ + ...fixture.options, + message: encodeCloudflareVersionMessage([], desired), + runWrangler: async (operation) => { + if ( + operation.type === 'worker.deploy' && + !operation.deferWorkflowSchedules?.includes('new') + ) { + const registered = publishNew(); + if (registered.status !== 0) { + return registered; + } + } + if (operation.type === 'worker.deploy') { + expect(operation.deferWorkflowSchedules).toEqual(['new']); + } + if (operation.type === 'triggers.clear-workflow-schedules') { + expect(operation.workflowName).toBe('old'); + installed.delete(operation.workflowName); + return ok(); + } + if (operation.type === 'triggers.deploy') { + return publishNew(); + } + return fixture.options.runWrangler(operation); + }, + }); + expect(result).toMatchObject({ ok: true }); + expect([...installed].sort()).toEqual(['new', 'steady']); }); it('retains failed schedule cleanup across atomic deploy retries and retires it after success', async () => { @@ -2941,6 +3042,7 @@ describe('Cloudflare version activation', () => { message: desired, runWrangler: async (operation) => { if (operation.type === 'worker.deploy') { + expect(operation.deferWorkflowSchedules).toEqual(attempt < 3 ? ['pinned'] : undefined); activeMessage = operation.message ?? ''; } if (operation.type === 'triggers.clear-workflow-schedules') { diff --git a/packages/void/src/cli/cf-version-message.ts b/packages/void/src/cli/cf-version-message.ts new file mode 100644 index 0000000000..0737e63cbe --- /dev/null +++ b/packages/void/src/cli/cf-version-message.ts @@ -0,0 +1,95 @@ +import { + constants, + cpSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { + cloudflareVersionMessageModule, + cloudflareVersionMessageReference, +} from '@void/deploy-cloudflare'; +import { isRecord } from '@void/deploy-core'; +import { join, resolve, toSlash } from 'pathslash'; + +/** Prepare a private version upload. Keep the input artifact reusable for a retry or preview. */ +export async function withCloudflareVersionMessage( + directory: string, + options: { message?: string; deferWorkflowSchedules?: ReadonlyArray }, + upload: (directory: string, annotation: string | undefined) => T | Promise, +): Promise { + const { message } = options; + const reference = message && cloudflareVersionMessageReference(message); + if (!reference && !options.deferWorkflowSchedules?.length) { + return upload(directory, message); + } + const staged = realpathSync(mkdtempSync(join(tmpdir(), 'void-cf-version-'))); + try { + cpSync(directory, staged, { + recursive: true, + verbatimSymlinks: true, + mode: constants.COPYFILE_FICLONE, + }); + const { getWorkerConfigPath, readBuildOutput } = await import('@cloudflare/build-output-utils'); + const configPath = getWorkerConfigPath(staged); + if (toSlash(realpathSync(configPath)) !== resolve(configPath)) { + throw new Error('The private Cloudflare Worker config cannot be changed through a symlink.'); + } + const config: unknown = JSON.parse(readFileSync(configPath, 'utf8')); + if (!isRecord(config)) { + throw new Error('The private Cloudflare Worker config was not readable.'); + } + if (options.deferWorkflowSchedules?.length) { + await deferWorkflowSchedules(config, options.deferWorkflowSchedules); + } + if (reference && message) { + const worker = (await readBuildOutput(staged)).workers.default; + const manifest = worker.config.manifest; + if (!worker.bundleDir || !manifest || manifest.type !== 'complete') { + throw new Error('The Cloudflare recovery snapshot requires a complete Worker bundle.'); + } + if (toSlash(realpathSync(worker.bundleDir)) !== resolve(worker.bundleDir)) { + throw new Error('The Cloudflare recovery snapshot cannot be written through a symlink.'); + } + const name = cloudflareVersionMessageModule(reference); + if (Object.hasOwn(manifest.modules, name)) { + throw new Error(`Worker module ${name} conflicts with the Cloudflare recovery snapshot.`); + } + // An undeclared file or dangling symlink must also retain its original contents. + writeFileSync(join(worker.bundleDir, name), message, { flag: 'wx', mode: 0o600 }); + config.manifest = { ...manifest, modules: { ...manifest.modules, [name]: { type: 'text' } } }; + } + writeFileSync(configPath, JSON.stringify(config)); + return await upload(staged, reference || message); + } finally { + rmSync(staged, { force: true, recursive: true }); + } +} + +/** cf deploy uses the export declarations both for its upload and for its separate Workflow PUTs. */ +async function deferWorkflowSchedules( + config: Record, + names: ReadonlyArray, +) { + const { exportsFromOutput } = await import('./cf-version-api.ts'); + const unsafe = isRecord(config.unsafe) ? config.unsafe : {}; + const metadata = isRecord(unsafe.metadata) ? unsafe.metadata : {}; + // Keep the version exports byte-for-byte compatible with the next staged upload. + config.unsafe = { + ...unsafe, + metadata: { exports: exportsFromOutput(config.exports, []), ...metadata }, + }; + for (const declaration of Object.values(isRecord(config.exports) ? config.exports : {})) { + if ( + isRecord(declaration) && + declaration.type === 'workflow' && + typeof declaration.name === 'string' && + names.includes(declaration.name) + ) { + delete declaration.schedules; + } + } +} diff --git a/packages/void/src/cli/cf-version-runner.ts b/packages/void/src/cli/cf-version-runner.ts index 03ebff32af..4ed33c4237 100644 --- a/packages/void/src/cli/cf-version-runner.ts +++ b/packages/void/src/cli/cf-version-runner.ts @@ -3,7 +3,10 @@ import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:f import { tmpdir } from 'node:os'; import { fileURLToPath } from 'node:url'; import { getWorkerConfigPath, readBuildOutput } from '@cloudflare/build-output-utils'; -import { parseCloudflareVersionMessage } from '@void/deploy-cloudflare'; +import { + cloudflareVersionMessageReference, + parseCloudflareVersionMessage, +} from '@void/deploy-cloudflare'; import type { CloudflareCommandResult, CloudflareCommandRunner, @@ -23,6 +26,7 @@ import { migrateBuiltWranglerConfig } from './cf-config-migrate.ts'; import { getCfCliVersion } from './cf-user-agent.ts'; import { isSecretBindingType, uploadPinnedCloudflareVersion } from './cf-version-api.ts'; import type { CfCommand } from './cf-version-api.ts'; +import { withCloudflareVersionMessage } from './cf-version-message.ts'; import { publishCloudflareWorkerSettings } from './cf-worker-settings.ts'; import { isCleanCloudflareExit } from './cloudflare-process.ts'; import type { WranglerAuthTokenResult } from './deploy-cloudflare-auth.ts'; @@ -500,25 +504,10 @@ export function createCfVersionRunner(options: { return failed('Cloudflare resources could not be verified before upload.'); } }; - /** Return a failure when the upload target drifted or its resources are not verified. */ - const checkUploadTarget = async ( - operation: Extract, - targetChanged: string, - ): Promise => { - if ( - operation.workerName !== workerName || - (operation.assetsDirectory !== undefined && - operation.assetsDirectory !== output.assetsDirectory) - ) { - return failed(targetChanged); - } - const verified = await verifyResources(output.directory); - return isCleanCloudflareExit(verified) ? null : verified; - }; - const uploadPinnedVersion = async ( operation: Extract, atomic: boolean, + directory: string, ) => { if (!options.pinnedUpload || !options.pinnedUpload.verifyUploader()) { return failed('The version-aware Cloudflare uploader is unavailable.'); @@ -533,7 +522,7 @@ export function createCfVersionRunner(options: { const { token } = credential; try { const version = await uploadPinnedCloudflareVersion({ - output, + output: { ...output, directory }, accountId: options.pinnedUpload.accountId, apiBaseUrl: options.pinnedUpload.apiBaseUrl, workerName, @@ -711,36 +700,58 @@ export function createCfVersionRunner(options: { }; } - if (operation.type === 'versions.upload') { - const blocked = await checkUploadTarget( - operation, - 'The Cloudflare version upload target changed.', - ); - if (blocked) { - return blocked; - } - const settings = await prepareSettingsCredential(operation.message); - if (settings) { - return settings; + if (operation.type === 'versions.upload' || operation.type === 'worker.deploy') { + const atomic = operation.type === 'worker.deploy'; + if ( + operation.workerName !== workerName || + (operation.assetsDirectory !== undefined && + operation.assetsDirectory !== output.assetsDirectory) + ) { + return failed( + atomic + ? 'The Cloudflare bootstrap target changed.' + : 'The Cloudflare version upload target changed.', + ); } - if (output.activeSecrets) { - return uploadPinnedVersion(operation, false); + try { + return await withCloudflareVersionMessage( + output.directory, + output.activeSecrets ? { message: operation.message } : operation, + async (directory, message) => { + const verified = await verifyResources(directory); + if (!isCleanCloudflareExit(verified)) { + return verified; + } + const settings = await prepareSettingsCredential(operation.message); + if (settings) { + return settings; + } + if (output.activeSecrets) { + return uploadPinnedVersion({ ...operation, message }, atomic, directory); + } + return uploadedResult( + await run( + [ + ...(atomic ? ['deploy'] : ['workers', 'versions', 'create']), + '--prebuilt', + // One argv item, so a message starting with "-" is never read as a flag. + ...(message ? [`--message=${message}`] : []), + ...(operation.secretsFilePath + ? ['--secrets-file', operation.secretsFilePath] + : []), + ...(!atomic && operation.previewAlias + ? ['--preview-alias', operation.previewAlias] + : []), + ], + command.capture, + directory, + ), + ); + }, + ); + } catch (cause) { + return failed(cause instanceof Error ? cause.message : 'Cloudflare version upload failed.'); } - return uploadedResult( - await run( - [ - 'workers', - 'versions', - 'create', - '--prebuilt', - // One argv item, so a message that starts with "-" is not read as a flag. - ...(operation.message ? [`--message=${operation.message}`] : []), - ...(operation.secretsFilePath ? ['--secrets-file', operation.secretsFilePath] : []), - ...(operation.previewAlias ? ['--preview-alias', operation.previewAlias] : []), - ], - command.capture, - ), - ); } if (operation.type === 'previews.deploy') { @@ -803,7 +814,10 @@ export function createCfVersionRunner(options: { JSON.stringify({ strategy: 'percentage', versions: parsed, - annotations: { 'workers/message': operation.message }, + annotations: { + 'workers/message': + cloudflareVersionMessageReference(operation.message) ?? operation.message, + }, }), ] : []), @@ -813,35 +827,6 @@ export function createCfVersionRunner(options: { ); } - if (operation.type === 'worker.deploy') { - const blocked = await checkUploadTarget( - operation, - 'The Cloudflare bootstrap target changed.', - ); - if (blocked) { - return blocked; - } - const settings = await prepareSettingsCredential(operation.message); - if (settings) { - return settings; - } - if (output.activeSecrets) { - return uploadPinnedVersion(operation, true); - } - return uploadedResult( - await run( - [ - 'deploy', - '--prebuilt', - // One argv item, so a message that starts with "-" is not read as a flag. - ...(operation.message ? [`--message=${operation.message}`] : []), - ...(operation.secretsFilePath ? ['--secrets-file', operation.secretsFilePath] : []), - ], - command.capture, - ), - ); - } - if (operation.type === 'triggers.deploy') { const configPath = operation.configPath; if (!configPath || operation.workerName !== workerName) { diff --git a/packages/void/src/cli/cloudflare-operation-process.ts b/packages/void/src/cli/cloudflare-operation-process.ts index aa91298036..a60198f0c4 100644 --- a/packages/void/src/cli/cloudflare-operation-process.ts +++ b/packages/void/src/cli/cloudflare-operation-process.ts @@ -8,6 +8,7 @@ import { fileURLToPath } from 'node:url'; * Execute typed Cloudflare operations using the pinned provider CLI and API. * Secret values arrive on stdin; captured results use one structured envelope. */ +import { cloudflareVersionMessageReference } from '@void/deploy-cloudflare'; import type { CloudflareCommandResult as Result, CloudflareOperation, @@ -24,6 +25,7 @@ import { import { importD1SqlFile } from './cf-d1-import.ts'; import { persistCfKeyringPreference, readCfSessionCredential } from './cf-session.ts'; import { getCfCliVersion, getVoidUserAgent } from './cf-user-agent.ts'; +import { withCloudflareVersionMessage } from './cf-version-message.ts'; import { publishCloudflareWorkerSettings } from './cf-worker-settings.ts'; import { cloudflareDeviceCode, @@ -41,7 +43,12 @@ type Json = Record; const cf = join(dirname(fileURLToPath(import.meta.resolve('cf/package.json'))), 'bin', 'cf'); const operation = (() => { try { - const parsed: unknown = JSON.parse(process.argv[2] ?? 'null'); + const argument = process.argv[2]; + const fileFlag = '--operation-file='; + const encoded = argument?.startsWith(fileFlag) + ? readFileSync(argument.slice(fileFlag.length), 'utf8') + : argument; + const parsed: unknown = JSON.parse(encoded ?? 'null'); return parsed; } catch { return null; @@ -214,7 +221,8 @@ function runInteractiveCf(command: Array): Promise { async function withBuildOutput( raw: Json, sourceMain: string | null, - action: (directory: string) => Result, + action: (directory: string, annotation: string | undefined) => Result, + options: { message?: string; deferWorkflowSchedules?: ReadonlyArray } = {}, ): Promise { const scratch = mkdtempSync(join(tmpdir(), 'void-cf-command-')); try { @@ -240,8 +248,14 @@ async function withBuildOutput( throw new Error('Could not prepare the Cloudflare Worker build output.'); } try { - await assertExistingProvisionableResources(output.directory, accountId); - return action(output.directory); + return await withCloudflareVersionMessage( + output.directory, + options, + async (directory, annotation) => { + await assertExistingProvisionableResources(directory, accountId); + return action(directory, annotation); + }, + ); } finally { await output.dispose(); } @@ -1297,14 +1311,15 @@ async function workerHistory(): Promise { return called; } const version = object(parsedJson(called.stdout)); - if (version.id !== versionId || !Array.isArray(version.bindings)) { + const bindings = version.bindings === undefined ? [] : version.bindings; + if (version.id !== versionId || !Array.isArray(bindings)) { throw new Error('Worker version bindings were malformed.'); } if (operation.includeSource) { - return result(0, '', called.stderr, version); + return result(0, '', called.stderr, { ...version, bindings }); } const resources = await readVersionResources(worker, versionId); - return result(0, '', called.stderr, { ...version, resources }); + return result(0, '', called.stderr, { ...version, bindings, resources }); } case 'versions.deploy': { const versions = operation.versions.map((value) => ({ @@ -1334,7 +1349,14 @@ async function workerHistory(): Promise { JSON.stringify({ strategy: 'percentage', versions, - ...(operation.message ? { annotations: { 'workers/message': operation.message } } : {}), + ...(operation.message + ? { + annotations: { + 'workers/message': + cloudflareVersionMessageReference(operation.message) ?? operation.message, + }, + } + : {}), }), ...(operation.bypassDeploymentChecks ? ['--bypass-deployment-checks'] : []), ]); @@ -1445,19 +1467,23 @@ async function workerChanges(): Promise { } const source = resolve(dirname(path), raw.main); const request = operation; - const called = await withBuildOutput(raw, source, (directory) => - runCf( - [ - ...(request.type === 'worker.deploy' ? ['deploy'] : ['workers', 'versions', 'create']), - '--prebuilt', - // One argv item, so a message that starts with "-" is not read as a flag. - ...(request.message ? [`--message=${request.message}`] : []), - ...(request.secretsFilePath ? ['--secrets-file', request.secretsFilePath] : []), - ], - directory, - undefined, - request.interactive === true, - ), + const called = await withBuildOutput( + raw, + source, + (directory, annotation) => + runCf( + [ + ...(request.type === 'worker.deploy' ? ['deploy'] : ['workers', 'versions', 'create']), + '--prebuilt', + // One argv item, so a message that starts with "-" is not read as a flag. + ...(annotation ? [`--message=${annotation}`] : []), + ...(request.secretsFilePath ? ['--secrets-file', request.secretsFilePath] : []), + ], + directory, + undefined, + request.interactive === true, + ), + request, ); // cf wrote an interactive upload to the terminal, so only its exit status is known. if (called.status !== 0 || request.interactive === true) { diff --git a/packages/void/src/cli/cloudflare-operations.ts b/packages/void/src/cli/cloudflare-operations.ts index 02052177e7..e1b5fb0ca5 100644 --- a/packages/void/src/cli/cloudflare-operations.ts +++ b/packages/void/src/cli/cloudflare-operations.ts @@ -5,6 +5,7 @@ import { encodeCloudflareVersionMessage, deployCloudflareVersionTraffic, parseCloudflareVersionMessage, + resolveCloudflareVersionMessage, parseRootWranglerConfig, readCloudflareTriggerConfig, stabilizeCloudflareVersionTriggers, @@ -435,6 +436,26 @@ export function parseCloudflareVersions(value: unknown): Array { + const message = await resolveCloudflareVersionMessage(version.message, version.id, async () => { + const source = await run(context, { + type: 'versions.view', + versionId: version.id, + workerName: context.workerName, + configPath: context.configPath, + includeSource: true, + }); + return source.data; + }); + return message === version.message + ? version + : { ...version, message, metadata: parseCloudflareVersionMessage(message) }; +} + export function parseActiveVersionId(value: unknown): string | null { const parsed = requireData(value, 'Cloudflare deployment status'); if (typeof parsed !== 'object' || parsed === null) { diff --git a/packages/void/src/cli/cloudflare-process.ts b/packages/void/src/cli/cloudflare-process.ts index 27738090e7..04005e8700 100644 --- a/packages/void/src/cli/cloudflare-process.ts +++ b/packages/void/src/cli/cloudflare-process.ts @@ -1,5 +1,10 @@ import { spawnSync } from 'node:child_process'; +import type { SpawnSyncReturns } from 'node:child_process'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { cloudflareVersionMessageReference } from '@void/deploy-cloudflare'; import type { CloudflareCommandResult, CloudflareOperation } from '@void/deploy-cloudflare'; +import { join } from 'pathslash'; import { CF_VERSION_SOURCE_MAX_OUTPUT_BYTES } from './cf-command-values.ts'; import { resolveCloudflareOperationArgv } from './preset.ts'; @@ -8,6 +13,38 @@ export function encodeCloudflareOperation(operation: CloudflareOperation): Array return [JSON.stringify(operation)]; } +type PreparedOperationArgs = { args: Array; dispose?: () => void }; + +/** Keep recovery records off the command line while leaving stdin available to the operation. */ +export function prepareCloudflareOperationArgs( + operation: CloudflareOperation, +): PreparedOperationArgs { + if ( + (operation.type === 'versions.upload' || + operation.type === 'worker.deploy' || + operation.type === 'versions.deploy') && + operation.message + ) { + const reference = cloudflareVersionMessageReference(operation.message); + if (reference) { + if (operation.type === 'versions.deploy') { + return { args: encodeCloudflareOperation({ ...operation, message: reference }) }; + } + const directory = mkdtempSync(join(tmpdir(), 'void-cf-operation-')); + const path = join(directory, 'operation.json'); + const dispose = () => rmSync(directory, { recursive: true, force: true }); + try { + writeFileSync(path, JSON.stringify(operation), { flag: 'wx', mode: 0o600 }); + return { args: ['--operation-file=' + path], dispose }; + } catch (error) { + dispose(); + throw error; + } + } + } + return { args: encodeCloudflareOperation(operation) }; +} + type ProcessResult = { status: number | null; stdout: string; @@ -138,24 +175,30 @@ export function createCloudflareProcessRunner(options: { const streaming = !run.capture && (operation.type === 'auth.login' || operation.type === 'tail'); const env = typeof options.env === 'function' ? options.env() : (options.env ?? process.env); - const result = spawnSync(command, [...prefix, ...encodeCloudflareOperation(operation)], { - cwd: run.cwd ?? options.root, - env: { - ...env, - ...(options.accountId ? { CLOUDFLARE_ACCOUNT_ID: options.accountId } : {}), - ...(options.apiBaseUrl ? { CLOUDFLARE_API_BASE_URL: options.apiBaseUrl } : {}), - }, - input: run.input, - encoding: 'utf8', - shell: false, - windowsHide: true, - maxBuffer: - operation.type === 'versions.view' && operation.includeSource - ? CF_VERSION_SOURCE_MAX_OUTPUT_BYTES - : 32 * 1024 * 1024, - timeout: options.timeoutMs, - stdio: streaming ? ['inherit', 'inherit', 'inherit'] : ['pipe', 'pipe', 'pipe'], - }); + const prepared = prepareCloudflareOperationArgs(operation); + let result: SpawnSyncReturns; + try { + result = spawnSync(command, [...prefix, ...prepared.args], { + cwd: run.cwd ?? options.root, + env: { + ...env, + ...(options.accountId ? { CLOUDFLARE_ACCOUNT_ID: options.accountId } : {}), + ...(options.apiBaseUrl ? { CLOUDFLARE_API_BASE_URL: options.apiBaseUrl } : {}), + }, + input: run.input, + encoding: 'utf8', + shell: false, + windowsHide: true, + maxBuffer: + operation.type === 'versions.view' && operation.includeSource + ? CF_VERSION_SOURCE_MAX_OUTPUT_BYTES + : 32 * 1024 * 1024, + timeout: options.timeoutMs, + stdio: streaming ? ['inherit', 'inherit', 'inherit'] : ['pipe', 'pipe', 'pipe'], + }); + } finally { + prepared.dispose?.(); + } const raw = { status: result.status ?? 1, stdout: result.stdout ?? '', diff --git a/packages/void/src/cli/deploy-cloudflare-build.ts b/packages/void/src/cli/deploy-cloudflare-build.ts index 5ea88902a1..c25def7894 100644 --- a/packages/void/src/cli/deploy-cloudflare-build.ts +++ b/packages/void/src/cli/deploy-cloudflare-build.ts @@ -182,9 +182,7 @@ export async function buildCloudflareWorker(input: { if ( atomic && !Array.isArray(parseRootWranglerConfig(lifecycleConfigPath).migrations) && - !input.preflight.expectedWorkflows.some( - (workflow) => workflow.script_name === undefined || workflow.script_name === workerName, - ) + !input.preflight.hasLocalWorkflows ) { previousWorkflowVersionId = await activeWorkflowVersionForRemoval( { runWrangler, configPath, workerName, accountId }, diff --git a/packages/void/src/cli/deploy-cloudflare-helpers.ts b/packages/void/src/cli/deploy-cloudflare-helpers.ts index f987fa4b23..896bbc205e 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -5,6 +5,7 @@ import { parseRootWranglerConfig, readExistingCloudflareWorker, readWranglerTopLevelString, + workflowExports, } from '@void/deploy-cloudflare'; import type { ApprovedCloudflareKvBinding, @@ -335,7 +336,7 @@ export async function activeWorkflowVersionForRemoval( typeof binding.class_name === 'string' && (binding.script_name === undefined || binding.script_name === options.workerName), ); - if (ownsWorkflow) { + if (ownsWorkflow || Object.keys(workflowExports(active.runtime.exports)).length > 0) { return active.versionId; } const metadata = parseCloudflareVersionMessage(active.versionMessage); diff --git a/packages/void/src/cli/deploy-cloudflare-preflight.ts b/packages/void/src/cli/deploy-cloudflare-preflight.ts index 8ac3a1330d..138e59f2be 100644 --- a/packages/void/src/cli/deploy-cloudflare-preflight.ts +++ b/packages/void/src/cli/deploy-cloudflare-preflight.ts @@ -232,6 +232,7 @@ export async function preflightCloudflareWorker(input: { expectedContainers: ReturnType; expectedDurableObjectState: ReturnType; expectedWorkflows: ReturnType; + hasLocalWorkflows: boolean; }> { const { root, @@ -811,5 +812,6 @@ export async function preflightCloudflareWorker(input: { expectedContainers, expectedDurableObjectState, expectedWorkflows, + hasLocalWorkflows: localWorkflows.length > 0, }; } diff --git a/packages/void/src/cli/platform-installer-inspection.ts b/packages/void/src/cli/platform-installer-inspection.ts index 5aca6a3150..a8a3396e29 100644 --- a/packages/void/src/cli/platform-installer-inspection.ts +++ b/packages/void/src/cli/platform-installer-inspection.ts @@ -1,6 +1,7 @@ import { parseCloudflareVersionMessage, readCloudflareVersionMigrationTag, + resolveCloudflareVersionMessage, } from '@void/deploy-cloudflare'; import type { CloudflareTriggerConfig } from '@void/deploy-cloudflare'; import { @@ -121,7 +122,15 @@ export async function platformWorkerVersionHasTriggerRecord( annotations && typeof annotations === 'object' ? (annotations as Record)['workers/message'] : null; - return parseCloudflareVersionMessage(typeof message === 'string' ? message : null)?.schema === 2; + const resolved = await resolveCloudflareVersionMessage( + typeof message === 'string' ? message : null, + versionId, + () => + readCloudflare( + `/accounts/${encodeURIComponent(accountId)}/workers/workers/${encodeURIComponent(workerName)}/versions/${encodeURIComponent(versionId)}?include=modules`, + ), + ); + return parseCloudflareVersionMessage(resolved)?.schema === 2; } export async function readPlatformWorkerDeployments( @@ -380,7 +389,17 @@ export async function readPlatformWorkerVersionSnapshot( typeof (annotations as Record)['workers/message'] === 'string' ? ((annotations as Record)['workers/message'] ?? null) : null; - const metadata = parseCloudflareVersionMessage(message); + const resolved = await resolveCloudflareVersionMessage(message, versionId, async () => { + const source = await runner( + { type: 'versions.view', versionId, configPath, workerName, includeSource: true }, + accountId, + process.cwd(), + true, + ); + assertCleanPlatformWrangler(source, `read recovery metadata for ${workerName}`, accountId); + return source.data; + }); + const metadata = parseCloudflareVersionMessage(resolved); // A version made outside Void has no Void record of its triggers. Only a run // that replaces those changes, with the operator's consent, gives Void's own. if (metadata?.schema !== 2 && unrecordedTriggerConfig) { diff --git a/packages/void/src/cli/provision.ts b/packages/void/src/cli/provision.ts index 03ea439b41..1c97f9a5e4 100644 --- a/packages/void/src/cli/provision.ts +++ b/packages/void/src/cli/provision.ts @@ -28,7 +28,7 @@ import { voidLog, voidWarn } from '../log.ts'; import type { CloudflareQueueNames } from '../queues/cloudflare-names.ts'; import { scanWranglerDotenvKeys } from '../shared/dotenv.ts'; import { - encodeCloudflareOperation, + prepareCloudflareOperationArgs, decodeCloudflareOperationResult, } from './cloudflare-process.ts'; import { resolveCloudflareOperationArgv } from './preset.ts'; @@ -1005,7 +1005,7 @@ export function createDefaultRunWrangler( const isWindows = process.platform === 'win32'; const teardownDeadlineMs = options?.signalTeardownDeadlineMs ?? confirmGraceMs + SIGNAL_TEARDOWN_DEADLINE_MARGIN_MS; - return (args, opts) => + const execute = (args: CloudflareOperation, opts: WranglerCallContext, argv: Array) => new Promise((resolvePromise, rejectPromise) => { const parallelWorkerUpload = options?.parallelWorkerUpload === true && args.type === 'versions.upload'; @@ -1036,7 +1036,7 @@ export function createDefaultRunWrangler( ); return; } - const child = spawn(command, [...prefix, ...encodeCloudflareOperation(args)], { + const child = spawn(command, [...prefix, ...argv], { cwd: opts.cwd ?? root, shell: false, env: { @@ -1363,6 +1363,14 @@ export function createDefaultRunWrangler( child.stdin?.end(opts.input); } }); + return async (args, opts) => { + const prepared = prepareCloudflareOperationArgs(args); + try { + return await execute(args, opts, prepared.args); + } finally { + prepared.dispose?.(); + } + }; } /** diff --git a/packages/void/src/cli/rollback.ts b/packages/void/src/cli/rollback.ts index ced38678d0..232f8d84ba 100644 --- a/packages/void/src/cli/rollback.ts +++ b/packages/void/src/cli/rollback.ts @@ -123,6 +123,7 @@ async function runCloudflareRollback( const { activateCloudflareExistingVersion, readCloudflareWorkerStatus, + resolveCloudflareWorkerVersion, resolveCloudflareOperationContext, } = await import('./cloudflare-operations.ts'); const context = resolveCloudflareOperationContext(root); @@ -176,7 +177,9 @@ async function runCloudflareRollback( target = selected; } - const current = status.versions.find((version) => version.id === status.activeVersionId); + const active = status.versions.find((version) => version.id === status.activeVersionId); + target = await resolveCloudflareWorkerVersion(context, target); + const current = active && (await resolveCloudflareWorkerVersion(context, active)); if ( target.metadata?.schema !== 2 || current?.metadata?.schema !== 2 || diff --git a/packages/void/test/unit/cf-version-message.test.ts b/packages/void/test/unit/cf-version-message.test.ts new file mode 100644 index 0000000000..9a0a18c9fa --- /dev/null +++ b/packages/void/test/unit/cf-version-message.test.ts @@ -0,0 +1,169 @@ +import { existsSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import { join } from 'node:path'; +import { + getWorkerAssetsDir, + getWorkerBundleDir, + getWorkerConfigPath, + readBuildOutput, +} from '@cloudflare/build-output-utils'; +import { + cloudflareVersionMessageModule, + cloudflareVersionMessageReference, +} from '@void/deploy-cloudflare'; +import { expect, it } from 'vite-plus/test'; +import { createCfVersionRunner } from '../../src/cli/cf-version-runner.ts'; +import { Buffer } from '../../src/cli/node-buffer.ts'; +import { listen, output } from '../helpers/cf-version-fixture.ts'; + +const message = 'void:' + JSON.stringify({ schema: 1, migrations: ['migration-例'.repeat(200)] }); +const reference = cloudflareVersionMessageReference(message)!; +const name = cloudflareVersionMessageModule(reference); +const versionId = '33333333-3333-4333-8333-333333333333'; +const workerName = 'void-test'; + +it('stages recovery modules only on version uploads, including an atomic retry', async () => { + const prepared = await output({ assets: { directory: '../client' } }); + try { + const original = readFileSync(getWorkerConfigPath(prepared.directory), 'utf8'); + const verified: Array = []; + const calls: Array> = []; + const runner = createCfVersionRunner({ + output: prepared, + workerName, + verifyResources: async (directory) => { + verified.push(directory); + return { status: 0, stdout: '', stderr: '' }; + }, + runCf: async (args, { cwd }) => { + calls.push(args); + const built = await readBuildOutput(cwd); + if (args.includes('--message=' + reference)) { + expect(verified.at(-1)).toBe(cwd); + expect(cwd).not.toBe(prepared.directory); + expect(built.workers.default.config.manifest?.modules[name]).toEqual({ type: 'text' }); + expect(readFileSync(join(getWorkerBundleDir(cwd), name), 'utf8')).toBe(message); + expect(existsSync(join(getWorkerAssetsDir(cwd), name))).toBe(false); + } else { + expect(cwd).toBe(prepared.directory); + expect(built.workers.default.config.manifest?.modules).not.toHaveProperty(name); + } + return { status: 0, stdout: '', stderr: '', data: { versionId } }; + }, + }); + for (const type of ['versions.upload', 'worker.deploy'] as const) { + const uploaded = await runner({ type, workerName, message }, { capture: true }); + expect(uploaded.status, uploaded.stderr).toBe(0); + expect(calls.at(-1)).toContain('--message=' + reference); + } + const traffic = await runner( + { + type: 'versions.deploy', + workerName, + message, + versions: [{ versionId, percentage: 100 }], + }, + { capture: true }, + ); + expect(traffic.status).toBe(0); + const args = calls.at(-1)!; + expect(JSON.parse(args[args.indexOf('--body') + 1]).annotations['workers/message']).toBe( + reference, + ); + expect(readFileSync(getWorkerConfigPath(prepared.directory), 'utf8')).toBe(original); + expect(existsSync(join(getWorkerBundleDir(prepared.directory), name))).toBe(false); + } finally { + await prepared.dispose(); + } +}); + +it('includes the referenced text in pinned-secret uploads', async () => { + const prepared = await output(); + const uploads: Array> = []; + const apiBaseUrl = await listen( + createServer(async (request, response) => { + if (request.method === 'POST') { + let json = ''; + for await (const chunk of request) { + json += chunk; + } + uploads.push(JSON.parse(json)); + } + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end( + JSON.stringify({ success: true, result: { id: versionId, bindings: [], urls: [] } }), + ); + }), + ); + try { + prepared.activeSecrets = { versionId, bindings: [] }; + const runner = createCfVersionRunner({ + output: prepared, + workerName, + pinnedUpload: { + accountId: 'account-id', + apiBaseUrl, + verifyUploader: () => true, + getToken: async () => ({ ok: true, token: 'synthetic-token' }), + }, + verifyResources: async () => ({ status: 0, stdout: '', stderr: '' }), + runCf: () => { + throw new Error('Unexpected cf command'); + }, + }); + for (const type of ['versions.upload', 'worker.deploy'] as const) { + const uploaded = await runner({ type, workerName, message }, { capture: true }); + expect(uploaded.status, uploaded.stderr).toBe(0); + expect(uploads.at(-1)).toMatchObject({ + annotations: { 'workers/message': reference }, + modules: expect.arrayContaining([ + { + name, + content_type: 'text/plain', + content_base64: Buffer.from(message).toString('base64'), + }, + ]), + }); + } + } finally { + await prepared.dispose(); + } +}); + +it.each( + process.platform === 'win32' ? ['declared', 'unlisted'] : ['declared', 'unlisted', 'symlink'], +)('preserves a %s module with a conflicting recovery name', async (kind) => { + const prepared = await output(); + try { + const path = join(getWorkerBundleDir(prepared.directory), name); + const configPath = getWorkerConfigPath(prepared.directory); + if (kind === 'symlink') { + symlinkSync(configPath, path); + } else { + writeFileSync(path, 'application text'); + if (kind === 'declared') { + const config = JSON.parse(readFileSync(configPath, 'utf8')); + config.manifest.modules[name] = { type: 'text' }; + writeFileSync(configPath, JSON.stringify(config)); + } + } + const original = readFileSync(path, 'utf8'); + const runner = createCfVersionRunner({ + output: prepared, + workerName, + verifyResources: async () => ({ status: 0, stdout: '', stderr: '' }), + runCf: () => { + throw new Error('Unexpected cf command'); + }, + }); + const failed = await runner( + { type: 'versions.upload', workerName, message }, + { capture: true }, + ); + expect(failed.status).toBe(1); + expect(failed.stderr).toContain(name); + expect(readFileSync(path, 'utf8')).toBe(original); + } finally { + await prepared.dispose(); + } +}); diff --git a/packages/void/test/unit/cf-version-runner.test.ts b/packages/void/test/unit/cf-version-runner.test.ts index 1c17aebd93..4406173c9a 100644 --- a/packages/void/test/unit/cf-version-runner.test.ts +++ b/packages/void/test/unit/cf-version-runner.test.ts @@ -2645,6 +2645,108 @@ it.each(['restore', 'remove', 'rename'] as const)( }, ); +it( + 'preserves version exports while deferring replacement schedules in the real atomic cf upload', + async () => { + const workflow = { + name: 'new', + class_name: 'Job', + binding: 'JOB', + schedules: ['0 0 * * *'], + limits: { steps: 400 }, + }; + const prepared = await output({ + workers_dev: false, + preview_urls: false, + workflows: [workflow], + }); + const original = readFileSync(getWorkerConfigPath(prepared.directory), 'utf8'); + const uploaded: Array = []; + const registered: Array = []; + const paths: Array = []; + const versionId = '22222222-2222-4222-8222-222222222222'; + const api = await listen( + createServer(async (request, response) => { + const path = new URL(request.url!, 'http://localhost').pathname; + paths.push(request.method + ' ' + path); + const chunks: Array = []; + for await (const chunk of request) { + chunks.push(Buffer.from(chunk)); + } + const body = Buffer.concat(chunks); + let result: unknown = {}; + if (path.endsWith('/workers/workers/void-test')) { + result = { subdomain: { enabled: false, previews_enabled: false } }; + } else if (path.endsWith('/secrets')) { + result = []; + } else if (path.endsWith('/workers/services/void-test')) { + result = { + default_environment: { + environment: 'production', + script: { id: 'void-test', last_deployed_from: 'wrangler' }, + }, + }; + } else if (request.headers['content-type']?.includes('multipart/form-data')) { + const form = await new Request('http://localhost', { + method: 'POST', + headers: { 'content-type': request.headers['content-type'] }, + body, + }).formData(); + uploaded.push(JSON.parse(String(form.get('metadata'))).exports); + result = { + id: versionId, + deployment_id: versionId, + version_id: versionId, + number: 2, + resources: { script: { etag: 'test' } }, + startup_time_ms: 2, + available_on_subdomain: false, + }; + } else if (path.endsWith('/workflows/new')) { + if (request.method === 'PUT') { + registered.push(JSON.parse(body.toString('utf8'))); + } + result = { name: 'new', class_name: 'Job', script_name: 'void-test' }; + } else if (path.endsWith('/workers/subdomain')) { + result = { subdomain: 'fixture' }; + } else if (path.endsWith('/subdomain')) { + result = { enabled: false, previews_enabled: false }; + } else if (path.endsWith('/deployments')) { + result = { deployments: [] }; + } + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.end(JSON.stringify({ success: true, errors: [], messages: [], result })); + }), + ); + try { + const runner = createCfVersionRunner({ + output: prepared, + workerName: 'void-test', + runCf: pinnedCf(api), + verifyResources: async () => ({ status: 0, stdout: '', stderr: '' }), + }); + const result = await runner( + { type: 'worker.deploy', workerName: 'void-test', deferWorkflowSchedules: ['new'] }, + { capture: true }, + ); + const detail = JSON.stringify({ paths, result }); + expect(result, detail).toMatchObject({ status: 0, data: { versionId } }); + expect(uploaded, detail).toEqual([ + { + Job: { type: 'workflow', name: 'new', schedules: ['0 0 * * *'], limits: { steps: 400 } }, + }, + ]); + expect(registered, detail).toEqual([ + { script_name: 'void-test', class_name: 'Job', limits: { steps: 400 } }, + ]); + expect(readFileSync(getWorkerConfigPath(prepared.directory), 'utf8')).toBe(original); + } finally { + await prepared.dispose(); + } + }, + REAL_CF_TIMEOUT_MS, +); + it( 'applies all local Workflow settings through the real pinned cf trigger transport', async () => { diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 9c574c00e8..548c659101 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -1764,13 +1764,24 @@ describe('existing Cloudflare site handoff', () => { } }); - it.each(['add', 'remove', 'remove to static', 'retry cleanup', 'completed cleanup'] as const)( + it.each([ + 'add', + 'add export only', + 'remove', + 'remove export only', + 'remove to static', + 'retry cleanup', + 'completed cleanup', + ] as const)( 'supports the %s operation for a local Workflow in an atomic deployment', async (operation) => { const root = site(); const configPath = join(root, 'wrangler.jsonc'); const config = parseRootWranglerConfig(configPath); config.preview_urls = false; + if (operation === 'add export only') { + config.exports = { NotifyWorkflow: { type: 'workflow', name: 'site_notify' } }; + } if (operation === 'add') { mkdirSync(join(root, 'workflows')); writeFileSync( @@ -1793,6 +1804,13 @@ describe('existing Cloudflare site handoff', () => { class_name: 'NotifyWorkflow', }, ], + ...(operation === 'remove export only' && { + bindings: [], + runtime: { + ...existing.runtime, + exports: { NotifyWorkflow: { type: 'workflow', name: 'site_notify' } }, + }, + }), ...((operation === 'retry cleanup' || operation === 'completed cleanup') && { bindings: [], versionMessage: @@ -1866,11 +1884,11 @@ describe('existing Cloudflare site handoff', () => { silentCliLog, deps, ); - expect(readExistingWorker).toHaveBeenCalledTimes(operation === 'add' ? 0 : 1); + expect(readExistingWorker).toHaveBeenCalledTimes(operation.startsWith('add') ? 0 : 1); expect(activateVersion).toHaveBeenCalledWith( expect.objectContaining({ atomic: true, - expectedPreviousVersionId: operation === 'add' ? undefined : existing.versionId, + expectedPreviousVersionId: operation.startsWith('add') ? undefined : existing.versionId, }), ); }, @@ -3121,7 +3139,7 @@ describe('runCloudflareDeploy — PostgreSQL checked-in migrations', () => { }); it.each(['authored', 'preserved'] as const)( - 'refuses an oversized %s trigger snapshot before applying pending migrations', + 'keeps oversized %s routes through migration and upload', async (source) => { vi.stubEnv('DATABASE_URL', 'postgresql://prod.example/app'); const routes = Array.from({ length: 40 }, (_, i) => { @@ -3131,7 +3149,15 @@ describe('runCloudflareDeploy — PostgreSQL checked-in migrations', () => { const root = pgProject(INIT_MIGRATION); const path = join(root, 'wrangler.jsonc'); if (source === 'authored') { - writeFileSync(path, JSON.stringify({ ...parseRootWranglerConfig(path), routes })); + writeFileSync( + path, + JSON.stringify({ + ...parseRootWranglerConfig(path), + routes, + workers_dev: true, + preview_urls: true, + }), + ); } else { writeWranglerPublishedTrafficSnapshot(path, { workers_dev: true, @@ -3150,7 +3176,15 @@ describe('runCloudflareDeploy — PostgreSQL checked-in migrations', () => { }); const runner = deps.runWrangler!; const active = '11111111-1111-4111-8111-111111111111'; + let uploadedMessage: string | undefined; deps.runWrangler = (operation, options) => { + if (operation.type === 'versions.upload') { + uploadedMessage = operation.message; + return { ...cleanExit, status: 1, stderr: 'End of test upload' }; + } + if (operation.type === 'versions.view') { + return { ...cleanExit, data: { id: active, resources: { bindings: [] } } }; + } if (operation.type === 'deployments.status') { return { ...cleanExit, data: { versions: [{ version_id: active, percentage: 100 }] } }; } @@ -3161,8 +3195,11 @@ describe('runCloudflareDeploy — PostgreSQL checked-in migrations', () => { }; await expect( runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps), - ).rejects.toThrow('1000-byte version message limit'); - expect(apply).not.toHaveBeenCalled(); + ).rejects.toBeInstanceOf(ExitError); + expect(apply).toHaveBeenCalledOnce(); + expect(parseCloudflareVersionMessage(uploadedMessage)).toMatchObject({ + triggerConfig: { routes }, + }); }, ); @@ -3621,7 +3658,8 @@ describe('runCloudflareDeploy — static, SPA, and SSG apps', () => { "producers": [{ "binding": "BILLING", "queue": "billing" }], "consumers": [{ "queue": "billing" }] }, - "workflows": [{ "name": "billing-flow", "class_name": "BillingFlow" }] + "workflows": [{ "name": "billing-flow", "class_name": "BillingFlow" }], + "exports": { "BillingFlow": { "type": "workflow", "name": "billing-flow", "schedules": ["0 0 * * *"] } } }\n`; const root = makeProject({ 'package.json': JSON.stringify({ name: 'switchable-app' }), @@ -3641,6 +3679,7 @@ describe('runCloudflareDeploy — static, SPA, and SSG apps', () => { expect(generated.durable_objects).toEqual({ bindings: [] }); expect(generated.queues).toEqual({ producers: [], consumers: [] }); expect(generated.workflows).toEqual([]); + expect(generated.exports).not.toHaveProperty('BillingFlow'); expect(output).toMatch(/[╭+].*https:\/\/preview\.example\.workers\.dev.*[╮+]/); expect(output).toContain('switchable-app → Cloudflare'); expect(output.indexOf('switchable-app → Cloudflare')).toBeLessThan( diff --git a/packages/void/test/unit/cloudflare-operation-process.test.ts b/packages/void/test/unit/cloudflare-operation-process.test.ts index fa8bc0650e..a56a9aaaf8 100644 --- a/packages/void/test/unit/cloudflare-operation-process.test.ts +++ b/packages/void/test/unit/cloudflare-operation-process.test.ts @@ -3,8 +3,13 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { createServer, request as httpRequest } from 'node:http'; import type { AddressInfo } from 'node:net'; import { connect } from 'node:net'; -import { join } from 'node:path'; +import { join, relative } from 'node:path'; import type { Duplex } from 'node:stream'; +import { getWorkerConfigPath, getWorkerBundleDir } from '@cloudflare/build-output-utils'; +import { + cloudflareVersionMessageModule, + cloudflareVersionMessageReference, +} from '@void/deploy-cloudflare'; import { expect, it as serialIt } from 'vite-plus/test'; import { isVoidSecretOnlyDraft } from '../../../deploy-cloudflare/src/secret-draft.ts'; import { voidSecretDraftVersion } from '../../../deploy-cloudflare/test/secret-draft-fixture.ts'; @@ -13,7 +18,10 @@ import { importCloudflareD1Sql, resolveCloudflareD1Context, } from '../../src/cli/cloudflare-operations.ts'; -import { decodeCloudflareOperationResult } from '../../src/cli/cloudflare-process.ts'; +import { + decodeCloudflareOperationResult, + prepareCloudflareOperationArgs, +} from '../../src/cli/cloudflare-process.ts'; import { Buffer } from '../../src/cli/node-buffer.ts'; import { cleanups, @@ -183,7 +191,14 @@ it.each([false, true])( userAgents.push(request.headers['user-agent']); request.resume(); response.writeHead(200, { 'Content-Type': 'application/json' }); - response.end(JSON.stringify({ success: true, errors: [], messages: [], result: draft })); + response.end( + JSON.stringify({ + success: true, + errors: [], + messages: [], + result: large ? { ...draft, bindings: undefined } : draft, + }), + ); }), ); const configPath = join(directory, 'wrangler.json'); @@ -206,7 +221,7 @@ it.each([false, true])( stderr: '', }); expect(result.status, result.stderr).toBe(0); - expect(result.data).toEqual(draft); + expect(result.data).toEqual(large ? { ...draft, bindings: [] } : draft); expect(isVoidSecretOnlyDraft(result.data as Record)).toBe(!large); expect(requests).toEqual([ `/client/v4/accounts/test-account/workers/workers/test-worker/versions/${draft.id}?include=modules`, @@ -1200,6 +1215,64 @@ it.each([401, 403, 404, 503])( 30_000, ); +it.each(['versions.upload', 'worker.deploy'] as const)( + 'passes a large recovery snapshot through the %s subprocess', + async (type) => { + const directory = temporaryDirectory('void-cf-recovery-'); + const configPath = join(directory, 'wrangler.json'); + writeFileSync( + configPath, + JSON.stringify({ + name: 'test-worker', + main: 'index.js', + no_bundle: true, + account_id: 'test-account', + }), + ); + writeFileSync( + join(directory, 'index.js'), + 'export default { fetch() { return new Response("ok"); } };', + ); + const message = 'void:' + JSON.stringify({ schema: 1, migrations: ['例'.repeat(50_000)] }); + const reference = cloudflareVersionMessageReference(message)!; + const name = cloudflareVersionMessageModule(reference); + const preload = join(directory, 'capture-upload.mjs'); + const capture = join(directory, 'capture.json'); + writeFileSync( + preload, + `import child from 'node:child_process'; +import { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { syncBuiltinESMExports } from 'node:module'; +child.spawnSync = (_binary, args, {cwd}) => { + const config = JSON.parse(readFileSync(join(cwd, ${JSON.stringify(relative(directory, getWorkerConfigPath(directory)))}), 'utf8')); + const name = ${JSON.stringify(name)}; + const message = readFileSync(join(cwd, ${JSON.stringify(relative(directory, getWorkerBundleDir(directory)))}, name), 'utf8'); + writeFileSync(${JSON.stringify(capture)}, JSON.stringify({ args: args.slice(1), module: config.manifest.modules[name], message })); + return {status:0,stdout:JSON.stringify({id:'11111111-1111-4111-8111-111111111111'}),stderr:''}; +}; +syncBuiltinESMExports();`, + ); + const request = prepareCloudflareOperationArgs({ type, configPath, message }); + try { + expect(request.args.join(' ').length).toBeLessThan(1000); + const called = await runOperation( + directory, + request.args, + unproxiedEnv('http://localhost'), + preload, + ); + expect(called.status, called.stderr).toBe(0); + const actual = JSON.parse(readFileSync(capture, 'utf8')); + expect(actual.args).toContain('--message=' + reference); + expect(actual.module).toEqual({ type: 'text' }); + expect(actual.message).toBe(message); + } finally { + request.dispose?.(); + } + }, +); + it.each(['ordinary', 'versions.upload', 'worker.deploy'] as const)( 'allows a prebuilt %s upload and scopes installation attribution to the cf child', async (uploadType) => { diff --git a/packages/void/test/unit/cloudflare-operations.test.ts b/packages/void/test/unit/cloudflare-operations.test.ts index 83f80a3984..aff0410028 100644 --- a/packages/void/test/unit/cloudflare-operations.test.ts +++ b/packages/void/test/unit/cloudflare-operations.test.ts @@ -1,7 +1,11 @@ import { existsSync, mkdtempSync, readFileSync, statSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { encodeCloudflareVersionMessage } from '@void/deploy-cloudflare'; +import { + cloudflareVersionMessageModule, + cloudflareVersionMessageReference, + encodeCloudflareVersionMessage, +} from '@void/deploy-cloudflare'; import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import { activateCloudflareExistingVersion, @@ -20,6 +24,7 @@ import { readCloudflareWorkerStatus, readCloudflareD1Migrations, resolveCloudflareD1Context, + resolveCloudflareWorkerVersion, restoreCloudflareD1Database, syncCloudflareSecrets, tailCloudflareWorker, @@ -284,6 +289,46 @@ describe('Cloudflare version operations', () => { expect(status.versions.map((version) => version.id)).toEqual(['v1', 'v2']); }); + it('reads recovery data only for the selected large version', async () => { + const crons = ['0 0 * * *']; + const routes = Array.from({ length: 1000 }, (_, i) => i + '.example.com/*'); + const message = encodeCloudflareVersionMessage(['001.sql'], { + workers_dev: true, + preview_urls: true, + routes, + crons, + queueConsumers: [], + workflows: [], + }); + const reference = cloudflareVersionMessageReference(message)!; + const [selected] = parseCloudflareVersions([ + { id: 'v2', annotations: { 'workers/message': reference } }, + ]); + const runner = vi.fn(() => + ok({ + id: 'v2', + modules: [ + { + name: cloudflareVersionMessageModule(reference), + content_type: 'text/plain', + content_base64: btoa(message), + }, + ], + }), + ); + const resolved = await resolveCloudflareWorkerVersion(context(runner), selected); + expect(resolved.metadata).toMatchObject({ + migrations: ['001.sql'], + triggerConfig: { routes, crons }, + }); + expect(runner).toHaveBeenCalledWith( + expect.objectContaining({ type: 'versions.view', versionId: 'v2', includeSource: true }), + { capture: true }, + ); + expect(await resolveCloudflareWorkerVersion(context(runner), resolved)).toBe(resolved); + expect(runner).toHaveBeenCalledOnce(); + }); + it('activates the selected version and restores its versioned triggers', async () => { let activeVersionId = 'v2'; const runner = vi.fn((args) => { diff --git a/packages/void/test/unit/rollback-platform.test.ts b/packages/void/test/unit/rollback-platform.test.ts index b5c74c6297..663388bd82 100644 --- a/packages/void/test/unit/rollback-platform.test.ts +++ b/packages/void/test/unit/rollback-platform.test.ts @@ -20,6 +20,7 @@ vi.mock('../../src/cli/auth.ts', () => ({ getToken: () => null })); vi.mock('../../src/cli/cloudflare-operations.ts', () => ({ activateCloudflareExistingVersion: mockActivateCloudflareExistingVersion, readCloudflareWorkerStatus: mockReadCloudflareWorkerStatus, + resolveCloudflareWorkerVersion: (_context: unknown, version: unknown) => version, resolveCloudflareOperationContext: () => ({ workerName: 'app' }), }));