Skip to content
Open
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/platform/installation/prerequisites.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ Use any PostgreSQL provider that accepts connections from your computer and Clou
| [PlanetScale Postgres](https://planetscale.com/docs/postgres/connecting) | Choose **Postgres**, not Vitess/MySQL. Open **Connect**, create role credentials, and use the direct primary connection on port `5432`, not PgBouncer on `6432`. |
| [Neon](https://neon.com/docs/get-started-with-neon/connect-neon) | Open **Connect**, select the database and owner role, and turn **connection pooling off**. |

When sizing your database, include the connection pools for every platform installation and application sharing that server. Adjust each Hyperdrive's [origin connection limit](https://developers.cloudflare.com/hyperdrive/configuration/tune-connection-pool/) to fit the server's capacity, leaving room for migrations, administration, provider-reserved connections, and temporary bursts.
When sizing your database, include the connection pools for every platform installation and application sharing that server. Install, repair, and upgrade lower the [origin connection limit](https://developers.cloudflare.com/hyperdrive/configuration/tune-connection-pool/) of the Hyperdrive Void creates so it stays five connections below what the server accepts (`max_connections` minus reserved slots), leaving room for migrations and administration. If other installations or applications share the server, or you use a separately managed Hyperdrive, adjust each Hyperdrive's limit yourself to fit the server's capacity, including provider-reserved connections and temporary bursts. Void warns when a separately managed Hyperdrive leaves fewer than five connections free.

Once installation claims the database, continue using that same database for resume and maintenance commands. If installation stops because it cannot use the database, for example because the database is not empty, set `VOID_PLATFORM_DATABASE_URL` to another database's URL before you resume. Uninstall never deletes external PostgreSQL.

Expand Down
26 changes: 25 additions & 1 deletion packages/void/src/cli/platform-cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,12 @@ export type CloudflareHyperdriveOrigin =
| CloudflareHyperdriveHostOrigin
| (CloudflareHyperdriveDatabase & Readonly<{ serviceId: string; host?: never }>);
export type CloudflareHyperdriveConfig = CloudflareNamedResource &
Readonly<{ origin: CloudflareHyperdriveOrigin; cachingDisabled?: boolean }>;
Readonly<{
origin: CloudflareHyperdriveOrigin;
cachingDisabled?: boolean;
/** The soft cap on connections Hyperdrive opens to the origin, when Cloudflare reports one. */
originConnectionLimit?: number;
}>;
export type CloudflareDnsRecord = CloudflareNamedResource &
Readonly<{
content: string;
Expand Down Expand Up @@ -1054,6 +1059,20 @@ export class PlatformCloudflareClient {
);
}

async setHyperdriveOriginConnectionLimit(
accountId: string,
id: string,
limit: number,
): Promise<void> {
await this.request(
`/accounts/${encodeURIComponent(accountId)}/hyperdrive/configs/${encodeURIComponent(id)}`,
{
method: 'PATCH',
body: JSON.stringify({ origin_connection_limit: limit }),
},
);
}

async putKvValue(
accountId: string,
namespaceId: string,
Expand Down Expand Up @@ -1920,5 +1939,10 @@ function parseHyperdriveConfig(value: Record<string, unknown>): CloudflareHyperd
!Array.isArray(value.caching) &&
(value.caching as Record<string, unknown>).disabled === true,
origin: parsedOrigin,
...(typeof value.origin_connection_limit === 'number' &&
Number.isInteger(value.origin_connection_limit) &&
value.origin_connection_limit > 0
? { originConnectionLimit: value.origin_connection_limit }
: {}),
};
}
53 changes: 53 additions & 0 deletions packages/void/src/cli/platform-hyperdrive-connections.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import type { InstallationResource } from '@void/platform';
import type { PlatformCloudflareClient } from './platform-cloudflare.ts';

/** Slots kept free for operators, migrations, and other direct database clients. */
export const PLATFORM_DIRECT_CONNECTION_RESERVE = 5;
/** Cloudflare does not accept an origin connection limit below this. */
const HYPERDRIVE_MIN_ORIGIN_CONNECTIONS = 5;

/** The Hyperdrive origin limit that leaves the direct-connection reserve free. */
export function platformHyperdriveConnectionLimit(connectionSlots: number): number {
return Math.max(
HYPERDRIVE_MIN_ORIGIN_CONNECTIONS,
connectionSlots - PLATFORM_DIRECT_CONNECTION_RESERVE,
);
}

/**
* Hyperdrive's default origin limit can exceed what a small database accepts. Once the
* pool fills every slot, direct connections (upgrade, repair, `psql`) fail with 53300.
* Lower the limit on the Hyperdrive this installation created; only warn for an adopted one,
* which its owner manages. Never raise a limit, so the value stays within the account plan.
*/
export async function fitPlatformHyperdriveToDatabase(input: {
readonly client: Pick<
PlatformCloudflareClient,
'getHyperdriveConfig' | 'setHyperdriveOriginConnectionLimit'
>;
readonly accountId: string;
readonly resource: InstallationResource;
readonly readConnectionSlots: (() => Promise<number>) | undefined;
readonly onProgress?: (message: string) => void;
}): Promise<void> {
const { client, accountId, resource, readConnectionSlots, onProgress } = input;
if (!readConnectionSlots || resource.kind !== 'hyperdrive') {
return;
}
const connectionSlots = await readConnectionSlots();
const limit = platformHyperdriveConnectionLimit(connectionSlots);
const current = (await client.getHyperdriveConfig(accountId, resource.id)).originConnectionLimit;
if (current === undefined || current <= limit) {
return;
}
if (resource.ownership !== 'created') {
onProgress?.(
`Warning: Hyperdrive ${resource.name} may open ${current} database connections, but the database accepts ${connectionSlots}. Set its origin connection limit to ${limit} or lower so upgrades and other direct connections can still connect.`,
);
return;
}
onProgress?.(
`Lowering the Hyperdrive origin connection limit from ${current} to ${limit} to fit the database's ${connectionSlots} connections`,
);
await client.setHyperdriveOriginConnectionLimit(accountId, resource.id, limit);
}
8 changes: 8 additions & 0 deletions packages/void/src/cli/platform-install-provisioning.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { PlatformRuntimeManifest } from '@void/platform/installer';
import { join } from 'pathslash';
import { publishInstallationAiLogging } from './platform-ai-logging-projection.ts';
import { verifyPlatformAuthenticationDatabase } from './platform-auth-database.ts';
import { fitPlatformHyperdriveToDatabase } from './platform-hyperdrive-connections.ts';
import { preparePlatformDatabaseSchema } from './platform-installer-database.ts';
import {
requireId,
Expand Down Expand Up @@ -173,6 +174,13 @@ export async function provisionInstallationServices(input: {
authenticationDatabase,
secrets.databaseUrl,
);
await fitPlatformHyperdriveToDatabase({
client: dependencies.client,
accountId: plan.account.id,
resource: authenticationDatabase,
readConnectionSlots: releaseDatabaseLock.readConnectionSlots,
onProgress: dependencies.onProgress,
});

state.manifest = await preparePlatformDatabaseSchema(
state.manifest,
Expand Down
20 changes: 20 additions & 0 deletions packages/void/src/cli/platform-installer-database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,25 @@ type PlatformDatabaseMigrationRow = Readonly<{
id: unknown;
}>;

/**
* Connections the server accepts from roles without SUPERUSER. PostgreSQL 16 added
* reserved_connections; older servers report it as missing, which counts as zero.
*/
export async function readPlatformDatabaseConnectionSlotsConnection(
client: QueryConnection,
): Promise<number> {
const result = await client.query<{ max: number; superuser: number; reserved: number }>(
`SELECT current_setting('max_connections')::int AS "max",
current_setting('superuser_reserved_connections')::int AS "superuser",
COALESCE(current_setting('reserved_connections', true), '0')::int AS "reserved"`,
);
const row = result.rows[0];
if (!row || ![row.max, row.superuser, row.reserved].every(Number.isInteger)) {
throw new Error('platform: Could not read the PostgreSQL connection limit.');
}
return Math.max(0, row.max - row.superuser - row.reserved);
}

export async function inspectPlatformDatabaseStateConnection(
client: QueryConnection,
database: PlatformRuntimeDatabaseManifest,
Expand Down Expand Up @@ -628,6 +647,7 @@ export async function acquirePlatformDatabaseLifecycleLockConnection(
release.readAdministratorSetup = () => readPlatformAdministratorSetupConnection(client);
release.readProjectZeroTrust = () => readPlatformProjectZeroTrustStateConnection(client);
release.readProjects = () => readPlatformProjectSlugsConnection(client);
release.readConnectionSlots = () => readPlatformDatabaseConnectionSlotsConnection(client);
release.publishAiLogging = (kv, onProgress) =>
projectPlatformAiLoggingConnection(client, kv, { onProgress });
release.lockProjectZeroTrust = () => lockPlatformProjectZeroTrustConnection(client);
Expand Down
7 changes: 7 additions & 0 deletions packages/void/src/cli/platform-installer-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@ export type PlatformDatabaseLifecycleLock = (() => Promise<void>) & {
kv: AiLoggingProjectionKv,
onProgress?: (message: string) => void,
) => Promise<AiLoggingProjectionResult>;
/**
* Connections the database accepts from roles without SUPERUSER:
* max_connections minus the reserved slots. Missing on test locks, which then skip
* fitting the Hyperdrive origin connection limit to the database.
*/
readConnectionSlots?: () => Promise<number>;
/** Project slugs, which --purge-resources requires to be empty. */
readProjects?: () => Promise<ReadonlyArray<string>>;
/** Block Zero Trust writers in the API until the returned release runs. */
Expand Down Expand Up @@ -204,6 +210,7 @@ export type InstallerClient = Pick<
| 'createHyperdrive'
| 'getHyperdriveConfig'
| 'disableHyperdriveCaching'
| 'setHyperdriveOriginConnectionLimit'
| 'createKvNamespace'
| 'createQueue'
| 'createR2Bucket'
Expand Down
36 changes: 36 additions & 0 deletions packages/void/test/unit/platform-cloudflare.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,42 @@ describe('platform Cloudflare client', () => {
expect(JSON.stringify(config)).not.toContain('secret');
});

it('reads and lowers the Hyperdrive origin connection limit', async () => {
const requests: Array<{ method: string; body: unknown }> = [];
const client = new PlatformCloudflareClient('token', {
fetcher: async (_input, init) => {
requests.push({
method: init?.method ?? 'GET',
body: init?.body ? JSON.parse(String(init.body)) : undefined,
});
return Response.json({
success: true,
result: {
id: 'hyperdrive-id',
name: 'void-db',
caching: { disabled: true },
origin_connection_limit: 60,
origin: {
database: 'void',
host: 'db.example.com',
port: 5432,
scheme: 'postgres',
user: 'void-user',
},
},
});
},
});

const config = await client.getHyperdriveConfig('account', 'hyperdrive-id');
expect(config.originConnectionLimit).toBe(60);
await client.setHyperdriveOriginConnectionLimit('account', 'hyperdrive-id', 17);
expect(requests).toEqual([
{ method: 'GET', body: undefined },
{ method: 'PATCH', body: { origin_connection_limit: 17 } },
]);
});

it('reads a Workers VPC origin without a hostname or port', async () => {
const client = new PlatformCloudflareClient('token', {
fetcher: async () =>
Expand Down
14 changes: 14 additions & 0 deletions packages/void/test/unit/platform-database-lock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,20 @@ it('preserves every database lifecycle capability through the pool wrapper on in
await expect(lock.verifyDatabase!(directory, runtime.database)).resolves.toBeUndefined();
}, 30_000);

it('reads the connection slots left for roles without SUPERUSER', async () => {
const url = 'postgresql://owner:pw@db.example.com/platform?sslmode=require';
await claimPlatformDatabase(url, 'test-install', 'test-owner');
lock = await acquirePlatformDatabaseLifecycleLock(url, 'test-install', 'test-owner');
const settings = await database.query<{ max: number; superuser: number; reserved: number }>(
`SELECT current_setting('max_connections')::int AS "max",
current_setting('superuser_reserved_connections')::int AS "superuser",
COALESCE(current_setting('reserved_connections', true), '0')::int AS "reserved"`,
);
const { max, superuser, reserved } = settings.rows[0]!;
expect(max).toBeGreaterThan(superuser + reserved);
await expect(lock.readConnectionSlots!()).resolves.toBe(max - superuser - reserved);
}, 30_000);

it('refuses leftover migration history before claiming and still resumes its own claim', async () => {
const url = 'postgresql://owner:pw@db.example.com/platform?sslmode=require';
await database.exec(`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ it.each([1, 0])(
createHyperdrive: provision,
getHyperdriveConfig: provision,
disableHyperdriveCaching: provision,
setHyperdriveOriginConnectionLimit: provision,
createKvNamespace: provision,
createQueue: provision,
createR2Bucket: provision,
Expand Down
108 changes: 108 additions & 0 deletions packages/void/test/unit/platform-hyperdrive-connections.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import type { InstallationResource } from '@void/platform';
import { describe, expect, it, vi } from 'vite-plus/test';
import { hyperdriveOriginFromConnectionString } from '../../src/cli/platform-cloudflare.ts';
import {
fitPlatformHyperdriveToDatabase,
platformHyperdriveConnectionLimit,
} from '../../src/cli/platform-hyperdrive-connections.ts';

const resource: InstallationResource = {
key: 'hyperdrive',
kind: 'hyperdrive',
id: 'database',
name: 'void-platform-db',
ownership: 'created',
state: 'ready',
configHash: 'hash',
};

function fakeClient(originConnectionLimit: number | undefined) {
return {
getHyperdriveConfig: vi.fn(async () => ({
id: resource.id,
name: resource.name,
cachingDisabled: true,
origin: hyperdriveOriginFromConnectionString('postgresql://user:pw@db.example.com/platform'),
...(originConnectionLimit === undefined ? {} : { originConnectionLimit }),
})),
setHyperdriveOriginConnectionLimit: vi.fn(async () => {}),
};
}

describe('Hyperdrive origin connection limit', () => {
it('keeps five slots for direct connections and never goes below the Hyperdrive minimum', () => {
expect(platformHyperdriveConnectionLimit(22)).toBe(17);
expect(platformHyperdriveConnectionLimit(97)).toBe(92);
expect(platformHyperdriveConnectionLimit(8)).toBe(5);
expect(platformHyperdriveConnectionLimit(0)).toBe(5);
});

it('lowers the default limit of a Hyperdrive Void created to fit a small database', async () => {
// max_connections=25 with 3 superuser slots: the live e2e install had a limit of 60.
const client = fakeClient(60);
const onProgress = vi.fn();
await fitPlatformHyperdriveToDatabase({
client,
accountId: 'account',
resource,
readConnectionSlots: async () => 22,
onProgress,
});
expect(client.setHyperdriveOriginConnectionLimit).toHaveBeenCalledExactlyOnceWith(
'account',
'database',
17,
);
expect(onProgress).toHaveBeenCalledWith(expect.stringContaining('from 60 to 17'));
});

it.each([17, 10])('keeps a limit of %s that already fits', async (limit) => {
const client = fakeClient(limit);
await fitPlatformHyperdriveToDatabase({
client,
accountId: 'account',
resource,
readConnectionSlots: async () => 22,
});
expect(client.setHyperdriveOriginConnectionLimit).not.toHaveBeenCalled();
});

it('never raises a limit or writes one Cloudflare did not report', async () => {
const client = fakeClient(undefined);
await fitPlatformHyperdriveToDatabase({
client,
accountId: 'account',
resource,
readConnectionSlots: async () => 22,
});
expect(client.setHyperdriveOriginConnectionLimit).not.toHaveBeenCalled();
});

it('only warns about an adopted Hyperdrive, which its owner manages', async () => {
const client = fakeClient(60);
const onProgress = vi.fn();
await fitPlatformHyperdriveToDatabase({
client,
accountId: 'account',
resource: { ...resource, ownership: 'adopted' },
readConnectionSlots: async () => 22,
onProgress,
});
expect(client.setHyperdriveOriginConnectionLimit).not.toHaveBeenCalled();
expect(onProgress).toHaveBeenCalledExactlyOnceWith(
expect.stringContaining('Set its origin connection limit to 17 or lower'),
);
});

it('skips the check when the database lock cannot read connection slots', async () => {
const client = fakeClient(60);
await fitPlatformHyperdriveToDatabase({
client,
accountId: 'account',
resource,
readConnectionSlots: undefined,
});
expect(client.getHyperdriveConfig).not.toHaveBeenCalled();
expect(client.setHyperdriveOriginConnectionLimit).not.toHaveBeenCalled();
});
});
1 change: 1 addition & 0 deletions packages/void/test/unit/platform-install-cutover.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,7 @@ async function createFakeCloudflare() {
kv.delete(`${namespace}/${key}`);
},
disableHyperdriveCaching: async () => {},
setHyperdriveOriginConnectionLimit: async () => {},
getHyperdriveConfig: async (_account: string, id: string) => ({
cachingDisabled: true,
id,
Expand Down
6 changes: 5 additions & 1 deletion packages/void/test/unit/platform-installer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,8 @@ type DefaultedClientMethods =
| 'publishWorkerCustomDomainsSafely'
| 'publishWorkerRoutesSafely'
| 'putKvBulk'
| 'request';
| 'request'
| 'setHyperdriveOriginConnectionLimit';
type TestInstallerDependencies = Omit<InstallArguments[3], 'client'> & {
client: Omit<InstallClient, DefaultedClientMethods> &
Partial<Pick<InstallClient, DefaultedClientMethods>>;
Expand Down Expand Up @@ -162,6 +163,9 @@ function installPlatform(
publishWorkerRoutesSafely: unexpectedCloudflareCall('publishWorkerRoutesSafely'),
putKvBulk: unexpectedCloudflareCall('putKvBulk'),
request: unexpectedCloudflareCall('request'),
setHyperdriveOriginConnectionLimit: unexpectedCloudflareCall(
'setHyperdriveOriginConnectionLimit',
),
...dependencies.client,
getHyperdriveConfig:
dependencies.client.getHyperdriveConfig ??
Expand Down
Loading