diff --git a/apps/api/src/lib/pg.test.ts b/apps/api/src/lib/pg.test.ts new file mode 100644 index 0000000..987a0ae --- /dev/null +++ b/apps/api/src/lib/pg.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from "vitest"; +import { isPostgresAdminShutdown, isPrismaConnectionClosed, retryOnConnectionClosed } from "./pg.js"; + +class PrismaLike extends Error { + constructor(readonly code: string, message: string) { + super(message); + } +} + +describe("isPrismaConnectionClosed", () => { + it("matches a PrismaClientKnownRequestError with code P1017 (BIT-32460)", () => { + const err = new PrismaLike( + "P1017", + "Invalid `prisma.sportsPlayer.findMany()` invocation:\n\nServer has closed the connection.", + ); + expect(isPrismaConnectionClosed(err)).toBe(true); + }); + + it("matches the server-closed message without the code", () => { + expect(isPrismaConnectionClosed(new Error("Server has closed the connection."))).toBe(true); + }); + + it("does not match an admin-shutdown (57P01) error", () => { + expect( + isPrismaConnectionClosed( + new Error("Raw query failed. Code: `57P01`. Message: `terminating connection due to administrator command`"), + ), + ).toBe(false); + }); + + it("does not match an unrelated query error", () => { + expect(isPrismaConnectionClosed(new PrismaLike("P2002", "Unique constraint failed"))).toBe(false); + expect(isPrismaConnectionClosed(null)).toBe(false); + expect(isPrismaConnectionClosed("string")).toBe(false); + }); +}); + +describe("isPostgresAdminShutdown", () => { + it("still matches 57P01 and is distinct from P1017", () => { + expect(isPostgresAdminShutdown(new Error("terminating connection due to administrator command (57P01)"))).toBe(true); + expect(isPostgresAdminShutdown(new PrismaLike("P1017", "Server has closed the connection."))).toBe(false); + }); +}); + +describe("retryOnConnectionClosed", () => { + it("retries once when the first attempt throws P1017 and returns the second result", async () => { + let calls = 0; + const out = await retryOnConnectionClosed(async () => { + calls++; + if (calls === 1) throw new PrismaLike("P1017", "Server has closed the connection."); + return "ok"; + }, 0); + expect(calls).toBe(2); + expect(out).toBe("ok"); + }); + + it("retries once when the server-closed message is surfaced without the code", async () => { + let calls = 0; + const out = await retryOnConnectionClosed(async () => { + calls++; + if (calls === 1) throw new Error("Invalid `prisma.sportsPlayer.findMany()` invocation:\n\nServer has closed the connection."); + return 42; + }, 0); + expect(calls).toBe(2); + expect(out).toBe(42); + }); + + it("does not retry a non-connection error", async () => { + let calls = 0; + await expect( + retryOnConnectionClosed(async () => { + calls++; + throw new PrismaLike("P2002", "Unique constraint failed"); + }, 0), + ).rejects.toThrow("Unique constraint failed"); + expect(calls).toBe(1); + }); + + it("does not retry a second P1017 (one retry only, then rethrows)", async () => { + let calls = 0; + await expect( + retryOnConnectionClosed(async () => { + calls++; + throw new PrismaLike("P1017", "Server has closed the connection."); + }, 0), + ).rejects.toThrow("Server has closed the connection."); + expect(calls).toBe(2); + }); + + it("returns the result without retry when the first attempt succeeds", async () => { + let calls = 0; + const out = await retryOnConnectionClosed(async () => { + calls++; + return "first"; + }, 0); + expect(calls).toBe(1); + expect(out).toBe("first"); + }); +}); diff --git a/apps/api/src/lib/pg.ts b/apps/api/src/lib/pg.ts index d01d84a..fb5883b 100644 --- a/apps/api/src/lib/pg.ts +++ b/apps/api/src/lib/pg.ts @@ -7,3 +7,31 @@ export function isPostgresAdminShutdown(err: unknown): boolean { if (!(err instanceof Error)) return false; return /57P01|terminating connection due to administrator command/i.test(err.message); } + +/** + * The server closed the pooled client before Prisma ran the query (idle timeout, restart, `pg_terminate_backend`, + * a network blip). Prisma surfaces this as `PrismaClientKnownRequestError` with code `P1017` + * ("Server has closed the connection."). The next attempt reclaims a fresh client from the pool, so this is + * transient and safe to retry for one-shot operations that are not already inside a retry loop (BIT-32460). + */ +export function isPrismaConnectionClosed(err: unknown): boolean { + if (!(err instanceof Error)) return false; + const code = (err as { code?: unknown }).code; + return code === "P1017" || /Server has closed the connection/i.test(err.message); +} + +/** + * Runs `fn`, retrying it once when Postgres closed the connection before the query (`P1017`). The pool hands out a + * fresh client on the next attempt, so a single retry clears the blip without surfacing it to the caller's + * `.catch()` (which would log a warn and page the error loop). Operations retried here must be idempotent under a + * re-run (upserts, findUnique lookups, unique-constraint creates whose `P2002` is already caught) (BIT-32460). + */ +export async function retryOnConnectionClosed(fn: () => Promise, delayMs = 250): Promise { + try { + return await fn(); + } catch (err) { + if (!isPrismaConnectionClosed(err)) throw err; + await new Promise((r) => setTimeout(r, delayMs)); + return fn(); + } +} diff --git a/apps/api/src/sports/service.ts b/apps/api/src/sports/service.ts index 06d2898..3996766 100644 --- a/apps/api/src/sports/service.ts +++ b/apps/api/src/sports/service.ts @@ -8,6 +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 { 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"; @@ -1424,7 +1425,10 @@ export class SportsService { async syncEventSquads(eventId: string): Promise<{ created: number; updated: number; headshots: number }> { // One at a time per event (the automatic sync on creation and a click on "update" can meet). const previous = this.syncing.get(eventId) ?? Promise.resolve(); - const run = previous.catch(() => {}).then(() => this.syncEventSquadsNow(eventId)); + // A pooled client the server closed before the query (idle timeout, restart, `pg_terminate_backend`) surfaces + // as `P1017`; the operation is idempotent under a re-run (upserts, findUnique lookups, P2002 caught), so one + // retry on a fresh client clears the blip instead of rejecting to the archive caller's warn (BIT-32460). + const run = previous.catch(() => {}).then(() => retryOnConnectionClosed(() => this.syncEventSquadsNow(eventId))); this.syncing.set(eventId, run); try { return await run;