From 6232b41e5c0cbc82a3bf4ddce65dfbe75e4397ff Mon Sep 17 00:00:00 2001 From: paula-alves Date: Wed, 18 Nov 2026 20:35:30 +0000 Subject: [PATCH] fix(sports): downgrade P1001 unreachable-database errors in syncEventSquads to info (BIT-32463) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Postgres restart or a downed route makes the database unreachable (Prisma P1001: "Can't reach database server at :") mid syncEventSquads — inside savePlayers' findMany during the liga squad re-read, or at the initial event findUnique, or in the second squad loop. The liga re-read catch logged it at warn ("liga squad re-read failed"), paging the error loop for a transient blip, and the outer syncEventSquads let uncaught P1001 propagate to the caller's warn. Detect P1001 with the shared isPrismaServerUnreachable helper (lib/pg.ts, added in BIT-32462 for the archive worker) and log at info instead: in the liga re-read catch, return the partial result early; in the syncEventSquads wrapper, catch P1001 from retryOnConnectionClosed and return zeros. The next scheduled sync retries once the server is back. Same pattern as archive/faces/ develop/autopilot (BIT-32448/32449/32450/32462). Paperclip-Issue: BIT-32463 --- apps/api/src/sports/service.test.ts | 102 ++++++++++++++++++++++++++++ apps/api/src/sports/service.ts | 21 +++++- 2 files changed, 121 insertions(+), 2 deletions(-) create mode 100644 apps/api/src/sports/service.test.ts diff --git a/apps/api/src/sports/service.test.ts b/apps/api/src/sports/service.test.ts new file mode 100644 index 0000000..a8ca765 --- /dev/null +++ b/apps/api/src/sports/service.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from "vitest"; +import { SportsService } from "./service.js"; + +type Level = "info" | "warn"; +type LogCall = { level: Level; msg: string }; + +const makeLog = (): { info: (obj: unknown, msg: string) => void; warn: (obj: unknown, msg: string) => void; error: () => void; debug: () => void; calls: LogCall[] } => { + const calls: LogCall[] = []; + return { + calls, + info: (_obj, msg) => calls.push({ level: "info", msg }), + warn: (_obj, msg) => calls.push({ level: "warn", msg }), + error: () => {}, + debug: () => {}, + }; +}; + +const p1001 = () => + Object.assign(new Error("Invalid `prisma.sportsPlayer.findMany()` invocation:\n\nCan't reach database server at 127.0.0.1:5432"), { code: "P1001" }); + +const ligaTeam = (id: string, externalId: string) => ({ + id, + provider: "LIGA", + externalId, + name: `Team ${id}`, + abbreviation: null, + logoUrl: null, +}); + +const makeEvent = (overrides: Record = {}) => ({ + id: "evt-1", + organizationId: "org-1", + startsAt: new Date("2026-04-26T15:00:00Z"), + homeTeam: ligaTeam("t-1", "liga-1"), + awayTeam: null, + fixture: null, + organization: { biometricsEnabled: false, codeGenerator: {} }, + ...overrides, +}); + +const makeDeps = (db: Record) => + ({ + db, + log: makeLog(), + fetch: (async () => new Response("{}")) as never, + storage: null, + signer: null, + }) as unknown as ConstructorParameters[0]; + +describe("syncEventSquads downgrades a P1001 unreachable database (BIT-32463)", () => { + it("logs at info and returns zeros when the initial event lookup is unreachable (P1001)", async () => { + const db = { + event: { findUnique: async () => { throw p1001(); } }, + }; + 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" && /database unreachable/.test(c.msg))).toBe(true); + expect(log.calls.some((c) => c.level === "warn")).toBe(false); + }); + + it("logs at info and stops when savePlayers is unreachable during the liga re-read (P1001)", async () => { + let findManyCalls = 0; + const db = { + event: { findUnique: async () => makeEvent() }, + sportsPlayer: { + findMany: async () => { findManyCalls++; throw p1001(); }, + findFirst: async () => null, + }, + }; + const service = new SportsService(makeDeps(db)); + (service as unknown as { liga: { squad: () => Promise } }).liga = { + squad: async () => [{ name: "Player 1", number: "1" }], + }; + 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" && /database unreachable/.test(c.msg))).toBe(true); + expect(log.calls.some((c) => c.level === "warn" && /liga squad re-read failed/.test(c.msg))).toBe(false); + // The sync stopped early — the second loop's squad() did not run another findMany. + expect(findManyCalls).toBe(1); + }); + + it("still warns on a real per-team error in the liga re-read", async () => { + const db = { + event: { findUnique: async () => makeEvent() }, + sportsPlayer: { + findMany: async () => [], + findFirst: async () => null, + }, + }; + const service = new SportsService(makeDeps(db)); + (service as unknown as { liga: { squad: () => Promise } }).liga = { + squad: async () => { throw new Error("provider timeout"); }, + }; + await service.syncEventSquads("evt-1"); + const log = (service as unknown as { deps: { log: { calls: LogCall[] } } }).deps.log; + expect(log.calls.some((c) => c.level === "warn" && /liga squad re-read failed/.test(c.msg))).toBe(true); + expect(log.calls.some((c) => c.level === "info" && /database unreachable/.test(c.msg))).toBe(false); + }); +}); diff --git a/apps/api/src/sports/service.ts b/apps/api/src/sports/service.ts index 3996766..99626a6 100644 --- a/apps/api/src/sports/service.ts +++ b/apps/api/src/sports/service.ts @@ -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 { retryOnConnectionClosed } from "../lib/pg.js"; +import { isPrismaServerUnreachable, 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"; @@ -1428,7 +1428,18 @@ export class SportsService { // 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))); + const run = previous.catch(() => {}).then(() => + retryOnConnectionClosed(() => this.syncEventSquadsNow(eventId)).catch((err) => { + // The database server is unreachable (P1001: a restart, a downed route). Every remaining query would fail + // the same way, so stop this sync and let the next call retry once the server is back — logging a warn + // pages the error loop for a transient blip (BIT-32463). + if (isPrismaServerUnreachable(err)) { + this.deps.log.info({ err: (err as Error).message, eventId }, "sports: squad sync stopped, database unreachable"); + return { created: 0, updated: 0, headshots: 0 }; + } + throw err; + }), + ); this.syncing.set(eventId, run); try { return await run; @@ -1462,6 +1473,12 @@ export class SportsService { try { await this.savePlayers(team.id, season, await this.liga.squad(team.externalId, season), "api"); } catch (err) { + // The database server is unreachable (P1001): stop the sync and let the next call retry once the server is + // back — a warn per team pages the error loop for a transient blip (BIT-32463). + if (isPrismaServerUnreachable(err)) { + log.info({ err: (err as Error).message, team: team.id }, "sports: squad sync stopped, database unreachable"); + 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");