Compare commits
40
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0121f950b5 | ||
|
|
7a02cce000 | ||
|
|
c9e4e4af53 | ||
|
|
7a71ff1d10 | ||
|
|
bdbb5c364a | ||
|
|
6d4bb4f19e | ||
|
|
7c0e92b5ae | ||
|
|
ae47a3f703 | ||
|
|
a661742733 | ||
|
|
b2de0d4215 | ||
|
|
2e6be068f5 | ||
|
|
8daa66573d | ||
|
|
53fa7e110c | ||
|
|
c9c994e0a0 | ||
|
|
5b80e614f6 | ||
|
|
812adb21a6 | ||
|
|
67adf1ce70 | ||
|
|
9f5456dfc1 | ||
|
|
03fdba9557 | ||
|
|
50f813b931 | ||
|
|
238f4cad1f | ||
|
|
6f57f8a06c | ||
|
|
49d3687973 | ||
|
|
16030b9249 | ||
|
|
6232b41e5c | ||
|
|
f43be9f978 | ||
|
|
0be8d27ffe | ||
|
|
0c20b6ba4a | ||
|
|
902ebda6fb | ||
|
|
99eb18aadb | ||
|
|
444c1e492a | ||
|
|
3f7455ebfa | ||
|
|
4e093af85d | ||
|
|
e242c8e45f | ||
|
|
50699fa675 | ||
|
|
76aadb60ae | ||
|
|
4a7dba5480 | ||
|
|
c774d6b0f1 | ||
|
|
f36eb25f47 | ||
|
|
9e464ee267 |
No files matched your search
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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) });
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"]);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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";
|
||||
@@ -292,7 +292,7 @@ export class AutopilotService {
|
||||
const edited = await db.photoEdit.count({ where: { photoId: framePick.id, NOT: { clientId: "autopilot" } } });
|
||||
if (edited) continue;
|
||||
const rect = constrainRotated(planned, framePick.rec?.angle ?? 0, framePick.width ?? 3, framePick.height ?? 2);
|
||||
const aspect = settings.aspect ?? [framePick.width ?? 3, framePick.height ?? 2];
|
||||
const aspect = photoAspect(framePick.width, framePick.height);
|
||||
await develop
|
||||
.append(framePick.id, framePick.uploaderId ?? event.createdById ?? null, {
|
||||
clientId: "autopilot",
|
||||
@@ -310,7 +310,7 @@ export class AutopilotService {
|
||||
if (crop2 && second.rec?.subject && settings.crop && !secondEdited) {
|
||||
// The planned crop already keeps the hands and the feet. Shrinking it again cuts them.
|
||||
const rect = wider ?? constrainRotated(crop2, second.rec.angle, second.width ?? 3, second.height ?? 2);
|
||||
const aspect = settings.aspect ?? [second.width ?? 3, second.height ?? 2];
|
||||
const aspect = photoAspect(second.width, second.height);
|
||||
await develop
|
||||
.append(second.id, second.uploaderId ?? event.createdById ?? null, {
|
||||
clientId: "autopilot",
|
||||
@@ -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,
|
||||
@@ -522,6 +533,14 @@ function subjectFocus(d: { people: { x0: number; y0: number; x1: number; y1: num
|
||||
return values.length ? Math.max(...values) : 0;
|
||||
}
|
||||
|
||||
/** The photograph's own pixel size, so the crop lock is that format and not another. */
|
||||
function photoAspect(width: number | null | undefined, height: number | null | undefined): [number, number] {
|
||||
if (width && height && width > 0 && height > 0) {
|
||||
return [Math.round(width), Math.round(height)];
|
||||
}
|
||||
return [3, 2];
|
||||
}
|
||||
|
||||
/** A tighter plan keeps the crop and the structure scaled to that crop, so the halo does not grow with the tighter frame. */
|
||||
function cropOps(photoId: string, key: string, rect: Box, angle: number, aspect: readonly number[], detail: Record<string, number>): { opId: string; command: EditCommand }[] {
|
||||
const ops: { opId: string; command: EditCommand }[] = [];
|
||||
@@ -537,6 +556,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 +590,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);
|
||||
|
||||
@@ -46,6 +46,33 @@ export function constrainRotated(r: Box, angle: number, w: number, h: number): B
|
||||
return { x0: 0.5 - (rw * k) / 2, y0: 0.5 - (rh * k) / 2, x1: 0.5 + (rw * k) / 2, y1: 0.5 + (rh * k) / 2 };
|
||||
}
|
||||
|
||||
/**
|
||||
* The crop on the photo's own aspect. In frame fractions that is a square: width and height match.
|
||||
* The horizontal centre stays, so the crop can still sit anywhere across the frame.
|
||||
*/
|
||||
export function keepPhotoAspect(rect: Box): Box {
|
||||
const width = rect.x1 - rect.x0;
|
||||
const height = rect.y1 - rect.y0;
|
||||
if (width <= 0 || height <= 0) return rect;
|
||||
let side = width;
|
||||
if (side > 1) side = 1;
|
||||
let x0 = (rect.x0 + rect.x1) / 2 - side / 2;
|
||||
let y0 = (rect.y0 + rect.y1) / 2 - side / 2;
|
||||
if (x0 < 0) x0 = 0;
|
||||
if (x0 + side > 1) x0 = 1 - side;
|
||||
if (y0 < 0) y0 = 0;
|
||||
if (y0 + side > 1) y0 = 1 - side;
|
||||
const room = Math.min(side, 1 - x0, 1 - y0);
|
||||
if (room < side) {
|
||||
const cx = x0 + side / 2;
|
||||
const cy = y0 + side / 2;
|
||||
side = room;
|
||||
x0 = Math.min(Math.max(0, cx - side / 2), 1 - side);
|
||||
y0 = Math.min(Math.max(0, cy - side / 2), 1 - side);
|
||||
}
|
||||
return { x0, y0, x1: x0 + side, y1: y0 + side };
|
||||
}
|
||||
|
||||
/** `r` shrunk by `factor` about the subject's centre, keeping the subject inside and the crop on the photo. */
|
||||
export function tighter(r: Box, subject: Box, factor: number): Box {
|
||||
const w = (r.x1 - r.x0) * factor;
|
||||
@@ -105,8 +132,13 @@ export function frameOnSubject(base: Box, subject: Box, intent: { cut?: number |
|
||||
|
||||
/** Expand `r` by `factor` (>1) about the subject's centre, without leaving the photo. */
|
||||
function looser(r: Box, subject: Box, factor: number): Box {
|
||||
const w = Math.min(1, (r.x1 - r.x0) * factor);
|
||||
const h = Math.min(1, (r.y1 - r.y0) * factor);
|
||||
let w = (r.x1 - r.x0) * factor;
|
||||
let h = (r.y1 - r.y0) * factor;
|
||||
if (w > 1 || h > 1) {
|
||||
const fit = Math.min(1 / w, 1 / h);
|
||||
w = w * fit;
|
||||
h = h * fit;
|
||||
}
|
||||
const cx = (subject.x0 + subject.x1) / 2;
|
||||
const cy = (r.y0 + r.y1) / 2;
|
||||
const x0 = Math.min(Math.max(0, cx - w / 2), 1 - w);
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { keepPhotoAspect } from "./geometry.js";
|
||||
import { planFrame, type PlanSettings } from "./planFrame.js";
|
||||
|
||||
const settings: PlanSettings = {
|
||||
crop: true,
|
||||
tone: false,
|
||||
whiteBalance: false,
|
||||
level: false,
|
||||
toneStrength: 0.75,
|
||||
look: "none",
|
||||
framing: "full",
|
||||
aspect: [4, 5],
|
||||
minLongEdge: 800,
|
||||
};
|
||||
|
||||
describe("keepPhotoAspect", () => {
|
||||
it("keeps the horizontal place and the photograph's aspect", () => {
|
||||
const crop = keepPhotoAspect({ x0: 0.2, y0: 0.1, x1: 0.7, y1: 0.95 });
|
||||
expect(crop.x1 - crop.x0).toBeCloseTo(crop.y1 - crop.y0, 5);
|
||||
expect((crop.x0 + crop.x1) / 2).toBeCloseTo(0.45, 5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("planFrame", () => {
|
||||
it("does not turn the photograph into another format", () => {
|
||||
const planned = planFrame({
|
||||
detections: {
|
||||
width: 6000,
|
||||
height: 4000,
|
||||
people: [{ x0: 0.4, y0: 0.15, x1: 0.62, y1: 0.92, score: 0.9, sharpness: 1 }],
|
||||
balls: [],
|
||||
},
|
||||
width: 6000,
|
||||
height: 4000,
|
||||
reportage: false,
|
||||
values: null,
|
||||
angle: 0,
|
||||
settings,
|
||||
});
|
||||
const crop = planned.ops.find((op) => op.command === "crop.set");
|
||||
expect(crop?.command).toBe("crop.set");
|
||||
if (!crop || crop.command !== "crop.set") return;
|
||||
const rect = crop.params.rect;
|
||||
const ratio = ((rect.x1 - rect.x0) * 6000) / ((rect.y1 - rect.y0) * 4000);
|
||||
expect(ratio).toBeCloseTo(6000 / 4000, 2);
|
||||
expect(crop.params.aspect).toEqual([6000, 4000]);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { EditCommand } from "@photoreport/contracts";
|
||||
import { type Box, type Detections, type FocusHint, clipsBall, compose, minCropWidth, planCrop } from "./compose.js";
|
||||
import { biasCrop, constrainRotated, frameOnSubject, tighter } from "./geometry.js";
|
||||
import { biasCrop, constrainRotated, frameOnSubject, keepPhotoAspect, tighter } from "./geometry.js";
|
||||
import { type Look, WB_KEYS, TONE_KEYS, detailForCrop, lookValues, toneApplied } from "../autopilot/look.js";
|
||||
import type { CropBias } from "../autopilot/cropBias.js";
|
||||
|
||||
@@ -18,6 +18,7 @@ export interface PlanSettings {
|
||||
toneStrength: number;
|
||||
look: Look;
|
||||
framing: "tight" | "full";
|
||||
/** Ignored. The autopilot keeps the photograph's own aspect and only moves the crop. */
|
||||
aspect: [number, number] | null;
|
||||
minLongEdge: number;
|
||||
}
|
||||
@@ -81,7 +82,8 @@ export function planFrame(input: {
|
||||
settings: PlanSettings;
|
||||
}): PlannedFrame {
|
||||
const { detections, settings, width: W, height: H, reportage } = input;
|
||||
const aspect = settings.aspect ? settings.aspect[0] / settings.aspect[1] : null;
|
||||
// The photograph's own aspect. A preset (4:5, 16:9, a portrait of a landscape frame) is not used.
|
||||
const aspect = null;
|
||||
const minWidth = minCropWidth(W, H, settings.minLongEdge);
|
||||
const context = reportage ? "reportage" : "sport";
|
||||
const faces = input.faces ?? [];
|
||||
@@ -113,15 +115,21 @@ export function planFrame(input: {
|
||||
// A learnt crop must not slice a ball the frame had kept whole.
|
||||
const balls = detections?.balls ?? [];
|
||||
if (clipsBall(rect, balls)) rect = composition.rect;
|
||||
if (!clipsBall(rect, balls) && rect.x1 - rect.x0 < KEEP_WHOLE) crop = constrainRotated(rect, angle, W, H);
|
||||
if (!clipsBall(rect, balls) && rect.x1 - rect.x0 < KEEP_WHOLE) crop = constrainRotated(keepPhotoAspect(rect), angle, W, H);
|
||||
}
|
||||
const wide = settings.crop && wideComposition && wideComposition.rect.x1 - wideComposition.rect.x0 < KEEP_WHOLE ? constrainRotated(wideComposition.rect, angle, W, H) : null;
|
||||
const wide = settings.crop && wideComposition && wideComposition.rect.x1 - wideComposition.rect.x0 < KEEP_WHOLE ? constrainRotated(keepPhotoAspect(wideComposition.rect), angle, W, H) : null;
|
||||
if (!crop && angle) crop = constrainRotated({ x0: 0, y0: 0, x1: 1, y1: 1 }, angle, W, H);
|
||||
const lockedPlans = plans
|
||||
? {
|
||||
half: plans.half ? keepPhotoAspect(plans.half) : null,
|
||||
threeQuarter: plans.threeQuarter ? keepPhotoAspect(plans.threeQuarter) : null,
|
||||
}
|
||||
: null;
|
||||
const ops: EditCommand[] = [];
|
||||
if (input.values) {
|
||||
const tuned = detailForCrop(input.values, crop, W, H);
|
||||
if (Object.keys(tuned).length) ops.push({ command: "develop.set", params: { values: tuned } });
|
||||
}
|
||||
if (crop) ops.push({ command: "crop.set", params: { rect: crop, angle, aspect: settings.aspect ?? [W, H] } });
|
||||
return { ops, crop, wide, composition, plans };
|
||||
if (crop) ops.push({ command: "crop.set", params: { rect: crop, angle, aspect: [Math.max(1, Math.round(W)), Math.max(1, Math.round(H))] } });
|
||||
return { ops, crop, wide, composition, plans: lockedPlans };
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,22 @@ import { createHash } from "node:crypto";
|
||||
*
|
||||
* Off without ERROR_REPORTING_TOKEN (the project's ingest key on the hub), or with ERROR_REPORTING_DISABLED=1.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Transient PostgreSQL connection errors during a restart, graceful shutdown, or network blip. Prisma surfaces
|
||||
* these as `PrismaClientKnownRequestError` wrapping the raw SQLSTATE (57P01/57P03) or its own P1001/P1017.
|
||||
* The pool reconnects on the next attempt, so these are not code bugs — reporting them only trips the Error
|
||||
* Loop with one-off incidents from every code path that touches the database during the brief outage.
|
||||
* Individual call sites that need to stop a batch or retry still check `isPostgresAdminShutdown` /
|
||||
* `isPrismaServerUnreachable` (lib/pg.ts); this filter keeps the hub quiet for the paths that just let the
|
||||
* error propagate to a generic log.error (BIT-32490 and 11 sibling clusters).
|
||||
*/
|
||||
function isTransientDatabaseError(err: unknown): boolean {
|
||||
if (!(err instanceof Error)) return false;
|
||||
const code = (err as { code?: unknown }).code;
|
||||
if (code === "P1001" || code === "P1017") return true;
|
||||
return /57P01|57P03|the database system is shutting down|the database system is starting up|Can't reach database server|Server has closed the connection/i.test(err.message);
|
||||
}
|
||||
export type ReportLevel = "critical" | "error" | "warning" | "info";
|
||||
|
||||
export interface ReportEvent {
|
||||
@@ -93,6 +109,7 @@ export class ErrorReporter {
|
||||
}
|
||||
|
||||
reportError(err: unknown, component: string, context: Record<string, unknown> = {}, level: ReportLevel = "error"): void {
|
||||
if (isTransientDatabaseError(err)) return;
|
||||
const e = err instanceof Error ? err : new Error(typeof err === "string" ? err : JSON.stringify(err));
|
||||
const code = (e as { code?: unknown }).code;
|
||||
this.report({ level, message: `${e.name}: ${e.message}`, stack: e.stack, component, context: { error_type: e.constructor?.name ?? "Error", ...(code !== undefined && { error_code: String(code) }), ...context } });
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import * as cheerio from "cheerio";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fpfDate, fpfSeasonId, parseFpfDetailsFixtures, parseFpfLineups } from "./providers.js";
|
||||
|
||||
describe("FPF catalogue helpers", () => {
|
||||
it("maps the football season to FPF's seasonId", () => {
|
||||
expect(fpfSeasonId(new Date("2026-11-20T12:00:00Z"))).toBe("106");
|
||||
expect(fpfSeasonId(new Date("2027-08-01T12:00:00Z"))).toBe("107");
|
||||
});
|
||||
|
||||
it("reads the kick-off when the day and time are stuck together", () => {
|
||||
const now = new Date("2026-11-20T12:00:00Z");
|
||||
expect(fpfDate("20 nov20:45", now)).toMatchObject({ timeKnown: true });
|
||||
expect(fpfDate("20 nov20:45", now)!.at.toISOString()).toBe("2026-11-20T20:45:00.000Z");
|
||||
});
|
||||
|
||||
it("reads Taça-style Details games without GetClassification links", () => {
|
||||
const html = `
|
||||
<h2>TAÇA DE PORTUGAL</h2>
|
||||
<div class="accordion-item">
|
||||
<div class="accordion-title">4.ª Eliminatória</div>
|
||||
<div class="accordion-content">
|
||||
<div class="game">
|
||||
<div class="home-team">Fc Porto Sad</div>
|
||||
<span class="game-schedule">20 nov<br />20:45</span>
|
||||
<div class="away-team">Usc Paredes</div>
|
||||
</div>
|
||||
<div class="game-list-stadium"><small>Estadio Do Dragao</small></div>
|
||||
<div class="game">
|
||||
<div class="home-team">Vencedor Jogo A x B</div>
|
||||
<span class="game-schedule">16 dez<br />15:00</span>
|
||||
<div class="away-team">Vencedor Jogo C x D</div>
|
||||
</div>
|
||||
<div class="game-list-stadium"><small>Recinto A Indicar</small></div>
|
||||
<a class="game-link" href="/Match/GetMatchInformation?matchId=2687999">
|
||||
<div class="game">
|
||||
<div class="home-team">Sporting Cp Sad</div>
|
||||
<span class="game-schedule">21 nov<br />18:00</span>
|
||||
<div class="away-team">União D. Serra</div>
|
||||
</div>
|
||||
<div class="game-list-stadium"><small>Estádio José Alvalade</small></div>
|
||||
</a>
|
||||
</div>
|
||||
</div>`;
|
||||
const fixtures = parseFpfDetailsFixtures(cheerio.load(html), {
|
||||
competitionId: "25263",
|
||||
seasonId: "106",
|
||||
competitionName: "Taça de Portugal",
|
||||
now: new Date("2026-11-20T12:00:00Z"),
|
||||
});
|
||||
expect(fixtures).toHaveLength(2);
|
||||
expect(fixtures[0]).toMatchObject({
|
||||
home: { name: "Fc Porto Sad" },
|
||||
away: { name: "Usc Paredes" },
|
||||
timeKnown: true,
|
||||
round: "4.ª Eliminatória",
|
||||
venue: "Estadio Do Dragao",
|
||||
});
|
||||
expect(fixtures[0]!.startsAt.toISOString()).toBe("2026-11-20T20:45:00.000Z");
|
||||
expect(fixtures[0]!.externalId).toContain("25263-");
|
||||
expect(fixtures[1]).toMatchObject({
|
||||
externalId: "2687999",
|
||||
home: { name: "Sporting Cp Sad" },
|
||||
away: { name: "União D. Serra" },
|
||||
venue: "Estádio José Alvalade",
|
||||
});
|
||||
});
|
||||
|
||||
it("reads each side of a match sheet with the federation headshot", () => {
|
||||
const html = `
|
||||
<section>
|
||||
<div class="title-bar">Equipas Iniciais</div>
|
||||
<div class="lineup-team home-team">
|
||||
<div class="player">
|
||||
<div class="photo">
|
||||
<img src="/Player/Logo/4487059">
|
||||
<span class="icons"><span class="icon icon-goal"><span>1</span></span></span>
|
||||
</div>
|
||||
<strong>1</strong> Duarte Jesus (GR)
|
||||
</div>
|
||||
<div class="player">
|
||||
<div class="photo"><img src="/Player/Logo/4487058"></div>
|
||||
<strong>9</strong> Roger Almeida
|
||||
</div>
|
||||
</div>
|
||||
<div class="lineup-team away-team">
|
||||
<div class="player">
|
||||
<div class="photo"><img src="/Player/Logo/4478263"></div>
|
||||
<strong>33</strong> José Costa (GR)
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section>
|
||||
<div class="title-bar">Suplentes</div>
|
||||
<div class="lineup-team home-team">
|
||||
<div class="player">
|
||||
<div class="photo"><img src="/Player/Logo/4484537"></div>
|
||||
<strong>7</strong> Antonio Andrade
|
||||
</div>
|
||||
</div>
|
||||
<div class="lineup-team away-team">
|
||||
<div class="player">
|
||||
<div class="photo"><img src="/Player/Logo/4478262"></div>
|
||||
<strong>4</strong> Tiago Araujo
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section>
|
||||
<div class="title-bar">Treinadores</div>
|
||||
<div class="lineup-team home-team">
|
||||
<div class="player">
|
||||
<div class="photo"><img src="/Player/Logo/4488001"></div>
|
||||
<span style="font-weight: bold">Treinador Principal</span>
|
||||
<span>Andre Henriques Anastacio</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="lineup-team home-team">
|
||||
<div class="player">
|
||||
<div class="photo"><img src="/Player/Logo/4488002"></div>
|
||||
<span style="font-weight: bold">Treinador Principal</span>
|
||||
<span>Rui Borges</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>`;
|
||||
const { home, away } = parseFpfLineups(html);
|
||||
expect(home.map((p) => p.name)).toEqual(["Duarte Jesus", "Roger Almeida", "Antonio Andrade", "Andre Henriques Anastacio"]);
|
||||
expect(home[0]).toMatchObject({
|
||||
number: "1",
|
||||
position: "Guarda-Redes",
|
||||
externalId: "4487059",
|
||||
photoUrl: "https://resultados.fpf.pt/Player/Logo/4487059",
|
||||
});
|
||||
expect(home[1]).toMatchObject({ number: "9", name: "Roger Almeida", position: null });
|
||||
expect(home[3]).toMatchObject({ number: null, position: "Treinador" });
|
||||
expect(away.map((p) => [p.number, p.name])).toEqual([
|
||||
["33", "José Costa"],
|
||||
["4", "Tiago Araujo"],
|
||||
[null, "Rui Borges"],
|
||||
]);
|
||||
expect(away[0]).toMatchObject({ position: "Guarda-Redes", photoUrl: "https://resultados.fpf.pt/Player/Logo/4478263" });
|
||||
});
|
||||
});
|
||||
@@ -894,11 +894,81 @@ function fpaFixture(r: Record<string, unknown>): FixtureData | null {
|
||||
|
||||
// --- FPF (resultados.fpf.pt, HTML) --------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Competitions we always follow. The Taça de Portugal is FPF's (not Liga Portugal's calendar). `externalId` is the
|
||||
* resultados.fpf.pt competitionId; the seasonId advances with {@link fpfSeasonId}.
|
||||
*/
|
||||
export const FPF_COMPETITIONS = [{ externalId: "25263", name: "Taça de Portugal", gender: "M" }] as const;
|
||||
|
||||
/** FPF's seasonId: 106 is 2026/27. Advances by one each July. */
|
||||
export function fpfSeasonId(now = new Date()): string {
|
||||
const start = Number(seasonOf(now).slice(0, 4));
|
||||
return String(106 + (start - 2026));
|
||||
}
|
||||
|
||||
const MONTHS: Record<string, number> = { jan: 1, fev: 2, mar: 3, abr: 4, mai: 5, jun: 6, jul: 7, ago: 8, set: 9, out: 10, nov: 11, dez: 12 };
|
||||
|
||||
/** "Vencedor Jogo …" on a later round: not a real club yet. */
|
||||
function isFpfUndecidedSide(name: string): boolean {
|
||||
return /^vencedor\b/i.test(name.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* Games listed on the competition Details page (accordion rounds). Some rounds wrap each game in a match link;
|
||||
* others (e.g. Taça 4.ª eliminatória) only print the teams and kick-off — then the id is derived from the kick-off
|
||||
* and the two clubs so a re-read stays stable.
|
||||
*/
|
||||
export function parseFpfDetailsFixtures(
|
||||
$: cheerio.CheerioAPI,
|
||||
opts: { competitionId: string; seasonId: string; competitionName: string; now?: Date },
|
||||
): FixtureData[] {
|
||||
const now = opts.now ?? new Date();
|
||||
const out: FixtureData[] = [];
|
||||
const items = $(".accordion-item");
|
||||
const roots = items.length ? items.toArray() : [$.root().get(0)!].filter(Boolean);
|
||||
for (const item of roots) {
|
||||
const root = $(item);
|
||||
const roundLabel = root.find(".accordion-title").first().text().replace(/\s+/g, " ").trim() || null;
|
||||
root.find(".game").each((_, gameEl) => {
|
||||
const game = $(gameEl);
|
||||
const homeName = game.find(".home-team").first().text().replace(/\s+/g, " ").trim();
|
||||
const awayName = game.find(".away-team").first().text().replace(/\s+/g, " ").trim();
|
||||
if (!homeName || !awayName) return;
|
||||
if (isFpfUndecidedSide(homeName) || isFpfUndecidedSide(awayName)) return;
|
||||
const when = fpfDate(game.find(".game-schedule").text(), now);
|
||||
if (!when) return;
|
||||
const parentLink = game.closest("a.game-link");
|
||||
const matchId = parentLink.length ? /matchId=(\d+)/i.exec(parentLink.attr("href") ?? "")?.[1] ?? null : null;
|
||||
const stadiumText = parentLink.length
|
||||
? parentLink.find(".game-list-stadium small").first().text().trim()
|
||||
: game.nextAll(".game-list-stadium").first().find("small").text().trim();
|
||||
const score = /(\d+)\s*-\s*(\d+)/.exec(game.find(".score span").first().text());
|
||||
const home = { externalId: slugify(homeName), name: homeName };
|
||||
const away = { externalId: slugify(awayName), name: awayName };
|
||||
const stamp = when.at.toISOString().slice(0, 16).replace(/[-:T]/g, "");
|
||||
out.push({
|
||||
externalId: matchId ?? `${opts.competitionId}-${stamp}-${home.externalId}-${away.externalId}`,
|
||||
competition: opts.competitionId,
|
||||
competitionName: opts.competitionName,
|
||||
season: opts.seasonId,
|
||||
home,
|
||||
away,
|
||||
startsAt: when.at,
|
||||
timeKnown: when.timeKnown,
|
||||
round: roundLabel,
|
||||
...fpfPlace(stadiumText),
|
||||
homeScore: score ? Number(score[1]) : null,
|
||||
awayScore: score ? Number(score[2]) : null,
|
||||
});
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** "12 out 15:00" (no year on the site): the year that puts it nearest to `now`. */
|
||||
export function fpfDate(text: string, now: Date): { at: Date; timeKnown: boolean } | null {
|
||||
const m = /(\d{1,2})\s*(?:de\s+)?([a-zç]{3})[a-zç]*\.?(?:\s+(\d{4}))?(?:\D+(\d{1,2}:\d{2}))?/i.exec(text.toLowerCase());
|
||||
// Cheerio's .text() on "20 nov<br />20:45" can yield "20 nov20:45" with no space before the time.
|
||||
const m = /(\d{1,2})\s*(?:de\s+)?([a-zç]{3})[a-zç]*\.?(?:\s+(\d{4}))?(?:\D*(\d{1,2}:\d{2}))?/i.exec(text.toLowerCase().replace(/\s+/g, " ").trim());
|
||||
if (!m) return null;
|
||||
const month = MONTHS[m[2]!.slice(0, 3)];
|
||||
if (!month) return null;
|
||||
@@ -948,6 +1018,14 @@ export class FpfProvider {
|
||||
for (const m of ($.html().match(/GetClassificationAndMatchesByFixture\?fixtureId=(\d+)/g) ?? [])) rounds.add(m.replace(/\D/g, ""));
|
||||
const teams = new Map<string, TeamData>();
|
||||
const fixtures: FixtureData[] = [];
|
||||
const seen = new Set<string>();
|
||||
const addFixture = (f: FixtureData) => {
|
||||
if (seen.has(f.externalId)) return;
|
||||
seen.add(f.externalId);
|
||||
teams.set(f.home.externalId, f.home);
|
||||
teams.set(f.away.externalId, f.away);
|
||||
fixtures.push(f);
|
||||
};
|
||||
let n = 0;
|
||||
for (const round of rounds) {
|
||||
n++;
|
||||
@@ -959,14 +1037,13 @@ export class FpfProvider {
|
||||
const homeName = game.find(".home-team").text().trim();
|
||||
const awayName = game.find(".away-team").text().trim();
|
||||
if (!matchId || !homeName || !awayName) return;
|
||||
if (isFpfUndecidedSide(homeName) || isFpfUndecidedSide(awayName)) return;
|
||||
const home = { externalId: slugify(homeName), name: homeName };
|
||||
const away = { externalId: slugify(awayName), name: awayName };
|
||||
teams.set(home.externalId, home);
|
||||
teams.set(away.externalId, away);
|
||||
const when = fpfDate(game.find(".game-schedule").text(), now);
|
||||
if (!when) return;
|
||||
const score = /(\d+)\s*-\s*(\d+)/.exec(game.find(".score span").first().text());
|
||||
fixtures.push({
|
||||
addFixture({
|
||||
externalId: matchId,
|
||||
competition: competitionId,
|
||||
competitionName: name,
|
||||
@@ -976,31 +1053,122 @@ export class FpfProvider {
|
||||
startsAt: when.at,
|
||||
timeKnown: when.timeKnown,
|
||||
round: roundLabel,
|
||||
...fpfPlace(r(link).next(".game-list-stadium").find("small").text().trim()),
|
||||
...fpfPlace(r(link).find(".game-list-stadium small").first().text().trim() || r(link).next(".game-list-stadium").find("small").text().trim()),
|
||||
homeScore: score ? Number(score[1]) : null,
|
||||
awayScore: score ? Number(score[2]) : null,
|
||||
});
|
||||
});
|
||||
}
|
||||
// Cups such as the Taça de Portugal list rounds on the Details page (accordion) and often omit the
|
||||
// GetClassificationAndMatchesByFixture links the older divisions use. Read those games too.
|
||||
for (const f of parseFpfDetailsFixtures($, { competitionId, seasonId, competitionName: name, now })) {
|
||||
addFixture(f);
|
||||
}
|
||||
return { name, teams: [...teams.values()], fixtures };
|
||||
}
|
||||
|
||||
/** Line-ups from the match sheet ("Equipas Iniciais", "Suplentes"): starters and substitutes per side. */
|
||||
/** Line-ups from the match sheet: numbers, names and the federation headshot (`/Player/Logo/{id}`). */
|
||||
async lineups(matchId: string): Promise<{ home: PlayerData[]; away: PlayerData[] }> {
|
||||
const $ = await this.page(`/Match/GetMatchInformation?matchId=${matchId}`);
|
||||
const parsed = parseFpfLineups($);
|
||||
if (parsed.home.length || parsed.away.length) return parsed;
|
||||
return parseFpfLineups($("body").text());
|
||||
}
|
||||
}
|
||||
|
||||
export function parseFpfLineups(text: string): { home: PlayerData[]; away: PlayerData[] } {
|
||||
const FPF_PLAYER_PHOTO = "https://resultados.fpf.pt";
|
||||
|
||||
/** The headshot on a match sheet. The id is the player's federation id. */
|
||||
function fpfPlayerPhoto(src: string | undefined): { externalId: string | null; photoUrl: string | null } {
|
||||
const id = /\/Player\/Logo\/(\d+)/.exec(src ?? "")?.[1] ?? null;
|
||||
if (!id) return { externalId: null, photoUrl: null };
|
||||
return { externalId: id, photoUrl: `${FPF_PLAYER_PHOTO}/Player/Logo/${id}` };
|
||||
}
|
||||
|
||||
function fpfCardPlayer($: cheerio.CheerioAPI, el: unknown): PlayerData | null {
|
||||
const card = $(el as never);
|
||||
const photo = fpfPlayerPhoto(card.find("img").first().attr("src"));
|
||||
const strong = card.find("strong").first().text().replace(/\s+/g, "").trim();
|
||||
const hasNumber = /^\d{1,3}$/.test(strong);
|
||||
if (hasNumber) {
|
||||
// Goal and card icons sit in `.photo` and their counts would stick to the name.
|
||||
card.find(".photo").remove();
|
||||
card.find("strong").first().remove();
|
||||
const raw = card.text().replace(/\s+/g, " ").trim();
|
||||
const name = raw.replace(/\s*\(GR\)\s*$/i, "").replace(/\s*\(C\)\s*$/i, "").trim();
|
||||
if (!name || name.length >= 80) return null;
|
||||
let position: string | null = null;
|
||||
if (/\(GR\)/i.test(raw)) position = "Guarda-Redes";
|
||||
return { externalId: photo.externalId, number: strong, name, position, photoUrl: photo.photoUrl };
|
||||
}
|
||||
const spans = card
|
||||
.find("span")
|
||||
.toArray()
|
||||
.map((span) => $(span).text().replace(/\s+/g, " ").trim())
|
||||
.filter((text) => text && !/^\d+$/.test(text));
|
||||
const role = spans[0] ?? "";
|
||||
const name = spans[1] ?? "";
|
||||
if (!name || name.length >= 80) return null;
|
||||
let position = role || "Equipa técnica";
|
||||
if (/treinador principal/i.test(role)) position = "Treinador";
|
||||
return { externalId: photo.externalId, number: null, name, position, photoUrl: photo.photoUrl };
|
||||
}
|
||||
|
||||
/** One column (home or away) of a named block on the match sheet. */
|
||||
function fpfColumn($: cheerio.CheerioAPI, title: string, side: "home-team" | "away-team"): PlayerData[] {
|
||||
const out: PlayerData[] = [];
|
||||
$("section").each((_, section) => {
|
||||
const heading = $(section).find(".title-bar").first().text().replace(/\s+/g, " ").trim();
|
||||
if (heading !== title) return;
|
||||
const root = $(section);
|
||||
let column = root.find(`.lineup-team.${side}`).first();
|
||||
// The coach block marks both columns `home-team`. The second column is the away coach.
|
||||
if (!column.length && side === "away-team") {
|
||||
const both = root.find(".lineup-team");
|
||||
if (both.length > 1) column = both.eq(1);
|
||||
}
|
||||
column.find(".player").each((__, el) => {
|
||||
const player = fpfCardPlayer($, el);
|
||||
if (player) out.push(player);
|
||||
});
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseFpfLineupDom($: cheerio.CheerioAPI): { home: PlayerData[]; away: PlayerData[] } {
|
||||
const titles = ["Equipas Iniciais", "Suplentes", "Treinadores"];
|
||||
const home: PlayerData[] = [];
|
||||
const away: PlayerData[] = [];
|
||||
for (const title of titles) {
|
||||
home.push(...fpfColumn($, title, "home-team"));
|
||||
away.push(...fpfColumn($, title, "away-team"));
|
||||
}
|
||||
return { home, away };
|
||||
}
|
||||
|
||||
/**
|
||||
* Match sheet. HTML keeps each side, the shirt number and the headshot. Plain text (no `lineup-team`) is the
|
||||
* older fallback: eleven starters a side, then the bench split in half. That path has no photos.
|
||||
*/
|
||||
export function parseFpfLineups(input: string | cheerio.CheerioAPI): { home: PlayerData[]; away: PlayerData[] } {
|
||||
if (typeof input !== "string") return parseFpfLineupDom(input);
|
||||
if (input.includes("lineup-team")) return parseFpfLineupDom(cheerio.load(input));
|
||||
return parseFpfLineupsText(input);
|
||||
}
|
||||
|
||||
function parseFpfLineupsText(text: string): { home: PlayerData[]; away: PlayerData[] } {
|
||||
const block = (from: string, to: string) => {
|
||||
const a = text.indexOf(from);
|
||||
if (a === -1) return [];
|
||||
const b = text.indexOf(to, a);
|
||||
const slice = b === -1 ? text.slice(a) : text.slice(a, b);
|
||||
const out: PlayerData[] = [];
|
||||
for (const m of (b === -1 ? text.slice(a) : text.slice(a, b)).matchAll(/^\s*(\d{1,3})\s+(.+?)\s*$/gm)) {
|
||||
for (const m of slice.matchAll(/^\s*(\d{1,3})\s+(.+?)\s*$/gm)) {
|
||||
const name = m[2]!.replace(/\s*\(GR\)\s*$/i, "").replace(/\s*\(C\)\s*$/i, "").trim();
|
||||
if (name && name.length < 80) out.push({ number: m[1]!, name, position: /\(GR\)/i.test(m[2]!) ? "Guarda-Redes" : null });
|
||||
if (!name || name.length >= 80) continue;
|
||||
let position: string | null = null;
|
||||
if (/\(GR\)/i.test(m[2]!)) position = "Guarda-Redes";
|
||||
out.push({ number: m[1]!, name, position });
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { SportsService } from "./service.js";
|
||||
|
||||
type Level = "info" | "warn";
|
||||
type LogCall = { level: Level; msg: string; obj: unknown };
|
||||
|
||||
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, obj }),
|
||||
warn: (obj, msg) => calls.push({ level: "warn", msg, obj }),
|
||||
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 p1017findUnique = () =>
|
||||
Object.assign(new Error("Invalid `prisma.person.findUnique()` 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("syncEventSquads downgrades a P1017 from person.findUnique in linkSquadPerson (BIT-32481)", () => {
|
||||
it("logs at info and returns zeros when the first person.findUnique is P1017 on both attempts", async () => {
|
||||
// The error loop reported P1017 ("Server has closed the connection.") from linkSquadPerson →
|
||||
// person.findUnique (the organizationId_sportsPlayerId lookup, the first DB call in the method). This is the
|
||||
// same catch path as BIT-32475 (retryOnConnectionClosed retries once, then isPrismaConnectionClosed downgrades
|
||||
// to info), but from the findUnique call rather than findFirst. This test proves that coverage.
|
||||
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: {
|
||||
// Throws on every call, so the retryOnConnectionClosed retry also fails with P1017.
|
||||
findUnique: async () => { throw p1017findUnique(); },
|
||||
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 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);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveHeadshot swallows a network-level fetch failure (BIT-31961)", () => {
|
||||
it("returns false and logs a warn without a bare Error when the headshot URL is unreachable, so the bare undici TypeError does not reach the hub fingerprint", async () => {
|
||||
const log = makeLog();
|
||||
const db = {
|
||||
person: { update: async () => { throw new Error("must not be reached on a network failure"); } },
|
||||
};
|
||||
const storage = { referenceKey: () => "key", write: async () => { throw new Error("must not be reached on a network failure"); } };
|
||||
const deps = { db, log, fetch: (async () => { throw new TypeError("fetch failed"); }) as never, storage: storage as never, signer: null as never };
|
||||
const service = new SportsService(deps as unknown as ConstructorParameters<typeof SportsService>[0]);
|
||||
const saveHeadshot = (service as unknown as { saveHeadshot: (orgId: string, personId: string, src: string) => Promise<boolean> }).saveHeadshot.bind(service);
|
||||
|
||||
await expect(saveHeadshot("org-1", "person-1", "https://www.ligaportugal.pt/headshot.jpg")).resolves.toBe(false);
|
||||
|
||||
const warn = log.calls.find((c) => c.level === "warn" && /headshot download unavailable/.test(c.msg));
|
||||
expect(warn).toBeTruthy();
|
||||
// The warn must not carry the bare undici TypeError as `err`: pino's logHooks fingerprints any warn that has an
|
||||
// Error `err`, and a bare `TypeError: fetch failed` has no frame in our code, so it would collapse into the
|
||||
// same ERRSIG as every other unwrapped fetch site (BIT-31961). The reason is logged as a plain string instead.
|
||||
expect(warn!.obj && typeof warn!.obj === "object" && "err" in (warn!.obj as Record<string, unknown>)).toBe(false);
|
||||
expect((warn!.obj as { reason?: string }).reason).toBe("fetch failed");
|
||||
expect(log.calls.some((c) => c.level === "info" && /must not be reached/.test(c.msg))).toBe(false);
|
||||
});
|
||||
});
|
||||
+152
-32
@@ -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";
|
||||
@@ -36,6 +37,8 @@ import {
|
||||
fpaShortName,
|
||||
lisbonTime,
|
||||
FpfProvider,
|
||||
FPF_COMPETITIONS,
|
||||
fpfSeasonId,
|
||||
LIGA_COMPETITIONS,
|
||||
type LigaClubCompetition,
|
||||
LigaProvider,
|
||||
@@ -62,7 +65,27 @@ import {
|
||||
export const REFRESH_EVERY_MS = 6 * 3600_000;
|
||||
/** FPF line-ups appear on the match sheet around kick-off: read them from 1 h before to 2 h after. */
|
||||
const LINEUP_WINDOW = { before: 3600_000, after: 2 * 3600_000 };
|
||||
const HEADSHOT_HOSTS = ["www.ligaportugal.pt", "ligaportugal.pt", "img.uefa.com", "si.fpa.pt", "res.ehf.eu"];
|
||||
|
||||
/**
|
||||
* Season the squad is stored under. FPF's own id (`106`) stays on the competition, because that is what
|
||||
* resultados.fpf.pt expects. Players share the football season (`20262027`) with Liga, so a cup tie against
|
||||
* a Liga club sees that club's headshots.
|
||||
*/
|
||||
function squadSeason(provider: string | null | undefined, fixtureSeason: string | null | undefined, startsAt: Date): string {
|
||||
if (provider === "FPF") return seasonOf(startsAt);
|
||||
if (fixtureSeason) return fixtureSeason;
|
||||
return seasonOf(startsAt);
|
||||
}
|
||||
const HEADSHOT_HOSTS = [
|
||||
"www.ligaportugal.pt",
|
||||
"ligaportugal.pt",
|
||||
"img.uefa.com",
|
||||
"si.fpa.pt",
|
||||
"res.ehf.eu",
|
||||
"resultados.fpf.pt",
|
||||
"fpf360cdnprd.blob.core.windows.net",
|
||||
"app2030-prd-images.fpf.pt",
|
||||
];
|
||||
/** The "club" of referees made people from a match's referee team. */
|
||||
export const REFEREES = "Arbitragem";
|
||||
/** UEFA match sheets read per refresh (past matches without one yet): squads grow from them. */
|
||||
@@ -157,6 +180,16 @@ export class SportsService {
|
||||
await this.deps.db.sportsCompetition.create({ data: { provider: "EHF", externalId: c.externalId, sport: "andebol", name: c.name, gender: c.gender, season } });
|
||||
else if (existing.season < season) await this.deps.db.sportsCompetition.update({ where: { id: existing.id }, data: { season, lastIngestAt: null } });
|
||||
}
|
||||
const fpfSeason = fpfSeasonId(now);
|
||||
for (const c of FPF_COMPETITIONS) {
|
||||
const existing = await this.deps.db.sportsCompetition.findUnique({ where: { provider_externalId: { provider: "FPF", externalId: c.externalId } } });
|
||||
if (!existing)
|
||||
await this.deps.db.sportsCompetition.create({
|
||||
data: { provider: "FPF", externalId: c.externalId, sport: "futebol", name: c.name, gender: c.gender, season: fpfSeason },
|
||||
});
|
||||
else if (existing.season !== fpfSeason)
|
||||
await this.deps.db.sportsCompetition.update({ where: { id: existing.id }, data: { season: fpfSeason, lastIngestAt: null } });
|
||||
}
|
||||
}
|
||||
|
||||
private due(c: SportsCompetition, now: Date): boolean {
|
||||
@@ -1225,10 +1258,13 @@ export class SportsService {
|
||||
if (spec && (await this.readEhfSheet(spec.site, f, now)).read) read++;
|
||||
continue;
|
||||
}
|
||||
// A cup game listed before FPF assigns a matchId cannot be read. The next refresh replaces that id.
|
||||
if (!/^\d+$/.test(f.externalId)) continue;
|
||||
const { home, away } = await this.fpf.lineups(f.externalId);
|
||||
if (!home.length && !away.length) continue;
|
||||
await this.savePlayers(f.homeTeamId, f.season, home, "lineup");
|
||||
await this.savePlayers(f.awayTeamId, f.season, away, "lineup");
|
||||
const season = squadSeason("FPF", f.season, f.startsAt);
|
||||
await this.savePlayers(f.homeTeamId, season, home, "lineup");
|
||||
await this.savePlayers(f.awayTeamId, season, away, "lineup");
|
||||
await db.sportsFixture.update({ where: { id: f.id }, data: { lineupAt: now } });
|
||||
read++;
|
||||
} catch (err) {
|
||||
@@ -1325,8 +1361,9 @@ export class SportsService {
|
||||
const home = await this.deps.db.sportsTeam.findUnique({ where: { id: homeTeamId }, select: { venue: true, city: true } });
|
||||
place = { venue: place.venue ?? home?.venue ?? null, city: place.city ?? home?.city ?? null };
|
||||
}
|
||||
const season = squadSeason(provider, f.season, f.startsAt);
|
||||
const data = {
|
||||
season: f.season,
|
||||
season,
|
||||
homeTeamId,
|
||||
awayTeamId,
|
||||
startsAt: f.startsAt,
|
||||
@@ -1337,6 +1374,32 @@ export class SportsService {
|
||||
awayScore: f.awayScore ?? null,
|
||||
...(f.officials?.length ? { officials: f.officials as unknown as object } : {}),
|
||||
};
|
||||
// The Taça lists a game before FPF assigns a matchId. When the id appears, keep the same fixture (the event
|
||||
// already points at it) instead of inserting a second row the line-up reader never sees.
|
||||
if (provider === "FPF" && /^\d+$/.test(f.externalId)) {
|
||||
const prior = await this.deps.db.sportsFixture.findFirst({
|
||||
where: {
|
||||
competitionId: c.id,
|
||||
startsAt: f.startsAt,
|
||||
homeTeamId,
|
||||
awayTeamId,
|
||||
NOT: { externalId: f.externalId },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (prior) {
|
||||
await this.deps.db.sportsFixture.update({
|
||||
where: { id: prior.id },
|
||||
data: {
|
||||
externalId: f.externalId,
|
||||
...data,
|
||||
...(place.venue ? { venue: place.venue } : {}),
|
||||
...(place.city ? { city: place.city } : {}),
|
||||
},
|
||||
});
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
// A sheet that does not name a hall must not wipe a venue we already stored (the youth article has none).
|
||||
await this.deps.db.sportsFixture.upsert({
|
||||
where: { competitionId_externalId: { competitionId: c.id, externalId: f.externalId } },
|
||||
@@ -1366,7 +1429,7 @@ export class SportsService {
|
||||
const { db } = this.deps;
|
||||
const event = await db.event.findUnique({
|
||||
where: { id: eventId },
|
||||
include: { homeTeam: true, awayTeam: true, fixture: { select: { season: true } } },
|
||||
include: { homeTeam: true, awayTeam: true, fixture: { select: { season: true, competition: { select: { provider: true } } } } },
|
||||
});
|
||||
if (!event) throw notFound("event_not_found");
|
||||
const sides = [] as { side: "home" | "away"; team: { id: string; name: string; abbreviation: string | null; logoUrl: string | null }; players: unknown[] }[];
|
||||
@@ -1386,7 +1449,7 @@ export class SportsService {
|
||||
["away", event.awayTeam],
|
||||
] as const) {
|
||||
if (!team) continue;
|
||||
const season = event.fixture?.season ?? seasonOf(event.startsAt);
|
||||
const season = squadSeason(event.fixture?.competition.provider, event.fixture?.season, event.startsAt);
|
||||
const players = await this.squad(team.id, season);
|
||||
const personOf = await this.peopleOf(event.organizationId, players);
|
||||
const faceOf = await this.facesOf([...personOf.values()]);
|
||||
@@ -1424,7 +1487,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;
|
||||
@@ -1452,12 +1537,19 @@ export class SportsService {
|
||||
const result = { created: 0, updated: 0, headshots: 0 };
|
||||
const headshots: { personId: string; url: string }[] = [];
|
||||
// Liga squads are read again right now (players and coaching staff), not only on the 6-hourly refresh.
|
||||
const season = event.fixture?.season ?? seasonOf(event.startsAt);
|
||||
// FPF fixtures keep the site's seasonId; the squad itself is the football season, same as Liga.
|
||||
const season = squadSeason(event.fixture?.competition.provider, event.fixture?.season, event.startsAt);
|
||||
for (const team of [event.homeTeam, event.awayTeam]) {
|
||||
if (team?.provider !== "LIGA") continue;
|
||||
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 +2016,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]));
|
||||
@@ -1989,7 +2098,18 @@ export class SportsService {
|
||||
private async saveHeadshot(orgId: string, personId: string, src: string): Promise<boolean> {
|
||||
const u = new URL(src);
|
||||
if (u.protocol !== "https:" || !HEADSHOT_HOSTS.includes(u.hostname)) return false;
|
||||
const res = await this.deps.fetch(u.toString(), { signal: AbortSignal.timeout(20_000) });
|
||||
let res: { ok: boolean; status: number; json(): Promise<unknown>; text(): Promise<string>; arrayBuffer(): Promise<ArrayBuffer> };
|
||||
try {
|
||||
res = await this.deps.fetch(u.toString(), { signal: AbortSignal.timeout(20_000) });
|
||||
} catch (err) {
|
||||
// A network-level failure (DNS, connection reset, timeout) has no Response and surfaces as a bare undici
|
||||
// `TypeError: fetch failed` whose stack has no frame in our code, so it collapses into a single hub
|
||||
// fingerprint regardless of the call site (BIT-31961). A headshot that can't be downloaded is not worth
|
||||
// paging: log the reason without the bare Error object (so pino's logHooks does not fingerprint it) and
|
||||
// skip this URL — the next sync retries it.
|
||||
this.deps.log.warn({ personId, host: u.hostname, reason: err instanceof Error ? err.message : "fetch failed" }, "sports: headshot download unavailable");
|
||||
return false;
|
||||
}
|
||||
if (!res.ok) return false;
|
||||
const data = Buffer.from(await res.arrayBuffer());
|
||||
if (data.length > HEADSHOT_MAX_BYTES) return false;
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -90,6 +90,28 @@ describe("errors to errors.bitreport.pt", () => {
|
||||
]);
|
||||
expect(events[0]!.context).toMatchObject({ log_message: "archive: image not indexed", fileId: "f2" });
|
||||
});
|
||||
|
||||
it("does not report transient PostgreSQL shutdown/restart errors (57P01/57P03/P1001/P1017)", async () => {
|
||||
const hub = fakeHub();
|
||||
const reporter = reporterWith(hub.fetchImpl);
|
||||
const sink = new Writable({ write: (_c, _e, cb) => cb() });
|
||||
const log = pino({ level: "info", hooks: reporter.logHooks("api") }, sink);
|
||||
const mk = (msg: string, code?: string) => {
|
||||
const e = new Error(msg);
|
||||
if (code) (e as { code?: string }).code = code;
|
||||
return e;
|
||||
};
|
||||
log.error({ err: mk("Database error. Code: 57P03. Message: the database system is shutting down") }, "sports: query failed");
|
||||
log.error({ err: mk("Database error. Code: 57P01. Message: terminating connection due to administrator command") }, "archive: query failed");
|
||||
log.error({ err: mk("Can't reach database server at localhost:5432", "P1001") }, "db unreachable");
|
||||
log.error({ err: mk("Server has closed the connection.", "P1017") }, "connection closed");
|
||||
reporter.reportError(mk("Database error. Code: 57P03. Message: the database system is shutting down"), "worker");
|
||||
log.error({ err: new Error("render crashed") }, "real error");
|
||||
await reporter.flush();
|
||||
const events = hub.sent.flatMap((s) => s.events);
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]!.message).toContain("render crashed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("browser errors through the API", () => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { CodeGeneratorSettings } from "@photoreport/contracts";
|
||||
import sharp from "sharp";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { BLOCK_START, buildCodeLines, mergeGenerated, teamPrefix, toTsv } from "../src/sports/codegen.js";
|
||||
import { type Fetch, fpaEpochFor, fpaProva, fpaShortName, fpfDate, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js";
|
||||
import { type Fetch, fpaEpochFor, fpaProva, fpaShortName, fpfDate, fpfSeasonId, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js";
|
||||
import { SportsService } from "../src/sports/service.js";
|
||||
import { LocalStorage, UrlSigner } from "../src/storage/storage.js";
|
||||
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
|
||||
@@ -111,6 +111,7 @@ describe("federation data", () => {
|
||||
const now = new Date("2026-12-20T12:00:00Z");
|
||||
expect(fpfDate("10 jan 15:00", now)!.at.toISOString()).toBe("2027-01-10T15:00:00.000Z");
|
||||
expect(fpfDate("12 out", now)).toMatchObject({ timeKnown: false });
|
||||
expect(fpfSeasonId(new Date("2026-11-20T12:00:00Z"))).toBe("106");
|
||||
const sheet = ["Equipas Iniciais", ...Array.from({ length: 22 }, (_, i) => `${i + 1} Jogador ${i + 1}${i === 0 ? " (GR)" : ""}`), "Suplentes", "30 Suplente A", "31 Suplente B", "Treinadores"].join("\n");
|
||||
const { home, away } = parseFpfLineups(sheet);
|
||||
expect(home).toHaveLength(12);
|
||||
@@ -232,6 +233,7 @@ const fakeSites = (state: { benfica: { shirtNumber: number; name: string; photos
|
||||
const u = new URL(url);
|
||||
const json = (body: unknown) => ({ ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body), arrayBuffer: async () => new ArrayBuffer(0) });
|
||||
const bytes = (b: Buffer) => ({ ok: true, status: 200, json: async () => ({}), text: async () => b.toString("latin1"), arrayBuffer: async () => b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer });
|
||||
if (u.host === "resultados.fpf.pt" && u.pathname === "/Competition/Details") return bytes(Buffer.from("<html><body><h2>TAÇA DE PORTUGAL</h2></body></html>", "utf8"));
|
||||
if (state.handball && u.host === "ws.fpa.pt" && u.pathname.includes("getJogosClubeEpocaEscalao"))
|
||||
return json(u.pathname.endsWith("/140/374/4") ? [fpaGame("323264", "2026-09-23", VITORIA, AGUAS, [33, 29]), fpaGame("323500", "2026-10-17", VITORIA, AGUAS, null)] : []);
|
||||
if (state.handball && u.host === "portal.fpa.pt" && u.pathname.startsWith("/clube/id/")) return bytes(Buffer.from(CLUB_PAGE, "utf8"));
|
||||
@@ -372,7 +374,8 @@ describe("sports data service", () => {
|
||||
const r = await sports.refreshDue(now);
|
||||
expect(r.errors).toEqual([]);
|
||||
const comps = await ctx.db.sportsCompetition.findMany({ orderBy: { name: "asc" } });
|
||||
expect(comps.map((c) => [c.provider, c.externalId, c.season])).toEqual([
|
||||
expect(comps.filter((c) => c.provider === "FPF").map((c) => [c.externalId, c.season])).toEqual([["25263", "106"]]);
|
||||
expect(comps.filter((c) => c.provider !== "FPF").map((c) => [c.provider, c.externalId, c.season])).toEqual([
|
||||
["LIGA", "allianzcup", "20262027"],
|
||||
["FPA", "PO09", "20262027"],
|
||||
["EHF", "cl-men", "20262027"],
|
||||
|
||||
@@ -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).`,
|
||||
|
||||
@@ -341,8 +341,15 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati
|
||||
existing FPA Nextcloud account and never sent on arrival. FPA licence or an older EHF club photo fills
|
||||
gaps. People and reference faces are created when the event syncs those teams (`POST …/squads/sync`), not on
|
||||
every sports refresh. Example match: Portugal–Switzerland `202811130101002`.
|
||||
- **FPF** (`resultados.fpf.pt`, HTML): competitions are added by link. It gives teams and fixtures, and squads
|
||||
from each match sheet, read from 1 h before to 2 h after kick-off.
|
||||
- **FPF** (`resultados.fpf.pt`, HTML): the Taça de Portugal is seeded in the catalogue; other competitions are
|
||||
added by link. It gives teams and fixtures (Details page and round sheets). The competition row keeps the
|
||||
site's seasonId (`106`); the fixture and the squad use the football season (`20262027`), the same key as Liga,
|
||||
so a Liga club in the cup keeps its headshots. Squads come from each match sheet (starters, substitutes and
|
||||
the two head coaches), including the federation headshot (`Player/Logo/{id}` or the
|
||||
`fpf360cdnprd` photo host), read from 1 h before to 2 h after kick-off. A game published before it has a `matchId` is stored with a stable
|
||||
synthetic id; the next read that finds the real id updates that same fixture. The federation's Cloudflare
|
||||
challenge blocks datacentre IPs: when the worker cannot reach the site, fixtures and squads must be seeded
|
||||
another way until the IP is allowed or a proxy is set.
|
||||
- **EHF** (the JSON `ehfcl`, `ehfel` and `ehfec.eurohandball.com` read; not a documented API): men's and women's
|
||||
Champions League, European League and European Cup. Fixtures with venue, and squads from the match sheet once
|
||||
it is published: the nominated players (number, position, photo) and the bench staff (letters A, B, …; the sheet
|
||||
|
||||
@@ -32,7 +32,9 @@ Following the AP and NPPA codes:
|
||||
below the knee is on the floor: it does not frame the photo, even when it overlaps the player's legs and sits
|
||||
closer to the middle of the body. Football plays the ball on the ground, so the ball at the feet is the one
|
||||
that stays. A spare ball that nobody is playing never wins, in either sport.
|
||||
- **Shape:** the photo's own aspect unless the event or the editor chose another (never turned vertical).
|
||||
- **Shape:** the autopilot keeps the photograph's own aspect. The crop may move anywhere across the frame,
|
||||
including a tighter window, but it is not turned into another format. A square, a 4:5, a 16:9, or a portrait
|
||||
crop of a landscape frame is not an autopilot crop. An editor, by hand, may still choose another aspect.
|
||||
- **Context:** a generic event (no opponent, no fixture) is reportage. A match is sport, and a photo of that
|
||||
match with no ball in play is cropped as a person. Reportage does not use the handball cut.
|
||||
- **Framing** (per event, sport only):
|
||||
|
||||
+18
-4
@@ -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
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -45,7 +45,7 @@ export const AutopilotSettings = z.object({
|
||||
* "natural" Getty-like.
|
||||
*/
|
||||
look: z.enum(["agency", "natural", "none"]).default("none"),
|
||||
/** Crop shape (width, height); null: the photo's own. */
|
||||
/** Unused. The autopilot always keeps the photograph's own aspect. */
|
||||
aspect: z.tuple([z.number().positive(), z.number().positive()]).nullable().default(null),
|
||||
/** The crop keeps at least this many pixels on its long edge of the original. */
|
||||
minLongEdge: z.number().int().min(800).max(12000).default(2400),
|
||||
|
||||
Reference in new issue
Block a user