diff --git a/.github/scripts/packed-consumer.mjs b/.github/scripts/packed-consumer.mjs index 383a57fb3..ba71cac2d 100644 --- a/.github/scripts/packed-consumer.mjs +++ b/.github/scripts/packed-consumer.mjs @@ -326,6 +326,41 @@ 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'; +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'), + 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/.vitepress/config.ts b/docs/.vitepress/config.ts index 722352aa1..1a91b28d5 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -127,6 +127,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' }, @@ -373,6 +374,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 000000000..bd0558889 --- /dev/null +++ b/docs/guide/workflows.md @@ -0,0 +1,176 @@ +--- +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. + +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. + +`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. + +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 +// 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`. 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()`: + +```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 reads the params type from the class’s `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`. 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: + +```ts +export const Onboarding = defineWorkflow({ + name: 'onboarding', + async run(event, step) { + // ... + }, +}); +``` + +`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 +import { defineConfig } from 'void/config'; + +export default defineConfig({ + cloudflare: { + workflows: [ + { name: 'onboarding', binding: 'WORKFLOW_ONBOARDING', class_name: 'OnboardingWorkflow' }, + ], + }, +}); +``` + +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`. + +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. + +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/docs/integrations/cloudflare.md b/docs/integrations/cloudflare.md index 9d23adde6..b3963ab10 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.md b/docs/reference/api.md index 05a09b43d..258377b18 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 000000000..8fa931507 --- /dev/null +++ b/docs/reference/api/workflows.md @@ -0,0 +1,44 @@ +--- +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. + +The definition accepts an optional `name`, an optional Standard Schema for `params`, and an async `run(event, step, { env, ctx })` function. + +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. + +## `defineWorkflowEntrypoint(definition)` {#defineworkflowentrypoint-definition} + +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 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. + +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? }`. + +## Types {#types} + +`WorkflowEvent`, `WorkflowStep`, `WorkflowContext`, `WorkflowCreateOptions`, `WorkflowApi`, and `WorkflowRun`. diff --git a/docs/reference/cli/deploy.md b/docs/reference/cli/deploy.md index 031eb779e..651273f9c 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/project.md b/docs/reference/cli/project.md index 699ba10b5..760ebe51d 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/docs/reference/cli/setup.md b/docs/reference/cli/setup.md index 00e3095ca..f3257e7dd 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 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 5ca4e1912..1bd9bcde6 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` @@ -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/docs/reference/resource-inference.md b/docs/reference/resource-inference.md index 7dcce1e62..e341447a7 100644 --- a/docs/reference/resource-inference.md +++ b/docs/reference/resource-inference.md @@ -20,6 +20,7 @@ Void configures Cloudflare bindings from the imports and environment bindings yo | `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/`**, where native Void apps discover Workflow definitions ## Custom Scan Directories @@ -83,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/docs/reference/structure.md b/docs/reference/structure.md index 954d5818b..e78b0fb39 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. This directory stays at the project root when `sourceDir` is configured. Each Workflow module 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/deploy-cloudflare/src/existing.ts b/packages/deploy-cloudflare/src/existing.ts index 202d3fa41..a53bdc1dd 100644 --- a/packages/deploy-cloudflare/src/existing.ts +++ b/packages/deploy-cloudflare/src/existing.ts @@ -10,9 +10,11 @@ import { isWranglerSecretOnlyDraft, } from './secret-draft.ts'; import { cloudflareStagingPairGuidance } from './staging-guidance.ts'; +import { resolveCloudflareVersionMessage } from './version.ts'; export type ExistingCloudflareWorker = { versionId: string; + versionMessage?: string; bindings: Array>; runtime: Record; script: Record; @@ -133,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 }); @@ -145,6 +153,7 @@ async function readCloudflareWorker( return { snapshot: { versionId, + ...(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 a62c9e480..a2eeda488 100644 --- a/packages/deploy-cloudflare/src/index.ts +++ b/packages/deploy-cloudflare/src/index.ts @@ -40,7 +40,12 @@ export { deployCloudflareVersionTriggers, deployCloudflareVersionTraffic, encodeCloudflareVersionMessage, + cloudflareVersionMessageReference, + cloudflareVersionMessageModule, + resolveCloudflareVersionMessage, + summarizeCloudflareMigrations, extractWorkersDevSubdomain, + hasWorkflowSchedules, normalizeReadinessAccessOrigin, normalizeWorkersDevSubdomain, parseCloudflareVersionMessage, @@ -73,3 +78,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 4ce493053..ae32278ff 100644 --- a/packages/deploy-cloudflare/src/operations.ts +++ b/packages/deploy-cloudflare/src/operations.ts @@ -4,12 +4,28 @@ 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) | ({ type: 'd1.list' | 'kv.namespace.list' | 'containers.list' | 'workers.subdomain.get'; } & ConfigTarget) | ({ type: 'd1.info'; name: string } & ConfigTarget) + | ({ + type: 'workflows.entitlement'; + fedramp: boolean; + 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 } & ( | { sql: string; file?: never } @@ -61,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 @@ -79,6 +97,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/static.ts b/packages/deploy-cloudflare/src/static.ts index 6ac970971..7588d4daa 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 df051c98d..52e0e8aee 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'; @@ -14,7 +16,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, @@ -23,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; @@ -58,6 +72,10 @@ 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; + /** 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 @@ -177,16 +195,112 @@ 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, + 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 }; - return `void:${JSON.stringify(metadata)}`; + ? { 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 + // 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) { + // Keep trigger recovery lossless. The digest still lets rollback distinguish + // identical migration histories when the individual filenames do not fit. + if (migrationState.migrations?.length) { + const summary = encodeCloudflareVersionMessage( + summarizeCloudflareMigrations(migrationState.migrations), + triggerConfig, + contentHash, + ); + if (Buffer.byteLength(summary) <= MAX_VERSION_MESSAGE_BYTES) { + return summary; + } + } + // 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; + } + } + } + } catch (cause) { + throw new CloudflareVersionRecoveryError( + `Could not read the recovery metadata for Cloudflare Worker version ${versionId}.`, + { cause }, + ); + } + throw new CloudflareVersionRecoveryError( + `Could not verify the recovery metadata for Cloudflare Worker version ${versionId}.`, + ); } /** Read migration state written by {@link encodeCloudflareVersionMessage}. */ @@ -197,7 +311,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) || @@ -209,11 +332,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) { @@ -221,7 +361,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 } @@ -282,19 +422,35 @@ 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 { writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 }); + // Workflow schedules share an account quota. Release the retired names before registering replacements. + 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; + } + } const deployed = await options.runWrangler( { type: 'triggers.deploy', configPath, workerName: options.workerName }, { capture: false }, @@ -511,6 +667,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 +725,114 @@ function triggerConfigWithQueueConsumerCleanup( }; } -function triggerConfigWithRemovedWorkflowSchedules( +export function hasWorkflowSchedules(schedules: unknown): boolean { + return (typeof schedules === 'string' || Array.isArray(schedules)) && schedules.length > 0; +} + +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' || + !hasWorkflowSchedules(workflow.schedules) || 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()]; +} + +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( + 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); + } + } + 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 { @@ -641,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 } : {}), @@ -654,7 +891,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 }), }; } @@ -670,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; @@ -690,7 +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', @@ -703,6 +942,15 @@ 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( + (entry): entry is WorkflowScheduleCleanup => + isRecord(entry) && + typeof entry.workflowName === 'string' && + typeof entry.className === 'string', + ))) || (value.addresses !== undefined && addresses === undefined) ) { return null; @@ -721,6 +969,8 @@ function parseTriggerConfig(value: unknown): CloudflareTriggerConfig | null { crons: value.crons, queueConsumers: value.queueConsumers, workflows: value.workflows, + ...(cleanup && { workflowScheduleCleanup: cleanup }), + ...(deferred && { deferredWorkflowSchedules: deferred }), ...(addresses === undefined ? {} : { addresses }), }; } @@ -741,6 +991,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 @@ -749,7 +1014,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, }; @@ -862,6 +1128,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; @@ -894,7 +1162,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 @@ -1199,12 +1467,33 @@ 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) + ? encodeCloudflareVersionMessage( + desiredMetadata.migrations ?? desiredMetadata.migrationSummary ?? null, + desiredTriggerConfig, + desiredMetadata.contentHash, + ) : options.message; - const versionedPreviousTriggerConfig = - previousMetadata?.schema === 2 ? previousMetadata.triggerConfig : undefined; + if (options.beforeUpload) { + await options.beforeUpload(); + if (!options.verifyUploader()) { + return { ok: false, reason: 'uploader-changed' }; + } + } const versionedPreviousTriggerConfigWithTraffic = versionedPreviousTriggerConfig && previousTrafficConfig ? { ...versionedPreviousTriggerConfig, ...previousTrafficConfig } @@ -1315,7 +1604,7 @@ async function activateCloudflareVersionWithSecretsFile( pinnedActiveSecrets = activeSecrets; } } - if (pinnedActiveSecrets) { + if (pinnedActiveSecrets || options.beforeUpload) { if (!options.verifyUploader()) { return { ok: false, reason: 'uploader-changed' }; } @@ -1325,11 +1614,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, @@ -2105,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 @@ -2118,7 +2426,10 @@ async function readCloudflareVersionInspection( draftUnknown, }; } - } catch { + } catch (error) { + if (error instanceof CloudflareVersionRecoveryError) { + throw error; + } return null; } return null; @@ -2382,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, }, @@ -2406,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/src/workflows.ts b/packages/deploy-cloudflare/src/workflows.ts new file mode 100644 index 000000000..cd134871a --- /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 50966c92e..5aa6f7f66 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'; @@ -7,6 +8,9 @@ import { assertCloudflareDurableObjectLifecycleSupported, deployCloudflareVersionTriggers, encodeCloudflareVersionMessage, + cloudflareVersionMessageReference, + cloudflareVersionMessageModule, + resolveCloudflareVersionMessage, extractWorkersDevSubdomain, normalizeReadinessAccessOrigin, normalizeWorkersDevSubdomain, @@ -18,7 +22,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'; @@ -384,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 { @@ -2759,25 +2768,371 @@ 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(); - }), - workerName: 'app', - triggerConfig: triggersWith(), - previousTriggerConfig: triggersWith({ - workflows: [{ name: 'nightly', class_name: 'NightlyWorkflow', schedules: ['0 0 * * *'] }], + 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('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('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 }); + 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 migration filenames with a trigger snapshot that requires a module', () => { + 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: history, + 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('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'), + ); + 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, }), + ).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( + 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']); + }); - expect(applied?.workflows).toEqual([ - { name: 'nightly', class_name: 'NightlyWorkflow', schedules: [] }, - ]); + 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') { + expect(operation.deferWorkflowSchedules).toEqual(attempt < 3 ? ['pinned'] : undefined); + 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', + 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(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()); const result = await deployCloudflareVersionTriggers({ diff --git a/packages/void/AGENTS.md b/packages/void/AGENTS.md index 43c0fc986..362827399 100644 --- a/packages/void/AGENTS.md +++ b/packages/void/AGENTS.md @@ -148,7 +148,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 4dc612757..0020d5802 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": { @@ -170,6 +171,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/schema.json b/packages/void/schema.json index 486c2043d..b6848490e 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/skills/void/SKILL.md b/packages/void/skills/void/SKILL.md index b85804dbb..5764e301c 100644 --- a/packages/void/skills/void/SKILL.md +++ b/packages/void/skills/void/SKILL.md @@ -53,6 +53,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 1d16cb999..fbbee8845 100644 --- a/packages/void/src/application-analysis.ts +++ b/packages/void/src/application-analysis.ts @@ -18,6 +18,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; @@ -43,6 +44,7 @@ export type ApplicationAnalysis = { websockets: ReturnType; allWebsockets: ReturnType; durableObjects: ReturnType; + workflows: ReturnType; email: ReturnType; routes: ReturnType; middleware: ReturnType; @@ -78,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] : []), ]; } @@ -94,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); @@ -163,6 +173,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/cf-config-migrate.ts b/packages/void/src/cli/cf-config-migrate.ts index b023dd61d..78f031027 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/cf-version-message.ts b/packages/void/src/cli/cf-version-message.ts new file mode 100644 index 000000000..0737e63cb --- /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 72982c92e..4ed33c423 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'; @@ -423,6 +427,7 @@ export function createCfVersionRunner(options: { workerName: string; runCf: CfCommand; verifyResources: (directory: string) => Promise; + clearWorkflowSchedules?: CloudflareCommandRunner; pinnedUpload?: { accountId: string; apiBaseUrl: string; @@ -499,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.'); @@ -532,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, @@ -556,6 +546,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)) { @@ -704,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') { @@ -796,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, + }, }), ] : []), @@ -806,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-deploy/classify.ts b/packages/void/src/cli/cloudflare-deploy/classify.ts index 37ed4c1bc..b78b93a13 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,12 +74,16 @@ export function classifyCloudflareDeployApp( ); } + if (framework && application.workflows.length > 0) { + return unsupported(FRAMEWORK_WORKFLOWS_ERROR); + } + if (!framework && !hasBackendFiles(root)) { return unsupported( [ '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/cloudflare-operation-process.ts b/packages/void/src/cli/cloudflare-operation-process.ts index 0021394a4..a60198f0c 100644 --- a/packages/void/src/cli/cloudflare-operation-process.ts +++ b/packages/void/src/cli/cloudflare-operation-process.ts @@ -8,12 +8,14 @@ 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, } 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, @@ -23,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, @@ -40,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; @@ -213,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 { @@ -239,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(); } @@ -384,6 +399,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, { @@ -720,8 +805,60 @@ async function readAllQueues(): Promise> { throw new Error('Cloudflare Queue list exceeded the supported page limit.'); } +async function checkWorkflowEntitlement( + request: Extract, +): Promise { + const body = await cloudflareApiGet( + `/accounts/${encodeURIComponent(accountId())}/entitlements`, + 'Could not read account entitlements for 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'); + const plan = allocation('workers.enabled'); + 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.retentionMs <= (paid ? PAID_WORKFLOW_RETENTION_MS : FREE_WORKFLOW_RETENTION_MS) && + (!request.schedules || schedulesAllowed), + ); +} + async function resources(): Promise { switch (operation.type) { + case 'workflows.entitlement': + return checkWorkflowEntitlement(operation); case 'd1.import': { const database = d1Database(operation.database); await importD1SqlFile({ @@ -1174,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) => ({ @@ -1211,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'] : []), ]); @@ -1281,10 +1426,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); @@ -1315,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 d4b120275..e1b5fb0ca 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) { @@ -506,7 +527,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/cloudflare-process.ts b/packages/void/src/cli/cloudflare-process.ts index 27738090e..04005e870 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-artifact-validation.ts b/packages/void/src/cli/deploy-artifact-validation.ts index c3cb11353..85483948d 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, @@ -144,6 +145,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 @@ -174,6 +177,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. */ @@ -370,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); @@ -448,6 +459,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 30fb5960d..7b5031ab1 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, DeployVerification } 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 = [ */ const DEPLOY_RAW_SNAPSHOT_FIELDS: ReadonlyArray = [ ...DEPLOY_WHOLE_OBJECT_PINNED_FIELDS, + 'exports', 'durable_objects', 'ai', 'migrations', @@ -289,6 +292,25 @@ type DurableObjectSnapshot = { migrations: Array>; }; +/** + * 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. + */ +export function reconstructExpectedWorkflows( + config: VoidConfig, + root: string, + rootConfig: Record, + workerName: string, + analysis?: ApplicationAnalysis, +): Array> { + const configured = workflowConfigEntries(rootConfig.workflows); + const modules = (analysis ?? analyzeApplicationSync(root, { config })).workflows; + return [ + ...configured, + ...planWorkflowAdditions(configured, modules, workerName, rootConfig.exports), + ]; +} + /** Reconstruct the Durable Object state emitted after the pre-build root config is synced. */ export function reconstructExpectedDurableObjectState( config: VoidConfig, diff --git a/packages/void/src/cli/deploy-cloudflare-build.ts b/packages/void/src/cli/deploy-cloudflare-build.ts index 1fa237ff9..c25def789 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 { @@ -20,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'; @@ -56,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; @@ -82,6 +88,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); @@ -169,13 +177,18 @@ 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.hasLocalWorkflows + ) { + previousWorkflowVersionId = await activeWorkflowVersionForRemoval( + { runWrangler, configPath, workerName, accountId }, + deps.readExistingWorker, + ); + } deduplicateGeneratedCompatibilityFlags(lifecycleConfigPath, configPath); await (deps.assertDurableObjectLifecycle ?? assertCloudflareDurableObjectLifecycleSupported)({ runWrangler, @@ -364,5 +377,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 999e641c3..896bbc205 100644 --- a/packages/void/src/cli/deploy-cloudflare-helpers.ts +++ b/packages/void/src/cli/deploy-cloudflare-helpers.ts @@ -1,9 +1,11 @@ import { existsSync } from 'node:fs'; import { assertCloudflareBindingsPreserved, + parseCloudflareVersionMessage, parseRootWranglerConfig, readExistingCloudflareWorker, readWranglerTopLevelString, + workflowExports, } from '@void/deploy-cloudflare'; import type { ApprovedCloudflareKvBinding, @@ -42,6 +44,7 @@ import { createCloudflareEmptyCronPublisher, createCloudflareEmptyDomainPublisher, } from './cloudflare-operations.ts'; +import { isCleanCloudflareExit } from './cloudflare-process.ts'; import { readCloudflareWorkersDevSubdomain, rememberCloudflareWorkersDevSubdomain, @@ -305,6 +308,7 @@ export function createCfActivationRunner(options: { output: cfOutput, workerName: options.workerName, runCf, + clearWorkflowSchedules: runWrangler, pinnedUpload: { accountId, apiBaseUrl, @@ -320,6 +324,49 @@ 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 || Object.keys(workflowExports(active.runtime.exports)).length > 0) { + 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; + } + } + } + throw new Error( + 'deploy: atomic deployment requires Durable Object migration history or a local Workflow in the new or active Worker.', + ); +} + /** * Activation options shared by the Worker and static deploys: candidate tracking, the uploaded * binding check, readiness probing and trigger cleanup. @@ -346,6 +393,7 @@ export function cloudflareCandidateActivationOptions(options: { assertUploaderStillPinned: () => boolean; approvedKv: ReadonlyArray; staticAssetsBinding?: string; + previousWorkflowVersionId?: string; queueConsumerCleanup: ReturnType; }): Omit< CloudflareActivationOptions, @@ -364,7 +412,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 +880,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-migrate.ts b/packages/void/src/cli/deploy-cloudflare-migrate.ts index 9707dac36..336e0aaa6 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 { @@ -58,6 +59,7 @@ export async function migrateCloudflareWorker(input: { passthroughRawFields, expectedContainers, expectedDurableObjectState, + expectedWorkflows, runWrangler, assertUploaderStillPinned, schemaFacts, @@ -78,10 +80,19 @@ export async function migrateCloudflareWorker(input: { authEnabled, expectedContainers, expectedDurableObjectBindings: expectedDurableObjectState.bindings, + expectedWorkflows, expectedMigrations: expectedDurableObjectState.migrations, 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) { @@ -125,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 218a50839..138e59f2b 100644 --- a/packages/void/src/cli/deploy-cloudflare-preflight.ts +++ b/packages/void/src/cli/deploy-cloudflare-preflight.ts @@ -5,11 +5,14 @@ import { readStoredResourceName, readWranglerTopLevelString, assertExistingCloudflareConfig, + hasWorkflowSchedules, + readWorkflowDeclarations, } from '@void/deploy-cloudflare'; 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'; @@ -19,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'; @@ -32,6 +36,7 @@ import { snapshotPassthroughRawFields, reconstructExpectedContainers, reconstructExpectedDurableObjectState, + reconstructExpectedWorkflows, } from './deploy-binding-snapshot.ts'; import { isWranglerNonInteractiveOrCI, @@ -54,6 +59,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'; @@ -225,6 +231,8 @@ export async function preflightCloudflareWorker(input: { passthroughRawFields: ReturnType; expectedContainers: ReturnType; expectedDurableObjectState: ReturnType; + expectedWorkflows: ReturnType; + hasLocalWorkflows: boolean; }> { const { root, @@ -288,8 +296,95 @@ 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'); + 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, + ...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, + ), + ); + 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( + { + type: 'workflows.entitlement', + schedules, + steps, + concurrency, + retentionMs, + configPath, + fedramp: complianceRegion === 'fedramp_high', + }, + { capture: true }, + ); + if (!isCleanCloudflareExit(checked) || checked.data !== true) { + log.error( + [ + `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.`] + : []), + ...(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'), + ); + 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; @@ -388,7 +483,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); } @@ -712,5 +811,7 @@ export async function preflightCloudflareWorker(input: { passthroughRawFields, expectedContainers, expectedDurableObjectState, + expectedWorkflows, + hasLocalWorkflows: localWorkflows.length > 0, }; } diff --git a/packages/void/src/cli/deploy-cloudflare-publish.ts b/packages/void/src/cli/deploy-cloudflare-publish.ts index 32de202db..e7250cae4 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,6 +75,7 @@ export async function publishCloudflareWorker(input: { if (usesCf && !cfUploaderIsPinned()) { return exit(1); } + let appliedMigrations = 0; const cfOutput = usesCf ? await prepareBuildOutput() : null; if (!cfOutput && usesCf) { log.error('deploy: cf could not prepare the built Worker for deployment.'); @@ -124,16 +120,27 @@ export async function publishCloudflareWorker(input: { initialCloudflareCandidate, assertUploaderStillPinned, approvedKv: approvedHandoffKv, + previousWorkflowVersionId: input.build.previousWorkflowVersionId, queueConsumerCleanup, }), runWrangler: activationRunner, verifyUploader: cfOutput ? cfUploaderIsPinned : assertUploaderStillPinned, requireVersionMetadata: existingWorker === null || hasVersionMetadata, requirePreviewForReadiness: existingWorker !== null && !hasVersionMetadata, - message: encodeCloudflareVersionMessage(input.migration.migrationHistory, { - ...readCloudflareTriggerConfig(generatedConfigPath, configPath), - ...(existingWorker ? { preserve: true } : {}), - }), + 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-static.ts b/packages/void/src/cli/deploy-cloudflare-static.ts index c80083a88..ea5b7677e 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, @@ -257,7 +260,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; } @@ -393,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}`, @@ -519,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, @@ -582,20 +605,34 @@ export async function runCloudflareStaticDeploy( assertUploaderStillPinned, approvedKv: [], staticAssetsBinding: 'ASSETS', + previousWorkflowVersionId, queueConsumerCleanup, }), runWrangler: activationRunner, 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 + ? { + 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 26b2ec8df..2ca84f2e1 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, @@ -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, @@ -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/deploy-helpers.ts b/packages/void/src/cli/deploy-helpers.ts index 547cf5c1e..2108ed07e 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, explicitStatic: { outputDir } }); + 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 }); - if (detectedPreset) { - preset.buildCommand = detectedPreset.buildCommand; - if (!outputDir) { - preset.outputDir = detectedPreset.outputDir; - } - } - return preset; } return null; diff --git a/packages/void/src/cli/deploy-resources.ts b/packages/void/src/cli/deploy-resources.ts index 39cec5490..c631b6f95 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/cli/deploy-types.ts b/packages/void/src/cli/deploy-types.ts index fec9064c7..9c2971f89 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/deploy.ts b/packages/void/src/cli/deploy.ts index 5e508d139..56f8d8253 100644 --- a/packages/void/src/cli/deploy.ts +++ b/packages/void/src/cli/deploy.ts @@ -5,6 +5,7 @@ import { readConfig } from '../config.ts'; import { detectFramework } from '../plugin-inference.ts'; import { hasOwnKey } from '../shared/has-own-key.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'; @@ -171,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); @@ -313,7 +323,6 @@ async function runManagedDeploy( dir: options?.dir, spa: options?.spa, }); - // 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/help.ts b/packages/void/src/cli/help.ts index 78783a256..69371d7d4 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 b2b9ee90c..6ea1d5955 100644 --- a/packages/void/src/cli/info.ts +++ b/packages/void/src/cli/info.ts @@ -9,11 +9,17 @@ import { deriveWebSocketClassNameFromName, 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'; + definition: + | 'defineDurableState' + | 'defineRoom' + | 'defineWebSocket' + | WorkflowModule['definition']; name: string; nameSource: 'inferred' | 'explicit'; className: string; @@ -135,6 +141,14 @@ export function getProjectInfo(root: string): ProjectInfo { className: module.className, bindingName: module.bindingName, })), + ...analysis.workflows.map((module) => ({ + file: relative(root, module.filePath), + definition: module.definition, + 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/cli/init.ts b/packages/void/src/cli/init.ts index f7c587c01..9d278799e 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/list.ts b/packages/void/src/cli/list.ts index deba4fcf3..745096518 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/platform-installer-inspection.ts b/packages/void/src/cli/platform-installer-inspection.ts index 5aca6a315..a8a3396e2 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/preset.ts b/packages/void/src/cli/preset.ts index 5e82b3c7d..73a4778d4 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'; @@ -244,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; + explicitStatic?: { outputDir?: string }; + }, ): StaticPreset | null { // 1. Explicit --dir flag: skip build, use provided directory if (options?.dir) { @@ -280,7 +286,10 @@ export function detectPreset( } // 3. Has backend files → full deploy - if (hasBackendFiles(root)) { + const hasBackend = hasBackendFiles(root, { + skipWorkflowDiscovery: Boolean(options?.explicitStatic), + }); + if (hasBackend && !options?.explicitStatic) { return null; } @@ -291,13 +300,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', }; } @@ -305,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, @@ -324,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 @@ -412,17 +440,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 { @@ -471,15 +505,25 @@ export function findBackendSources(root: string): Array { if (ssrEntry) { found.push(relative(root, ssrEntry)); } + if (scanWorkflowModules(root).length > 0) { + found.push('workflows/'); + } return found; } /** * 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); + return ( + backendDirs(paths).some((dir) => existsSync(dir)) || + hasSsrEntry(root, paths) || + (!options?.skipWorkflowDiscovery && scanWorkflowModules(root).length > 0) + ); } function backendDirs(paths: ProjectPaths): Array { diff --git a/packages/void/src/cli/provision.ts b/packages/void/src/cli/provision.ts index 03ea439b4..1c97f9a5e 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 8a999546c..232f8d84b 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); @@ -154,13 +155,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.'); @@ -174,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 || @@ -185,17 +190,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 2157bad83..c6c756290 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,12 +76,27 @@ export function generateBindingTypes(config: VoidConfig): string | null { } } } + const workflowTypes: Array = []; + for (const { bindingName, relativePath } of workflows) { + const module = JSON.stringify('../workflows/' + relativePath); + if (/\.(?:[cm]?js|jsx)$/.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, `WorkflowBinding<${bindingName}Params>`); + } if (bindings.size === 0) { return null; } return [ '// Auto-generated by void — do not edit', 'export {};', + ...(workflows.length ? ['import type { WorkflowBinding } from "void/workflows";'] : []), + ...workflowTypes, 'declare global {', ' interface VoidGeneratedEnvBindings {', ...[...bindings] @@ -89,9 +108,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 84ce159f5..cdceeaa04 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/deploy.ts b/packages/void/src/deploy.ts index 0216c529f..c68d9d23e 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 @@ -86,6 +87,7 @@ export async function prepareDeployArtifact( 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/index.ts b/packages/void/src/index.ts index 011c7215c..ab7e4da89 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(); @@ -116,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; @@ -170,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) => { @@ -266,6 +267,30 @@ 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(FRAMEWORK_WORKFLOWS_ERROR); + } + 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, @@ -302,10 +327,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, ], }) @@ -407,6 +434,7 @@ export function voidPlugin(options?: { devTriggerToken, queues, durableObjects, + workflows, sandboxConfig, shouldEmitLive, liveConfig, @@ -579,7 +607,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) => { @@ -874,6 +905,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. @@ -1031,6 +1067,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/inference/client-auth.ts b/packages/void/src/inference/client-auth.ts index c2e830b45..0d3cb6b35 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 95a8b3f0d..f42badf05 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/plugin-client-stubs.ts b/packages/void/src/plugin-client-stubs.ts index 21cc73812..f663ec03c 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 stubSources = new Map(Object.entries(SERVER_ONLY_STUBS)); const STUB_RESOLVE_FILTER = new RegExp( @@ -76,11 +77,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 a32972d59..01a3e32d1 100644 --- a/packages/void/src/plugin-cloudflare-config.ts +++ b/packages/void/src/plugin-cloudflare-config.ts @@ -94,18 +94,24 @@ export function mergeCloudflareConfig(patch: object, fallback: object): WorkerCo return result; } -/** Translate Void's Wrangler-shaped settings to the configuration that the Cloudflare plugin takes. */ -export function toNativeCloudflareConfig(raw: WorkerConfig, root: string): CloudflareConfig { +/** 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'); const packageName = existsSync(packagePath) ? (JSON.parse(readFileSync(packagePath, 'utf8')) as { name?: unknown }).name : undefined; - const name = + return ( String(packageName ?? basename(root)) .replaceAll('_', '-') .replaceAll(/[^a-z0-9- ]/g, '-') .replaceAll(/^(-+)|(-+)$/g, '') - .slice(0, 63) || 'my-worker'; + .slice(0, 63) || 'my-worker' + ); +} + +/** 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; const selected = process.env.CLOUDFLARE_ENV ? env?.[process.env.CLOUDFLARE_ENV] : undefined; const values = selected ? selected.vars : vars; diff --git a/packages/void/src/plugin-inference.ts b/packages/void/src/plugin-inference.ts index 8a3f4a47a..dc18a01dc 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'; @@ -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}'; @@ -118,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 { @@ -151,18 +154,36 @@ export function inferProjectBindings( scanDirs?: ReadonlyArray, ): InferredBindings { const paths = options?.paths ?? readProjectPaths(root); - const dirs = - scanDirs ?? (paths.sourceDir ? [paths.sourceDir, 'durable-objects'] : 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(/\/$/, '')}/`; const pagesDir = toSlash(paths.pagesDir); const pagesPrefix = pagesDir.endsWith('/') ? pagesDir : `${pagesDir}/`; - const scanSourceFiles = (dirPath: string): Array => - globSync(conventionFileGlobs(dirPath, SOURCE_GLOB, paths.routesDir), { + 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/. + if (insideWorkflows) { + patterns.push('**/*.{cts,cjs}'); + } else if (prefix !== '..' && !prefix.startsWith('../')) { + patterns.push(join(prefix, '**/*.{cts,cjs}')); + } + } + return globSync(patterns, { cwd: dirPath, absolute: true, + ignore: [join(insideWorkflows ? '' : prefix, '**/node_modules/**')], }); + }; 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 0b8c6f399..9b79f2163 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'; @@ -58,6 +63,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'; @@ -101,6 +107,13 @@ type RoutingPluginOptions = { filePath: string; name?: string; }>; + 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; @@ -185,6 +198,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( @@ -664,6 +678,7 @@ export function routingPlugin( isr, notFound: policy.assetConfig.not_found_handling ?? 'none', durableObjects: options.durableObjects, + workflows: options.workflows, }), ); } @@ -691,6 +706,7 @@ export function routingPlugin( sandbox: sandboxEntry, live: options.live, durableObjects: options.durableObjects, + workflows: options.workflows, }), ); } @@ -897,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) { @@ -991,6 +1025,8 @@ export function routingPlugin( const authImportCreated = event === 'add' && authConfigStale && compileOptions.auth !== null; + const workflowChanged = + options.workflows && isInDirectory(normalizedPath, normalizedWorkflowsDir); const sourceConventionChanged = isInDirectory(normalizedPath, normalizedRoutesDir) || isInDirectory(normalizedPath, normalizedMiddlewareDir) || @@ -1001,12 +1037,20 @@ 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 && !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, // not the client — so we must iterate all environments. diff --git a/packages/void/src/plugin-worker-bindings.ts b/packages/void/src/plugin-worker-bindings.ts index b3aeb6c45..c6787a52b 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'; @@ -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, WorkerConfigFields } 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,35 @@ 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)), + { ...resolved.exports, ...(isRecord(result.exports) ? result.exports : {}) }, + ); + if (additions.length > 0) { + result.workflows = [...patchEntries, ...additions]; + } +} + type WorkerBindingPatch = { patch: Partial; versionMetadataBinding: string | undefined; @@ -86,6 +117,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; @@ -109,6 +141,7 @@ export function mergeWorkerBindings( devTriggerToken, queues, durableObjects, + workflows, sandboxConfig, shouldEmitLive, liveConfig, @@ -395,6 +428,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/plugin-worker-environment.ts b/packages/void/src/plugin-worker-environment.ts index ef0272035..ecf6158c3 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/src/router/compile.ts b/packages/void/src/router/compile.ts index 3b12e08b2..a4424b4ed 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -1199,12 +1199,62 @@ 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; + wrapClass?: (classExpression: string) => 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}.`; + 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)}` : ''});`, + `export const ${className} = ${options.wrapClass?.(resourceClass) ?? resourceClass};`, + ].join('\n'); + }) + .join('\n'); + return { imports, exports }; } /** @@ -1240,6 +1290,7 @@ export function compileWorkerEntry(options: WorkerEntryOptions = {}): string { isr, notFound = 'none', durableObjects = [], + workflows = [], } = options; const remotePath = remote?.remotePath; const remoteBindingNames = JSON.stringify(remote?.bindingNames); @@ -1282,17 +1333,36 @@ 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()', + wrapClass: (workflowClass) => + `__createWorkflowEntrypoint(${workflowClass}, { ${[ + isr && 'isrDeploymentId: __VOID_ISR_DEPLOYMENT_ID', + envSchemaModule && 'validateEnv: _validateEnvOnce', + remotePath && `remoteEnv: (env) => ${createRemoteEnvCall}`, + ] + .filter(Boolean) + .join(', ')} })`, + }); + 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 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 @@ -1432,7 +1502,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} @@ -1440,7 +1510,7 @@ ${emailReceiptHandler} ${queueFunction}${webSocketClasses.map((name) => `export { ${name} };`).join('\n')} ${liveExport} ${sandboxExport} -${durableObjectExports} +${resourceModuleExports} ${entryClass}`; } diff --git a/packages/void/src/runtime/workflows/entry.ts b/packages/void/src/runtime/workflows/entry.ts new file mode 100644 index 000000000..18189a441 --- /dev/null +++ b/packages/void/src/runtime/workflows/entry.ts @@ -0,0 +1,101 @@ +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: { + isrDeploymentId?: string; + 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.isrDeploymentId !== undefined) { + env.__VOID_ISR_DEPLOYMENT_ID ??= options.isrDeploymentId; + } + if (options.validateEnv) { + await options.validateEnv(env); + } + return withRuntimeEnv(env, () => super.run(event, scopedStep(step, env))); + } + }; +} diff --git a/packages/void/src/runtime/workflows/index.ts b/packages/void/src/runtime/workflows/index.ts new file mode 100644 index 000000000..774a2d817 --- /dev/null +++ b/packages/void/src/runtime/workflows/index.ts @@ -0,0 +1,298 @@ +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 { getRuntimeEnv, requireRuntimeBinding, withRuntimeEnv } from '../env/runtime.ts'; + +export type { WorkflowEvent, WorkflowStep }; + +// 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< + 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 = { + readonly env: TEnv; + readonly ctx: ExecutionContext; +}; + +/** Options for starting one Workflow instance. */ +export type WorkflowCreateOptions = Omit & + (undefined extends TParams ? { params?: TParams } : { params: TParams }); + +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 + | (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: CompatibleBinding, + ...args: WorkflowCreateArguments + ): Promise; + /** Start up to 100 instances. Each instance's params are validated first. */ + createBatch( + instances: ReadonlyArray>, + ): Promise; + createBatch( + binding: CompatibleBinding, + instances: ReadonlyArray>, + ): Promise; + /** Get a handle to an existing instance. */ + get(id: string): Promise; + get(binding: Workflow, id: string): Promise; +}; + +type WorkflowCallback = ( + event: Readonly>, + step: WorkflowStep, + context: WorkflowContext, +) => TResult; + +export type WorkflowRun = WorkflowCallback>; + +export type WorkflowClass> = new ( + ctx: ExecutionContext, + env: TEnv, +) => WorkflowEntrypoint; + +/** 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 && !isWorkflowName(definitionName)) { + throw new Error('workflows: name must contain a letter or digit.'); + } + 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; +}; + +// 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/`. + */ +export function defineWorkflow>( + definition: WorkflowDefinitionBase & { + /** Standard Schema that validates params in `create()` and `createBatch()`. */ + params: TSchema; + run: DefinitionRun>, TEnv>; + }, +): WorkflowApi< + WorkflowClass>, TEnv>, + StandardSchemaV1.InferInput, + WorkflowPayload> +>; +export function defineWorkflow>( + definition: WorkflowDefinitionBase & { + params?: undefined; + run: DefinitionRun, TEnv>; + }, +): WorkflowApi, TEnv>, TParams, WorkflowPayload>; +export function defineWorkflow( + definition: WorkflowDefinitionBase & { + params?: StandardSchemaV1; + run: WorkflowCallback, unknown>; + }, +): 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 async run( + event: Readonly>, + step: WorkflowStep, + ): Promise { + const env = this.env; + const ctx = this.ctx; + return withRuntimeEnv(env, () => run(event, step, { env: getRuntimeEnv(), ctx })); + } + } + + 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( + definition: WorkflowDefinitionBase & { class: TClass }, +): WorkflowApi< + TClass, + NativeWorkflowInput>, + Exclude, void> +> { + 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/env.ts b/packages/void/src/shared/env.ts index fdb3322eb..fdb638041 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 2c74460b2..b98e81902 100644 --- a/packages/void/src/shared/resource-definition.ts +++ b/packages/void/src/shared/resource-definition.ts @@ -5,16 +5,17 @@ import { isIdentifier, isMemberExpression, isObjectExpression, + moduleExportName, } from './ast.ts'; import type { + AstExportNamedDeclaration, AstImportDeclaration, AstImportNamespaceSpecifier, AstImportSpecifier, AstNode, - 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,19 +23,48 @@ export function readResourceDefinition( filename: string, source: string, 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)) + ) { + 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); const constants = new Map(); 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; + 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); @@ -55,6 +85,36 @@ 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 ( + 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; @@ -63,7 +123,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); @@ -91,6 +153,9 @@ export function readResourceDefinition( } for (const variable of (declaration as AstVariableDeclaration).declarations ?? []) { recordBindings(variable.id); + 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); if (declaration.kind === 'const') { @@ -109,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 { @@ -153,9 +240,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 }; @@ -164,34 +254,60 @@ export function readResourceDefinition( return name; } - const statement = program.body?.find((node) => node.type === 'ExportDefaultDeclaration'); - const declaration = unwrapStaticExpression(statement?.declaration as AstNode | undefined); - 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) ?? (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)) { + const namespace = resolve(callee.object); + const property = + !callee.computed && isIdentifier(callee.property) + ? callee.property.name + : staticLiteral(callee.property); + if ( + typeof property === 'string' && + helpers.has(property) && + ((isIdentifier(namespace) && namespaces.get(namespace.name)?.has(property)) || + isWorkflowRequire(namespace)) + ) { + 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') { + 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( + (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 options = resolve(call.arguments?.[0]); - const name = readName(options).value; - return { helper, options, ...(name === undefined ? {} : { name }) }; + const name = readName(definition.options).value; + return { ...definition, ...(name === undefined ? {} : { name }) }; } diff --git a/packages/void/src/shared/resource-name.ts b/packages/void/src/shared/resource-name.ts index 3552ed660..d5224a749 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/shared/static-exports.ts b/packages/void/src/shared/static-exports.ts index 1b8f06d89..da814c8b3 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/config.ts b/packages/void/src/workflows/config.ts new file mode 100644 index 000000000..b9b123eb6 --- /dev/null +++ b/packages/void/src/workflows/config.ts @@ -0,0 +1,64 @@ +import { isRecord } from '@void/deploy-core'; +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, + 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) { + const configured = existing.find((entry) => entry.binding === module.bindingName); + if (configured) { + 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}'.`, + ); + } + continue; + } + 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( + `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 000000000..c88b69a14 --- /dev/null +++ b/packages/void/src/workflows/platform.ts @@ -0,0 +1,13 @@ +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) { + 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/retention.ts b/packages/void/src/workflows/retention.ts new file mode 100644 index 000000000..b9df7684e --- /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/src/workflows/scan.ts b/packages/void/src/workflows/scan.ts new file mode 100644 index 000000000..5fd25bee0 --- /dev/null +++ b/packages/void/src/workflows/scan.ts @@ -0,0 +1,122 @@ +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; + /** 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. */ + resourceName: string; + name?: string; +}; + +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']); + +/** + * 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, ignore: ['**/node_modules/**'] }) + .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, +): Pick { + const parts = resourceNameWords(name); + const classBase = parts.map((part) => part[0].toUpperCase() + part.slice(1)).join(''); + return { + bindingName: `WORKFLOW_${parts.join('_').toUpperCase()}`, + className: /^\d/.test(classBase) ? `Workflow${classBase}` : `${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 { + // 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.`, + ); + } + return name; +} + +export function scanWorkflowModules(root: string): Array { + const directory = join(root, 'workflows'); + if (!existsSync(directory)) { + return []; + } + + const modules = listWorkflowFiles(directory).flatMap((relativePath) => { + const filePath = join(directory, relativePath); + const definition = deriveFromSource(filePath, 'workflow-definition', (source) => + readResourceDefinition(filePath, source, WORKFLOW_HELPERS, 'workflows'), + ); + 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, + definition: + definition.helper === 'defineWorkflowEntrypoint' + ? 'defineWorkflowEntrypoint' + : 'defineWorkflow', + ...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 571e2f8fa..cb405fe2f 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'; @@ -9,6 +10,7 @@ import { verifyGeneratedDeployConfig } from '../../src/cli/deploy-artifact-valid import { reconstructExpectedContainers, reconstructExpectedDurableObjectState, + reconstructExpectedWorkflows, snapshotBindingIdentities, snapshotPassthroughIdentities, snapshotPassthroughRawFields, @@ -18,7 +20,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 +154,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 +184,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 +230,133 @@ export default defineDurableState({ initialState: { count: 0 }, methods: { incre } }, ); + + 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 { + 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`, + ); + 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], + exports: { NightlyImportWorkflow: workflowExport, DailyWorkflow: exportOnly }, + }, + }), + ); + 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: exportOnly.name, + binding: 'WORKFLOW_DAILY', + class_name: 'DailyWorkflow', + }, + { + 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 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/); + 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/full-deploy-manifest.test.ts b/packages/void/test/integration/full-deploy-manifest.test.ts index dc2d853af..eed52fd8b 100644 --- a/packages/void/test/integration/full-deploy-manifest.test.ts +++ b/packages/void/test/integration/full-deploy-manifest.test.ts @@ -218,6 +218,26 @@ 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 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 }); + } + }); + beforeEach(() => { mockDetectFramework.mockReset().mockReturnValue(undefined); diff --git a/packages/void/test/integration/typed-routing-runtime.test.ts b/packages/void/test/integration/typed-routing-runtime.test.ts index cf41a1082..9ff434984 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'); 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 000000000..84c6a37ef --- /dev/null +++ b/packages/void/test/integration/workflow-dev.test.ts @@ -0,0 +1,269 @@ +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'; +import { + createIsolatedPlayground, + killChild, + spawnFixtureServer, + startServer, + 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(repository, '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'); + const declaration = join(fixture.root, '.void', 'bindings.d.ts'); + expect(readFileSync(declaration, 'utf8')).toContain('"WORKFLOW_WELCOME"'); + 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); + } + }, +});`, + ); + 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 });`, + ); + 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"'); + writeFileSync( + join(fixture.root, 'binding.ts'), + `import { defineHandler } from 'void'; +import Notify from './workflows/notify'; +export const GET = defineHandler(async c => { + 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 [legacy.length, list.created.length, shared.created.length]; +});`, + ); + 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'], + lib: ['ES2022'], + skipLibCheck: true, + }, + include: ['binding.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('types JavaScript Workflow bindings with and without allowJs', async () => { + const fixture = createIsolatedPlayground(repository, 'playground/ssr'); + onTestFinished(() => fixture.cleanup()); + mkdirSync(join(fixture.root, 'workflows')); + 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]) { + 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" } }); +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', + 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'])( + '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/integration/workflow-runtime.test.ts b/packages/void/test/integration/workflow-runtime.test.ts new file mode 100644 index 000000000..feb82e24b --- /dev/null +++ b/packages/void/test/integration/workflow-runtime.test.ts @@ -0,0 +1,374 @@ +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'; +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; + +afterAll(() => rmSync(temporary, { recursive: true, force: true })); + +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(); + }); + + 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('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 { 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) { + const value = env.VALUE; + 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 }; + }); +} +${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 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 }], + }, + ); + const worker = new Miniflare( + convertV4MiniflareOptions({ + compatibilityDate: '2026-07-01', + compatibilityFlags: ['nodejs_compat'], + modules: true, + modulesRoot: output, + scriptPath: join(output, 'worker.mjs'), + bindings: { VALUE: '41' }, + d1Databases: { DB: 'test' }, + kvNamespaces: ['ISR_CACHE'], + workflows: { COLD: { name: 'cold', className: 'ColdWorkflow' } }, + }), + ); + try { + 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, { + timeout: 5000, + }) + .toMatch(/^(complete|errored)$/); + expect(await instance.status()).toMatchObject({ + status: 'complete', + output: { value: 42, sameSession: true }, + }); + expect(await ISR_CACHE.get(cachedPage)).toBeNull(); + } finally { + await worker.dispose(); + } + }, + ); +}); + +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([ + { + 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/cf-version-message.test.ts b/packages/void/test/unit/cf-version-message.test.ts new file mode 100644 index 000000000..9a0a18c9f --- /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 ce68d5bed..4406173c9 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, @@ -2628,6 +2645,108 @@ it.each(['restore', 'remove'] 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-classify.test.ts b/packages/void/test/unit/cloudflare-classify.test.ts index bdecd37f1..d4338c0c6 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,51 @@ 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 }); + + 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 () => { + 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/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index 0ac6c802b..548c65910 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, @@ -756,7 +757,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'); @@ -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' }; } @@ -1732,12 +1734,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 +1755,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 +1764,136 @@ describe('existing Cloudflare site handoff', () => { } }); + 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( + 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', + }, + ], + ...(operation === 'remove export only' && { + bindings: [], + runtime: { + ...existing.runtime, + exports: { NotifyWorkflow: { type: 'workflow', name: 'site_notify' } }, + }, + }), + ...((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>() + .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, + }); + 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, + { + platform: 'cloudflare', + atomic: true, + ...(operation === 'remove to static' ? { dir: 'dist' } : {}), + }, + silentCliLog, + deps, + ); + expect(readExistingWorker).toHaveBeenCalledTimes(operation.startsWith('add') ? 0 : 1); + expect(activateVersion).toHaveBeenCalledWith( + expect.objectContaining({ + atomic: true, + expectedPreviousVersionId: operation.startsWith('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'); @@ -2980,6 +3116,93 @@ 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)( + '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) => { + 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, + workers_dev: true, + preview_urls: true, + }), + ); + } 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'; + 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 }] } }; + } + 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.toBeInstanceOf(ExitError); + expect(apply).toHaveBeenCalledOnce(); + expect(parseCloudflareVersionMessage(uploadedMessage)).toMatchObject({ + triggerConfig: { routes }, + }); + }, + ); + it('still deploys a pg app WITHOUT checked-in migrations (external schema — no false-reject)', async () => { const root = pgProject(); const { deps, wranglerArgs, exitCalls } = harness(); @@ -3435,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' }), @@ -3455,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( @@ -4371,6 +4596,107 @@ 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: 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 }, + { 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 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, + ...(exportOnly + ? { exports: { NotifyWorkflow: { type: 'workflow', ...workflowSettings } } } + : { + workflows: [ + { binding: 'WORKFLOW_NOTIFY', class_name: 'NotifyWorkflow', ...workflowSettings }, + ], + }), + }, + { + '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.entitlement') { + expect(operation.steps).toBe(steps ?? 0); + expect(operation.concurrency).toBe(concurrency ?? 0); + expect(operation.schedules).toBe(Boolean(schedules?.length)); + expect(operation.retentionMs ?? 0).toBe(retentionMs ?? 0); + trace.push('check-workflows'); + 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-workflows'); + expect(trace).not.toContain('provision'); + expect(trace).not.toContain('build'); + } else { + await deploy; + expect(trace.includes('check-workflows')).toBe(shouldProbe); + expect(trace).toContain('provision'); + if (shouldProbe) { + 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')); + } + }, + ); + it('fails before provisioning or building when Sandbox Containers are unavailable', async () => { const root = sandboxProject(); const errors: Array = []; @@ -9868,7 +10194,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'); @@ -9895,9 +10224,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( @@ -9914,7 +10252,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'); }, }); @@ -9933,7 +10272,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 6f65f6308..a56a9aaaf 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`, @@ -319,6 +334,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) => { @@ -1121,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) => { @@ -1788,6 +1940,124 @@ syncBuiltinESMExports();`, 30_000, ); +const workflowEntitlementCases: Array<{ + name: string; + entitlements: Array; + eligible?: boolean; + status?: number; + fedramp?: boolean; + schedules?: boolean; + steps?: number; + concurrency?: number; + retentionMs?: number; +}> = [ + { + 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, + }, + ...[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, + })), + ...[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 }, + { + 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 }, +]; + +it.each(workflowEntitlementCases)( + 'reads scheduled Workflow eligibility using the pinned account: $name', + async ({ + entitlements, + eligible, + status, + fedramp = false, + schedules = true, + steps = 0, + concurrency = 0, + retentionMs = 0, + }) => { + 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.entitlement', fedramp, schedules, steps, concurrency, retentionMs }, + 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) => { diff --git a/packages/void/test/unit/cloudflare-operations.test.ts b/packages/void/test/unit/cloudflare-operations.test.ts index 83f80a398..aff041002 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/compile.test.ts b/packages/void/test/unit/compile.test.ts index 267e6d9bd..a58549c44 100644 --- a/packages/void/test/unit/compile.test.ts +++ b/packages/void/test/unit/compile.test.ts @@ -857,11 +857,63 @@ 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 = __createWorkflowEntrypoint(__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/deploy-artifact-preparation.test.ts b/packages/void/test/unit/deploy-artifact-preparation.test.ts index dd84832dc..f01255bfe 100644 --- a/packages/void/test/unit/deploy-artifact-preparation.test.ts +++ b/packages/void/test/unit/deploy-artifact-preparation.test.ts @@ -178,6 +178,44 @@ 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.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/deploy-project.test.ts b/packages/void/test/unit/deploy-project.test.ts index 6c8f2b95c..7033aeed7 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/info.test.ts b/packages/void/test/unit/info.test.ts index c1474d0f4..533fedd6a 100644 --- a/packages/void/test/unit/info.test.ts +++ b/packages/void/test/unit/info.test.ts @@ -92,6 +92,61 @@ 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', + "import { defineWorkflow } from 'void/workflows'; 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: 'defineWorkflowEntrypoint', + 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('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/init.test.ts b/packages/void/test/unit/init.test.ts index ae8bb331b..5e573be32 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/plugin-inference.test.ts b/packages/void/test/unit/plugin-inference.test.ts index 62e95f309..02aef9109 100644 --- a/packages/void/test/unit/plugin-inference.test.ts +++ b/packages/void/test/unit/plugin-inference.test.ts @@ -378,6 +378,87 @@ 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'; + 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); + } });`, + ); + 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 }); + }); + + 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('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'), + `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, + needsD1: true, + needsAI: false, + needsAuth: false, + }); + expect(inferProjectBindings(root, undefined, ['.'])).toMatchObject({ + needsKV: true, + needsR2: true, + }); + expect(inferProjectBindings(root, undefined, ['src'])).toMatchObject({ + 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', () => { const root = createTempRoot(); mkdirSync(join(root, 'routes'), { recursive: true }); @@ -768,6 +849,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(); } @@ -837,8 +929,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', @@ -848,6 +941,66 @@ 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'), + "import { defineWorkflow } from 'void/workflows'; export default defineWorkflow({ async run() {} });", + ); + 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 = __createWorkflowEntrypoint(__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' } }), + ); + 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' })); + 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"'); + } 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/rollback-platform.test.ts b/packages/void/test/unit/rollback-platform.test.ts index 209063da9..663388bd8 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' }), })); @@ -60,6 +61,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-runtime.test.ts b/packages/void/test/unit/workflow-runtime.test.ts new file mode 100644 index 000000000..f6f705444 --- /dev/null +++ b/packages/void/test/unit/workflow-runtime.test.ts @@ -0,0 +1,220 @@ +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, + 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('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({ + 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', + __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 }>, + 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'); + // @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 } }]), + ).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: '---', 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) { + 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-runtime.typecheck.ts b/packages/void/test/unit/workflow-runtime.typecheck.ts new file mode 100644 index 000000000..708f3b399 --- /dev/null +++ b/packages/void/test/unit/workflow-runtime.typecheck.ts @@ -0,0 +1,147 @@ +import { WorkflowEntrypoint } from 'cloudflare:workers'; +import { defineWorkflow, defineWorkflowEntrypoint } 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; + +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' }]); + +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 }>; +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. +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' }); +// @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' }); + +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 }); +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. +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 new file mode 100644 index 000000000..61311c8a2 --- /dev/null +++ b/packages/void/test/unit/workflow-scan.test.ts @@ -0,0 +1,311 @@ +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 = []; +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-')); + 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.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({});', + }); + + expect(scanWorkflowModules(root)).toEqual([]); + 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('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); + expect(scanWorkflowModules(root)).toEqual([]); + 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([ + { + filePath: toSlash(join(root, 'workflows', 'send-welcome.ts')), + relativePath: 'send-welcome.ts', + definition: 'defineWorkflow', + bindingName: 'WORKFLOW_SEND_WELCOME', + className: 'SendWelcomeWorkflow', + resourceName: 'send-welcome', + }, + ]); + }); + + 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([ + { + filePath: toSlash(join(root, 'workflows', 'order', 'notifications.ts')), + relativePath: 'order/notifications.ts', + definition: 'defineWorkflow', + bindingName: 'WORKFLOW_ORDER_NOTIFICATIONS', + className: 'OrderNotificationsWorkflow', + resourceName: 'order-notifications', + }, + ]); + }); + + 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': "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, + '_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': definition, + 'order-notifications.ts': definition, + }); + 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': 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': definition }); + 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('eu-charge', 'billing')).not.toBe( + cloudflareWorkflowName('charge', 'billing-eu'), + ); + expect(cloudflareWorkflowName('welcome')).toBe('welcome'); + 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', () => { + 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([{ ...authored, script_name: 'app' }], 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 c82778852..9a99f2225 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; @@ -104,6 +105,8 @@ 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/workflows/entry.ts', 'src/runtime/db/seed.ts', 'src/runtime/db/validators/drizzle-zod.ts', 'src/runtime/db/validators/drizzle-valibot.ts',