diff --git a/docs/guide/platform/installation/prerequisites.md b/docs/guide/platform/installation/prerequisites.md index 6e972236f..78f0b6033 100644 --- a/docs/guide/platform/installation/prerequisites.md +++ b/docs/guide/platform/installation/prerequisites.md @@ -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. diff --git a/packages/void/src/cli/platform-cloudflare.ts b/packages/void/src/cli/platform-cloudflare.ts index 56108ed72..bc2864a8f 100644 --- a/packages/void/src/cli/platform-cloudflare.ts +++ b/packages/void/src/cli/platform-cloudflare.ts @@ -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; @@ -1054,6 +1059,20 @@ export class PlatformCloudflareClient { ); } + async setHyperdriveOriginConnectionLimit( + accountId: string, + id: string, + limit: number, + ): Promise { + 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, @@ -1920,5 +1939,10 @@ function parseHyperdriveConfig(value: Record): CloudflareHyperd !Array.isArray(value.caching) && (value.caching as Record).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 } + : {}), }; } diff --git a/packages/void/src/cli/platform-hyperdrive-connections.ts b/packages/void/src/cli/platform-hyperdrive-connections.ts new file mode 100644 index 000000000..fd078068b --- /dev/null +++ b/packages/void/src/cli/platform-hyperdrive-connections.ts @@ -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) | undefined; + readonly onProgress?: (message: string) => void; +}): Promise { + 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); +} diff --git a/packages/void/src/cli/platform-install-provisioning.ts b/packages/void/src/cli/platform-install-provisioning.ts index 386778316..5387960f4 100644 --- a/packages/void/src/cli/platform-install-provisioning.ts +++ b/packages/void/src/cli/platform-install-provisioning.ts @@ -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, @@ -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, diff --git a/packages/void/src/cli/platform-installer-database.ts b/packages/void/src/cli/platform-installer-database.ts index 09846d92b..6012ab7ba 100644 --- a/packages/void/src/cli/platform-installer-database.ts +++ b/packages/void/src/cli/platform-installer-database.ts @@ -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 { + 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, @@ -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); diff --git a/packages/void/src/cli/platform-installer-types.ts b/packages/void/src/cli/platform-installer-types.ts index 46a4be4ea..00e2c363a 100644 --- a/packages/void/src/cli/platform-installer-types.ts +++ b/packages/void/src/cli/platform-installer-types.ts @@ -137,6 +137,12 @@ export type PlatformDatabaseLifecycleLock = (() => Promise) & { kv: AiLoggingProjectionKv, onProgress?: (message: string) => void, ) => Promise; + /** + * 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; /** Project slugs, which --purge-resources requires to be empty. */ readProjects?: () => Promise>; /** Block Zero Trust writers in the API until the returned release runs. */ @@ -204,6 +210,7 @@ export type InstallerClient = Pick< | 'createHyperdrive' | 'getHyperdriveConfig' | 'disableHyperdriveCaching' + | 'setHyperdriveOriginConnectionLimit' | 'createKvNamespace' | 'createQueue' | 'createR2Bucket' diff --git a/packages/void/test/unit/platform-cloudflare.test.ts b/packages/void/test/unit/platform-cloudflare.test.ts index 86dd5033d..942cea1d9 100644 --- a/packages/void/test/unit/platform-cloudflare.test.ts +++ b/packages/void/test/unit/platform-cloudflare.test.ts @@ -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 () => diff --git a/packages/void/test/unit/platform-database-lock.test.ts b/packages/void/test/unit/platform-database-lock.test.ts index 70a237501..4dbe1d92e 100644 --- a/packages/void/test/unit/platform-database-lock.test.ts +++ b/packages/void/test/unit/platform-database-lock.test.ts @@ -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(` diff --git a/packages/void/test/unit/platform-deployment-execution.test.ts b/packages/void/test/unit/platform-deployment-execution.test.ts index 89b30d2fd..a05886126 100644 --- a/packages/void/test/unit/platform-deployment-execution.test.ts +++ b/packages/void/test/unit/platform-deployment-execution.test.ts @@ -181,6 +181,7 @@ it.each([1, 0])( createHyperdrive: provision, getHyperdriveConfig: provision, disableHyperdriveCaching: provision, + setHyperdriveOriginConnectionLimit: provision, createKvNamespace: provision, createQueue: provision, createR2Bucket: provision, diff --git a/packages/void/test/unit/platform-hyperdrive-connections.test.ts b/packages/void/test/unit/platform-hyperdrive-connections.test.ts new file mode 100644 index 000000000..be1530823 --- /dev/null +++ b/packages/void/test/unit/platform-hyperdrive-connections.test.ts @@ -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(); + }); +}); diff --git a/packages/void/test/unit/platform-install-cutover.test.ts b/packages/void/test/unit/platform-install-cutover.test.ts index 5775a7b70..93c64d71a 100644 --- a/packages/void/test/unit/platform-install-cutover.test.ts +++ b/packages/void/test/unit/platform-install-cutover.test.ts @@ -263,6 +263,7 @@ async function createFakeCloudflare() { kv.delete(`${namespace}/${key}`); }, disableHyperdriveCaching: async () => {}, + setHyperdriveOriginConnectionLimit: async () => {}, getHyperdriveConfig: async (_account: string, id: string) => ({ cachingDisabled: true, id, diff --git a/packages/void/test/unit/platform-installer.test.ts b/packages/void/test/unit/platform-installer.test.ts index 639e00fa7..0721f7e1a 100644 --- a/packages/void/test/unit/platform-installer.test.ts +++ b/packages/void/test/unit/platform-installer.test.ts @@ -124,7 +124,8 @@ type DefaultedClientMethods = | 'publishWorkerCustomDomainsSafely' | 'publishWorkerRoutesSafely' | 'putKvBulk' - | 'request'; + | 'request' + | 'setHyperdriveOriginConnectionLimit'; type TestInstallerDependencies = Omit & { client: Omit & Partial>; @@ -162,6 +163,9 @@ function installPlatform( publishWorkerRoutesSafely: unexpectedCloudflareCall('publishWorkerRoutesSafely'), putKvBulk: unexpectedCloudflareCall('putKvBulk'), request: unexpectedCloudflareCall('request'), + setHyperdriveOriginConnectionLimit: unexpectedCloudflareCall( + 'setHyperdriveOriginConnectionLimit', + ), ...dependencies.client, getHyperdriveConfig: dependencies.client.getHyperdriveConfig ??