fix(sports): downgrade transient P2037 too-many-connections to info in squad sync (BIT-33538)
ci / rust (push) Failing after 6s
ci / typescript (push) Successful in 10m10s

Prisma P2037 ("Too many database connections opened: remaining connection
slots are reserved for roles with the SUPERUSER attribute") is pool
exhaustion under concurrent worker load — the next scheduled tick reclaims
a freed slot. syncEventSquads already downgrades P1001 (unreachable) and
P1017 (connection closed) to info; P2037 was missing, so it escaped to the
archive caller's log.warn and paged the error loop.

Add isPrismaTooManyConnections to lib/pg.ts and handle it in both catch
sites of syncEventSquads (the outer wrapper and the inner savePlayers
loop), following the same stop-and-retry-next-run pattern.

Paperclip-Issue: BIT-33538
This commit is contained in:
paula-alves committed 2026-12-04 10:49:42 +00:00
1 parent ea29bd9b6e
commit 6182c03cd5
3 files changed
+50 -1

No files matched your search

+13
View File
@@ -39,6 +39,19 @@ export function isPrismaServerUnreachable(err: unknown): boolean {
);
}
/**
* The Postgres server has no free connection slots for non-superuser roles — every slot is in use and the
* remaining ones are reserved for SUPERUSER. Prisma surfaces this as `PrismaClientKnownRequestError` with
* code `P2037` and message "Too many database connections opened: …". This is pool exhaustion under concurrent
* worker load; the next scheduled tick reclaims a freed slot, so it is transient and must not page the error
* loop — the caller should stop the current batch and let the next run retry (BIT-33538).
*/
export function isPrismaTooManyConnections(err: unknown): boolean {
if (!(err instanceof Error)) return false;
const code = (err as { code?: unknown }).code;
return code === "P2037" || /Too many database connections opened/i.test(err.message);
}
/**
* Prisma could not acquire a pooled connection to start a transaction within `maxWait`
* (code P2028, "Transaction API error: Unable to start a transaction in the given time.").
+23
View File
@@ -42,6 +42,12 @@ const p1017 = () =>
const p1017findUnique = () =>
Object.assign(new Error("Invalid `prisma.person.findUnique()` invocation:\n\nServer has closed the connection."), { code: "P1017" });
const p2037 = () =>
Object.assign(
new Error("Invalid `prisma.event.findUnique()` invocation:\n\nToo many database connections opened: remaining connection slots are reserved for roles with the SUPERUSER attribute"),
{ code: "P2037" },
);
const ligaTeam = (id: string, externalId: string) => ({
id,
provider: "LIGA",
@@ -271,6 +277,23 @@ describe("syncEventSquads downgrades a P1017 from person.findUnique in linkSquad
});
});
describe("syncEventSquads downgrades a P2037 too-many-connections error (BIT-33538)", () => {
it("logs at info and returns zeros when the initial event lookup hits P2037", async () => {
// The error loop reported P2037 ("Too many database connections opened: remaining connection slots are
// reserved for roles with the SUPERUSER attribute") from syncEventSquadsNow → db.event.findUnique. Without
// this guard the rejection escapes to the archive caller's warn and pages the error loop for a transient blip.
const db = {
event: { findUnique: async () => { throw p2037(); } },
};
const service = new SportsService(makeDeps(db));
const out = await service.syncEventSquads("evt-1");
expect(out).toEqual({ created: 0, updated: 0, headshots: 0 });
const log = (service as unknown as { deps: { log: { calls: LogCall[] } } }).deps.log;
expect(log.calls.some((c) => c.level === "info" && /too many database connections/.test(c.msg))).toBe(true);
expect(log.calls.some((c) => c.level === "warn")).toBe(false);
});
});
describe("linkStoredSquads downgrades a 57P01 admin-terminated connection (BIT-32471)", () => {
it("logs at info and returns 0 when the raw query is terminated mid-flight (57P01)", async () => {
const db = {
+14 -1
View File
@@ -8,7 +8,7 @@ import type { IngestLogger } from "../ingest/service.js";
import { DEFAULT_CODE_LIST } from "../library/iptc.js";
import { badRequest, notFound } from "../lib/errors.js";
import { waitUntil } from "../lib/idle.js";
import { isPostgresAdminShutdown, isPrismaConnectionClosed, isPrismaServerUnreachable, isPrismaTransactionClosed, isPrismaTransactionTimeout, retryOnConnectionClosed } from "../lib/pg.js";
import { isPostgresAdminShutdown, isPrismaConnectionClosed, isPrismaServerUnreachable, isPrismaTooManyConnections, isPrismaTransactionClosed, isPrismaTransactionTimeout, retryOnConnectionClosed } from "../lib/pg.js";
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js";
import { fetchYouthCamps, youthAbbrev } from "./fpa-youth.js";
@@ -1976,6 +1976,13 @@ export class SportsService {
this.deps.log.info({ err: (err as Error).message, eventId }, "sports: squad sync stopped, database connection closed");
return { created: 0, updated: 0, headshots: 0 };
}
// The Postgres server is at max_connections and only SUPERUSER slots remain (P2037): every remaining query
// would fail the same way, so stop this sync and let the next scheduled run retry once a slot frees —
// rejecting to the archive caller's warn pages the error loop for a transient blip (BIT-33538).
if (isPrismaTooManyConnections(err)) {
this.deps.log.info({ err: (err as Error).message, eventId }, "sports: squad sync stopped, too many database connections");
return { created: 0, updated: 0, headshots: 0 };
}
throw err;
}),
);
@@ -2019,6 +2026,12 @@ export class SportsService {
log.info({ err: (err as Error).message, team: team.id }, "sports: squad sync stopped, database unreachable");
return result;
}
// The Postgres server is at max_connections (P2037): stop the sync and let the next scheduled run retry
// once a slot frees — a warn per team pages the error loop for a transient blip (BIT-33538).
if (isPrismaTooManyConnections(err)) {
log.info({ err: (err as Error).message, team: team.id }, "sports: squad sync stopped, too many database connections");
return result;
}
// Same not-yet-published 400 as importLigaSquads/backfillLigaRegister: expected, kept out of the error hub.
if (err instanceof ProviderHttpError && err.status === 400)
log.info({ err, team: team.id }, "sports: liga squad not published yet for this team");