diff --git a/docs/integrations/frameworks/overview.md b/docs/integrations/frameworks/overview.md index f635b0f11..72f4c5adc 100644 --- a/docs/integrations/frameworks/overview.md +++ b/docs/integrations/frameworks/overview.md @@ -42,6 +42,8 @@ With `voidPlugin()` added to the framework's Vite config, frameworks get most of - **Queue consumers:** typed producers and consumers via the `queues/` directory. - **Revalidation and prerendering:** configure them with [`routing.revalidate`](../../guide/edge/revalidation.md) and [`routing.prerender`](../../guide/edge/prerendering.md) in `void.config.ts`. Void apps can also set these per page in companion `.server.ts` files. +In vinext dev and preview, `send()` succeeds but doesn't run this app's queue handler. In dev, run the handler with the [manual queue trigger](../../guide/queues.md#local-development), using the dev server's port and the token in `.void/dev-trigger-token`. Preview reads `queues/` and `env.ts` from the source tree, so don't change them between the build and preview. + For framework apps, Void revalidation caches public HTML document responses with both `void deploy` and `void deploy --platform cloudflare`. Client data requests continue to use the framework's own behavior. A response with `Set-Cookie` or `Cache-Control: private`, `no-store`, or `no-cache` is never shared. Frameworks can also access bindings directly via the framework's own mechanisms (e.g. `env` from `cloudflare:workers` in SvelteKit 3, Analog, and Astro, `platform.env` in SvelteKit 2, `event.context.cloudflare.env` in Nuxt). diff --git a/docs/integrations/frameworks/react-router.md b/docs/integrations/frameworks/react-router.md index 149f739c1..0f623070d 100644 --- a/docs/integrations/frameworks/react-router.md +++ b/docs/integrations/frameworks/react-router.md @@ -68,6 +68,8 @@ export async function loader({}: Route.LoaderArgs) { Use [KV](../../guide/kv.md), [object storage](../../guide/storage.md), and [AI](../../guide/ai.md) from server-side code with the same imports as a Void app. Add [cron jobs](../../guide/jobs.md) in `crons/` and [queue consumers](../../guide/queues.md) in `queues/`. +In dev and preview, `send()` succeeds but doesn't run this app's queue handler. In dev, run the handler with the [manual queue trigger](../../guide/queues.md#local-development), using the dev server's port and the token in `.void/dev-trigger-token`. Preview reads `queues/` and `env.ts` from the source tree, so don't change them between the build and preview. + ### Environment Variables Declare variables in `env.ts` and read them with `import { env } from "void/env"`. See [Environment Variables](../../guide/env-vars.md) for local values, production secrets, and public `VITE_*` values. diff --git a/docs/integrations/frameworks/tanstack-start.md b/docs/integrations/frameworks/tanstack-start.md index 4ca758074..57cdf3f88 100644 --- a/docs/integrations/frameworks/tanstack-start.md +++ b/docs/integrations/frameworks/tanstack-start.md @@ -68,6 +68,8 @@ const getUsers = createServerFn().handler(async () => { Use [KV](../../guide/kv.md), [object storage](../../guide/storage.md), and [AI](../../guide/ai.md) from server-side code with the same imports as a Void app. Add [cron jobs](../../guide/jobs.md) in `crons/` and [queue consumers](../../guide/queues.md) in `queues/`. +In dev and preview, `send()` succeeds but doesn't run this app's queue handler. In dev, run the handler with the [manual queue trigger](../../guide/queues.md#local-development), using the dev server's port and the token in `.void/dev-trigger-token`. Preview reads `queues/` and `env.ts` from the source tree, so don't change them between the build and preview. + ### Environment Variables Declare variables in `env.ts` and read them with `import { env } from "void/env"`. See [Environment Variables](../../guide/env-vars.md) for local values, production secrets, and public `VITE_*` values. diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index 632f1eaba..21933e397 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -809,6 +809,10 @@ export function voidPlugin(options?: { auxiliaryWorkers: options?.auxiliaryWorkers, viteEnvironment, config: mergeBindings, + localQueueProducers: () => ({ + queues: application.queues, + reserved: envSchemaFacts?.serverKeys ?? [], + }), }), implicitDeployGuard, ]; diff --git a/packages/void/src/plugin-cloudflare-config.ts b/packages/void/src/plugin-cloudflare-config.ts index 0124e69a9..a32972d59 100644 --- a/packages/void/src/plugin-cloudflare-config.ts +++ b/packages/void/src/plugin-cloudflare-config.ts @@ -1,15 +1,59 @@ import { existsSync, readFileSync } from 'node:fs'; -import { convertToWranglerConfig } from '@cloudflare/config'; +import { bindings, convertToWranglerConfig } from '@cloudflare/config'; import type { CloudflareConfig, PluginConfig } from '@cloudflare/vite-plugin'; import { resolve, dirname, basename, join } from 'pathslash'; import { parse as parseToml } from 'smol-toml'; import { migrateBuiltWranglerConfig } from './cli/cf-config-migrate.ts'; import { readGeneratedWranglerConfigFile } from './cli/generated-wrangler-config.ts'; +import { voidWarn } from './log.ts'; +import type { QueueDefinition } from './queues/scan.ts'; /** Void keeps its Wrangler-shaped public options independently of the upstream plugin. */ export type WorkerConfig = ReturnType; export type WorkerConfigFields = Record; +export type LocalQueueProducers = () => { + queues: ReadonlyArray>; + reserved: ReadonlyArray; +}; + +export function addLocalQueueProducers( + worker: Pick, + read: LocalQueueProducers | undefined, + warn: (message: string) => void = voidWarn, +): Array | undefined { + // A framework can open a dev or preview server while building its pages. + if (!read || process.env.CLOUDFLARE_VITE_BUILD === 'true') { + return; + } + const { queues, reserved } = read(); + if (queues.length === 0) { + return; + } + const taken = new Set(reserved); + const byBinding = new Map>(); + for (const queue of queues) { + const group = byBinding.get(queue.bindingName) ?? []; + group.push(queue); + byBinding.set(queue.bindingName, group); + } + let added: Array | undefined; + for (const [binding, group] of byBinding) { + if (group.length > 1) { + const files = group.map(({ filePath }) => filePath).join(', '); + warn( + `Queue files ${files} share binding ${binding}. Void skips inference for this binding. Rename the conflicting files so each queue has a distinct binding.`, + ); + continue; + } + if (!taken.has(binding) && !Object.hasOwn(worker.env ?? {}, binding)) { + (worker.env ??= {})[binding] = bindings.queue({ name: group[0].name }); + (added ??= []).push(binding); + } + } + return added; +} + type AuxiliaryConfig = | Partial | (( @@ -133,6 +177,7 @@ export function restoreLocalContainerBindings(worker: CloudflareConfig['worker'] export function nativeAuxiliaryWorkers( workers: Array | undefined, root: string, + readLocalQueueBindings?: () => ReadonlyArray | undefined, ): PluginConfig['auxiliaryWorkers'] { return workers?.map(({ configPath, config, ...options }) => ({ ...options, @@ -145,11 +190,20 @@ export function nativeAuxiliaryWorkers( : readGeneratedWranglerConfigFile(path) : {} ) as WorkerConfig; + let worker = entryWorkerConfig; + const localBindings = readLocalQueueBindings?.(); + if (localBindings && typeof config === 'function') { + const env = { ...entryWorkerConfig.env }; + for (const name of localBindings) { + delete env[name]; + } + worker = { ...entryWorkerConfig, env }; + } const patch = typeof config === 'function' ? config(base, { entryWorkerConfig: convertToWranglerConfig({ - worker: entryWorkerConfig, + worker, containers: [], }), }) diff --git a/packages/void/src/plugin-cloudflare-preview.ts b/packages/void/src/plugin-cloudflare-preview.ts index 3392df936..07713d7bd 100644 --- a/packages/void/src/plugin-cloudflare-preview.ts +++ b/packages/void/src/plugin-cloudflare-preview.ts @@ -1,12 +1,19 @@ import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { getRootConfigPath, getWorkerConfigPath } from '@cloudflare/build-output-utils'; +import type { CloudflareConfig } from '@cloudflare/vite-plugin'; import { dirname, join } from 'pathslash'; import type { Plugin } from 'vite'; +import { addLocalQueueProducers } from './plugin-cloudflare-config.ts'; +import type { LocalQueueProducers } from './plugin-cloudflare-config.ts'; import { writeFileAtomic } from './shared/atomic-write.ts'; import { loadLocalEnv } from './shared/env.ts'; /** Give preview local bindings without changing the deployable build or storing their values. */ -export function withLocalPreviewBindings(plugins: Array, root: string): Array { +export function withLocalPreviewBindings( + plugins: Array, + root: string, + localQueueProducers?: LocalQueueProducers, +): Array { let directory: string | undefined; const cleanup = () => { if (directory) { @@ -35,9 +42,10 @@ export function withLocalPreviewBindings(plugins: Array, root: string): const output = dirname(getRootConfigPath(root)); cpSync(output, dirname(getRootConfigPath(directory)), { recursive: true }); const path = getWorkerConfigPath(directory); - const worker = JSON.parse(readFileSync(path, 'utf8')) as { - env?: Record; - }; + const worker = JSON.parse(readFileSync(path, 'utf8')) as Pick< + CloudflareConfig['worker'], + 'env' + >; worker.env ??= {}; const inlineBindingTypes = new Set(['text', 'json', 'secret']); for (const name of Object.keys(loadLocalEnv(root))) { @@ -46,6 +54,7 @@ export function withLocalPreviewBindings(plugins: Array, root: string): worker.env[name] = { type: 'secret' }; } } + addLocalQueueProducers(worker, localQueueProducers); writeFileAtomic(path, JSON.stringify(worker)); // The upstream preview resolves declared secrets from this env directory. // A private artifact copy isolates local-only declarations from deployment diff --git a/packages/void/src/plugin-cloudflare.ts b/packages/void/src/plugin-cloudflare.ts index b0ba1268f..6b672d410 100644 --- a/packages/void/src/plugin-cloudflare.ts +++ b/packages/void/src/plugin-cloudflare.ts @@ -10,13 +10,19 @@ import type { PluginConfig } from '@cloudflare/vite-plugin'; import { dirname, isAbsolute, join, relative, resolve } from 'pathslash'; import type { BuildEnvironment, Plugin } from 'vite'; import { readGeneratedWranglerConfigFile } from './cli/generated-wrangler-config.ts'; +import { voidWarn } from './log.ts'; import { + addLocalQueueProducers, mergeCloudflareConfig, nativeAuxiliaryWorkers, restoreLocalContainerBindings, toNativeCloudflareConfig, } from './plugin-cloudflare-config.ts'; -import type { AuxiliaryWorkerConfig, WorkerConfig } from './plugin-cloudflare-config.ts'; +import type { + AuxiliaryWorkerConfig, + LocalQueueProducers, + WorkerConfig, +} from './plugin-cloudflare-config.ts'; import { withLocalPreviewBindings } from './plugin-cloudflare-preview.ts'; import { isVitestServer } from './plugin-dev-config.ts'; import { writeFileAtomic } from './shared/atomic-write.ts'; @@ -55,16 +61,21 @@ export function cloudflare(options: { inspectorPort?: PluginConfig['inspectorPort']; persistState?: PluginConfig['persistState']; viteEnvironment: NonNullable; + localQueueProducers?: LocalQueueProducers; finalizeAssets?: (clientDir: string, environment: BuildEnvironment | undefined) => void; }): Array { const root = process.cwd(); let workerConfig: WorkerConfig; let native: ReturnType; let pluginNative: ReturnType; + let localQueueBindings: Array | undefined; + let localQueueWarnings: Array | undefined; const outputDirectories = new Map(); const bridge: Plugin = { name: 'void:cloudflare-config', config(_userConfig, environment) { + localQueueBindings = undefined; + localQueueWarnings = undefined; if (environment.isPreview) { return; } @@ -101,8 +112,16 @@ export function cloudflare(options: { } } else if (environment.command === 'serve') { restoreLocalContainerBindings(pluginNative.worker); + localQueueBindings = addLocalQueueProducers( + pluginNative.worker, + options.localQueueProducers, + (message) => (localQueueWarnings ??= []).push(message), + ); } }, + configureServer() { + localQueueWarnings?.forEach(voidWarn); + }, }; const directories: Plugin = { name: 'void:cloudflare-output-directories', @@ -271,7 +290,11 @@ export function cloudflare(options: { inspectorPort: options.inspectorPort, persistState: options.persistState, viteEnvironment: options.viteEnvironment, - auxiliaryWorkers: nativeAuxiliaryWorkers(options.auxiliaryWorkers, root), + auxiliaryWorkers: nativeAuxiliaryWorkers( + options.auxiliaryWorkers, + root, + () => localQueueBindings, + ), types: { generate: false }, config() { // Replace the complete parsed configuration, including account settings @@ -280,6 +303,7 @@ export function cloudflare(options: { }, }), root, + options.localQueueProducers, ), output, ]); diff --git a/packages/void/test/integration/plugin-cloudflare-v2.test.ts b/packages/void/test/integration/plugin-cloudflare-v2.test.ts index bed574f35..9210415be 100644 --- a/packages/void/test/integration/plugin-cloudflare-v2.test.ts +++ b/packages/void/test/integration/plugin-cloudflare-v2.test.ts @@ -426,6 +426,35 @@ export default { expect(existsSync(join(root, '.gitignore'))).toBe(false); }); + it('keeps inferred local producers out of auxiliary Worker config callbacks', async () => { + const root = project(); + vi.stubEnv('CLOUDFLARE_VITE_BUILD', undefined); + const helperProducers = vi.fn(); + const plugins = cloudflare({ + config: () => ({ name: 'entry', main: 'virtual:entry' }), + viteEnvironment: { name: 'ssr' }, + localQueueProducers: () => ({ + queues: [{ filePath: 'inbox.ts', name: 'inbox', bindingName: 'QUEUE_INBOX' }], + reserved: [], + }), + auxiliaryWorkers: [ + { + config(_config, { entryWorkerConfig }) { + const producers = entryWorkerConfig.queues?.producers ?? [ + { binding: 'QUEUE_INBOX', queue: 'helper-original' }, + ]; + helperProducers(producers); + return { name: 'helper', main: 'helper.js', queues: { producers } }; + }, + }, + ], + }); + await resolveConfig({ root, configFile: false, plugins }, 'serve'); + expect(helperProducers).toHaveBeenCalledExactlyOnceWith([ + { binding: 'QUEUE_INBOX', queue: 'helper-original' }, + ]); + }); + it("starts no Worker in Vitest's server, in any mode, but keeps it in servers that tests start", async () => { const root = project(); const plugins = () => @@ -462,7 +491,16 @@ export default { writeFileSync(join(oldOutput, 'config.json'), '{}'); writeFileSync( join(root, 'worker.js'), - "export default { fetch: (_request, env) => new Response(env.PREVIEW_VALUE ?? 'built-worker') };", + `export default { async fetch(_request, env) { + await env.QUEUE_INBOX?.send({ test: true }); + return Response.json({ + value: env.PREVIEW_VALUE ?? 'built-worker', + sent: Boolean(env.QUEUE_INBOX), + dotenv: env.QUEUE_DOTENV, + reserved: 'QUEUE_RESERVED' in env, + collision: 'QUEUE_TWO_NAMES' in env, + }); + } };`, ); writeFileSync(join(root, 'index.html'), '

