Skip to content

Commit 3ec7caa

Browse files
authored
Merge pull request #5993 from JSONbored/fix/pg-pool-error-handler
fix(selfhost): attach a pg.Pool error listener to prevent uncaught-exception crashes
2 parents fd2738e + 592fdc8 commit 3ec7caa

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

src/server.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,22 @@ async function buildPostgresBackend(
219219
const pg = (await import("pg")).default;
220220
pg.types.setTypeParser(20, (v: string) => Number.parseInt(v, 10)); // int8 (COUNT) → number, like D1
221221
const pool = new pg.Pool({ connectionString: url, max: resolvePostgresPoolMax() });
222+
// node-postgres crashes the WHOLE process with an uncaught exception if the pool has no "error" listener and
223+
// an IDLE client's connection drops (Node's EventEmitter throws on an unhandled "error" event) -- confirmed
224+
// live (GITTENSORY-1R/1S): Postgres itself being restarted ("terminating connection due to administrator
225+
// command") took the whole app down, which then crash-looped for ~29 minutes hitting waitForPostgres's 30s
226+
// boot timeout (GITTENSORY-1T) until Postgres was fully back up. The pool already removes a broken client and
227+
// opens a fresh one on the next checkout on its own -- the only thing missing was a listener so Node stops
228+
// treating an idle client's connection-level error as unhandled.
229+
pool.on("error", (error) => {
230+
console.error(
231+
JSON.stringify({
232+
level: "error",
233+
event: "selfhost_pg_pool_error",
234+
message: error instanceof Error ? error.message : "unknown error",
235+
}),
236+
);
237+
});
222238
const db = createPgAdapter(pool);
223239
const queue = createPgQueue(pool, consume);
224240
await queue.init();

0 commit comments

Comments
 (0)