diff --git a/packages/db/package.json b/packages/db/package.json index e3e339150..4346868da 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -23,7 +23,7 @@ "db:migrate": "prisma migrate dev", "db:deploy": "prisma migrate deploy", "db:status": "prisma migrate status", - "test:integration": "node --test test/database.test.mjs test/report.test.mjs test/training.test.mjs test/reportReliabilityMigration.test.mjs", + "test:integration": "node --test test/connection-retry.test.mjs test/database.test.mjs test/report.test.mjs test/training.test.mjs test/reportReliabilityMigration.test.mjs", "test:practice-migration": "node --test test/practiceScheduleMigration.test.mjs" }, "engines": { diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index f07f76a17..e6e751515 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -1,5 +1,5 @@ import "dotenv/config"; -import { PrismaPg } from "@prisma/adapter-pg"; +import { ConnectionRetryAdapter } from "./connection-retry.js"; import { PrismaClient } from "./generated/prisma/client.js"; export function createDb(connectionString = process.env.DATABASE_URL) { @@ -9,7 +9,7 @@ export function createDb(connectionString = process.env.DATABASE_URL) { throw new Error("DATABASE_URL must be a PostgreSQL connection URL"); } - const adapter = new PrismaPg({ + const adapter = new ConnectionRetryAdapter({ connectionString, max: 10, connectionTimeoutMillis: 5_000, diff --git a/packages/db/src/connection-retry.ts b/packages/db/src/connection-retry.ts new file mode 100644 index 000000000..3ae8d321d --- /dev/null +++ b/packages/db/src/connection-retry.ts @@ -0,0 +1,92 @@ +import { Pool } from "pg"; +import type { PoolConfig } from "pg"; +import { PrismaPg } from "@prisma/adapter-pg"; + +const transientConnectionCodes = new Set([ + "ETIMEDOUT", + "ECONNRESET", + "ECONNREFUSED", + "EAI_AGAIN", + "57P03", +]); + +/** Only acquire a connection again: never replay a statement or transaction. */ +export async function acquireConnection( + connect: () => Promise, + wait: (ms: number) => Promise = (ms) => + new Promise((resolve) => setTimeout(resolve, ms)), +) { + const delays = [250, 750]; + for (let attempt = 0; ; attempt++) { + try { + return await connect(); + } catch (error) { + let cause = error; + let code = ""; + for ( + let depth = 0; + depth < 4 && cause && typeof cause === "object"; + depth++ + ) { + if ( + cause instanceof Error && + [ + "Connection terminated due to connection timeout", + "timeout exceeded when trying to connect", + ].includes(cause.message) + ) { + code = "ETIMEDOUT"; + break; + } + if ( + "code" in cause && + transientConnectionCodes.has(String(cause.code)) + ) { + code = String(cause.code); + break; + } + cause = "cause" in cause ? cause.cause : undefined; + } + const delay = delays[attempt]; + if (delay === undefined || !transientConnectionCodes.has(code)) + throw error; + console.info( + JSON.stringify({ + event: "database.connection_retry", + code, + attempt: attempt + 1, + delayMs: delay, + }), + ); + await wait(delay); + } + } +} + +function createRetryPool(config: PoolConfig) { + const pool = new Pool(config); + const connect = pool.connect.bind(pool); + type Callback = Parameters[0]; + pool.connect = ((callback?: Callback) => { + const pending = acquireConnection(() => connect()); + if (!callback) return pending; + void pending.then( + (client) => callback(undefined, client, client.release.bind(client)), + (error: Error) => callback(error, undefined, () => {}), + ); + }) as Pool["connect"]; + return pool; +} + +/** Create a fresh owned pool on reconnect, including after a batch disconnect. */ +export class ConnectionRetryAdapter extends PrismaPg { + constructor(private readonly poolConfig: PoolConfig) { + super(poolConfig); + } + + override connect(): ReturnType { + return new PrismaPg(createRetryPool(this.poolConfig), { + disposeExternalPool: true, + }).connect(); + } +} diff --git a/packages/db/test/connection-retry.test.mjs b/packages/db/test/connection-retry.test.mjs new file mode 100644 index 000000000..3a96654b6 --- /dev/null +++ b/packages/db/test/connection-retry.test.mjs @@ -0,0 +1,83 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { acquireConnection } from "../dist/connection-retry.js"; + +test("retries transient cold connection failures before returning a client", async () => { + let attempts = 0; + const delays = []; + const client = {}; + const result = await acquireConnection( + async () => { + if (++attempts < 3) + throw Object.assign(new Error("starting"), { + code: attempts === 1 ? "ETIMEDOUT" : "57P03", + }); + return client; + }, + async (ms) => { + delays.push(ms); + }, + ); + assert.equal(result, client); + assert.equal(attempts, 3); + assert.deepEqual(delays, [250, 750]); +}); + +test("authentication and statement-like errors fail without retry", async () => { + for (const code of ["28P01", "23505", "40001", undefined]) { + let attempts = 0; + const error = Object.assign(new Error("failure"), { code }); + await assert.rejects( + acquireConnection( + async () => { + attempts++; + throw error; + }, + async () => {}, + ), + (actual) => actual === error, + ); + assert.equal(attempts, 1); + } +}); + +test("connection retries are bounded and preserve the final failure", async () => { + let attempts = 0; + const error = Object.assign(new Error("offline"), { code: "ECONNREFUSED" }); + await assert.rejects( + acquireConnection( + async () => { + attempts++; + throw error; + }, + async () => {}, + ), + (actual) => actual === error, + ); + assert.equal(attempts, 3); +}); + +test("recovers pg-pool's code-less startup timeouts and nested DNS errors", async () => { + for (const error of [ + new Error("Connection terminated due to connection timeout", { + cause: new Error("Connection terminated unexpectedly"), + }), + new Error("timeout exceeded when trying to connect"), + new Error("connect failed", { + cause: Object.assign(new Error("lookup"), { code: "ETIMEDOUT" }), + }), + ]) { + let attempts = 0; + assert.equal( + await acquireConnection( + async () => { + if (++attempts === 1) throw error; + return "connected"; + }, + async () => {}, + ), + "connected", + ); + assert.equal(attempts, 2); + } +}); diff --git a/packages/db/test/database.test.mjs b/packages/db/test/database.test.mjs index ebe874a0e..14833e99f 100644 --- a/packages/db/test/database.test.mjs +++ b/packages/db/test/database.test.mjs @@ -46,3 +46,24 @@ test("shared client supports writes, relations, JSON, enums, errors and rollback await db.$disconnect(); } }); + +test("owned pools close and a later query obtains a fresh pool", async () => { + const { createDb } = await import("../dist/index.js"); + const clientUrl = new URL(url.href); + const applicationName = `pool-close-${randomUUID()}`; + clientUrl.searchParams.set("application_name", applicationName); + const client = createDb(clientUrl.href); + try { + assert.deepEqual(await client.$queryRaw`SELECT 1 AS value`, [{ value: 1 }]); + await client.$disconnect(); + const [connections] = await db.$queryRaw`SELECT count(*)::int AS count FROM pg_stat_activity WHERE application_name = ${applicationName}`; + assert.equal(connections.count, 0); + assert.deepEqual(await client.$queryRaw`SELECT 2 AS value`, [{ value: 2 }]); + await client.$transaction(async (tx) => { + assert.deepEqual(await tx.$queryRaw`SELECT 3 AS value`, [{ value: 3 }]); + }); + } finally { + await client.$disconnect(); + await db.$disconnect(); + } +});