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
43 changes: 39 additions & 4 deletions packages/void/src/cli/platform-installer-database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,26 +211,61 @@ export async function acquirePlatformDatabaseLifecycleLock(
): Promise<PlatformDatabaseLifecycleLock> {
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 lostError = (cause: Error) =>
new Error(
`platform: The PostgreSQL connection that holds the lifecycle lock was closed (${cause.message}). Rerun the command to continue.`,
{ cause },
);
const connection: QueryConnection = {
query: async <Row extends Record<string, unknown>>(
sql: string,
values?: ReadonlyArray<unknown>,
) => {
if (lost) {
throw lostError(lost);
}
try {
return await client.query<Row>(sql, values ? [...values] : undefined);
} catch (error) {
throw lost ? lostError(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();
}
};
// Keep the complete session-lock contract when adding pool cleanup. Safety
// 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;
}
Expand Down
58 changes: 57 additions & 1 deletion packages/void/test/unit/platform-database-lock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ beforeEach(async () => {
return database.query(sql, values);
};
return {
connect: async () => ({ query, release: () => {} }),
connect: async () => ({ query, on: () => {}, release: () => {} }),
on: () => {},
query,
end: async () => {},
};
Expand Down Expand Up @@ -101,3 +102,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<unknown> = [];
const query = async (sql: string, values?: Array<unknown>) => {
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 () {
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);
1 change: 1 addition & 0 deletions packages/void/test/unit/platform-database-ssl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ beforeEach(() => {
query: async () => {
throw new Error('Stopped before network access.');
},
on: () => {},
end: async () => {},
};
});
Expand Down