Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/guide/database/d1.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ outline: deep

## Local Database

The dev server and local `void db` commands share the same database. If `cloudflare.d1_databases` in `void.config.ts` declares the D1 binding, Void uses its ID. A `preview_database_id` takes precedence during local development.
The dev server, local preview, and local `void db` commands share the same database. If you set a `preview_database_id` on a binding in `cloudflare.d1_databases`, Void uses it locally and keeps `database_id` for deployment. When using `CLOUDFLARE_ENV`, declare the D1 binding in that environment.

To store local data outside `.void`, set `voidPlugin({ persistTo: 'local-state' })` in your Vite config. Start the dev server once to record that directory before running database commands. After changing the Vite config, start it again to refresh it. Frameworks that manage their own Cloudflare runtime use `.wrangler/state`.

Expand Down
29 changes: 27 additions & 2 deletions packages/void/src/cli/cf-config-migrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,40 @@ function normalizeQueueConcurrency(raw: JsonObject) {
return result;
}

/**
* A deployment uses `database_id`. Void selects the local D1 database, including a
* `preview_database_id`, itself (see `local-d1.ts` and `applyLocalD1PreviewIds()`).
*/
function withoutD1PreviewIds(raw: JsonObject) {
if (!Array.isArray(raw.d1_databases)) {
return raw;
}
return {
...raw,
d1_databases: raw.d1_databases.map((value: unknown) => {
const database = record(value);
if (!database || !('preview_database_id' in database)) {
return value;
}
const { preview_database_id: _local, ...rest } = database;
return rest;
}),
};
}

function normalizeBindings(raw: JsonObject) {
return withoutD1PreviewIds(normalizeQueueConcurrency(raw));
}

/** Remove build-only fields and settings translated into cf's typed config below. */
function migrationInput(raw: JsonObject): JsonObject {
const result = normalizeQueueConcurrency(raw);
const result = normalizeBindings(raw);
const environments = record(result.env);
if (environments) {
result.env = Object.fromEntries(
Object.entries(environments).map(([name, value]) => [
name,
record(value) ? normalizeQueueConcurrency(value as JsonObject) : value,
record(value) ? normalizeBindings(value as JsonObject) : value,
]),
);
}
Expand Down
1 change: 1 addition & 0 deletions packages/void/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ export type CloudflareConfig = Record<string, unknown> & {
binding: string;
database_name?: string;
database_id?: string;
preview_database_id?: string;
migrations_dir?: string;
migrations_table?: string;
}>
Expand Down
50 changes: 35 additions & 15 deletions packages/void/src/local-d1.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createHash } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { isRecord } from '@void/deploy-core';
import { isAbsolute, join, resolve } from 'pathslash';
import { readRootWranglerConfig } from './cli/wrangler.ts';
import { getMiniflareDatabasePath } from './migrations/runner.ts';
Expand Down Expand Up @@ -28,22 +29,25 @@ export type LocalD1Target = {
databasePath: string;
};

