From 2ec4f263b6996a29f30d597f4b49a8ea07af5d95 Mon Sep 17 00:00:00 2001 From: paula-alves Date: Fri, 4 Dec 2026 07:31:32 +0000 Subject: [PATCH] Stop the health-check error loop on Postgres connection exhaustion (BIT-33548) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The /health endpoint ran db.$queryRaw`SELECT 1` with no error handling. When PostgreSQL hits max_connections (error 53300), the query threw PrismaClientKnownRequestError, the error handler logged it as 'unhandled error', and the reporter sent it to errors.bitreport.pt — creating an error loop of one-off incidents from every health check. Two fixes: - /health now catches DB failures and returns 503 { status: 'degraded' } instead of throwing, so a connection-starved health check degrades gracefully rather than generating an error report. - isTransientDatabaseError now filters 53300 (pool exhaustion) alongside the existing 57P01/57P03/P1001/P1017 filters, so even if a 53300 surfaces through another code path it does not trip the error loop. Paperclip-Issue: BIT-33548 --- apps/api/src/app.ts | 11 ++++++++--- apps/api/src/lib/reporter.ts | 17 +++++++++-------- apps/api/test/auth.test.ts | 21 +++++++++++++++++++++ apps/api/test/reporter.test.ts | 1 + 4 files changed, 39 insertions(+), 11 deletions(-) diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 89c68aa..677bbc8 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -142,9 +142,14 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give registerClientErrors(app, reporter); - app.get("/health", async () => { - await db.$queryRaw`SELECT 1`; - return { status: "ok", version: config.APP_VERSION }; + app.get("/health", async (_req, reply) => { + try { + await db.$queryRaw`SELECT 1`; + return { status: "ok", version: config.APP_VERSION }; + } catch { + reply.code(503); + return { status: "degraded", version: config.APP_VERSION }; + } }); const authenticate = requireAuth(sessions); diff --git a/apps/api/src/lib/reporter.ts b/apps/api/src/lib/reporter.ts index 7399ccf..62f2ad1 100644 --- a/apps/api/src/lib/reporter.ts +++ b/apps/api/src/lib/reporter.ts @@ -10,19 +10,20 @@ import { createHash } from "node:crypto"; */ /** - * Transient PostgreSQL connection errors during a restart, graceful shutdown, or network blip. Prisma surfaces - * these as `PrismaClientKnownRequestError` wrapping the raw SQLSTATE (57P01/57P03) or its own P1001/P1017. - * The pool reconnects on the next attempt, so these are not code bugs — reporting them only trips the Error - * Loop with one-off incidents from every code path that touches the database during the brief outage. - * Individual call sites that need to stop a batch or retry still check `isPostgresAdminShutdown` / - * `isPrismaServerUnreachable` (lib/pg.ts); this filter keeps the hub quiet for the paths that just let the - * error propagate to a generic log.error (BIT-32490 and 11 sibling clusters). + * Transient PostgreSQL connection errors during a restart, graceful shutdown, network blip, or pool + * exhaustion. Prisma surfaces these as `PrismaClientKnownRequestError` wrapping the raw SQLSTATE + * (57P01/57P03/53300) or its own P1001/P1017. The pool reconnects on the next attempt, so these are not + * code bugs — reporting them only trips the Error Loop with one-off incidents from every code path that + * touches the database during the brief outage. Individual call sites that need to stop a batch or retry + * still check `isPostgresAdminShutdown` / `isPrismaServerUnreachable` (lib/pg.ts); this filter keeps the + * hub quiet for the paths that just let the error propagate to a generic log.error (BIT-32490 and 11 + * sibling clusters, BIT-33548 for 53300). */ function isTransientDatabaseError(err: unknown): boolean { if (!(err instanceof Error)) return false; const code = (err as { code?: unknown }).code; if (code === "P1001" || code === "P1017") return true; - return /57P01|57P03|the database system is shutting down|the database system is starting up|Can't reach database server|Server has closed the connection/i.test(err.message); + return /57P01|57P03|53300|remaining connection slots are reserved|the database system is shutting down|the database system is starting up|Can't reach database server|Server has closed the connection/i.test(err.message); } export type ReportLevel = "critical" | "error" | "warning" | "info"; diff --git a/apps/api/test/auth.test.ts b/apps/api/test/auth.test.ts index f67cd4e..a815618 100644 --- a/apps/api/test/auth.test.ts +++ b/apps/api/test/auth.test.ts @@ -1,4 +1,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { buildApp } from "../src/app.js"; +import { loadConfig } from "../src/config.js"; +import { createDb } from "../src/db.js"; import { bearer, createTestApp, login, PASSWORD, resetDb, seedUser, type TestContext } from "./helpers.js"; let ctx: TestContext; @@ -16,6 +19,24 @@ describe("health", () => { const res = await ctx.app.inject({ method: "GET", url: "/health" }); expect(res.json()).toEqual({ status: "ok", version: "dev" }); }); + + it("returns 503 degraded when the database is unreachable", async () => { + const config = loadConfig({ + NODE_ENV: "test", + DATABASE_URL: "postgresql://x@127.0.0.1:1/photoreport_test", + JWT_SECRET: "test-secret-test-secret-test-secret-123", + }); + const db = createDb(config.DATABASE_URL); + const app = await buildApp({ config, db }); + try { + const res = await app.inject({ method: "GET", url: "/health" }); + expect(res.statusCode).toBe(503); + expect(res.json()).toEqual({ status: "degraded", version: "dev" }); + } finally { + await app.close(); + await db.$disconnect(); + } + }); }); describe("login", () => { diff --git a/apps/api/test/reporter.test.ts b/apps/api/test/reporter.test.ts index aafec08..1f8959c 100644 --- a/apps/api/test/reporter.test.ts +++ b/apps/api/test/reporter.test.ts @@ -105,6 +105,7 @@ describe("errors to errors.bitreport.pt", () => { log.error({ err: mk("Database error. Code: 57P01. Message: terminating connection due to administrator command") }, "archive: query failed"); log.error({ err: mk("Can't reach database server at localhost:5432", "P1001") }, "db unreachable"); log.error({ err: mk("Server has closed the connection.", "P1017") }, "connection closed"); + log.error({ err: mk("Raw query failed. Code: `53300`. Message: `remaining connection slots are reserved for roles with the SUPERUSER attribute`", "P2010") }, "health: query failed"); reporter.reportError(mk("Database error. Code: 57P03. Message: the database system is shutting down"), "worker"); log.error({ err: new Error("render crashed") }, "real error"); await reporter.flush();