Compare commits

..
Author SHA1 Message Date
spark c9c994e0a0 fix(boot): retry a hung PM2 start so a reboot cannot leave the API down
ci / rust (pull_request) Successful in 5m13s
ci / typescript (pull_request) Successful in 8m55s
pm2 startOrReload hung on pr-api after the 2026-11-18 reboot. systemd killed
photoreport-boot and the process list stayed empty, so nothing could report
the outage. Bound the call, reset the daemon once, and retry the unit.
2026-11-19 00:11:50 +00:00
spark 5b80e614f6 Merge pull request 'fix(sports): stop syncEventSquads when P1017 exhausts the retry (BIT-32475)' (#279) from fix/BIT-32475-sports-p1017-connection-closed-retry-exhausted into main
ci / rust (push) Successful in 3m51s
ci / typescript (push) Successful in 8m50s
2026-11-18 22:35:45 +00:00
spark 812adb21a6 Merge pull request 'fix(archive): downgrade 57P01 admin-terminated connection in rematch and takeOffFutureGames to info (BIT-32473)' (#277) from fix/BIT-32473-archive-57p01-admin-shutdown into main
ci / rust (push) Successful in 3m45s
ci / typescript (push) Successful in 9m39s
2026-11-18 22:31:17 +00:00
paula-alves 67adf1ce70 fix(sports): stop syncEventSquads when P1017 exhausts the retry (BIT-32475)
ci / rust (pull_request) Successful in 5m54s
ci / typescript (pull_request) Successful in 11m6s
The error loop reported PrismaClientKnownRequestError P1017 ("Server has
closed the connection.") from linkSquadPerson -> person.findFirst.
retryOnConnectionClosed (BIT-32460) already retries syncEventSquadsNow once
on a fresh client; when the server keeps closing the pool (a restart or
pg_terminate_backend tearing through clients), the second attempt fails the
same way and the rejection escaped the syncEventSquads catch, which only
matched isPrismaServerUnreachable (P1001/57P03). The warn paged the error
loop for a transient blip.

Treat a P1017 that survives the retry like the existing unreachable
handling: log at info and stop the sync, letting the next scheduled call
retry once the pool is stable. Mirrors BIT-32463/BIT-32470/BIT-32471.

Paperclip-Issue: BIT-32475
Paperclip-Cluster: 792bb5de9fcb
2026-11-18 22:22:41 +00:00
spark 9f5456dfc1 test(sports): cover 57P03 from personForIdentity sportsPlayer.findMany (BIT-32474) (#278)
ci / rust (push) Successful in 4m20s
ci / typescript (push) Successful in 9m34s
2026-11-18 22:17:05 +00:00
paula-alves 03fdba9557 fix(archive): downgrade 57P01 admin-terminated connection in rematch and takeOffFutureGames to info (BIT-32473)
ci / rust (pull_request) Successful in 4m22s
ci / typescript (pull_request) Successful in 10m41s
Postgres killing a pooled client mid-query (a restart, pg_terminate_backend,
SQLSTATE 57P01) surfaced as a PrismaClientKnownRequestError (P2039 wrapping
'Database error. Code: 57P01') inside findFixture -> eventOf -> rematch, and
again in takeOffFutureGames. Both loops already stopped the batch on an
unreachable database (P1001/57P03, BIT-32462/BIT-32469) but logged a warn per
folder for 57P01, which paged the error loop for a transient blip.

Treat isPostgresAdminShutdown the same way: log at info, stop the batch, and
let the next verifyAll retry once the pool reclaims a fresh client.

Paperclip-Issue: BIT-32473
Paperclip-Cluster: 53d4888f9b94
2026-11-18 22:00:30 +00:00
spark 50f813b931 fix(archive): stop takeOffFutureGames and downgrade P2010 unreachable-database errors to info (BIT-32469) (#276)
ci / rust (push) Successful in 3m57s
ci / typescript (push) Successful in 10m56s
2026-11-18 21:54:53 +00:00
spark 238f4cad1f fix(sports): downgrade 57P01 admin-terminated connection in linkStoredSquads to info (BIT-32471) (#275)
ci / rust (push) Successful in 3m44s
ci / typescript (push) Successful in 9m36s
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 ran an unguarded $queryRaw, so the rejection escaped to SportsWorker.fillRegister catch and logged warn ("sports: register not filled"), paging the error loop for a transient blip (BIT-32471, ERRCLUSTER 498b9b73d09c).

Wrap the $queryRaw (extracted into linkStoredSquadsRows) so an admin-shutdown is detected via isPostgresAdminShutdown, logged at info, and returns 0 — fillRegister loop breaks and the next scheduled tick retries on a fresh client. Non-transient errors still rethrow.

Tests: 23 pass (pg.test.ts, service.test.ts) incl. 2 new cases. Typecheck clean.

Paperclip-Issue: BIT-32471
2026-11-18 21:39:58 +00:00
spark 6f57f8a06c fix(sports): downgrade 57P03 database-shutting-down errors in syncEventSquads to info (BIT-32470) (#274)
ci / rust (push) Successful in 4m5s
ci / typescript (push) Successful in 9m34s
Paperclip-Issue: BIT-32470
2026-11-18 21:20:11 +00:00
paula-alves 49d3687973 fix(sports): downgrade 57P03 database-shutting-down errors in syncEventSquads to info (BIT-32470)
ci / rust (pull_request) Successful in 4m26s
ci / typescript (pull_request) Successful in 9m40s
Postgres surfaces a graceful shutdown as SQLSTATE 57P03 ("the database system
is shutting down") wrapped inside a PrismaClientKnownRequestError message.
syncEventSquads already stops the batch and logs info for P1001 (server
unreachable) via isPrismaServerUnreachable, but 57P03 escaped the catch and
rejected to the archive caller's warn, paging the error loop for a transient
blip. Extend isPrismaServerUnreachable to also match 57P03 / "the database
system is shutting down" so the same stop-and-retry-next-run path applies.

Paperclip-Issue: BIT-32470
2026-11-18 21:09:37 +00:00
spark 16030b9249 fix(sports): downgrade P1001 unreachable-database errors in syncEventSquads to info (BIT-32463) (#273)
ci / rust (push) Successful in 3m59s
ci / typescript (push) Successful in 9m14s
2026-11-18 20:47:51 +00:00
paula-alves 6232b41e5c fix(sports): downgrade P1001 unreachable-database errors in syncEventSquads to info (BIT-32463)
ci / rust (pull_request) Successful in 4m56s
ci / typescript (pull_request) Successful in 10m37s
A Postgres restart or a downed route makes the database unreachable
(Prisma P1001: "Can't reach database server at <host>:<port>") 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
2026-11-18 20:35:30 +00:00
spark f43be9f978 fix(archive): stop rematch and downgrade P1001 unreachable-database errors to info (BIT-32462) (#272)
ci / rust (push) Successful in 3m25s
ci / typescript (push) Successful in 10m35s
A Postgres restart or a downed route makes the database unreachable (Prisma P1001) mid-rematch. The per-folder catch logged it at warn, paging the error loop for a transient blip, and every remaining folder would fail the same way. Detect P1001 with isPrismaServerUnreachable (lib/pg.ts), log at info and break the folder loop; the next verifyAll retries. Same pattern as faces/develop/autopilot (BIT-32448/32449/32450).

Paperclip-Issue: BIT-32462
2026-11-18 20:31:56 +00:00
paula-alves 0be8d27ffe fix(archive): stop rematch and downgrade P1001 unreachable-database errors to info (BIT-32462)
ci / rust (pull_request) Successful in 4m29s
ci / typescript (pull_request) Successful in 9m14s
A Postgres restart or a downed route makes the database unreachable
(Prisma P1001: "Can't reach database server at <host>:<port>") 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
2026-11-18 20:22:17 +00:00
spark 0c20b6ba4a fix(sports): retry syncEventSquads when Postgres closes the pooled client (BIT-32460) (#271)
ci / rust (push) Successful in 4m10s
ci / typescript (push) Successful in 10m35s
2026-11-18 20:17:37 +00:00
spark 902ebda6fb Merge pull request 'fix(develop): downgrade 57P01 admin-shutdown poll errors to info (BIT-32449)' (#269) from fix/BIT-32449-develop-pg-admin-shutdown into main
ci / rust (push) Successful in 4m29s
ci / typescript (push) Successful in 10m33s
2026-11-18 18:26:38 +00:00
spark 99eb18aadb Merge branch 'main' into fix/BIT-32449-develop-pg-admin-shutdown
ci / rust (pull_request) Successful in 4m11s
ci / typescript (pull_request) Successful in 8m53s
2026-11-18 18:15:22 +00:00
spark 444c1e492a fix(faces): downgrade 57P01 admin-shutdown poll errors to info (BIT-32450) (#270)
ci / rust (push) Successful in 4m17s
ci / typescript (push) Successful in 9m1s
2026-11-18 18:14:31 +00:00
paula-alves 3f7455ebfa fix(faces): downgrade 57P01 admin-shutdown poll errors to info so they stop paging the error loop (BIT-32450)
ci / rust (pull_request) Successful in 4m24s
ci / typescript (pull_request) Successful in 9m47s
A Postgres restart or pg_terminate_backend (error 57P01) kills the pooled
client mid-`prisma.` in FaceWorker.claimWhere. Prisma surfaces it
as P2010 wrapping the server message. The next tick re-claims a fresh
client, so this is a transient blip: log it at info and keep looping instead
of warning, which was paging the error loop.

Reuses the shared isPostgresAdminShutdown helper from lib/pg.js (introduced
for the autopilot and develop workers in BIT-32448/BIT-32449).
2026-11-18 18:04:28 +00:00
paula-alves 4e093af85d fix(develop): downgrade 57P01 admin-shutdown poll errors to info so they stop paging the error loop (BIT-32449)
ci / rust (pull_request) Successful in 3m29s
ci / typescript (pull_request) Successful in 8m31s
A Postgres restart or `pg_terminate_backend` (error 57P01) takes the render worker's pooled client mid-`$queryRaw` in `DevelopService.claimRenders`. Prisma surfaces it as P2010 wrapping the server message, and the catch in `RenderWorker.start` logged it at warn as "develop: poll failed" — which fed the error loop on every tick during a DB restart. The next tick re-claims a fresh client, so this is a transient blip: detect 57P01 and log at info instead, keeping the warn path for real poll failures. Extract `isPostgresAdminShutdown` into `lib/pg.ts` so develop and autopilot share one definition.

Paperclip-Issue: BIT-32449
Paperclip-Cluster: 8d12f6208533
2026-11-18 18:00:19 +00:00
spark e242c8e45f fix(autopilot): downgrade 57P01 admin-shutdown poll errors to info (BIT-32448) (#268)
ci / rust (push) Successful in 3m12s
ci / typescript (push) Successful in 7m31s
A Postgres restart or pg_terminate_backend (57P01) kills the autopilot worker's pooled client mid-$queryRaw; the tick catch logged it at warn as "autopilot: poll failed", feeding the error loop on every tick during a DB restart. Detect 57P01 and log at info; keep warn for real poll failures.

Paperclip-Issue: BIT-32448
Paperclip-Cluster: 5019795ae39d
2026-11-18 17:52:28 +00:00
paula-alves 50699fa675 fix(autopilot): downgrade 57P01 admin-shutdown poll errors to info so they stop paging the error loop (BIT-32448)
ci / rust (pull_request) Successful in 3m49s
ci / typescript (pull_request) Successful in 9m21s
A Postgres restart or `pg_terminate_backend` (error 57P01) takes the autopilot's pooled client mid-`$queryRaw`. Prisma surfaces it as P2010 wrapping the server message, and the catch in `AutopilotWorker.start` logged it at warn as "autopilot: poll failed" — which fed the error loop on every tick during a DB restart. The next tick re-claims a fresh client, so this is a transient blip: detect 57P01 and log at info instead, keeping the warn path for real poll failures.

Paperclip-Issue: BIT-32448
Paperclip-Cluster: 5019795ae39d
2026-11-18 17:42:15 +00:00
spark 76aadb60ae Merge pull request 'fix(realtime): handle pg.Pool idle-client errors so admin-killed connections do not crash the worker (BIT-32447)' (#267) from fix/BIT-32447-pg-pool-error-handler into main
ci / rust (push) Successful in 4m48s
ci / typescript (push) Successful in 10m48s
2026-11-18 17:33:19 +00:00
paula-alves 4a7dba5480 fix(realtime): handle pg.Pool idle-client errors so admin-killed connections do not crash the worker (BIT-32447)
ci / rust (pull_request) Successful in 4m22s
ci / typescript (pull_request) Successful in 10m36s
PostgreSQL error 57P01 (terminating connection due to administrator command)
is emitted as an 'error' event on the pg.Pool when an idle pooled client is
killed. Both attachRealtime (API) and createRemoteBroadcaster (ingest worker)
created pools without an 'error' listener, so Node treated it as an
uncaughtException and crashed the process. Add pool.on('error') handlers that
forward to onError (and skip noise during shutdown), mirroring the existing
client.on('error') reconnection logic.

Paperclip-Issue: BIT-32447
Paperclip-Cluster: 52b3174b839d
2026-11-18 17:19:03 +00:00
spark c774d6b0f1 fix(autopilot): send warm-up and other picks to the rest client (BIT-265) (#266)
ci / rust (push) Successful in 4m16s
ci / typescript (push) Successful in 8m46s
fix(autopilot): send warm-up and other picks to the rest client (BIT-265)

Closes #265
2026-11-15 20:11:27 +00:00
spark f36eb25f47 fix(autopilot): send warm-up and other picks to the rest client (BIT-265)
ci / rust (pull_request) Successful in 5m27s
ci / typescript (pull_request) Successful in 10m35s
With «Só as melhores», FPA (rest) only got the 2nd frame of gallery moments.
Aquecimento, Betclic ads and people-without-ball picks never left the window
because delivery only iterated curated chosen ids. Rest now also gets
restBeside for each closed window, including warm-up (−1).
2026-11-15 19:58:35 +00:00
spark 9e464ee267 Merge pull request 'fix(desktop): flush remembered Lightroom marks into work-folder files (BIT-262)' (#264) from task/BIT-262-flush-work-folder-xmp into main
ci / rust (push) Successful in 4m54s
ci / typescript (push) Successful in 9m40s
2026-11-14 18:31:55 +00:00
21 changed files with 1218 additions and 64 deletions

No files matched your search

+158
View File
@@ -48,3 +48,161 @@ 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<unknown>) => ({
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<number> }).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("logs at info and stops the batch when the database is unreachable (P2010 raw-query wrapper, BIT-32469)", async () => {
const log = makeLog();
const calls: string[] = [];
const db = makeDb(async () => {
calls.push("findUnique");
throw Object.assign(
new Error("Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `N/A`. Message: `Can't reach database server at 127.0.0.1:5432`"),
{ code: "P2010" },
);
});
const service = new ArchiveService({ db, log } as never);
const moved = await (service as unknown as { rematch: (sourceId: string) => Promise<number> }).rematch("src-1");
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("logs at info and stops the batch when Postgres terminates the connection (57P01, BIT-32473)", async () => {
const log = makeLog();
const calls: string[] = [];
const db = makeDb(async () => {
calls.push("findUnique");
throw Object.assign(
new Error("Invalid `prisma.sportsFixture.findMany()` invocation:\n\nDatabase error. Code: `57P01`. Message: `terminating connection due to administrator command`"),
{ code: "P2039" },
);
});
const service = new ArchiveService({ db, log } as never);
const moved = await (service as unknown as { rematch: (sourceId: string) => Promise<number> }).rematch("src-1");
expect(calls).toEqual(["findUnique"]);
expect(moved).toBe(0);
expect(log.calls.some((c) => c.level === "info" && /connection terminated/.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<number> }).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);
});
});
describe("takeOffFutureGames stops and downgrades an unreachable database (BIT-32469)", () => {
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: () => {},
};
};
it("logs at info and stops the batch when the database is unreachable (P2010, BIT-32469)", async () => {
const log = makeLog();
const calls: string[] = [];
const db = {
cloudFolder: {
findMany: async () => [
{ id: "f-1", path: "/Future Game", eventId: "evt-1", matchedBy: "NAME", fixtureRejected: false, source: { id: "src-1" } },
{ id: "f-2", path: "/Future Game 2", eventId: "evt-2", matchedBy: "NAME", fixtureRejected: false, source: { id: "src-1" } },
],
},
event: {
findUnique: async () => {
calls.push("findUnique");
throw Object.assign(
new Error("Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `N/A`. Message: `Can't reach database server at 127.0.0.1:5432`"),
{ code: "P2010" },
);
},
},
};
const service = new ArchiveService({ db, log } as never);
const moved = await (service as unknown as { takeOffFutureGames: () => Promise<number> }).takeOffFutureGames();
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" && /not moved/.test(c.msg))).toBe(false);
});
it("logs at info and stops the batch when Postgres terminates the connection (57P01, BIT-32473)", async () => {
const log = makeLog();
const calls: string[] = [];
const db = {
cloudFolder: {
findMany: async () => [
{ id: "f-1", path: "/Future Game", eventId: "evt-1", matchedBy: "NAME", fixtureRejected: false, source: { id: "src-1" } },
{ id: "f-2", path: "/Future Game 2", eventId: "evt-2", matchedBy: "NAME", fixtureRejected: false, source: { id: "src-1" } },
],
},
event: {
findUnique: async () => {
calls.push("findUnique");
throw Object.assign(
new Error("Invalid `prisma.sportsFixture.findMany()` invocation:\n\nDatabase error. Code: `57P01`. Message: `terminating connection due to administrator command`"),
{ code: "P2039" },
);
},
},
};
const service = new ArchiveService({ db, log } as never);
const moved = await (service as unknown as { takeOffFutureGames: () => Promise<number> }).takeOffFutureGames();
expect(calls).toEqual(["findUnique"]);
expect(moved).toBe(0);
expect(log.calls.some((c) => c.level === "info" && /connection terminated/.test(c.msg))).toBe(true);
expect(log.calls.some((c) => c.level === "warn" && /not moved/.test(c.msg))).toBe(false);
});
});
+29
View File
@@ -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 { isPostgresAdminShutdown, isPrismaServerUnreachable } from "../lib/pg.js";
import type { LocalStorage } from "../storage/storage.js";
import { CloudClient, cleanBase, pollLogin, startLogin, type CloudEntry } from "./nextcloud.js";
import {
@@ -617,6 +618,20 @@ export class ArchiveService {
moved++;
log.warn({ folderId: folder.id, path: folder.path }, "archive: gallery taken off a game still to come");
} catch (err) {
// The database server is unreachable (P1001/P2010 wrapping "Can't reach database server": a restart, a
// downed route). Every remaining folder would fail the same way, so stop the batch and let the next
// verifyAll retry — logging a warn per folder pages the error loop for a transient blip (BIT-32469).
if (isPrismaServerUnreachable(err)) {
log.info({ err: (err as Error).message, folderId: folder.id, path: folder.path }, "archive: future-game check stopped, database unreachable");
break;
}
// Postgres killed the pooled client mid-query (a restart, `pg_terminate_backend`, error 57P01): the next
// folder would hit the same terminated connection until the pool reclaims a fresh client, so stop the batch
// and let the next verifyAll retry — a warn per folder pages the error loop for a transient blip (BIT-32473).
if (isPostgresAdminShutdown(err)) {
log.info({ err: (err as Error).message, folderId: folder.id, path: folder.path }, "archive: future-game check stopped, database connection terminated");
break;
}
log.warn({ err, folderId: folder.id, path: folder.path }, "archive: gallery on a game still to come not moved");
}
}
@@ -661,6 +676,20 @@ 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;
}
// Postgres killed the pooled client mid-query (a restart, `pg_terminate_backend`, error 57P01): the next
// folder would hit the same terminated connection until the pool reclaims a fresh client, so stop the batch
// and let the next verifyAll retry — a warn per folder pages the error loop for a transient blip (BIT-32473).
if (isPostgresAdminShutdown(err)) {
log.info({ err: (err as Error).message, folderId: folder.id, path: folder.path }, "archive: gallery check stopped, database connection terminated");
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) });
}
+71
View File
@@ -95,6 +95,77 @@ export function restBeside(
return out;
}
export interface WindowExportPhoto {
id: string;
flag: string;
score: number;
hold: string | null;
capturedAt: Date | null;
cameraSerial: string | null;
cameraModel: string | null;
uploaderId: string | null;
}
/**
* Where each frame of a decided "only the best" window goes. Gallery targets get the best of each chosen
* moment (rank i → gallery target i). The rest target (when set) gets the next ranks of those bursts and
* every other pick / sequence mate in the window — including warm-up, where there are no chosen moments.
* Same photo never listed twice.
*/
export function assignBestRestExports(opts: {
targets: readonly string[];
restId: string | null;
chosenMoments: readonly string[];
burstOf: ReadonlyMap<string, readonly string[]>;
photos: readonly WindowExportPhoto[];
windowIds: ReadonlySet<string>;
allowed: (id: string) => boolean;
}): { targetId: string; photoId: string }[] {
const { targets, restId, chosenMoments, burstOf, photos, windowIds, allowed } = opts;
if (!targets.length) return [];
const byId = new Map(photos.map((p) => [p.id, p]));
const galleryTargets = restId
? targets.filter((t) => t !== restId)
: [...targets];
const assignTargets = restId
? [...galleryTargets, restId]
: [...targets];
const out: { targetId: string; photoId: string }[] = [];
const sent = new Set<string>();
const gallerySent: string[] = [];
for (const momentId of chosenMoments) {
const burstIds = burstOf.get(momentId) ?? [momentId];
const ranked = burstIds
.map((id) => byId.get(id))
.filter((p): p is WindowExportPhoto => !!p)
.filter((p) => p.flag !== "REJECT" && p.hold !== "ball")
.sort((a, b) => b.score - a.score);
for (let i = 0; i < assignTargets.length && i < ranked.length; i++) {
const photo = ranked[i]!;
if (sent.has(photo.id)) continue;
if (!allowed(photo.id)) continue;
const targetId = assignTargets[i]!;
out.push({ targetId, photoId: photo.id });
sent.add(photo.id);
if (targetId !== restId) gallerySent.push(photo.id);
}
}
if (!restId) return out;
const windowPhotos = photos.filter((p) => windowIds.has(p.id));
for (const id of restBeside(windowPhotos, gallerySent)) {
if (sent.has(id)) continue;
if (byId.get(id)?.hold === "ball") continue;
if (!allowed(id)) continue;
out.push({ targetId: restId, photoId: id });
sent.add(id);
}
return out;
}
/**
* Grow a curated set up to `count`. First prefers spread (no twin within `minGapMs`), then drops the time gap,
* then — only if still short — takes a second frame from bursts already used. The number the photographer asked
+71 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { restBeside } from "./best.js";
import { assignBestRestExports, restBeside, type WindowExportPhoto } from "./best.js";
const at = (iso: string) => new Date(iso);
const shot = (id: string, flag: string, iso: string) => ({
@@ -11,6 +11,12 @@ const shot = (id: string, flag: string, iso: string) => ({
uploaderId: null,
});
const exportShot = (id: string, flag: string, iso: string, score: number, hold: string | null = null): WindowExportPhoto => ({
...shot(id, flag, iso),
score,
hold,
});
describe("the rest beside the best", () => {
it("keeps the other picks and the other frames of those sequences, and drops rejects and untouched sequences", () => {
const photos = [
@@ -23,3 +29,67 @@ describe("the rest beside the best", () => {
expect(restBeside(photos, ["best"])).toEqual(["pick", "frame"]);
});
});
describe("assignBestRestExports", () => {
const record = "11111111-1111-4111-8111-111111111111";
const fap = "22222222-2222-4222-8222-222222222222";
it("sends warm-up and other picks to the rest client, gallery moments only to the gallery", () => {
const photos = [
exportShot("warm", "PICK", "2026-10-18T13:40:00.000Z", 4),
exportShot("a1", "PICK", "2026-10-18T14:00:00.000Z", 9),
exportShot("a2", "PICK", "2026-10-18T14:00:00.100Z", 6),
exportShot("b1", "PICK", "2026-10-18T14:00:30.000Z", 3),
exportShot("b2", "PICK", "2026-10-18T14:00:30.100Z", 2),
];
const burstOf = new Map<string, string[]>([
["warm", ["warm"]],
["a1", ["a1", "a2"]],
["b1", ["b1", "b2"]],
]);
// Match window: only a1 chosen for the gallery.
const match = assignBestRestExports({
targets: [record, fap],
restId: fap,
chosenMoments: ["a1"],
burstOf,
photos,
windowIds: new Set(["a1", "a2", "b1", "b2"]),
allowed: () => true,
});
expect(match.filter((x) => x.targetId === record).map((x) => x.photoId)).toEqual(["a1"]);
expect(match.filter((x) => x.targetId === fap).map((x) => x.photoId).sort()).toEqual(["a2", "b1", "b2"]);
// Warm-up window: nothing chosen for the gallery; every pick goes to the rest client.
const warm = assignBestRestExports({
targets: [record, fap],
restId: fap,
chosenMoments: [],
burstOf,
photos,
windowIds: new Set(["warm"]),
allowed: () => true,
});
expect(warm).toEqual([{ targetId: fap, photoId: "warm" }]);
});
it("never sends the same photo to both clients, and skips a cut ball", () => {
const photos = [
exportShot("best", "PICK", "2026-10-18T14:00:00.000Z", 9),
exportShot("cut", "PICK", "2026-10-18T14:00:00.200Z", 8, "ball"),
exportShot("second", "PICK", "2026-10-18T14:00:00.400Z", 5),
];
const out = assignBestRestExports({
targets: [record, fap],
restId: fap,
chosenMoments: ["best"],
burstOf: new Map([["best", ["best", "cut", "second"]]]),
photos,
windowIds: new Set(["best", "cut", "second"]),
allowed: () => true,
});
expect(out.map((x) => x.photoId).sort()).toEqual(["best", "second"]);
expect(out.filter((x) => x.targetId === record).map((x) => x.photoId)).toEqual(["best"]);
expect(out.filter((x) => x.targetId === fap).map((x) => x.photoId)).toEqual(["second"]);
});
});
+66
View File
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import { AutopilotWorker, isPostgresAdminShutdown, type AutopilotService } from "./service.js";
import type { IngestLogger } from "../ingest/service.js";
describe("isPostgresAdminShutdown", () => {
it("matches the 57P01 admin-shutdown message Prisma surfaces from a raw query (BIT-32448)", () => {
const err = new Error(
"Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `57P01`. Message: `terminating connection due to administrator command`",
);
expect(isPostgresAdminShutdown(err)).toBe(true);
});
it("does not match an unrelated query error", () => {
expect(isPostgresAdminShutdown(new Error("relation \"photos\" does not exist"))).toBe(false);
expect(isPostgresAdminShutdown(null)).toBe(false);
expect(isPostgresAdminShutdown("string")).toBe(false);
});
});
describe("AutopilotWorker poll error handling", () => {
type Level = "info" | "warn";
const makeLog = (): IngestLogger & { 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 }),
};
};
const makeService = (decideErr: unknown): Pick<AutopilotService, "requeueStale" | "claim" | "decideBursts" | "process"> => ({
requeueStale: async () => undefined,
claim: async () => [],
decideBursts: async () => {
throw decideErr;
},
process: async () => undefined,
});
it("logs a 57P01 admin shutdown at info, not warn, and keeps looping (BIT-32448)", async () => {
const log = makeLog();
const worker = new AutopilotWorker(makeService(new Error("terminating connection due to administrator command (57P01)")) as AutopilotService, {
concurrency: 1,
intervalMs: 60_000,
log,
});
worker.start();
await new Promise((r) => setTimeout(r, 20));
await worker.stop();
expect(log.calls.some((c) => c.level === "info" && /db connection was reset/.test(c.msg))).toBe(true);
expect(log.calls.some((c) => c.level === "warn" && /poll failed/.test(c.msg))).toBe(false);
});
it("still warns on a real poll failure", async () => {
const log = makeLog();
const worker = new AutopilotWorker(makeService(new Error("relation photos does not exist")) as AutopilotService, {
concurrency: 1,
intervalMs: 60_000,
log,
});
worker.start();
await new Promise((r) => setTimeout(r, 20));
await worker.stop();
expect(log.calls.some((c) => c.level === "warn" && /poll failed/.test(c.msg))).toBe(true);
});
});
+39 -21
View File
@@ -14,7 +14,7 @@ import type { Broadcaster } from "../realtime.js";
import type { LocalStorage } from "../storage/storage.js";
import { focusFromExifJson } from "../ingest/focus.js";
import { readFocusPoint } from "../ingest/exif.js";
import { CANDIDATE_SELECT, candidatesOf } from "./best.js";
import { assignBestRestExports, CANDIDATE_SELECT, candidatesOf } from "./best.js";
import { sequenceWeights } from "./sequence.js";
import { bestOf, FOCUS_SHARP, groupBursts, reportagePickCount } from "./bursts.js";
import { curate, matchMinutes } from "./curate.js";
@@ -436,26 +436,41 @@ export class AutopilotService {
const when = new Map(photos.map((p) => [p.id, p.capturedAt]));
chosenCount += chosen.size;
if (!galleries.length && targets.length && this.deps.deliveries && event.createdById) {
// Per chosen moment (burst): rank i → export i. Same photo never to two destinations.
for (const momentId of chosen) {
const burstIds = burstOf.get(momentId) ?? [momentId];
const burstPhotos = burstIds.map((id) => photos.find((p) => p.id === id)).filter(Boolean) as typeof photos;
const rankedBurst = burstPhotos
.map((p) => ({ ...p, score: ((p.autopilot as AutopilotRecord | null)?.score ?? 0) * (look.get(p.id) ?? 1) }))
.filter((p) => p.flag !== "REJECT" && (p.autopilot as AutopilotRecord | null)?.hold !== "ball")
.sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
for (let i = 0; i < targets.length && i < rankedBurst.length; i++) {
const photo = rankedBurst[i]!;
if (!takenHere([photo.id], when, event).length) continue;
await this.deps.deliveries
.enqueue({ organizationId: event.organizationId, targetId: targets[i]!, photoIds: [photo.id], again: false, requestedById: event.createdById })
.catch((err: unknown) => log.warn({ err, targetId: targets[i] }, "autopilot: delivery not queued"));
}
const restId =
settings.restTargetId && targets.includes(settings.restTargetId)
? settings.restTargetId
: null;
const exports = assignBestRestExports({
targets,
restId,
chosenMoments: [...chosen],
burstOf,
windowIds: ids,
allowed: (id) => takenHere([id], when, event).length > 0,
photos: photos.map((p) => {
const rec = p.autopilot as AutopilotRecord | null;
return {
id: p.id,
flag: p.flag,
score: (rec?.score ?? 0) * (look.get(p.id) ?? 1),
hold: rec?.hold ?? null,
capturedAt: p.capturedAt,
cameraSerial: p.cameraSerial,
cameraModel: p.cameraModel,
uploaderId: p.uploaderId,
};
}),
});
for (const { targetId, photoId } of exports) {
await this.deps.deliveries
.enqueue({ organizationId: event.organizationId, targetId, photoIds: [photoId], again: false, requestedById: event.createdById })
.catch((err: unknown) => log.warn({ err, targetId }, "autopilot: delivery not queued"));
}
} else if (targets.length === 0) {
/* no auto-export */
}
if (d.window >= 0) log.info({ eventId, window: d.window, candidates: d.ids.length, chosen: chosen.size }, "autopilot: best of the window");
else if (d.window === -1) log.info({ eventId, window: -1, candidates: d.ids.length }, "autopilot: warm-up window decided");
}
if (galleries.length && this.deps.deliveries && event.createdById) {
const when = new Map(photos.map((p) => [p.id, p.capturedAt]));
@@ -488,10 +503,6 @@ export class AutopilotService {
}
}
/**
* The photos of a decided window that go to the second client: the picked ones (by the autopilot or a person) the
* gallery did not take. Never a chosen one, so no photo reaches both clients.
*/
/** Gallery flags for a frame whose window was decided this pass. Unmentioned destinations stay as they were. */
function galleryMarks(
id: string,
@@ -537,6 +548,10 @@ function distinctPlan(a: Box, b: Box): boolean {
return Math.abs(ah - bh) / Math.max(ah, bh, 1e-6) > 0.12;
}
import { isPostgresAdminShutdown } from "../lib/pg.js";
export { isPostgresAdminShutdown };
/** Polls the autopilot queue and settles bursts. */
export class AutopilotWorker {
private timer: ReturnType<typeof setTimeout> | undefined;
@@ -567,7 +582,10 @@ export class AutopilotWorker {
await this.service.decideBursts();
}
} catch (err) {
this.opts.log.warn({ err }, "autopilot: poll failed");
// A DB restart or `pg_terminate_backend` (57P01) takes the pooled client mid-query; the next tick
// re-claims a fresh one, so log at info and let the loop continue instead of paging the error loop (BIT-32448).
if (isPostgresAdminShutdown(err)) this.opts.log.info({ err: (err as Error).message }, "autopilot: poll skipped, db connection was reset");
else this.opts.log.warn({ err }, "autopilot: poll failed");
} finally {
this.ticking = false;
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
+66
View File
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import { RenderWorker, type DevelopService } from "./service.js";
import { isPostgresAdminShutdown } from "../lib/pg.js";
import type { IngestLogger } from "../ingest/service.js";
describe("isPostgresAdminShutdown", () => {
it("matches the 57P01 admin-shutdown message Prisma surfaces from a raw query (BIT-32449)", () => {
const err = new Error(
"Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `57P01`. Message: `terminating connection due to administrator command`",
);
expect(isPostgresAdminShutdown(err)).toBe(true);
});
it("does not match an unrelated query error", () => {
expect(isPostgresAdminShutdown(new Error("relation \"photos\" does not exist"))).toBe(false);
expect(isPostgresAdminShutdown(null)).toBe(false);
expect(isPostgresAdminShutdown("string")).toBe(false);
});
});
describe("RenderWorker poll error handling", () => {
type Level = "info" | "warn";
const makeLog = (): IngestLogger & { 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 }),
};
};
const makeService = (claimErr: unknown): Pick<DevelopService, "requeueStale" | "claimRenders" | "render"> => ({
requeueStale: async () => 0,
claimRenders: async () => {
throw claimErr;
},
render: async () => undefined,
});
it("logs a 57P01 admin shutdown at info, not warn, and keeps looping (BIT-32449)", async () => {
const log = makeLog();
const worker = new RenderWorker(makeService(new Error("terminating connection due to administrator command (57P01)")) as DevelopService, {
concurrency: 1,
intervalMs: 60_000,
log,
});
worker.start();
await new Promise((r) => setTimeout(r, 20));
await worker.stop();
expect(log.calls.some((c) => c.level === "info" && /db connection was reset/.test(c.msg))).toBe(true);
expect(log.calls.some((c) => c.level === "warn" && /poll failed/.test(c.msg))).toBe(false);
});
it("still warns on a real poll failure", async () => {
const log = makeLog();
const worker = new RenderWorker(makeService(new Error("relation photos does not exist")) as DevelopService, {
concurrency: 1,
intervalMs: 60_000,
log,
});
worker.start();
await new Promise((r) => setTimeout(r, 20));
await worker.stop();
expect(log.calls.some((c) => c.level === "warn" && /poll failed/.test(c.msg))).toBe(true);
});
});
+5 -1
View File
@@ -3,6 +3,7 @@ import type { Db } from "../db.js";
import { Prisma, type PhotoEdit } from "../generated/prisma/client.js";
import type { IngestLogger } from "../ingest/service.js";
import { waitUntil } from "../lib/idle.js";
import { isPostgresAdminShutdown } from "../lib/pg.js";
import { photoUrls } from "../library/serialize.js";
import type { Broadcaster } from "../realtime.js";
import { type LocalStorage, type UrlSigner, VARIANT_SIZE } from "../storage/storage.js";
@@ -219,7 +220,10 @@ export class RenderWorker {
});
}
} catch (err) {
this.opts.log.warn({ err }, "develop: poll failed");
// A DB restart or `pg_terminate_backend` (57P01) takes the pooled client mid-`$queryRaw`; the next tick
// re-claims a fresh one, so log at info and let the loop continue instead of paging the error loop (BIT-32449).
if (isPostgresAdminShutdown(err)) this.opts.log.info({ err: (err as Error).message }, "develop: poll skipped, db connection was reset");
else this.opts.log.warn({ err }, "develop: poll failed");
} finally {
this.ticking = false;
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
+5 -1
View File
@@ -6,6 +6,7 @@ import { DEFAULT_CODE_LIST } from "../library/iptc.js";
import type { FaceGroup, Person } from "../generated/prisma/client.js";
import type { IngestLogger } from "../ingest/service.js";
import { waitUntil } from "../lib/idle.js";
import { isPostgresAdminShutdown } from "../lib/pg.js";
import type { Broadcaster } from "../realtime.js";
import type { LocalStorage } from "../storage/storage.js";
import { normLabel } from "../jersey/service.js";
@@ -1530,7 +1531,10 @@ export class FaceWorker {
}
}
} catch (err) {
this.opts.log.warn({ err }, "faces: poll failed");
// A DB restart or `pg_terminate_backend` (57P01) takes the pooled client mid-`$queryRaw` (claimWhere); the next
// tick re-claims a fresh one, so log at info and let the loop continue instead of paging the error loop (BIT-32450).
if (isPostgresAdminShutdown(err)) this.opts.log.info({ err: (err as Error).message }, "faces: poll skipped, db connection was reset");
else this.opts.log.warn({ err }, "faces: poll failed");
} finally {
this.ticking = false;
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
+74
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { waitUntil } from "../lib/idle.js";
import { isPostgresAdminShutdown } from "../lib/pg.js";
import { FaceWorker, type FaceService } from "./service.js";
const quiet = { info() {}, warn() {}, error() {}, debug() {} } as never;
@@ -62,3 +63,76 @@ describe("the face worker", () => {
expect(started).toEqual([]);
});
});
describe("isPostgresAdminShutdown", () => {
it("matches the 57P01 admin-shutdown message Prisma surfaces from claimWhere's raw query (BIT-32450)", () => {
const err = new Error(
"Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `57P01`. Message: `terminating connection due to administrator command`",
);
expect(isPostgresAdminShutdown(err)).toBe(true);
});
it("does not match an unrelated query error", () => {
expect(isPostgresAdminShutdown(new Error("relation \"photos\" does not exist"))).toBe(false);
expect(isPostgresAdminShutdown(null)).toBe(false);
expect(isPostgresAdminShutdown("string")).toBe(false);
});
});
describe("FaceWorker poll error handling", () => {
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 makeService = (claimErr: unknown): Pick<FaceService, "requeueStale" | "refreshLineupEvents" | "queueMissed" | "requeueFailed" | "requeueVideos" | "claimVideos" | "claim" | "claimReferences" | "processReference" | "process" | "processVideo" | "stopVideos"> => ({
requeueStale: async () => 0,
refreshLineupEvents: async () => 0,
queueMissed: async () => {
throw claimErr;
},
requeueFailed: async () => 0,
requeueVideos: async () => 0,
claimVideos: async () => [],
claim: async () => [],
claimReferences: async () => [],
processReference: async () => {},
process: async () => {},
processVideo: async () => {},
stopVideos: () => {},
});
it("logs a 57P01 admin shutdown at info, not warn, and keeps looping (BIT-32450)", async () => {
const log = makeLog();
const worker = new FaceWorker(makeService(new Error("terminating connection due to administrator command (57P01)")) as unknown as FaceService, {
concurrency: 1,
intervalMs: 60_000,
log: log as unknown as never,
});
worker.start();
await new Promise((r) => setTimeout(r, 20));
await worker.stop();
expect(log.calls.some((c) => c.level === "info" && /db connection was reset/.test(c.msg))).toBe(true);
expect(log.calls.some((c) => c.level === "warn" && /poll failed/.test(c.msg))).toBe(false);
});
it("still warns on a real poll failure", async () => {
const log = makeLog();
const worker = new FaceWorker(makeService(new Error("relation photos does not exist")) as unknown as FaceService, {
concurrency: 1,
intervalMs: 60_000,
log: log as unknown as never,
});
worker.start();
await new Promise((r) => setTimeout(r, 20));
await worker.stop();
expect(log.calls.some((c) => c.level === "warn" && /poll failed/.test(c.msg))).toBe(true);
});
});
+147
View File
@@ -0,0 +1,147 @@
import { describe, expect, it } from "vitest";
import { isPostgresAdminShutdown, isPrismaConnectionClosed, isPrismaServerUnreachable, 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("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 a P2010 raw-query failure wrapping the unreachable message (BIT-32469)", () => {
const err = new PrismaLike(
"P2010",
"Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `N/A`. Message: `Can'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("matches a Postgres graceful-shutdown error surfaced as 57P03 (BIT-32470)", () => {
const err = new PrismaLike(
"P2039",
"Invalid `prisma.person.findFirst()` invocation:\n\nDatabase error. Code: `57P03`. Message: `the database system is shutting down`",
);
expect(isPrismaServerUnreachable(err)).toBe(true);
});
it("matches the 57P03 shutdown message without the Prisma code", () => {
expect(isPrismaServerUnreachable(new Error("Database error. Code: `57P03`. Message: `the database system is shutting down`"))).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;
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");
});
});
+56
View File
@@ -0,0 +1,56 @@
/**
* Postgres killed a pooled client mid-query (restart, `pg_terminate_backend`, error 57P01). Prisma surfaces the
* raw-query failure as P2010 wrapping the server message; the next tick re-claims a fresh client, so this is a
* transient blip and must not surface as a worker error (BIT-32448, BIT-32449).
*/
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);
}
/**
* The database server is unreachable — Prisma never opened a connection (the server is down, restarting, or a
* network blip dropped the route), or Postgres is mid graceful shutdown. Prisma surfaces the former as
* `PrismaClientKnownRequestError` with code `P1001` ("Can't reach database server at <host>:<port>"), and a
* graceful shutdown (SQLSTATE `57P03`, "the database system is shutting down") as a `Database error` message
* wrapping the raw SQLSTATE. 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, BIT-32470).
*/
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) ||
/57P03|the database system is shutting down/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<T>(fn: () => Promise<T>, delayMs = 250): Promise<T> {
try {
return await fn();
} catch (err) {
if (!isPrismaConnectionClosed(err)) throw err;
await new Promise((r) => setTimeout(r, delayMs));
return fn();
}
}
+12 -1
View File
@@ -93,7 +93,14 @@ export function attachRealtime(
deps: { db: Db; sessions: SessionService; databaseUrl: string; corsOrigins: string[]; onError?: (err: unknown) => void },
): Broadcaster {
const onError = deps.onError ?? (() => {});
let closed = false;
const pool = new pg.Pool({ connectionString: deps.databaseUrl, max: 2 });
// An idle pooled client killed by Postgres (restart, pg_terminate_backend, error 57P01) surfaces as an
// 'error' event on the pool itself; without a listener Node throws and crashes the process (BIT-32447).
pool.on("error", (err) => {
if (closed || isPoolEndedError(err)) return;
onError(err);
});
const io = new Server(server, {
path: "/v1/realtime",
transports: ["websocket"],
@@ -114,7 +121,6 @@ export function attachRealtime(
// A dedicated connection listens; it reconnects if Postgres restarts.
let listener: pg.Client | undefined;
let closed = false;
let retry: NodeJS.Timeout | undefined;
const pending = new Set<Promise<unknown>>();
const listen = async () => {
@@ -183,6 +189,11 @@ export function attachRealtime(
export function createRemoteBroadcaster(databaseUrl: string, onError: (err: unknown) => void = () => {}): Broadcaster {
const pool = new pg.Pool({ connectionString: databaseUrl, max: 1 });
let closed = false;
// Same guard as attachRealtime: an idle client killed by Postgres (57P01) must not crash the worker (BIT-32447).
pool.on("error", (err) => {
if (closed || isPoolEndedError(err)) return;
onError(err);
});
const pending = new Set<Promise<unknown>>();
const desk = (userId: string, command: DeskCommand) => {
if (closed) return;
+257
View File
@@ -0,0 +1,257 @@
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 p57p03 = () =>
Object.assign(
new Error("Invalid `prisma.person.findFirst()` invocation:\n\nDatabase error. Code: `57P03`. Message: `the database system is shutting down`"),
{ code: "P2039" },
);
const p57p03SportsPlayer = () =>
Object.assign(
new Error("Invalid `prisma.sportsPlayer.findMany()` invocation:\n\nDatabase error. Code: `57P03`. Message: `the database system is shutting down`"),
{ 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 p1017 = () =>
Object.assign(new Error("Invalid `prisma.person.findFirst()` invocation:\n\nServer has closed the connection."), { code: "P1017" });
const ligaTeam = (id: string, externalId: string) => ({
id,
provider: "LIGA",
externalId,
name: `Team ${id}`,
abbreviation: null,
logoUrl: null,
});
const makeEvent = (overrides: Record<string, unknown> = {}) => ({
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<string, unknown>) =>
({
db,
log: makeLog(),
fetch: (async () => new Response("{}")) as never,
storage: null,
signer: null,
}) as unknown as ConstructorParameters<typeof SportsService>[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<unknown[]> } }).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<unknown[]> } }).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);
});
});
describe("syncEventSquads downgrades a 57P03 database-shutting-down error (BIT-32470)", () => {
it("logs at info and returns zeros when linkSquadPerson hits 57P03 on person.findFirst", async () => {
const fpaTeam = {
id: "t-fpa",
provider: "FPA",
externalId: "fpa-1",
name: "Team FPA",
abbreviation: "FPA",
logoUrl: null,
};
const db = {
event: { findUnique: async () => makeEvent({ homeTeam: fpaTeam, awayTeam: null }) },
sportsPlayer: {
findFirst: async () => ({ season: "2026" }),
findMany: async () => [{ id: "pl-1", name: "Player 1", externalId: "lic-1", number: "1", photoUrl: null, season: "2026" }],
findUnique: async () => null,
},
person: {
findUnique: async () => null,
findFirst: async () => { throw p57p03(); },
},
};
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);
});
});
describe("syncEventSquads downgrades a 57P03 from personForIdentity's sportsPlayer.findMany (BIT-32474)", () => {
it("logs at info and returns zeros when personForIdentity hits 57P03 on sportsPlayer.findMany", async () => {
// The error loop reported 57P03 escaping at personForIdentity → sportsPlayer.findMany, one call deeper than
// the BIT-32470 test's person.findFirst. The same syncEventSquads catch (isPrismaServerUnreachable, which
// matches 57P03 since BIT-32470) covers this path: the error propagates through linkSquadPerson (no catch) to
// the syncEventSquads wrapper. This test proves that coverage.
const fpaTeam = {
id: "t-fpa",
provider: "FPA",
externalId: "fpa-1",
name: "Team FPA",
abbreviation: "FPA",
logoUrl: null,
};
let findManyCalls = 0;
const db = {
event: { findUnique: async () => makeEvent({ homeTeam: fpaTeam, awayTeam: null }) },
sportsPlayer: {
findFirst: async () => ({ season: "2026" }),
// First call: squad() reads the team's players. Second call: personForIdentity looks up the same human
// by birthDate/fullName (no externalId on the player, so the FPA licence lookup is skipped) and hits 57P03.
findMany: async () => {
findManyCalls++;
if (findManyCalls === 1)
return [{ id: "pl-1", name: "Player 1", externalId: null, birthDate: "2000-01-01", fullName: "Player One", number: "1", photoUrl: null, season: "2026" }];
throw p57p03SportsPlayer();
},
findUnique: async () => null,
},
person: {
findUnique: async () => null,
findFirst: async () => null,
},
};
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);
});
});
describe("syncEventSquads downgrades a P1017 server-closed connection that exhausts the retry (BIT-32475)", () => {
it("logs at info and returns zeros when person.findFirst is P1017 on both attempts", async () => {
// The error loop reported P1017 ("Server has closed the connection.") from linkSquadPerson → person.findFirst.
// retryOnConnectionClosed (BIT-32460) retries once on a fresh client; when the server keeps closing the pool
// (a restart tearing through clients), the second attempt fails the same way. Without this guard the rejection
// escapes to the archive caller's warn and pages the error loop for a transient blip.
const fpaTeam = {
id: "t-fpa",
provider: "FPA",
externalId: "fpa-1",
name: "Team FPA",
abbreviation: "FPA",
logoUrl: null,
};
const db = {
event: { findUnique: async () => makeEvent({ homeTeam: fpaTeam, awayTeam: null }) },
sportsPlayer: {
findFirst: async () => ({ season: "2026" }),
findMany: async () => [{ id: "pl-1", name: "Player 1", externalId: "lic-1", number: "1", photoUrl: null, season: "2026" }],
findUnique: async () => null,
},
person: {
findUnique: async () => null,
// Throws on every call, so the retry also fails with P1017.
findFirst: async () => { throw p1017(); },
},
};
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 connection closed/.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 = {
$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);
});
});
+70 -24
View File
@@ -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 { isPostgresAdminShutdown, isPrismaConnectionClosed, 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";
@@ -1424,7 +1425,29 @@ 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)).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 };
}
// The server closed the pooled client again on the retry (P1017): a restart or `pg_terminate_backend` is
// tearing through the pool, so the next query would fail the same way. The one retry already tried a fresh
// client (BIT-32460); stop here and let the next scheduled sync retry once the pool is stable, instead of
// rejecting to the archive caller's warn and paging the error loop for a transient blip (BIT-32475).
if (isPrismaConnectionClosed(err)) {
this.deps.log.info({ err: (err as Error).message, eventId }, "sports: squad sync stopped, database connection closed");
return { created: 0, updated: 0, headshots: 0 };
}
throw err;
}),
);
this.syncing.set(eventId, run);
try {
return await run;
@@ -1458,6 +1481,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");
@@ -1924,30 +1953,47 @@ export class SportsService {
async linkStoredSquads(limit = 8): Promise<number> {
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<number> {
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]));
+7 -7
View File
@@ -328,7 +328,7 @@ describe("autopilot", () => {
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: w2c } })).flag).toBe("PICK");
});
it("two clients: best of each chosen moment to the first export, second best to the second, never both", async () => {
it("two clients: gallery gets the best moments; rest gets seconds and every other pick (warm-up included)", async () => {
const { eventId, orgId, userId } = await setup();
const start = new Date(1_800_000_000_000);
const record = "11111111-1111-4111-8111-111111111111";
@@ -347,27 +347,27 @@ describe("autopilot", () => {
const sent: { targetId: string; photoIds: string[] }[] = [];
const deliveries = { enqueue: async (r: { targetId: string; photoIds: string[] }) => void sent.push({ targetId: r.targetId, photoIds: [...r.photoIds] }) };
const service = new AutopilotService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), broadcaster, log: quiet, develop, engine: new FakeEngine(), detector: () => Promise.resolve(detector as unknown as SubjectDetector), deliveries: deliveries as unknown as DeliveryService });
// Warm-up (ads / line-up): never a gallery moment, but still a pick for the rest client.
const warm = await shot(orgId, userId, eventId, -20 * 60_000, 400);
// Window 0: a strong burst and a weaker one.
const a1 = await shot(orgId, userId, eventId, 60_000, 900);
const a2 = await shot(orgId, userId, eventId, 60_100, 600);
const b1 = await shot(orgId, userId, eventId, 120_000, 300);
const b2 = await shot(orgId, userId, eventId, 120_100, 200);
// Taken before this event's window, still filed here: not this client's folder.
// Taken before this event's ingest window, still filed here: not this client's folder.
const later = await shot(orgId, userId, eventId, -3 * 60 * 60 * 1000, 950);
for (let ids = await service.claim(10); ids.length; ids = await service.claim(10)) for (const id of ids) await service.process(id);
await service.decideBursts(new Date(start.getTime() + 7 * 60_000));
const to = (target: string) => sent.filter((x) => x.targetId === target).flatMap((x) => x.photoIds);
// First export gets the best of each chosen moment; second export gets the second best. Same file never both.
// Gallery: best of the chosen moment only. Rest: second of that sequence, the other picks, and warm-up.
expect(to(record)).toEqual([a1]);
expect(to(fap)).toEqual([a2]);
expect(to(fap).sort()).toEqual([warm, a2, b1, b2].sort());
expect(to(record).filter((id) => to(fap).includes(id))).toEqual([]);
expect([...to(record), ...to(fap)]).not.toContain(later);
expect([...to(record), ...to(fap)]).not.toContain(b1);
expect([...to(record), ...to(fap)]).not.toContain(b2);
// Decided once: nothing is sent again.
await service.decideBursts(new Date(start.getTime() + 8 * 60_000));
expect(to(record)).toEqual([a1]);
expect(to(fap)).toEqual([a2]);
expect(to(fap).sort()).toEqual([warm, a2, b1, b2].sort());
});
it("never edits over a person's edit (made on the desktop app before the photo was uploaded)", async () => {
+44
View File
@@ -1,5 +1,6 @@
import { LIBRARY_CHANNEL, type LibraryMessage } from "@photoreport/contracts";
import type { AddressInfo } from "node:net";
import pg from "pg";
import { io, type Socket } from "socket.io-client";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { buildApp } from "../src/app.js";
@@ -75,4 +76,47 @@ describe("realtime", () => {
await worker.close();
expect(errors.filter((e) => e instanceof Error && /pool after calling end/i.test(e.message))).toEqual([]);
});
it("does not crash when Postgres terminates an idle pooled connection (BIT-32447)", async () => {
const errors: unknown[] = [];
const worker = createRemoteBroadcaster(ctx.config.DATABASE_URL, (err) => errors.push(err));
const message: LibraryMessage = {
type: "photo.updated",
ids: ["3f2a9c1e-5b7d-4e8a-9c21-7d4e5f6a8b90"],
patch: { flag: "PICK" },
};
// Establish the pool's single connection by publishing once.
worker.library("00000000-0000-0000-8000-000000000002", message);
// Give the NOTIFY query a moment to complete so the client returns idle to the pool.
await new Promise((r) => setTimeout(r, 200));
// An uncaughtException here would fail the test.
const uncaught: unknown[] = [];
const onUncaught = (err: unknown) => uncaught.push(err);
process.once("uncaughtException", onUncaught);
try {
// Find the pool's idle backend and terminate it, simulating an admin command (error 57P01).
const admin = new pg.Client({ connectionString: ctx.config.DATABASE_URL });
await admin.connect();
const db = await admin.query<{ pid: number }>(
`SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND state = 'idle' AND pid <> pg_backend_pid()`,
);
for (const { pid } of db.rows) await admin.query(`SELECT pg_terminate_backend($1)`, [pid]);
await admin.end();
// The pool emits 'error' for the killed client; wait for it to reach onError.
await new Promise((r) => setTimeout(r, 500));
expect(uncaught).toEqual([]);
expect(errors.some((e) => e instanceof Error && /terminating connection/i.test(e.message))).toBe(true);
// The pool must recover and publish again on a fresh connection without throwing.
worker.library("00000000-0000-0000-8000-000000000003", message);
await new Promise((r) => setTimeout(r, 300));
expect(uncaught).toEqual([]);
} finally {
process.removeListener("uncaughtException", onUncaught);
await worker.close();
}
});
});
+1 -1
View File
@@ -566,7 +566,7 @@ export const t = {
bestHelp: "Uma galeria curta de momentos de jogo: bola em jogo, duelos e festejos, jogadores grandes e nítidos no enquadramento, espalhados pelo jogo (a cada 5 minutos entram as melhores desse período). O número é a meta: num jogo rico pode ir um pouco acima (cerca de 15%, nunca mais de 25 fotos), num jogo fraco fica aquém. Numa sequência fica a de frente e com os olhos abertos, quando dá para distinguir. Aquecimento e intervalo ficam de fora; as fotos com estrelas têm prioridade e as rejeitadas nunca vão.",
restTarget: "As outras escolhidas para",
restHelp:
"Cada foto vai só para um cliente. A galeria acima leva a segunda melhor de cada sequência escolhida; todas as outras escolhidas seguem para aqui quando fecha cada período de 5 minutos.",
"Cada foto vai só para um cliente. A galeria acima leva a melhor de cada momento escolhido; a segunda dessa sequência e todas as outras escolhidas (aquecimento, publicidade, pessoas sem bola) seguem para aqui quando fecha cada período de 5 minutos.",
learnt: "Aprendido com as tuas correções",
learntHelp: (n: number, venue: string | null) => `${n} ${n === 1 ? "foto corrigida" : "fotos corrigidas"}${venue ? " neste recinto" : ""}. Aplica-se às próximas fotos que chegarem.`,
learning: (n: number) => `A aprender: ${n} ${n === 1 ? "correção" : "correções"} até agora (a partir de 5 que concordem, as próximas fotos já chegam assim).`,
+18 -4
View File
@@ -39,18 +39,32 @@ wait_for() {
return 1
}
# pm2 startOrReload has hung forever against a half-spawned daemon (pr-api, 2026-11-18): systemd then
# killed this unit at TimeoutStartSec and left the process list empty, so nothing was listening and nothing
# could report the outage. Bound the call; if it does not return, kill that daemon and try once more.
pm2_start() {
local config="$1"
if timeout 60s env APP_VERSION="$SHA" pm2 startOrReload "$config" --update-env; then
pm2 save --force >/dev/null
return 0
fi
log "pm2 startOrReload did not finish; resetting the daemon and retrying once"
pm2 kill >/dev/null 2>&1 || true
sleep 2
timeout 60s env APP_VERSION="$SHA" pm2 startOrReload "$config" --update-env
pm2 save --force >/dev/null
}
case "$SERVICE" in
api)
APP_VERSION="$SHA" pm2 startOrReload infra/pm2/api.config.cjs --update-env
pm2 save --force >/dev/null
pm2_start infra/pm2/api.config.cjs
# The database may come up after this container: PM2 keeps retrying (exp_backoff_restart_delay), so a slow
# start is reported, not treated as fatal.
wait_for "http://127.0.0.1:${API_PORT}/health" && log "api up at $SHA" || log "WARNING: api not healthy yet (PM2 keeps retrying)"
;;
site)
if [[ -f apps/site/.env ]]; then set -a; source apps/site/.env; set +a; fi
APP_VERSION="$SHA" pm2 startOrReload infra/pm2/site.config.cjs --update-env
pm2 save --force >/dev/null
pm2_start infra/pm2/site.config.cjs
wait_for "http://127.0.0.1:${SITE_PORT}/" && log "site up at $SHA" || log "WARNING: site not answering yet (PM2 keeps retrying)"
;;
app | ingest | workers | ml)
+16 -2
View File
@@ -45,6 +45,20 @@ wait_for_version() {
return 1
}
# pm2 startOrReload has hung forever against a half-spawned daemon (pr-api, 2026-11-18).
# Bound it; if it does not return, kill that daemon and try once more.
pm2_reload() {
local sha="$1"
local config="$2"
if timeout 90s env APP_VERSION="$sha" pm2 startOrReload "$config" --update-env; then
return 0
fi
log "pm2 startOrReload did not finish; resetting the daemon and retrying once"
pm2 kill >/dev/null 2>&1 || true
sleep 2
timeout 90s env APP_VERSION="$sha" pm2 startOrReload "$config" --update-env
}
deploy_api() {
local sha="$1"
node_install
@@ -65,7 +79,7 @@ deploy_api() {
# Same lock as boot.sh: a reboot racing this deploy's pm2 call against a freshly-spawned, still-empty PM2
# daemon duplicated photoreport-api on 2026-10-19 (crash-looped on EADDRINUSE forever). Serialize instead.
( exec 9>/run/photoreport-pm2.lock; flock 9
APP_VERSION="$sha" pm2 startOrReload infra/pm2/api.config.cjs --update-env
pm2_reload "$sha" infra/pm2/api.config.cjs
)
wait_for_version "http://127.0.0.1:${API_PORT}/health" "$sha"
# The process list PM2 restores after a reboot follows every deploy (photoreport-boot.service starts it too).
@@ -151,7 +165,7 @@ deploy_site() {
# class as the prisma CLI fix above, so a host's API_URL override actually reaches pm2.
if [[ -f apps/site/.env ]]; then set -a; source apps/site/.env; set +a; fi
( exec 9>/run/photoreport-pm2.lock; flock 9
APP_VERSION="$sha" pm2 startOrReload infra/pm2/site.config.cjs --update-env
pm2_reload "$sha" infra/pm2/site.config.cjs
)
local i
for ((i = 1; i <= HEALTH_TRIES; i++)); do
+6 -1
View File
@@ -11,7 +11,12 @@ RemainAfterExit=yes
Environment=HOME=/root
EnvironmentFile=/etc/photoreport/deploy-receiver.env
ExecStart=/bin/bash /srv/photoreport/infra/deploy/boot.sh
TimeoutStartSec=300
TimeoutStartSec=420
# A hung PM2 leaves this oneshot failed and the port closed. Retry instead of staying down until someone notices.
Restart=on-failure
RestartSec=30
StartLimitIntervalSec=900
StartLimitBurst=5
[Install]
WantedBy=multi-user.target