function readConfiguredDatabaseId(root: string, bindingName: string): string | undefined {
let rootConfig: ReturnType<typeof readRootWranglerConfig>;
try {
rootConfig = readRootWranglerConfig(root);
} catch (error) {
throw new Error(`db: cannot read malformed Wrangler configuration in ${root}.`, {
cause: error,
});
}
if (!rootConfig) {
return undefined;
/** D1 bindings are not inherited by a named Wrangler environment. */
export function configuredD1Databases(
config: { env?: unknown; d1_databases?: unknown },
configPath: string,
options: { allowMissingEnvironment?: boolean } = {},
): Array<Record<string, unknown>> {
const environment = process.env.CLOUDFLARE_ENV;
let settings = config;
if (environment && isRecord(config.env)) {
const selected = config.env[environment];
if (isRecord(selected)) {
settings = selected;
} else if (!options.allowMissingEnvironment) {
throw new Error(`Cloudflare environment ${environment} is not configured.`);
}
}
const { configPath, config } = rootConfig;
const rawDatabases = config.d1_databases;
const rawDatabases = settings.d1_databases;
if (rawDatabases === undefined) {
return undefined;
return [];
}
if (!Array.isArray(rawDatabases)) {
throw new Error(`db: cannot read ${configPath}: "d1_databases" must be an array.`);
Expand All @@ -63,7 +67,23 @@ function readConfiguredDatabaseId(root: string, bindingName: string): string | u
);
}

const matches = (rawDatabases as Array<Record<string, unknown>>).filter(
return rawDatabases as Array<Record<string, unknown>>;
}

function readConfiguredDatabaseId(root: string, bindingName: string): string | undefined {
let rootConfig: ReturnType<typeof readRootWranglerConfig>;
try {
rootConfig = readRootWranglerConfig(root);
} catch (error) {
throw new Error(`db: cannot read malformed Wrangler configuration in ${root}.`, {
cause: error,
});
}
if (!rootConfig) {
return undefined;
}
const { configPath, config } = rootConfig;
const matches = configuredD1Databases(config, configPath).filter(
(entry) => entry.binding === bindingName,
);
if (matches.length > 1) {
Expand Down
56 changes: 36 additions & 20 deletions packages/void/src/plugin-cloudflare-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,20 @@ export function toNativeCloudflareConfig(
return { ...config, worker: config.worker };
}

export type D1PreviewIds = Array<[binding: string, id: string]>;

export function applyLocalD1PreviewIds(
worker: Pick<CloudflareConfig['worker'], 'env'>,
ids: D1PreviewIds,
): void {
for (const [name, id] of ids) {
const binding = worker.env?.[name];
if (binding?.type === 'd1') {
binding.id = id;
}
}
}

/**
* Give Container Durable Objects a regular binding in the dev server. Their unsafe
* binding from `migrateBuiltWranglerConfig()` exists only for the Worker upload, and
Expand Down Expand Up @@ -209,6 +223,10 @@ export function nativeAuxiliaryWorkers(
workers: Array<AuxiliaryWorkerConfig> | undefined,
root: string,
readLocalQueueBindings?: () => ReadonlyArray<string> | undefined,
d1?: {
configure: (worker: CloudflareConfig['worker'], settings: WorkerConfig) => void;
restoreEntryPreviewIds: (entryConfig: WorkerConfig) => void;
},
): PluginConfig['auxiliaryWorkers'] {
return workers?.map(({ configPath, config, ...options }) => ({
...options,
Expand All @@ -221,28 +239,26 @@ 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];
let patch: Partial<WorkerConfig> | void;
if (typeof config === 'function') {
let worker = entryWorkerConfig;
const localBindings = readLocalQueueBindings?.();
if (localBindings) {
const env = { ...worker.env };
for (const name of localBindings) {
delete env[name];
}
worker = { ...worker, env };
}
worker = { ...entryWorkerConfig, env };
const entry = convertToWranglerConfig({ worker, containers: [] });
d1?.restoreEntryPreviewIds(entry);
patch = config(base, { entryWorkerConfig: entry });
} else {
patch = config;
}
const patch =
typeof config === 'function'
? config(base, {
entryWorkerConfig: convertToWranglerConfig({
worker,
containers: [],
}),
})
: config;
const native = toNativeCloudflareConfig(
mergeCloudflareConfig(patch ?? {}, base),
path ? dirname(path) : root,
);
const settings = mergeCloudflareConfig(patch ?? {}, base);
const native = toNativeCloudflareConfig(settings, path ? dirname(path) : root);
d1?.configure(native.worker, settings);
return native.worker;
},
}));
Expand Down
32 changes: 28 additions & 4 deletions packages/void/src/plugin-cloudflare-preview.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { getRootConfigPath, getWorkerConfigPath } from '@cloudflare/build-output-utils';
import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import {
getRootConfigPath,
getWorkerConfigPath,
readBuildOutput,
} from '@cloudflare/build-output-utils';
import type { CloudflareConfig } from '@cloudflare/vite-plugin';
import { dirname, join } from 'pathslash';
import type { Plugin } from 'vite';
import { addLocalQueueProducers, restoreLocalD1Binding } from './plugin-cloudflare-config.ts';
import type { LocalQueueProducers } from './plugin-cloudflare-config.ts';
import {
addLocalQueueProducers,
applyLocalD1PreviewIds,
restoreLocalD1Binding,
} from './plugin-cloudflare-config.ts';
import type { D1PreviewIds, LocalQueueProducers } from './plugin-cloudflare-config.ts';
import { writeFileAtomic } from './shared/atomic-write.ts';
import { loadLocalEnv } from './shared/env.ts';

export const D1_PREVIEW_FILE = 'void-d1-preview.json';

/** Give preview local bindings without changing the deployable build or storing their values. */
export function withLocalPreviewBindings(
plugins: Array<Plugin>,
Expand Down Expand Up @@ -42,6 +52,20 @@ export function withLocalPreviewBindings(
try {
const output = dirname(getRootConfigPath(root));
cpSync(output, dirname(getRootConfigPath(directory)), { recursive: true });
const d1Overrides = join(output, D1_PREVIEW_FILE);
if (existsSync(d1Overrides)) {
const ids = new Map(
JSON.parse(readFileSync(d1Overrides, 'utf8')) as Array<[string, D1PreviewIds]>,
);
const { workers } = await readBuildOutput(directory);
for (const { config, configPath } of Object.values(workers)) {
const overrides = config.name && ids.get(config.name);
if (overrides) {
applyLocalD1PreviewIds(config, overrides);
writeFileAtomic(configPath, JSON.stringify(config));
}
}
}
const path = getWorkerConfigPath(directory);
const worker = JSON.parse(readFileSync(path, 'utf8')) as Pick<
CloudflareConfig['worker'],
Expand Down
52 changes: 51 additions & 1 deletion packages/void/src/plugin-cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ 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 { configuredD1Databases } from './local-d1.ts';
import { voidWarn } from './log.ts';
import {
addLocalQueueProducers,
Expand All @@ -18,13 +19,15 @@ import {
restoreLocalContainerBindings,
restoreLocalD1Binding,
toNativeCloudflareConfig,
applyLocalD1PreviewIds,
} from './plugin-cloudflare-config.ts';
import type {
AuxiliaryWorkerConfig,
LocalQueueProducers,
WorkerConfig,
} from './plugin-cloudflare-config.ts';
import { withLocalPreviewBindings } from './plugin-cloudflare-preview.ts';
import type { D1PreviewIds } from './plugin-cloudflare-config.ts';
import { D1_PREVIEW_FILE, withLocalPreviewBindings } from './plugin-cloudflare-preview.ts';
import { isVitestServer } from './plugin-dev-config.ts';
import { writeFileAtomic } from './shared/atomic-write.ts';
import { CLOUDFLARE_DEPLOY_BUILD_ENV } from './shared/env.ts';
Expand Down Expand Up @@ -73,10 +76,34 @@ export function cloudflare(options: {
let pluginNative: ReturnType<typeof toNativeCloudflareConfig>;
let localQueueBindings: Array<string> | undefined;
let localQueueWarnings: Array<string> | undefined;
const previewIdsByWorker = new Map<string, D1PreviewIds>();
let serving = false;
function configureD1(worker: typeof native.worker, settings: WorkerConfig) {
const ids: D1PreviewIds = [];
for (const { binding, preview_database_id } of configuredD1Databases(settings, root, {
allowMissingEnvironment: true,
})) {
if (
typeof binding === 'string' &&
typeof preview_database_id === 'string' &&
preview_database_id
) {
ids.push([binding, preview_database_id]);
}
}
if (ids.length) {
previewIdsByWorker.set(worker.name, ids);
if (serving) {
applyLocalD1PreviewIds(worker, ids);
}
}
}
const outputDirectories = new Map<string, string>();
const bridge: Plugin = {
name: 'void:cloudflare-config',
config(_userConfig, environment) {
serving = environment.command === 'serve';
previewIdsByWorker.clear();
localQueueBindings = undefined;
localQueueWarnings = undefined;
if (environment.isPreview) {
Expand All @@ -85,6 +112,7 @@ export function cloudflare(options: {
let base = (
options.configPath ? readGeneratedWranglerConfigFile(options.configPath) : {}
) as WorkerConfig;
const raw = base;
if (process.env.CLOUDFLARE_ENV && base.env) {
const selected = base.env[process.env.CLOUDFLARE_ENV];
if (!selected) {
Expand All @@ -104,6 +132,7 @@ export function cloudflare(options: {
workerConfig = mergeCloudflareConfig(options.config(base), base);
native = toNativeCloudflareConfig(workerConfig, root, environment.command);
pluginNative = structuredClone(native);
configureD1(pluginNative.worker, process.env.CLOUDFLARE_ENV && raw.env ? raw : workerConfig);
if (environment.command === 'build' && (native.containers?.length ?? 0) > 0) {
// Void builds images during deployment preparation. Managed builds consume
// the Worker bundle and must not acquire a local Docker prerequisite.
Expand Down Expand Up @@ -175,6 +204,12 @@ export function cloudflare(options: {
mkdirSync(getWorkerAssetsDir(root), { recursive: true });
}
const built = await readBuildOutput(root);
if (previewIdsByWorker.size) {
writeFileAtomic(
join(dirname(getRootConfigPath(root)), D1_PREVIEW_FILE),
JSON.stringify([...previewIdsByWorker]),
);
}
const worker = built.workers.default;
const environment = options.viteEnvironment.name ?? 'ssr';
const destination = outputDirectories.get(environment);
Expand Down Expand Up @@ -298,6 +333,21 @@ export function cloudflare(options: {
options.auxiliaryWorkers,
root,
() => localQueueBindings,
{
configure: configureD1,
restoreEntryPreviewIds(entryConfig) {
// Auxiliary callbacks may forward the entry's D1 declaration. Keep
// both IDs without replacing unrelated bindings' local defaults.
for (const [name, id] of previewIdsByWorker.get(native.worker.name) ?? []) {
const entry = entryConfig.d1_databases?.find((db) => db.binding === name);
const deployed = native.worker.env?.[name];
if (entry && deployed?.type === 'd1') {
entry.database_id = deployed.id;
entry.preview_database_id = id;
}
}
},
},
),
types: { generate: false },
config() {
Expand Down
Loading