asset

'); const plugins = () => @@ -476,6 +514,16 @@ export default { }), inspectorPort: false, viteEnvironment: { name: 'ssr' }, + localQueueProducers: () => ({ + queues: [ + { filePath: 'inbox.ts', name: 'inbox', bindingName: 'QUEUE_INBOX' }, + { filePath: 'dotenv.ts', name: 'dotenv', bindingName: 'QUEUE_DOTENV' }, + { filePath: 'reserved.ts', name: 'reserved', bindingName: 'QUEUE_RESERVED' }, + { filePath: 'two-names.ts', name: 'two-names', bindingName: 'QUEUE_TWO_NAMES' }, + { filePath: 'two_names.ts', name: 'two_names', bindingName: 'QUEUE_TWO_NAMES' }, + ], + reserved: ['QUEUE_RESERVED'], + }), }); const builder = await createBuilder({ root, @@ -492,26 +540,35 @@ export default { expect(existsSync(join(root, 'dist/ssr/index.js'))).toBe(true); expect(existsSync(join(root, 'dist/client/index.html'))).toBe(true); expect(existsSync(join(getWorkerAssetsDir(root), 'index.html'))).toBe(true); - expect(readFileSync(join(root, 'dist/ssr/wrangler.json'), 'utf8')).toContain( - '"main": "index.js"', - ); - writeFileSync(join(root, '.env'), 'PREVIEW_VALUE=local-preview-only'); - // Exercise the native plugin's Worker runtime as well as its build output. - const server = await preview({ - root, - configFile: false, - plugins: plugins(), - logLevel: 'silent', - server: { port: 0 }, - }); - try { - const response = await fetch(server.resolvedUrls!.local[0]); - expect(await response.text()).toBe('local-preview-only'); - expect((await readBuildOutput(root)).workers.default.config.env).not.toHaveProperty( - 'PREVIEW_VALUE', - ); - } finally { - await server.close(); + const files = [output.workers.default.configPath, join(root, 'dist/ssr/wrangler.json')]; + const buildConfigs = files.map((file) => readFileSync(file, 'utf8')); + expect(buildConfigs[1]).toContain('"main": "index.js"'); + expect(buildConfigs.every((text) => !text.includes('QUEUE_INBOX'))).toBe(true); + writeFileSync(join(root, '.env'), 'PREVIEW_VALUE=local-preview-only\nQUEUE_DOTENV=kept'); + // Framework prerendering opens preview while the build flag is set. + // Clear the flag for the second check to simulate a separate CLI invocation. + for (const building of [true, false]) { + vi.stubEnv('CLOUDFLARE_VITE_BUILD', building ? 'true' : undefined); + const server = await preview({ + root, + configFile: false, + plugins: plugins(), + logLevel: 'silent', + server: { port: 0 }, + }); + try { + const response = await fetch(server.resolvedUrls!.local[0]); + expect(await response.json()).toEqual({ + value: 'local-preview-only', + sent: !building, + dotenv: 'kept', + reserved: false, + collision: false, + }); + } finally { + await server.close(); + } + expect(files.map((file) => readFileSync(file, 'utf8'))).toEqual(buildConfigs); } }); }); diff --git a/packages/void/test/unit/cloudflare-deploy.test.ts b/packages/void/test/unit/cloudflare-deploy.test.ts index b61787c0f..608c210f4 100644 --- a/packages/void/test/unit/cloudflare-deploy.test.ts +++ b/packages/void/test/unit/cloudflare-deploy.test.ts @@ -7952,42 +7952,45 @@ describe('runCloudflareDeploy — framework artifact guard', () => { expect(trace).toContain('wrangler:deploy'); }); - it('persists framework queue bindings before building', async () => { - const root = makeProject({ - 'package.json': JSON.stringify({ - name: 'skapp', - dependencies: { '@sveltejs/kit': '2.0.0' }, - }), - 'void.json': JSON.stringify({}), - 'queues/email.ts': [ - 'export const maxBatchSize = 25;', - 'export const maxBatchTimeout = 10;', - 'export const maxConcurrency = 2;', - 'export const maxRetries = 4;', - 'export const retryDelay = 30;', - 'export default async function email() {}', - ].join('\n'), - 'wrangler.jsonc': JSON.stringify({ account_id: 'acc123', name: 'skapp' }, null, 2), - }); - const { deps } = harness(); - await runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps); + it.each(['@sveltejs/kit', '@tanstack/react-start'])( + 'persists framework queue bindings before building %s', + async (framework) => { + const root = makeProject({ + 'package.json': JSON.stringify({ + name: 'skapp', + dependencies: { [framework]: '2.0.0' }, + }), + 'void.json': JSON.stringify({}), + 'queues/email.ts': [ + 'export const maxBatchSize = 25;', + 'export const maxBatchTimeout = 10;', + 'export const maxConcurrency = 2;', + 'export const maxRetries = 4;', + 'export const retryDelay = 30;', + 'export default async function email() {}', + ].join('\n'), + 'wrangler.jsonc': JSON.stringify({ account_id: 'acc123', name: 'skapp' }, null, 2), + }); + const { deps } = harness(); + await runCloudflareDeploy(root, { platform: 'cloudflare' }, silentCliLog, deps); - expect(parseRootWranglerConfig(join(root, 'wrangler.jsonc'))).toMatchObject({ - queues: { - producers: [{ binding: 'QUEUE_EMAIL', queue: 'skapp-email' }], - consumers: [ - { - queue: 'skapp-email', - max_batch_size: 25, - max_batch_timeout: 10, - max_concurrency: 2, - max_retries: 4, - retry_delay: 30, - }, - ], - }, - }); - }); + expect(parseRootWranglerConfig(join(root, 'wrangler.jsonc'))).toMatchObject({ + queues: { + producers: [{ binding: 'QUEUE_EMAIL', queue: 'skapp-email' }], + consumers: [ + { + queue: 'skapp-email', + max_batch_size: 25, + max_batch_timeout: 10, + max_concurrency: 2, + max_retries: 4, + retry_delay: 30, + }, + ], + }, + }); + }, + ); it('clears removed framework concurrency from generated config and the lock before building', async () => { const root = makeProject({ diff --git a/packages/void/test/unit/plugin-cloudflare-config.test.ts b/packages/void/test/unit/plugin-cloudflare-config.test.ts new file mode 100644 index 000000000..020f01bec --- /dev/null +++ b/packages/void/test/unit/plugin-cloudflare-config.test.ts @@ -0,0 +1,26 @@ +import { afterEach, expect, it, vi } from 'vite-plus/test'; +import { addLocalQueueProducers } from '../../src/plugin-cloudflare-config.ts'; + +afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); + +it('warns once for an inferred binding shared by queue files', () => { + vi.stubEnv('CLOUDFLARE_VITE_BUILD', undefined); + const log = vi.spyOn(console, 'log').mockImplementation(() => {}); + const worker = { env: {} }; + const queues = [ + { filePath: 'a-b.ts', name: 'a-b', bindingName: 'QUEUE_A_B' }, + { filePath: 'a_b.ts', name: 'a_b', bindingName: 'QUEUE_A_B' }, + { filePath: 'inbox.ts', name: 'inbox', bindingName: 'QUEUE_INBOX' }, + ]; + + expect(addLocalQueueProducers(worker, () => ({ queues, reserved: [] }))).toEqual(['QUEUE_INBOX']); + expect(worker.env).toEqual({ QUEUE_INBOX: { type: 'queue', name: 'inbox' } }); + expect(log).toHaveBeenCalledExactlyOnceWith( + expect.stringContaining( + 'Queue files a-b.ts, a_b.ts share binding QUEUE_A_B. Void skips inference for this binding. Rename the conflicting files so each queue has a distinct binding.', + ), + ); +});