diff --git a/packages/void/src/cli/platform-installer-database.ts b/packages/void/src/cli/platform-installer-database.ts index 0fb3b653f..98af7e7f1 100644 --- a/packages/void/src/cli/platform-installer-database.ts +++ b/packages/void/src/cli/platform-installer-database.ts @@ -205,6 +205,14 @@ export function claimPlatformDatabase( }); } +/** The error a lifecycle-lock operation fails with once pg reported the held client closed. */ +function lostLockConnectionError(cause: Error): Error { + return new Error( + `platform: The PostgreSQL connection that holds the lifecycle lock was closed (${cause.message}). Rerun the command to continue.`, + { cause }, + ); +} + export async function acquirePlatformDatabaseLifecycleLock( databaseUrl: string, installationId: string, @@ -212,18 +220,48 @@ export async function acquirePlatformDatabaseLifecycleLock( ): Promise { const { Pool } = await import('pg'); const pool = new Pool({ connectionString: platformDatabaseClientUrl(databaseUrl), max: 1 }); + // pg emits 'error' on the pool for an idle client and on a checked-out client + // when the server drops its socket. Without listeners Node exits the process. + pool.on('error', () => {}); const client = await pool.connect(); + // The lock holds this client for the whole lifecycle command, which can stay + // idle for minutes while Workers deploy. Keep the first error and fail the + // next lock operation with it. + let lost: Error | undefined; + client.on('error', (error) => { + lost ??= error; + }); + const connection: QueryConnection = { + query: async >( + sql: string, + values?: ReadonlyArray, + ) => { + if (lost) { + throw lostLockConnectionError(lost); + } + try { + return await client.query(sql, values ? [...values] : undefined); + } catch (error) { + throw lost ? lostLockConnectionError(lost) : error; + } + }, + }; try { const releaseConnectionLock = await acquirePlatformDatabaseLifecycleLockConnection( - client, + connection, installationId, ownershipNonce, ); const release: PlatformDatabaseLifecycleLock = async () => { try { - await releaseConnectionLock(); + // The server ends a session advisory lock with its connection, so a + // lost connection has nothing left to unlock. + if (!lost) { + await releaseConnectionLock(); + } } finally { - client.release(); + // Passing the error destroys the broken client instead of pooling it. + client.release(lost); await pool.end(); } }; @@ -231,7 +269,7 @@ export async function acquirePlatformDatabaseLifecycleLock( // and verification hooks must not disappear at this wrapper boundary. return Object.assign(release, releaseConnectionLock); } catch (error) { - client.release(); + client.release(lost); await pool.end(); throw error; } diff --git a/packages/void/test/unit/platform-database-lock.test.ts b/packages/void/test/unit/platform-database-lock.test.ts index 0367dce08..63b0e7f58 100644 --- a/packages/void/test/unit/platform-database-lock.test.ts +++ b/packages/void/test/unit/platform-database-lock.test.ts @@ -29,7 +29,8 @@ beforeEach(async () => { return database.query(sql, values); }; return { - connect: async () => ({ query, release: () => {} }), + connect: async () => ({ query, on: () => {}, release: () => {} }), + on: () => {}, query, end: async () => {}, }; @@ -99,3 +100,58 @@ it('tells a reinstall on the same database to use a new empty database', async ( 'platform: This PostgreSQL database is already claimed by Void platform installation test-install. Uninstall keeps the database and its data, so use a dedicated empty database for each installation.', ); }, 30_000); + +it('turns a dropped lifecycle lock connection into a clear failure instead of a crash', async () => { + const url = 'postgresql://owner:pw@db.example.com/platform?sslmode=require'; + await claimPlatformDatabase(url, 'test-install', 'test-owner'); + const { EventEmitter } = await import('node:events'); + const pool = new EventEmitter(); + const client = new EventEmitter(); + let dropped = false; + const releases: Array = []; + const query = async (sql: string, values?: Array) => { + queries.push(sql); + if (dropped) { + throw new Error('Client has encountered a connection error and is not queryable'); + } + if (sql.includes('pg_try_advisory_lock')) { + return { rows: [{ acquired: true }] }; + } + return database.query(sql, values); + }; + mocks.pool.mockImplementation(function MockPool() { + return Object.assign(pool, { + connect: async () => + Object.assign(client, { + query, + release: (error?: unknown) => releases.push(error), + }), + end: async () => {}, + }); + }); + lock = await acquirePlatformDatabaseLifecycleLock(url, 'test-install', 'test-owner'); + const runtime = readPlatformRuntimeManifest(); + const directory = getPlatformRuntimeDirectory(); + await lock.prepareDatabase!(directory, runtime.database, null, false); + + // pg emits 'error' on a checked-out client when the server resets its socket, + // for example while the upgrade is deploying Workers and the client is idle. + const reset = Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' }); + dropped = true; + expect(() => client.emit('error', reset)).not.toThrow(); + // The pool reports idle client errors on itself. + expect(() => pool.emit('error', reset)).not.toThrow(); + + const lost = + 'platform: The PostgreSQL connection that holds the lifecycle lock was closed (read ECONNRESET). Rerun the command to continue.'; + await expect(lock.verifyDatabase!(directory, runtime.database)).rejects.toThrow(lost); + await expect(lock.readAdministratorSetup!()).rejects.toThrow(lost); + + // The server ends the session lock with the connection, so release only + // closes the broken client and the pool. + queries = []; + await expect(lock()).resolves.toBeUndefined(); + lock = undefined; + expect(queries).toEqual([]); + expect(releases).toEqual([reset]); +}, 30_000); diff --git a/packages/void/test/unit/platform-database-ssl.test.ts b/packages/void/test/unit/platform-database-ssl.test.ts index b29ca77bd..b534b3fca 100644 --- a/packages/void/test/unit/platform-database-ssl.test.ts +++ b/packages/void/test/unit/platform-database-ssl.test.ts @@ -20,6 +20,7 @@ beforeEach(() => { query: async () => { throw new Error('Stopped before network access.'); }, + on: () => {}, end: async () => {}, }; });