From 0be8d27ffe942da0a6137fcdcbc7bf8aee9aa77f Mon Sep 17 00:00:00 2001 From: paula-alves Date: Wed, 18 Nov 2026 20:22:17 +0000 Subject: [PATCH] fix(archive): stop rematch and downgrade P1001 unreachable-database errors to info (BIT-32462) 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-rematch, inside eventForName's findUnique. The per-folder catch logged it at warn, which paged the error loop for a transient blip — and every remaining folder in the batch would fail the same way, producing redundant failing queries. Detect P1001 with a shared isPrismaServerUnreachable helper (lib/pg.js, next to isPrismaConnectionClosed/isPostgresAdminShutdown from BIT-32448/32460), log it at info and break out of the folder loop. The next verifyAll (on start, every six hours) retries once the server is back. Reuses the same downgrade-to-info pattern as the faces/develop/autopilot workers (BIT-32448/ 32449/32450). Paperclip-Issue: BIT-32462 --- apps/api/src/archive/service.test.ts | 52 ++++++++++++++++++++++++++++ apps/api/src/archive/service.ts | 8 +++++ apps/api/src/lib/pg.test.ts | 30 +++++++++++++++- apps/api/src/lib/pg.ts | 13 +++++++ 4 files changed, 102 insertions(+), 1 deletion(-) diff --git a/apps/api/src/archive/service.test.ts b/apps/api/src/archive/service.test.ts index fb784da..72e2c09 100644 --- a/apps/api/src/archive/service.test.ts +++ b/apps/api/src/archive/service.test.ts @@ -48,3 +48,55 @@ describe("dropIfEmpty retries a deadlock (BIT-32041)", () => { expect(calls).toBe(1); }); }); + +describe("rematch stops and downgrades a P1001 unreachable database (BIT-32462)", () => { + type Level = "info" | "warn"; + const makeLog = (): { info: (obj: unknown, msg: string) => void; warn: (obj: unknown, msg: string) => void; error: () => void; debug: () => void; calls: { level: Level; msg: string }[] } => { + const calls: { level: Level; msg: string }[] = []; + return { + calls, + info: (obj, msg) => calls.push({ level: "info", msg }), + warn: (obj, msg) => calls.push({ level: "warn", msg }), + error: () => {}, + debug: () => {}, + }; + }; + + const makeDb = (findUnique: () => Promise) => ({ + cloudSource: { findUniqueOrThrow: async () => ({ id: "src-1" }) }, + cloudFolder: { + findMany: async () => [ + { id: "f-1", path: "/26.04.2026 Festa Maritimo", eventId: "evt-1", matchedBy: "FIXTURE", fixtureRejected: false }, + { id: "f-2", path: "/27.04.2026 Outro", eventId: "evt-2", matchedBy: "FIXTURE", fixtureRejected: false }, + ], + }, + event: { findUnique }, + }); + + it("logs at info and stops the batch when the database is unreachable (P1001)", async () => { + const log = makeLog(); + const calls: string[] = []; + const db = makeDb(async () => { + calls.push("findUnique"); + throw Object.assign(new Error("Can't reach database server at 127.0.0.1:5432"), { code: "P1001" }); + }); + const service = new ArchiveService({ db, log } as never); + const moved = await (service as unknown as { rematch: (sourceId: string) => Promise }).rematch("src-1"); + // Only the first folder's query ran before the batch stopped. + expect(calls).toEqual(["findUnique"]); + expect(moved).toBe(0); + expect(log.calls.some((c) => c.level === "info" && /database unreachable/.test(c.msg))).toBe(true); + expect(log.calls.some((c) => c.level === "warn" && /gallery not checked/.test(c.msg))).toBe(false); + }); + + it("still warns on a real per-folder error", async () => { + const log = makeLog(); + const db = makeDb(async () => { + throw Object.assign(new Error("relation \"events\" does not exist"), { code: "P2021" }); + }); + const service = new ArchiveService({ db, log } as never); + await (service as unknown as { rematch: (sourceId: string) => Promise }).rematch("src-1"); + expect(log.calls.some((c) => c.level === "warn" && /gallery not checked/.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/archive/service.ts b/apps/api/src/archive/service.ts index e0602e9..6d6d280 100644 --- a/apps/api/src/archive/service.ts +++ b/apps/api/src/archive/service.ts @@ -14,6 +14,7 @@ import type { CloudFolder, CloudSource } from "../generated/prisma/client.js"; import type { IngestLogger, IngestService } from "../ingest/service.js"; import { ingestWindow } from "../library/events.js"; import { waitUntil } from "../lib/idle.js"; +import { isPrismaServerUnreachable } from "../lib/pg.js"; import type { LocalStorage } from "../storage/storage.js"; import { CloudClient, cleanBase, pollLogin, startLogin, type CloudEntry } from "./nextcloud.js"; import { @@ -661,6 +662,13 @@ export class ArchiveService { } await this.namePeople(folder); } catch (err) { + // The database server is unreachable (P1001: a restart, a downed route). Every remaining folder would fail + // the same way, so stop this source's batch and let the next verifyAll (on start, every six hours) retry — + // logging a warn per folder pages the error loop for a transient blip (BIT-32462). + if (isPrismaServerUnreachable(err)) { + log.info({ err: (err as Error).message, folderId: folder.id, path: folder.path }, "archive: gallery check stopped, database unreachable"); + break; + } log.warn({ err, folderId: folder.id, path: folder.path }, "archive: gallery not checked"); report?.errors.push({ path: folder.path, error: err instanceof Error ? err.message : String(err) }); } diff --git a/apps/api/src/lib/pg.test.ts b/apps/api/src/lib/pg.test.ts index 987a0ae..76c2c30 100644 --- a/apps/api/src/lib/pg.test.ts +++ b/apps/api/src/lib/pg.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { isPostgresAdminShutdown, isPrismaConnectionClosed, retryOnConnectionClosed } from "./pg.js"; +import { isPostgresAdminShutdown, isPrismaConnectionClosed, isPrismaServerUnreachable, retryOnConnectionClosed } from "./pg.js"; class PrismaLike extends Error { constructor(readonly code: string, message: string) { @@ -42,6 +42,34 @@ describe("isPostgresAdminShutdown", () => { }); }); +describe("isPrismaServerUnreachable", () => { + it("matches a PrismaClientKnownRequestError with code P1001 (BIT-32462)", () => { + const err = new PrismaLike( + "P1001", + "Invalid `prisma.event.findUnique()` invocation:\n\nCan't reach database server at 127.0.0.1:5432", + ); + expect(isPrismaServerUnreachable(err)).toBe(true); + }); + + it("matches the unreachable message without the code", () => { + expect(isPrismaServerUnreachable(new Error("Can't reach database server at pr-db:5432"))).toBe(true); + }); + + it("does not match a server-closed (P1017) error", () => { + expect(isPrismaServerUnreachable(new PrismaLike("P1017", "Server has closed the connection."))).toBe(false); + }); + + it("does not match an admin-shutdown (57P01) error", () => { + expect(isPrismaServerUnreachable(new Error("terminating connection due to administrator command (57P01)"))).toBe(false); + }); + + it("does not match an unrelated query error", () => { + expect(isPrismaServerUnreachable(new PrismaLike("P2002", "Unique constraint failed"))).toBe(false); + expect(isPrismaServerUnreachable(null)).toBe(false); + expect(isPrismaServerUnreachable("string")).toBe(false); + }); +}); + describe("retryOnConnectionClosed", () => { it("retries once when the first attempt throws P1017 and returns the second result", async () => { let calls = 0; diff --git a/apps/api/src/lib/pg.ts b/apps/api/src/lib/pg.ts index fb5883b..d464f93 100644 --- a/apps/api/src/lib/pg.ts +++ b/apps/api/src/lib/pg.ts @@ -20,6 +20,19 @@ export function isPrismaConnectionClosed(err: unknown): boolean { return code === "P1017" || /Server has closed the connection/i.test(err.message); } +/** + * The database server is unreachable — Prisma never opened a connection (the server is down, restarting, or a + * network blip dropped the route). Prisma surfaces this as `PrismaClientKnownRequestError` with code `P1001` + * ("Can't reach database server at :"). The pool reconnects on the next attempt once the server is + * back, so this is transient and must not page the error loop: the caller should stop the current batch and let + * the next scheduled run retry (BIT-32462). + */ +export function isPrismaServerUnreachable(err: unknown): boolean { + if (!(err instanceof Error)) return false; + const code = (err as { code?: unknown }).code; + return code === "P1001" || /Can't reach database server/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