From b7aa187154ac24379dba2810fac0a5a1302d6cc8 Mon Sep 17 00:00:00 2001 From: paula-alves Date: Wed, 18 Nov 2026 21:25:13 +0000 Subject: [PATCH] fix(sports): downgrade 57P01 admin-terminated connection in linkStoredSquads to info (BIT-32471) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Postgres terminates a pooled client mid-query on restart or `pg_terminate_backend` (SQLSTATE 57P01); Prisma surfaces the raw-query failure as P2010 wrapping "terminating connection due to administrator command". linkStoredSquads runs an unguarded `$queryRaw`, so the rejection escaped to SportsWorker.fillRegister's catch and logged `warn` ("sports: register not filled"), paging the error loop for a transient blip. Wrap the `$queryRaw` (extracted into linkStoredSquadsRows) so an admin-shutdown is detected via isPostgresAdminShutdown, logged at info, and returns 0 — fillRegister's loop breaks and the next scheduled tick retries on a fresh client. Non-transient errors still rethrow. The same helper already covers the equivalent raw-query path (BIT-32448/32449). Paperclip-Issue: BIT-32471 --- apps/api/src/sports/service.test.ts | 30 +++++++++++++ apps/api/src/sports/service.ts | 65 ++++++++++++++++++----------- 2 files changed, 71 insertions(+), 24 deletions(-) diff --git a/apps/api/src/sports/service.test.ts b/apps/api/src/sports/service.test.ts index 89f1f8c..df9dfc5 100644 --- a/apps/api/src/sports/service.test.ts +++ b/apps/api/src/sports/service.test.ts @@ -24,6 +24,12 @@ const p57p03 = () => { code: "P2039" }, ); +const p57p01 = () => + Object.assign( + new Error("Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `57P01`. Message: `terminating connection due to administrator command`"), + { code: "P2010" }, + ); + const ligaTeam = (id: string, externalId: string) => ({ id, provider: "LIGA", @@ -137,3 +143,27 @@ describe("syncEventSquads downgrades a 57P03 database-shutting-down error (BIT-3 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 = { + $queryRaw: async () => { throw p57p01(); }, + }; + const service = new SportsService(makeDeps(db)); + const out = await service.linkStoredSquads(24); + expect(out).toBe(0); + const log = (service as unknown as { deps: { log: { calls: LogCall[] } } }).deps.log; + expect(log.calls.some((c) => c.level === "info" && /database connection terminated/.test(c.msg))).toBe(true); + expect(log.calls.some((c) => c.level === "warn")).toBe(false); + }); + + it("still rethrows a non-transient raw-query error", async () => { + const db = { + $queryRaw: async () => { throw new Error("syntax error at or near 'FROM'"); }, + }; + const service = new SportsService(makeDeps(db)); + await expect(service.linkStoredSquads(24)).rejects.toThrow("syntax error"); + const log = (service as unknown as { deps: { log: { calls: LogCall[] } } }).deps.log; + expect(log.calls.some((c) => c.level === "info" && /database connection terminated/.test(c.msg))).toBe(false); + }); +}); diff --git a/apps/api/src/sports/service.ts b/apps/api/src/sports/service.ts index 99626a6..812d955 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 { isPrismaServerUnreachable, retryOnConnectionClosed } from "../lib/pg.js"; +import { isPostgresAdminShutdown, 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"; @@ -1945,30 +1945,47 @@ export class SportsService { async linkStoredSquads(limit = 8): Promise { const { db, log } = this.deps; - const rows = await db.$queryRaw<{ organization_id: string; player_id: string }[]>` - SELECT e.organization_id, sp.id AS player_id - FROM sports_players sp - JOIN sports_teams t ON t.id = sp.team_id - JOIN events e ON (e.home_team_id = t.id OR e.away_team_id = t.id) - JOIN organizations o ON o.id = e.organization_id AND o.biometrics_enabled - WHERE NOT EXISTS ( - SELECT 1 FROM people p - JOIN sports_players mine ON mine.id = p.sports_player_id - WHERE p.organization_id = e.organization_id - AND ( - mine.id = sp.id - OR (sp.external_id IS NOT NULL AND mine.external_id = sp.external_id) - OR ( - sp.birth_date IS NOT NULL AND sp.full_name IS NOT NULL - AND mine.birth_date = sp.birth_date - AND lower(mine.full_name) = lower(sp.full_name) + // Postgres may terminate a pooled client mid-query (restart, `pg_terminate_backend`, SQLSTATE 57P01). Prisma + // surfaces the raw-query failure as P2010 wrapping "terminating connection due to administrator command"; the + // next tick reclaims a fresh client, so this is a transient blip. Without this guard the rejection escapes to + // fillRegister/tick's `warn` ("register not filled" / "tick failed") and pages the error loop (BIT-32471). + try { + const rows = await db.$queryRaw<{ organization_id: string; player_id: string }[]>` + SELECT e.organization_id, sp.id AS player_id + FROM sports_players sp + JOIN sports_teams t ON t.id = sp.team_id + JOIN events e ON (e.home_team_id = t.id OR e.away_team_id = t.id) + JOIN organizations o ON o.id = e.organization_id AND o.biometrics_enabled + WHERE NOT EXISTS ( + SELECT 1 FROM people p + JOIN sports_players mine ON mine.id = p.sports_player_id + WHERE p.organization_id = e.organization_id + AND ( + mine.id = sp.id + OR (sp.external_id IS NOT NULL AND mine.external_id = sp.external_id) + OR ( + sp.birth_date IS NOT NULL AND sp.full_name IS NOT NULL + AND mine.birth_date = sp.birth_date + AND lower(mine.full_name) = lower(sp.full_name) + ) + OR (mine.team_id = sp.team_id AND mine.name = sp.name) ) - OR (mine.team_id = sp.team_id AND mine.name = sp.name) - ) - ) - GROUP BY e.organization_id, sp.id, sp.season - ORDER BY sp.season DESC - LIMIT ${limit}`; + ) + GROUP BY e.organization_id, sp.id, sp.season + ORDER BY sp.season DESC + LIMIT ${limit}`; + return await this.linkStoredSquadsRows(rows); + } catch (err) { + if (isPostgresAdminShutdown(err)) { + log.info({ err: (err as Error).message }, "sports: link stored squads stopped, database connection terminated"); + return 0; + } + throw err; + } + } + + private async linkStoredSquadsRows(rows: { organization_id: string; player_id: string }[]): Promise { + const { db, log } = this.deps; if (!rows.length) return 0; const players = await db.sportsPlayer.findMany({ where: { id: { in: rows.map((r) => r.player_id) } }, include: { team: true } }); const byId = new Map(players.map((p) => [p.id, p])); -- 2.47.3