Skip to content
Merged
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 packages/db/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
4 changes: 2 additions & 2 deletions packages/db/src/client.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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,
Expand Down
92 changes: 92 additions & 0 deletions packages/db/src/connection-retry.ts
Original file line number Diff line number Diff line change
@@ -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<T>(
connect: () => Promise<T>,
wait: (ms: number) => Promise<void> = (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<Pool["connect"]>[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);
Comment thread
jackshim415 marked this conversation as resolved.
Resolved
}

override connect(): ReturnType<PrismaPg["connect"]> {
return new PrismaPg(createRetryPool(this.poolConfig), {
disposeExternalPool: true,
}).connect();
}
}
83 changes: 83 additions & 0 deletions packages/db/test/connection-retry.test.mjs
Original file line number Diff line number Diff line change
@@ -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);
}
});
21 changes: 21 additions & 0 deletions packages/db/test/database.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
});
Loading