Repository navigation
LVT-382: Retry connections while sleeping Postgres wakes #134
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
|
|
||
| override connect(): ReturnType<PrismaPg["connect"]> { | ||
| return new PrismaPg(createRetryPool(this.poolConfig), { | ||
| disposeExternalPool: true, | ||
| }).connect(); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.