Compare commits

...
Author SHA1 Message Date
paula-alves d2616ce539 fix(worker): account for worker deploy overlap in DB connection budget (BIT-33530)
ci / typescript (push) Skipped
ci / rust (push) Skipped
ci / rust (pull_request) Successful in 6m9s
ci / typescript (pull_request) Successful in 11m47s
dbConnectionBudget reserved room for an API deploy overlap (apiReloadOverlap,
BIT-31550) but not for a worker deploy overlap. PM2 startOrReload on the
fork-mode photoreport-worker starts the new process before the old one finishes
its 25 s drain, so both Prisma pools and both broadcasters are open at once.
With defaults that is 2 * (47 + 1) + 26 = 122 > 100 max_connections, tipping
Postgres into error 53300 "sorry, too many clients already".

Add workerReloadOverlap (default 1) that divides the remaining budget by the
number of concurrent workers, so the total stays under max_connections even
during a reload. The worker's Prisma pool drops from 47 to 23 with defaults —
enough for the concurrent jobs the capacity planner sizes, and the headroom
and ad-hoc connection margin are preserved.

Paperclip-Issue: BIT-33530
2026-12-04 09:20:43 +00:00
paula-alves 465937212c fix(delivery): raise $transaction timeout to 30 s in enqueue (BIT-33904)
ci / rust (push) Successful in 5m26s
ci / typescript (push) Successful in 11m29s
Advisory-lock contention with 40-photo chunks from sendGalleryRest
expired the default 10 s transaction timeout (Prisma P2028). Pass an
explicit { timeout: 30_000 } so only the execution timeout is raised;
maxWait stays at the global 10 s default for pool acquisition.

Paperclip: BIT-33904
2026-12-04 07:47:35 +00:00
paula-alves 2ec4f263b6 Stop the health-check error loop on Postgres connection exhaustion (BIT-33548)
ci / typescript (push) Skipped
ci / rust (push) Skipped
ci / rust (pull_request) Successful in 4m33s
ci / typescript (pull_request) Successful in 11m56s
The /health endpoint ran db.$queryRaw`SELECT 1` with no error handling.
When PostgreSQL hits max_connections (error 53300), the query threw
PrismaClientKnownRequestError, the error handler logged it as 'unhandled
error', and the reporter sent it to errors.bitreport.pt — creating an
error loop of one-off incidents from every health check.

Two fixes:
- /health now catches DB failures and returns 503 { status: 'degraded' }
  instead of throwing, so a connection-starved health check degrades
  gracefully rather than generating an error report.
- isTransientDatabaseError now filters 53300 (pool exhaustion) alongside
  the existing 57P01/57P03/P1001/P1017 filters, so even if a 53300 surfaces
  through another code path it does not trip the error loop.

Paperclip-Issue: BIT-33548
2026-12-04 07:31:32 +00:00
spark cac99af991 Merge pull request 'Send unsure leftover picks unless the frame is only the away team' (#320) from task/gitea-319-leiria-unsure-picks into main
ci / rust (push) Successful in 3m55s
ci / typescript (push) Successful in 9m15s
ci / rust (pull_request) Successful in 4m21s
ci / typescript (pull_request) Successful in 11m13s
Send unsure leftover picks unless the frame is only the away team
2026-12-02 20:50:19 +00:00
spark 312c1f1a68 Send unsure leftover picks unless the frame is only the away team.
ci / rust (pull_request) Successful in 3m59s
ci / typescript (pull_request) Successful in 9m26s
Reference faces are missing for part of the squad, so holding every unnamed pick left the rest client empty during the match.
2026-12-02 20:40:12 +00:00
spark 5da37adf33 Send leftover picks to the rest client during a live gallery
ci / rust (push) Successful in 4m1s
ci / typescript (push) Successful in 9m33s
Closed windows can leave while later frames are still being analysed. Leftover picks follow the configured delivery counts.
2026-12-02 19:56:13 +00:00
sparkandCursor 6b03ae5d11 Send leftover picks to the rest client during a live gallery.
ci / rust (pull_request) Successful in 3m53s
ci / typescript (pull_request) Successful in 9m27s
Closed windows can leave while later frames are still being analysed. Picks that miss the galleries go to the rest destination: all of them until ten minutes before kick-off, then only home-team players.

Co-authored-by: Cursor <[email protected]>
2026-12-02 19:39:37 +00:00
spark d165996046 Split each burst across the autopilot's destinations
ci / rust (push) Successful in 3m53s
ci / typescript (push) Successful in 9m23s
One different frame per destination, rotation when a sequence is short, and an optional copy or camera original.
2026-11-29 16:07:13 +00:00
spark c8949c690d Let the autopilot split each burst across every configured destination.
ci / rust (pull_request) Successful in 3m59s
ci / typescript (pull_request) Successful in 9m54s
One different frame goes to each export, a short burst rotates so every total can still be met, and a destination can share that same frame or take the camera original.
2026-11-29 15:55:30 +00:00
spark 690b35389d Add the Cloud W17 delivery profile
ci / rust (push) Successful in 4m8s
ci / typescript (push) Successful in 9m48s
Organisations that already send to the FPA cloud get a Cloud W17 destination.
2026-11-27 19:23:25 +00:00
spark cb2b887a48 Add a Cloud W17 destination beside Cloud M19 for the women's under-17 games.
ci / rust (pull_request) Successful in 5m1s
ci / typescript (pull_request) Successful in 11m4s
It uses the organisation's existing FPA Nextcloud account and sends into Seleções Nacionais/W17, only when the photographer picks it.
2026-11-27 19:08:09 +00:00
spark 413983a057 Merge pull request 'List each under-17 EHF match once' (#314) from task/w17-fold-friendly into main
ci / rust (push) Successful in 4m7s
ci / typescript (push) Successful in 9m42s
2026-11-27 15:30:58 +00:00
spark 30b30ef122 Fold the under-17 friendly into the official EHF match so Portugal–Italy is listed once.
ci / rust (pull_request) Successful in 4m9s
ci / typescript (pull_request) Successful in 9m50s
The FPA camp and the EHF page were storing the same kick-off as two fixtures. An event already opened on the friendly stays on the one row.
2026-11-27 15:14:26 +00:00
spark 2fad6e96c3 Merge pull request 'Import the women's under-17 EHF EURO qualification' (#313) from task/w17-ehf-euro into main
ci / rust (push) Successful in 4m13s
ci / typescript (push) Successful in 9m47s
2026-11-27 14:33:30 +00:00
spark ae6e467103 Import the women's under-17 EHF EURO qualification so Portugal–Italy can be picked.
ci / rust (pull_request) Successful in 4m38s
ci / typescript (pull_request) Successful in 10m0s
The standing list was only the men's Euro Cup. Tonight's game is on the W17 page and never reached the event form.
2026-11-27 13:59:55 +00:00
spark 360dc5efb8 Sign in to ZeroZero again when publish returns 403
ci / rust (push) Successful in 5m52s
ci / typescript (push) Successful in 11m29s
A stale desk session answers 403. Sign in once more before accepting the refusal.
2026-11-26 22:33:59 +00:00
spark 92cecc7214 Merge pull request 'fix(delivery): idempotent retry when item leaves FAILED between render and click (BIT-33418)' (#312) from task/BIT-33418-retry-race-condition into main
ci / rust (push) Successful in 6m28s
ci / typescript (push) Successful in 11m55s
2026-11-26 22:31:41 +00:00
paula-alves a9b7007d5d fix(delivery): idempotent retry when item leaves FAILED between render and click (BIT-33418)
ci / rust (pull_request) Successful in 7m10s
ci / typescript (pull_request) Successful in 12m3s
Race condition: between the desktop rendering a FAILED delivery row and the
user clicking "Repetir", the autopilot/queue worker can requeue, retry, or
retract the item. The retry endpoint's updateMany (where status=FAILED)
matched zero rows and threw notFound("failed_item_not_found") -> 404, and
the frontend promise had no .catch -> unhandledrejection -> error loop.

API: when the item no longer matches FAILED, fetch it; if it exists return
its current state (200, idempotent), only 404 when the row is gone.
Frontend: add a rejection handler that reloads the list so a stale FAILED
row refreshes instead of becoming an unhandled rejection.

Paperclip-BIT-33418
2026-11-26 22:19:13 +00:00
38 changed files with 1716 additions and 86 deletions

No files matched your search

+8 -3
View File
@@ -142,9 +142,14 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give
registerClientErrors(app, reporter);
app.get("/health", async () => {
await db.$queryRaw`SELECT 1`;
return { status: "ok", version: config.APP_VERSION };
app.get("/health", async (_req, reply) => {
try {
await db.$queryRaw`SELECT 1`;
return { status: "ok", version: config.APP_VERSION };
} catch {
reply.code(503);
return { status: "degraded", version: config.APP_VERSION };
}
});
const authenticate = requireAuth(sessions);
+38 -3
View File
@@ -82,6 +82,41 @@ const median = (xs: number[]) => {
return s[Math.floor(s.length / 2)]!;
};
/** A gallery window. Warm-up (more than one window before kick-off) is −1 and is never sent. */
export const BEST_WINDOW_MS = 5 * 60_000;
/** Window index from kick-off. The five minutes just before the start still belong to the first window. */
export function bestWindow(at: number, start: number, windowMs = BEST_WINDOW_MS): number {
if (at < start - windowMs) return -1;
const index = Math.floor((at - start) / windowMs);
if (index < 0) return 0;
return index;
}
/**
* Windows that still have a frame being analysed. A live match keeps receiving photos, so a closed
* window must be allowed to send while a later one is still open.
*/
export function windowsStillArriving(start: number, inflightAt: readonly number[], windowMs = BEST_WINDOW_MS): Set<number> {
const blocked = new Set<number>();
for (const at of inflightAt) {
const window = bestWindow(at, start, windowMs);
if (window < 0) continue;
blocked.add(window);
}
return blocked;
}
/** True when another frame of this same moment is still being analysed, so the burst is not complete. */
export function burstStillArriving(from: number, to: number, inflightAt: readonly number[], gapMs: number): boolean {
for (const at of inflightAt) {
if (at < from - gapMs) continue;
if (at > to + gapMs) continue;
return true;
}
return false;
}
/**
* How many frames a gallery may reach. The asked size is the target: about 15% more when the match is rich,
* at least 2 and never more than 25 past it, so a short gallery stays close and a long one can breathe.
@@ -96,7 +131,7 @@ export function galleryCeiling(count: number): number {
* (chosen or not), so earlier choices count against the gallery size.
*/
export function curate(candidates: Candidate[], decided: { id: string; chosen: boolean; at?: number }[], opts: CurateOptions): WindowDecision[] {
const windowMs = opts.windowMs ?? 5 * 60_000;
const windowMs = opts.windowMs ?? BEST_WINDOW_MS;
const minGapMs = opts.minGapMs ?? 5_000;
const sequenceGapMs = opts.sequenceGapMs ?? SEQUENCE_PICK_GAP_MS;
const sequenceCap = opts.sequenceCap ?? SEQUENCE_PICK_CAP;
@@ -119,8 +154,8 @@ export function curate(candidates: Candidate[], decided: { id: string; chosen: b
const byWindow = new Map<number, typeof scored>();
for (const x of scored) {
if (done.has(x.c.id)) continue;
// Warm-up and line-ups (more than 5 minutes before kick-off) are not game moments.
const w = x.c.at < opts.start - 5 * 60_000 ? -1 : Math.max(0, Math.floor((x.c.at - opts.start) / windowMs));
// Warm-up and line-ups (more than one window before kick-off) are not game moments.
const w = bestWindow(x.c.at, opts.start, windowMs);
byWindow.set(w, [...(byWindow.get(w) ?? []), x]);
}
const out: WindowDecision[] = [];
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { BEST_WINDOW_MS, bestWindow, burstStillArriving, windowsStillArriving } from "./curate.js";
const start = Date.parse("2026-11-29T17:00:00Z");
describe("best windows while a match is still being analysed", () => {
it("keeps the five minutes before kick-off in the first window and the warm-up out", () => {
expect(bestWindow(start - BEST_WINDOW_MS - 1, start)).toBe(-1);
expect(bestWindow(start - 60_000, start)).toBe(0);
expect(bestWindow(start + BEST_WINDOW_MS, start)).toBe(1);
});
it("blocks only the window that still has a frame in analysis", () => {
const later = start + 10 * BEST_WINDOW_MS + 30_000;
const blocked = windowsStillArriving(start, [later]);
expect(blocked.has(0)).toBe(false);
expect(blocked.has(10)).toBe(true);
});
it("holds a burst when another frame of the same moment is still in analysis", () => {
const from = start + 1_000;
const to = start + 1_400;
expect(burstStillArriving(from, to, [to + 500], 1_000)).toBe(true);
expect(burstStillArriving(from, to, [to + 5_000], 1_000)).toBe(false);
});
});
+81
View File
@@ -0,0 +1,81 @@
import { describe, expect, it } from "vitest";
import { homeRestDecision, type FaceHint } from "./home-rest.js";
const start = Date.parse("2026-12-02T20:15:00Z");
const leadMin = 10;
const homeNames = new Set(["joao silva"]);
const homeClubs = new Set(["u. leiria"]);
const awayNames = new Set(["costa"]);
const awayClubs = new Set(["sporting cp b"]);
function decide(extra: {
at: number;
playerNames?: string[];
faces?: FaceHint[];
homeTeamId?: string | null;
}) {
return homeRestDecision({
at: extra.at,
start,
leadMin,
playerNames: extra.playerNames ?? [],
faces: extra.faces ?? [],
homeTeamId: extra.homeTeamId ?? "home",
homeNames,
homeClubs,
awayTeamId: "away",
awayNames,
awayClubs,
});
}
describe("leftover picks before and during a match", () => {
it("sends every leftover pick until ten minutes before kick-off", () => {
expect(decide({ at: start - 10 * 60_000 })).toBe("send");
expect(decide({ at: start - 10 * 60_000 - 1 })).toBe("send");
});
it("sends a home player and a frame we cannot name after the cutoff", () => {
const after = start - 10 * 60_000 + 1;
expect(decide({ at: after, playerNames: ["João Silva"] })).toBe("send");
expect(
decide({
at: after,
faces: [{ teamId: "home", name: "Outro", club: null, open: false }],
}),
).toBe("send");
expect(
decide({
at: after,
faces: [{ teamId: null, name: null, club: null, open: true }],
}),
).toBe("send");
expect(decide({ at: after })).toBe("send");
});
it("does not send a frame that is clearly only the away team", () => {
const after = start + 30_000;
expect(
decide({
at: after,
faces: [{ teamId: "away", name: "Costa", club: "Sporting CP B", open: false }],
}),
).toBe("skip");
expect(decide({ at: after, playerNames: ["Costa"] })).toBe("skip");
expect(
decide({
at: after,
faces: [
{ teamId: "away", name: "Costa", club: "Sporting CP B", open: false },
{ teamId: null, name: null, club: null, open: true },
],
}),
).toBe("send");
expect(
decide({
at: after,
faces: [{ teamId: null, name: "Árbitro", club: "Arbitragem", open: false }],
}),
).toBe("send");
});
});
+165
View File
@@ -0,0 +1,165 @@
/** Same bar the face worker uses before it trusts a suggestion (faces/service.ts). */
export const STRONG_FACE = 0.85;
export interface FaceHint {
teamId: string | null;
name: string | null;
club: string | null;
/** A face is in the frame and nobody confident has been named yet. */
open: boolean;
}
export interface NamedPerson {
name: string;
club: string | null;
teamId: string | null;
}
/** One face group, reduced to whether we can already tell the team. Ignored groups are not people. */
export function hintFromGroup(
group: {
personId: string | null;
suggestedPersonId: string | null;
suggestionScore: number | null;
ignored: boolean;
} | null,
person: NamedPerson | null,
suggested: NamedPerson | null,
): FaceHint | null {
if (!group || group.ignored) return null;
if (group.personId) {
if (!person) return { teamId: null, name: null, club: null, open: true };
return { teamId: person.teamId, name: person.name, club: person.club, open: false };
}
const score = group.suggestionScore ?? 0;
if (group.suggestedPersonId && score >= STRONG_FACE) {
if (!suggested) return { teamId: null, name: null, club: null, open: true };
return { teamId: suggested.teamId, name: suggested.name, club: suggested.club, open: false };
}
return { teamId: null, name: null, club: null, open: true };
}
export function foldName(value: string | null | undefined): string {
if (!value) return "";
return value
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/\s+/g, " ")
.trim();
}
function namedHome(
name: string | null,
club: string | null,
homeNames: ReadonlySet<string>,
homeClubs: ReadonlySet<string>,
): boolean {
const foldedName = foldName(name);
if (foldedName && homeNames.has(foldedName)) return true;
const foldedClub = foldName(club);
if (foldedClub && homeClubs.has(foldedClub)) return true;
return false;
}
/** True when this frame shows someone from the home squad. */
export function isHomePlayer(input: {
playerNames: readonly string[];
faces: readonly FaceHint[];
homeTeamId: string | null;
homeNames: ReadonlySet<string>;
homeClubs: ReadonlySet<string>;
}): boolean {
for (const name of input.playerNames) {
if (namedHome(name, null, input.homeNames, input.homeClubs)) return true;
}
for (const face of input.faces) {
if (face.open) continue;
if (input.homeTeamId && face.teamId === input.homeTeamId) return true;
if (namedHome(face.name, face.club, input.homeNames, input.homeClubs)) return true;
}
return false;
}
function matchesSide(
name: string | null,
club: string | null,
teamId: string | null,
sideTeamId: string | null,
sideNames: ReadonlySet<string>,
sideClubs: ReadonlySet<string>,
): boolean {
if (sideTeamId && teamId === sideTeamId) return true;
const foldedName = foldName(name);
if (foldedName && sideNames.has(foldedName)) return true;
const foldedClub = foldName(club);
if (foldedClub && sideClubs.has(foldedClub)) return true;
return false;
}
/**
* True when every identified person in the frame is the away side, and nobody is still unnamed.
* A missing face, a weak guess, or a home player is not this case.
*/
export function isClearlyOnlyAway(input: {
playerNames: readonly string[];
faces: readonly FaceHint[];
awayTeamId: string | null;
awayNames: ReadonlySet<string>;
awayClubs: ReadonlySet<string>;
homeTeamId: string | null;
homeNames: ReadonlySet<string>;
homeClubs: ReadonlySet<string>;
}): boolean {
const namedPlayers: string[] = [];
for (const name of input.playerNames) {
if (foldName(name)) namedPlayers.push(name);
}
if (namedPlayers.length === 0 && input.faces.length === 0) return false;
for (const face of input.faces) {
if (face.open) return false;
}
for (const name of namedPlayers) {
const home = matchesSide(name, null, null, input.homeTeamId, input.homeNames, input.homeClubs);
if (home) return false;
const away = matchesSide(name, null, null, input.awayTeamId, input.awayNames, input.awayClubs);
if (!away) return false;
}
for (const face of input.faces) {
const home = matchesSide(face.name, face.club, face.teamId, input.homeTeamId, input.homeNames, input.homeClubs);
if (home) return false;
const away = matchesSide(face.name, face.club, face.teamId, input.awayTeamId, input.awayNames, input.awayClubs);
if (!away) return false;
}
return true;
}
/**
* Leftover picks for the rest destination.
* Up to `leadMin` before kick-off, every leftover pick goes.
* After that, a pick still goes unless the frame is clearly only the away team.
* An unidentified player is sent: the reference set is incomplete, and the client deletes the odd frame.
*/
export function homeRestDecision(input: {
at: number;
start: number;
leadMin: number;
playerNames: readonly string[];
faces: readonly FaceHint[];
homeTeamId: string | null;
homeNames: ReadonlySet<string>;
homeClubs: ReadonlySet<string>;
awayTeamId: string | null;
awayNames: ReadonlySet<string>;
awayClubs: ReadonlySet<string>;
}): "send" | "skip" | "wait" {
const cutoff = input.start - input.leadMin * 60_000;
if (input.at <= cutoff) return "send";
if (isHomePlayer(input)) return "send";
if (isClearlyOnlyAway(input)) return "skip";
return "send";
}
+375 -20
View File
@@ -26,10 +26,11 @@ import {
sequenceIndex,
sequenceSendRoom,
} from "./bursts.js";
import { curate, matchMinutes } from "./curate.js";
import { bestWindow, burstStillArriving, curate, matchMinutes, windowsStillArriving } from "./curate.js";
import { foldName, hintFromGroup, homeRestDecision, type FaceHint, type NamedPerson } from "./home-rest.js";
import { type LearntStyle, learntStyle } from "./learning.js";
import { detailForCrop, lookValues } from "./look.js";
import { exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, type GalleryExport } from "./targets.js";
import { assignBurstExports, exportSlots, exportTargets, galleryReceivers, MELHORES_GAP_MS, picksNeeded, type BurstExportSlot, type GalleryExport } from "./targets.js";
const STALE_RUNNING_MS = 10 * 60_000;
/** A burst is decided once no new frame of it has arrived for this long. */
@@ -46,6 +47,20 @@ function takenHere(ids: readonly string[], when: ReadonlyMap<string, Date | null
return ids.filter((id) => takenDuring(when.get(id), event));
}
/** Capture time of photos this event is still analysing. A live match uses this so closed windows are not held back. */
async function inflightCaptureTimes(db: Db, eventId: string): Promise<number[]> {
const rows = await db.photo.findMany({
where: { eventId, autopilotStatus: { in: ["PENDING", "RUNNING"] } },
select: { capturedAt: true, createdAt: true },
});
const times: number[] = [];
for (const row of rows) {
const at = row.capturedAt ?? row.createdAt;
times.push(at.getTime());
}
return times;
}
export interface AutopilotRecord {
score: number;
reason: string | null;
@@ -78,6 +93,12 @@ export interface AutopilotRecord {
hold?: "ball";
/** Per destination gallery: true when this frame was picked for it, false when its window decided against it. */
gallery?: Record<string, boolean>;
/** Leftover pick already queued for the rest destination. */
restSent?: boolean;
/** Leftover pick that is clearly only the away team, so it stays out of the rest destination. */
restSkip?: boolean;
/** `restSkip` was decided by the away-team rule. Older skips without this are looked at again. */
restAway?: boolean;
/**
* Planned develop/crop ops from analysis. Applied only when this frame is picked for the burst — never on the
* near-duplicates left unflagged.
@@ -104,6 +125,9 @@ export class AutopilotService {
},
) {}
/** Leftover picks are retried on a slow cadence: face names arrive after the window has closed. */
private restFlushAt = 0;
/** The upright preview, so a sequence can compare eyes. Null when it was never rendered. */
private previewFile(photo: { organizationId: string; sha256: string }): string | null {
const file = this.deps.storage.resolve(this.deps.storage.derivedKey(photo.organizationId, photo.sha256, "preview"));
@@ -263,8 +287,8 @@ export class AutopilotService {
const event = await db.event.findUnique({ where: { id: eventId }, select: { id: true, organizationId: true, autopilot: true, createdById: true, away: true, fixtureId: true, ingestFrom: true, ingestUntil: true } });
if (!event) continue;
const settings = AutopilotSettings.parse(event.autopilot ?? {});
const busy = await db.photo.count({ where: { eventId, autopilotStatus: { in: ["PENDING", "RUNNING"] } } });
if (busy) continue;
// A live match always has photos still being analysed. That must not hold the windows that already closed.
const inflightAt = await inflightCaptureTimes(db, eventId);
const photos = await db.photo.findMany({
where: { eventId, autopilotStatus: "DONE" },
select: { id: true, capturedAt: true, cameraSerial: true, cameraModel: true, uploaderId: true, createdAt: true, flag: true, autopilot: true, width: true, height: true, sha256: true, facesStatus: true, iso: true },
@@ -282,10 +306,24 @@ export class AutopilotService {
const score = rec?.score == null ? null : rec.score * (look.get(p.id) ?? 1);
return { ...p, rec, camera: p.cameraSerial ?? p.cameraModel ?? p.uploaderId ?? "?", score };
});
for (const burst of groupBursts(frames, settings.burstGapSec * 1000)) {
const orderedBursts = groupBursts(frames, settings.burstGapSec * 1000);
const sentByTarget = new Map<string, number>();
if (settings.deliverExports.length > 0) {
const sentRows = await db.deliveryItem.groupBy({
by: ["targetId"],
where: { eventId, status: { in: ["QUEUED", "RUNNING", "WAITING", "DONE"] } },
_count: true,
});
for (const row of sentRows) sentByTarget.set(row.targetId, row._count);
}
for (let burstIndex = 0; burstIndex < orderedBursts.length; burstIndex++) {
const burst = orderedBursts[burstIndex]!;
if (burst.every((f) => f.rec?.decided)) continue;
// Still arriving: wait until the burst has settled.
// Still arriving: wait until the burst has settled, and until a frame of the same moment finishes analysis.
if (Math.max(...burst.map((f) => f.createdAt.getTime())) > now.getTime() - BURST_SETTLE_MS) continue;
const burstFrom = Math.min(...burst.map((f) => (f.capturedAt ?? f.createdAt).getTime()));
const burstTo = Math.max(...burst.map((f) => (f.capturedAt ?? f.createdAt).getTime()));
if (burstStillArriving(burstFrom, burstTo, inflightAt, settings.burstGapSec * 1000)) continue;
const reportage = reportageEvent;
const sharp = burst.filter((f) => (f.rec?.focus ?? 0) >= FOCUS_SHARP).length;
const need = picksNeeded(settings);
@@ -301,9 +339,10 @@ export class AutopilotService {
// between frames) is still that sequence. A frame that looks different may add another, up to four.
let take = asked;
if (!reportage) {
take = Math.min(asked, Math.max(0, settings.picksPerBurst));
const cap = settings.deliverExports.length > 0 ? settings.deliverExports.length : settings.picksPerBurst;
take = Math.min(asked, Math.max(0, cap));
}
const start = Math.min(...burst.map((f) => (f.capturedAt ?? f.createdAt).getTime()));
const start = burstFrom;
const sameCamera = frames
.filter((f) => f.camera === burst[0]!.camera && !burst.some((b) => b.id === f.id))
.map((f) => ({
@@ -323,13 +362,16 @@ export class AutopilotService {
});
if (already.length > 0) {
const next = bestOf(pool, 1)[0];
const room = next
? sequenceSendRoom(settings.picksPerBurst, already.map((frame) => frame.look), {
subject: next.rec?.subject ?? null,
people: next.rec?.people ?? null,
reason: next.rec?.reason ?? null,
})
: 0;
let sequenceCap = settings.picksPerBurst;
if (settings.deliverExports.length > 0) sequenceCap = settings.deliverExports.length;
let room = 0;
if (next) {
room = sequenceSendRoom(sequenceCap, already.map((frame) => frame.look), {
subject: next.rec?.subject ?? null,
people: next.rec?.people ?? null,
reason: next.rec?.reason ?? null,
});
}
take = Math.min(take, room);
}
const chosen = bestOf(pool, take)
@@ -408,11 +450,37 @@ export class AutopilotService {
await db.photo.update({ where: { id: f.id }, data: { autopilot: { ...(f.rec ?? {}), decided: true, picked: pickedIds.has(f.id) } as object } });
}
// "Only the best" delivers per window of the match instead (below), not every burst's picks.
// N exports → rank i of this burst to export i (same file never to two).
const targets = exportTargets(settings);
if (settings.selection === "bursts" && targets.length && best.length && this.deps.deliveries && event.createdById) {
// One different frame per destination still under its total. A copy (Direto → Arquivo) shares the frame.
const slots: BurstExportSlot[] = exportSlots(settings).map((slot) => ({
...slot,
sent: sentByTarget.get(slot.targetId) ?? 0,
}));
if (settings.selection === "bursts" && settings.deliverExports.length > 0 && slots.length && best.length && this.deps.deliveries && event.createdById) {
const when = new Map(photos.map((p) => [p.id, p.capturedAt]));
const sendable = best.filter((f) => f.rec?.hold !== "ball" && takenHere([f.id], when, event).length);
const plan = assignBurstExports(slots, burstIndex, sendable.length);
for (const assignment of plan) {
const frame = sendable[assignment.rank];
if (!frame) continue;
const targets = [assignment.targetId, ...assignment.alsoTargetIds];
for (const targetId of targets) {
await this.deps.deliveries
.enqueue({
organizationId: event.organizationId,
targetId,
photoIds: [frame.id],
again: false,
originals: assignment.originals,
requestedById: event.createdById,
})
.catch((err: unknown) => log.warn({ err, targetId }, "autopilot: delivery not queued"));
}
sentByTarget.set(assignment.targetId, (sentByTarget.get(assignment.targetId) ?? 0) + 1);
}
} else if (settings.selection === "bursts" && slots.length && best.length && this.deps.deliveries && event.createdById) {
const when = new Map(photos.map((p) => [p.id, p.capturedAt]));
const sendable = best.filter((f) => f.rec?.hold !== "ball" && takenHere([f.id], when, event).length);
const targets = exportTargets(settings);
for (let i = 0; i < targets.length && i < sendable.length; i++) {
const id = sendable[i]!.id;
await this.deps.deliveries
@@ -434,6 +502,10 @@ export class AutopilotService {
const settings = AutopilotSettings.parse(event?.autopilot ?? {});
if (settings.selection === "best") picked += await this.curateEvent(eventId, settings, now);
}
if (now.getTime() - this.restFlushAt >= 20_000) {
this.restFlushAt = now.getTime();
await this.flushHomeRest();
}
return picked;
}
@@ -464,6 +536,13 @@ export class AutopilotService {
// With 2+ exports, curate on the best frame; delivery below assigns best/2nd/… to each target.
// Separate gallery sizes curate to the largest, and each smaller one keeps its own spread.
const candidates = candidatesOf(ranked, settings.burstGapSec * 1000, true, "best");
// A window that still has a frame in analysis stays open. The ones already complete can leave now.
const blockedWindows = windowsStillArriving(event.startsAt.getTime(), await inflightCaptureTimes(db, eventId));
const ready = candidates.filter((candidate) => {
const window = bestWindow(candidate.at, event.startsAt.getTime());
if (blockedWindows.has(window)) return false;
return true;
});
const curateOpts = {
start: event.startsAt.getTime(),
durationMs: matchMinutes(event.sport) * 60_000,
@@ -471,7 +550,7 @@ export class AutopilotService {
minGapMs: MELHORES_GAP_MS,
sequenceCap: settings.picksPerBurst,
};
const decisions = curate(candidates, decided, {
const decisions = curate(ready, decided, {
count: galleries.length ? Math.max(...galleries.map((g) => g.count)) : settings.bestCount,
...curateOpts,
});
@@ -492,7 +571,7 @@ export class AutopilotService {
const flag = (p.autopilot as unknown as AutopilotRecord | null)?.gallery?.[g.targetId];
return flag === undefined ? [] : [{ id: p.id, chosen: flag, at: p.capturedAt?.getTime() ?? 0 }];
});
const parts = curate(candidates, earlier, { count: g.count, ...curateOpts });
const parts = curate(ready, earlier, { count: g.count, ...curateOpts });
chosenBy.set(g.targetId, new Set(parts.flatMap((d) => d.chosen)));
seenBy.set(g.targetId, new Set(parts.flatMap((d) => d.ids)));
}
@@ -584,8 +663,284 @@ export class AutopilotService {
}
}
}
if (typeof settings.restHomeFromMin === "number" && settings.restTargetId && galleries.length) {
await this.sendGalleryRest(eventId, settings);
}
return chosenCount;
}
/** Events whose leftover picks have not been sent, including skips made before the away-team rule. */
private async flushHomeRest(): Promise<void> {
const { db, log } = this.deps;
const rows = await db.$queryRaw<{ event_id: string }[]>`
SELECT DISTINCT p.event_id
FROM photos p
JOIN events e ON e.id = p.event_id
WHERE p.flag = 'PICK'
AND p.autopilot_status = 'DONE'
AND p.created_at > now() - interval '2 days'
AND (p.autopilot->>'curated') = 'true'
AND (p.autopilot->>'restSent') IS DISTINCT FROM 'true'
AND (
(p.autopilot->>'restSkip') IS DISTINCT FROM 'true'
OR (p.autopilot->>'restAway') IS DISTINCT FROM 'true'
)
AND jsonb_typeof(e.autopilot->'restHomeFromMin') = 'number'
AND e.autopilot->>'restTargetId' IS NOT NULL
AND jsonb_typeof(e.autopilot->'galleries') = 'array'
AND jsonb_array_length(e.autopilot->'galleries') > 0
`;
for (const row of rows) {
const event = await db.event.findUnique({ where: { id: row.event_id }, select: { autopilot: true } });
const settings = AutopilotSettings.parse(event?.autopilot ?? {});
await this.sendGalleryRest(row.event_id, settings).catch((err: unknown) => {
log.warn({ err, eventId: row.event_id }, "autopilot: leftover delivery not queued");
});
}
}
/**
* Picks that did not make a gallery. Until `restHomeFromMin` before kick-off they all go to the rest
* destination. From then on they still go, unless every identified person in the frame is the away team.
*/
private async sendGalleryRest(eventId: string, settings: AutopilotSettings): Promise<number> {
const leadMin = settings.restHomeFromMin;
const restTargetId = settings.restTargetId;
const galleries = settings.galleries ?? [];
if (typeof leadMin !== "number" || !restTargetId || !galleries.length) return 0;
if (!this.deps.deliveries) return 0;
const { db, log } = this.deps;
const event = await db.event.findUnique({
where: { id: eventId },
select: {
organizationId: true,
startsAt: true,
createdById: true,
ingestFrom: true,
ingestUntil: true,
home: true,
homeShort: true,
away: true,
awayShort: true,
homeTeamId: true,
awayTeamId: true,
fixture: { select: { season: true } },
homeTeam: { select: { name: true, abbreviation: true } },
awayTeam: { select: { name: true, abbreviation: true } },
},
});
if (!event?.createdById) return 0;
const photos = await db.photo.findMany({
where: { eventId, flag: "PICK", autopilotStatus: "DONE" },
select: { id: true, capturedAt: true, createdAt: true, players: true, autopilot: true },
});
const cutoff = event.startsAt.getTime() - leadMin * 60_000;
const pending: typeof photos = [];
for (const photo of photos) {
const rec = photo.autopilot as AutopilotRecord | null;
if (!rec?.curated) continue;
if (rec.restSent) continue;
if (rec.restSkip && rec.restAway) continue;
if (rec.hold === "ball" || rec.chosen) continue;
if (!takenDuring(photo.capturedAt, event)) continue;
let inGallery = false;
for (const gallery of galleries) {
if (rec.gallery?.[gallery.targetId] === true) inGallery = true;
}
if (inGallery) continue;
pending.push(photo);
}
if (!pending.length) return 0;
const season = event.fixture?.season ?? null;
const homeNames = await squadNames(db, event.homeTeamId, season);
const awayNames = await squadNames(db, event.awayTeamId, season);
const homeClubs = labelSet([event.home, event.homeShort, event.homeTeam?.name, event.homeTeam?.abbreviation]);
const awayClubs = labelSet([event.away, event.awayShort, event.awayTeam?.name, event.awayTeam?.abbreviation]);
const faceIds: string[] = [];
for (const photo of pending) {
const at = photo.capturedAt?.getTime() ?? photo.createdAt.getTime();
if (at > cutoff) faceIds.push(photo.id);
}
const hints = new Map<string, FaceHint[]>();
if (faceIds.length) {
const faces = await db.face.findMany({
where: { photoId: { in: faceIds } },
select: {
photoId: true,
group: {
select: {
personId: true,
suggestedPersonId: true,
suggestionScore: true,
ignoredAt: true,
},
},
},
});
const personIds: string[] = [];
for (const face of faces) {
if (face.group?.personId) personIds.push(face.group.personId);
if (face.group?.suggestedPersonId) personIds.push(face.group.suggestedPersonId);
}
let people: { id: string; name: string; club: string | null; sportsPlayerId: string | null }[] = [];
if (personIds.length > 0) {
people = await db.person.findMany({
where: { id: { in: [...new Set(personIds)] } },
select: { id: true, name: true, club: true, sportsPlayerId: true },
});
}
const sportsIds: string[] = [];
for (const person of people) {
if (person.sportsPlayerId) sportsIds.push(person.sportsPlayerId);
}
let sports: { id: string; teamId: string }[] = [];
if (sportsIds.length > 0) {
sports = await db.sportsPlayer.findMany({
where: { id: { in: sportsIds } },
select: { id: true, teamId: true },
});
}
const teamOf = new Map(sports.map((player) => [player.id, player.teamId]));
const named = new Map<string, NamedPerson>();
for (const person of people) {
let teamId: string | null = null;
if (person.sportsPlayerId) {
const found = teamOf.get(person.sportsPlayerId);
if (found) teamId = found;
}
named.set(person.id, { name: person.name, club: person.club, teamId });
}
for (const face of faces) {
let group: {
personId: string | null;
suggestedPersonId: string | null;
suggestionScore: number | null;
ignored: boolean;
} | null = null;
if (face.group) {
group = {
personId: face.group.personId,
suggestedPersonId: face.group.suggestedPersonId,
suggestionScore: face.group.suggestionScore,
ignored: face.group.ignoredAt !== null,
};
}
let person: NamedPerson | null = null;
if (face.group?.personId) {
person = named.get(face.group.personId) ?? null;
}
let suggested: NamedPerson | null = null;
if (face.group?.suggestedPersonId) {
suggested = named.get(face.group.suggestedPersonId) ?? null;
}
const hint = hintFromGroup(group, person, suggested);
if (!hint) continue;
const list = hints.get(face.photoId) ?? [];
list.push(hint);
hints.set(face.photoId, list);
}
}
const send: typeof photos = [];
for (const photo of pending) {
const at = photo.capturedAt?.getTime() ?? photo.createdAt.getTime();
const decision = homeRestDecision({
at,
start: event.startsAt.getTime(),
leadMin,
playerNames: photo.players,
faces: hints.get(photo.id) ?? [],
homeTeamId: event.homeTeamId,
homeNames,
homeClubs,
awayTeamId: event.awayTeamId,
awayNames,
awayClubs,
});
if (decision === "wait") continue;
if (decision === "skip") {
await this.markRest(photo, "restSkip");
continue;
}
send.push(photo);
}
if (!send.length) return 0;
let queued = 0;
const chunk = 40;
for (let index = 0; index < send.length; index += chunk) {
const slice = send.slice(index, index + chunk);
const result = await this.deps.deliveries.enqueue({
organizationId: event.organizationId,
targetId: restTargetId,
photoIds: slice.map((photo) => photo.id),
again: false,
requestedById: event.createdById,
});
const done = new Set(result.queued.map((item) => item.photoId));
for (const skipped of result.skipped) {
if (skipped.reason === "already_delivered") done.add(skipped.photoId);
}
for (const photo of slice) {
if (!done.has(photo.id)) continue;
await this.markRest(photo, "restSent");
queued += 1;
}
}
if (queued) log.info({ eventId, queued, restTargetId }, "autopilot: leftover picks queued");
return queued;
}
private async markRest(photo: { id: string; autopilot: unknown }, key: "restSent" | "restSkip"): Promise<void> {
const rec = photo.autopilot;
if (!rec || typeof rec !== "object" || Array.isArray(rec)) return;
let extra: { restSkip: true; restAway: true } | { restSent: true };
if (key === "restSkip") {
extra = { restSkip: true, restAway: true };
} else {
extra = { restSent: true };
}
await this.deps.db.photo.update({
where: { id: photo.id },
data: { autopilot: { ...rec, ...extra } as object },
});
}
}
function labelSet(labels: readonly (string | null | undefined)[]): Set<string> {
const names = new Set<string>();
for (const label of labels) {
const folded = foldName(label);
if (folded) names.add(folded);
}
return names;
}
async function squadNames(db: Db, teamId: string | null, season: string | null): Promise<Set<string>> {
const names = new Set<string>();
if (!teamId) return names;
let squad: { name: string; fullName: string | null }[] = [];
if (season) {
squad = await db.sportsPlayer.findMany({
where: { teamId, goneAt: null, season },
select: { name: true, fullName: true },
});
}
if (squad.length === 0) {
squad = await db.sportsPlayer.findMany({
where: { teamId, goneAt: null },
select: { name: true, fullName: true },
});
}
for (const player of squad) {
const name = foldName(player.name);
const fullName = foldName(player.fullName);
if (name) names.add(name);
if (fullName) names.add(fullName);
}
return names;
}
/** Gallery flags for a frame whose window was decided this pass. Unmentioned destinations stay as they were. */
+88
View File
@@ -22,8 +22,96 @@ export function exportTargets(settings: Pick<AutopilotSettings, "deliverTargetId
return out;
}
export interface BurstExportSlot {
targetId: string;
alsoTargetIds: string[];
/** Null: this destination stays in every burst. */
count: number | null;
originals: boolean;
/** Photos already queued or delivered to `targetId` in this event. */
sent: number;
}
export interface BurstAssignment {
targetId: string;
alsoTargetIds: string[];
originals: boolean;
/** Index into the burst's ranked frames. 0 is the best available. */
rank: number;
}
/** The configured exports, or one slot per legacy destination when that list is empty. */
export function exportSlots(
settings: Pick<AutopilotSettings, "deliverExports" | "deliverTargetIds" | "deliverTargetId" | "restTargetId">,
): Omit<BurstExportSlot, "sent">[] {
const configured = settings.deliverExports ?? [];
if (configured.length) {
const seen = new Set<string>();
const slots: Omit<BurstExportSlot, "sent">[] = [];
for (const row of configured) {
if (!row.targetId || seen.has(row.targetId)) continue;
seen.add(row.targetId);
const also: string[] = [];
for (const id of row.alsoTargetIds) {
if (!id || id === row.targetId || seen.has(id)) continue;
seen.add(id);
also.push(id);
}
slots.push({
targetId: row.targetId,
alsoTargetIds: also,
count: row.count,
originals: row.originals,
});
}
return slots;
}
return exportTargets(settings).map((targetId) => ({
targetId,
alsoTargetIds: [],
count: null,
originals: false,
}));
}
/**
* One different frame per destination that is still under its total. A short burst starts at the next
* destination, so the frames that do exist rotate and every total can still be met. A destination that
* already has its `count` is skipped. `alsoTargetIds` ride with that frame and do not take another one.
*/
export function assignBurstExports(slots: readonly BurstExportSlot[], burstIndex: number, frameCount: number): BurstAssignment[] {
if (frameCount <= 0 || slots.length === 0) return [];
const open: { slot: BurstExportSlot; order: number }[] = [];
for (let order = 0; order < slots.length; order++) {
const slot = slots[order]!;
if (slot.count !== null && slot.sent >= slot.count) continue;
open.push({ slot, order });
}
if (open.length === 0) return [];
const start = burstIndex % slots.length;
open.sort((left, right) => {
const leftTurn = (left.order - start + slots.length) % slots.length;
const rightTurn = (right.order - start + slots.length) % slots.length;
return leftTurn - rightTurn;
});
const take = Math.min(open.length, frameCount);
const assigned: BurstAssignment[] = [];
for (let rank = 0; rank < take; rank++) {
const slot = open[rank]!.slot;
assigned.push({
targetId: slot.targetId,
alsoTargetIds: slot.alsoTargetIds,
originals: slot.originals,
rank,
});
}
return assigned;
}
/** How many frames of a burst to keep: one per configured export, else `picksPerBurst`. */
export function picksNeeded(settings: AutopilotSettings): number {
const configured = settings.deliverExports?.length ?? 0;
if (configured > 0) return Math.min(10, configured);
const n = exportTargets(settings).length;
if (n > 0) return Math.min(5, Math.max(1, n));
return settings.picksPerBurst;
+28 -6
View File
@@ -4,13 +4,19 @@ import type { Db } from "../db.js";
/** The destination photographers pick to send an under-19 national game to the FPA cloud. */
export const CLOUD_M19_TARGET = "Cloud M19";
/** The same kind of destination for the women's under-17 side. */
export const CLOUD_W17_TARGET = "Cloud W17";
/**
* One Nextcloud destination per organisation that already delivers club games to cloud.photoreport.pt.
* Same account and file name as that destination; the folder is Seleções Nacionais/M19.
* Same account and file name as that destination; the folder is under Seleções Nacionais.
* It does not send on arrival: the photographer chooses it for this game.
* Returns how many destinations were created.
*/
export async function ensureCloudM19Target(db: Db): Promise<number> {
async function ensureNationalCloudTarget(
db: Db,
target: { name: string; folder: string; fileName: string },
): Promise<number> {
const sources = await db.deliveryTarget.findMany({
where: {
kind: "NEXTCLOUD",
@@ -31,21 +37,21 @@ export async function ensureCloudM19Target(db: Db): Promise<number> {
if (seen.has(source.organizationId)) continue;
seen.add(source.organizationId);
const exists = await db.deliveryTarget.findUnique({
where: { organizationId_name: { organizationId: source.organizationId, name: CLOUD_M19_TARGET } },
where: { organizationId_name: { organizationId: source.organizationId, name: target.name } },
select: { id: true },
});
if (exists) continue;
await db.deliveryTarget.create({
data: {
organizationId: source.organizationId,
name: CLOUD_M19_TARGET,
name: target.name,
kind: source.kind,
baseUrl: source.baseUrl,
username: source.username,
secretEnc: source.secretEnc,
hostFingerprint: source.hostFingerprint,
folderTemplate: DESTINATION_EXAMPLES.fpaM19.folder,
fileNameTemplate: source.fileNameTemplate || DESTINATION_EXAMPLES.fpaM19.fileName,
folderTemplate: target.folder,
fileNameTemplate: source.fileNameTemplate || target.fileName,
longEdge: source.longEdge,
jpegQuality: source.jpegQuality,
sharpen: source.sharpen,
@@ -64,3 +70,19 @@ export async function ensureCloudM19Target(db: Db): Promise<number> {
}
return created;
}
export function ensureCloudM19Target(db: Db): Promise<number> {
return ensureNationalCloudTarget(db, {
name: CLOUD_M19_TARGET,
folder: DESTINATION_EXAMPLES.fpaM19.folder,
fileName: DESTINATION_EXAMPLES.fpaM19.fileName,
});
}
export function ensureCloudW17Target(db: Db): Promise<number> {
return ensureNationalCloudTarget(db, {
name: CLOUD_W17_TARGET,
folder: DESTINATION_EXAMPLES.fpaW17.folder,
fileName: DESTINATION_EXAMPLES.fpaW17.fileName,
});
}
+8 -3
View File
@@ -151,7 +151,7 @@ function checkTemplates(folderTemplate: string, fileNameTemplate: string, extra:
matchNumber: "1",
startsAt,
},
{ capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1 },
{ capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1, fileName: "IMG_0001.JPG" },
"Fotógrafo",
);
const fileSample = { ...built, ...extra };
@@ -392,8 +392,13 @@ export async function registerDeliveryRoutes(
where: { id: itemId, organizationId: orgId, status: "FAILED" },
data: { status: "QUEUED", attempts: 0, nextAttemptAt: new Date(), lastError: null },
});
if (!result.count) throw notFound("failed_item_not_found");
return toItemSummary(await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId } }));
if (result.count) return toItemSummary(await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId } }));
// Race: the item was no longer FAILED between the render and the retry (autopilot/queue worker
// requeued, retried, or retracted it). The retry is idempotent — return the current state instead
// of a 404, so the desktop does not unhandledrejection into the error loop (BIT-33418).
const current = await db.deliveryItem.findUnique({ where: { id: itemId } });
if (!current) throw notFound("item_not_found");
return toItemSummary(current);
});
/** ZeroZero: the event's game on the photo desk (chosen, or found by teams and time). */
+1 -1
View File
@@ -288,7 +288,7 @@ export class DeliveryService {
);
}
return created;
});
}, { timeout: 30_000 });
queued.push(...items);
}
for (const item of queued) this.deps.broadcaster.library(item.organizationId, { type: "delivery.updated", item: toItemSummary(item) });
@@ -0,0 +1,60 @@
import { describe, expect, it } from "vitest";
import { DeliveryService } from "./service.js";
import type { Db } from "../db.js";
/** A minimal hand-rolled Db whose `$transaction` spy captures the options argument. */
function mockDb(captured: { options: unknown }): Pick<Db, "$transaction"> & Record<string, unknown> {
const tx = {
$executeRaw: (strings: TemplateStringsArray) => Promise.resolve(strings.length),
deliveryItem: {
aggregate: async () => ({ _max: { sequence: null } }),
create: async ({ data }: { data: Record<string, unknown> }) => ({
id: "item-1",
targetId: data.targetId,
photoId: data.photoId,
eventId: data.eventId,
sequence: data.sequence,
status: "QUEUED",
attempts: 0,
lastError: null,
remotePath: null,
byteSize: null,
updatedAt: new Date(),
organizationId: data.organizationId,
}),
},
};
return {
$transaction: async (fn: (tx: typeof tx) => Promise<unknown>, options?: unknown) => {
captured.options = options;
return fn(tx);
},
deliveryTarget: { findFirst: async () => ({ id: "t1", colorLabel: null, copyTargetId: null }) },
photo: { findMany: async () => [{ id: "p1", organizationId: "org", status: "READY", eventId: "ev1" }] },
deliveryItem: { findMany: async () => [] },
} as unknown as Pick<Db, "$transaction"> & Record<string, unknown>;
}
describe("DeliveryService.enqueue transaction timeout (BIT-33904)", () => {
it("passes a 30 s execution timeout to $transaction so advisory-lock contention doesn't hit P2028", async () => {
const captured: { options: unknown } = { options: undefined };
const db = mockDb(captured) as unknown as Db;
const delivery = new DeliveryService({
db,
storage: {} as never,
secrets: undefined,
broadcaster: { library: () => {}, broadcast: () => {} } as never,
log: { info: () => {}, warn: () => {} } as never,
});
await delivery.enqueue({
organizationId: "org",
targetId: "t1",
photoIds: ["p1"],
again: false,
requestedById: null,
});
expect(captured.options).toEqual({ timeout: 30_000 });
});
});
+1
View File
@@ -17,6 +17,7 @@ describe("selectionKey", () => {
expect(selectionKey(["Seleção Nacional sub-19 Masculina"])).toBe("m19");
expect(selectionKey(["Portugal", "Espanha", "sub-19"])).toBe("m19");
expect(selectionKey(["Seleção Nacional sub-19 feminina"])).toBe("w19");
expect(selectionKey(["/FPA/Fotos/2026_2027/Seleções Nacionais/W17/20261127 - POR x ITA"])).toBe("w17");
});
it("names no team for a club game, a gala, or a gathering", () => {
+14 -5
View File
@@ -144,10 +144,13 @@ export class Pressure {
* instance's worth of API connections during a deploy (`pm2 startOrReload` on the clustered `photoreport-api`
* app brings a new instance online and confirms it before stopping an old one, so for a few seconds there are
* `apiInstances + 1` live, not just `apiInstances` — BIT-31550 was this exact overlap tipping the API's steady
* -state budget into Postgres' `superuser_reserved_connections`); Postgres' `superuser_reserved_connections`
* itself (reserved below `max_connections`, never available to the app no matter how much headroom is left —
* this is what "reserved for roles with the SUPERUSER attribute" means); and extra headroom for ad hoc
* connections (migrations, scripts, psql, admin tools) that aren't sized here.
* -state budget into Postgres' `superuser_reserved_connections`); one extra worker during a deploy
* (`pm2 startOrReload` on the fork-mode `photoreport-worker` starts the new process before the old one finishes
* its 25 s drain, so both Prisma pools and both broadcasters are open at once — BIT-33530 was this overlap
* exhausting all slots with "sorry, too many clients already", error 53300); Postgres'
* `superuser_reserved_connections` itself (reserved below `max_connections`, never available to the app no
* matter how much headroom is left — this is what "reserved for roles with the SUPERUSER attribute" means); and
* extra headroom for ad hoc connections (migrations, scripts, psql, admin tools) that aren't sized here.
*/
export function dbConnectionBudget(
wanted: number,
@@ -157,6 +160,7 @@ export function dbConnectionBudget(
apiPoolSize = 10,
realtimePerInstance = 3,
apiReloadOverlap = 1,
workerReloadOverlap = 1,
superuserReserved = 3,
headroom = 10,
}: {
@@ -165,10 +169,15 @@ export function dbConnectionBudget(
apiPoolSize?: number;
realtimePerInstance?: number;
apiReloadOverlap?: number;
workerReloadOverlap?: number;
superuserReserved?: number;
headroom?: number;
} = {},
): number {
const available = max - superuserReserved - (apiInstances + apiReloadOverlap) * (apiPoolSize + realtimePerInstance) - 1 - headroom;
const apiConnections = (apiInstances + apiReloadOverlap) * (apiPoolSize + realtimePerInstance);
// Room for (1 + workerReloadOverlap) workers, each with `available` Prisma connections + 1 broadcaster.
// Solving (1 + workerReloadOverlap) * (available + 1) <= max - superuserReserved - apiConnections - headroom
// gives available <= floor((max - superuserReserved - apiConnections - headroom) / (1 + workerReloadOverlap)) - 1.
const available = Math.floor((max - superuserReserved - apiConnections - headroom) / (1 + workerReloadOverlap)) - 1;
return Math.max(1, Math.min(wanted, available));
}
+9 -8
View File
@@ -10,19 +10,20 @@ import { createHash } from "node:crypto";
*/
/**
* 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).
* Transient PostgreSQL connection errors during a restart, graceful shutdown, network blip, or pool
* exhaustion. Prisma surfaces these as `PrismaClientKnownRequestError` wrapping the raw SQLSTATE
* (57P01/57P03/53300) 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, BIT-33548 for 53300).
*/
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);
return /57P01|57P03|53300|remaining connection slots are reserved|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";
+15 -5
View File
@@ -16,14 +16,24 @@ import { claimInbox } from "./adopt.js";
const HOUR = 3600_000;
/** An older app does not send `galleries`. Keep the sizes already stored instead of clearing them. */
/**
* An older app does not send `galleries` or `restHomeFromMin`. Keep what is already stored instead of clearing it.
*/
function keptGalleries(next: AutopilotSettings | null, current: Prisma.JsonValue): AutopilotSettings | typeof Prisma.DbNull {
if (!next) return Prisma.DbNull;
if (next.galleries !== undefined) return next;
if (!current || typeof current !== "object" || Array.isArray(current)) return next;
const kept = (current as { galleries?: AutopilotSettings["galleries"] }).galleries;
if (!Array.isArray(kept) || kept.length === 0) return next;
return { ...next, galleries: kept };
const prev = current as {
galleries?: AutopilotSettings["galleries"];
restHomeFromMin?: number | null;
};
let out = next;
if (next.galleries === undefined && Array.isArray(prev.galleries) && prev.galleries.length > 0) {
out = { ...out, galleries: prev.galleries };
}
if (next.restHomeFromMin === undefined && typeof prev.restHomeFromMin === "number") {
out = { ...out, restHomeFromMin: prev.restHomeFromMin };
}
return out;
}
const OrgParams = z.object({ orgId: z.uuid() });
const EventParams = z.object({ eventId: z.uuid() });
+2 -1
View File
@@ -1,4 +1,4 @@
import { ensureCloudM19Target } from "./delivery/fpa-m19.js";
import { ensureCloudM19Target, ensureCloudW17Target } from "./delivery/fpa-m19.js";
import { preferIpv4 } from "./lib/prefer-ipv4.js";
import { buildApp, reporterFor } from "./app.js";
import { loadConfig } from "./config.js";
@@ -21,6 +21,7 @@ process.on("SIGTERM", () => void shutdown("SIGTERM"));
process.on("SIGINT", () => void shutdown("SIGINT"));
ensureCloudM19Target(db).catch((err) => app.log.warn({ err }, "delivery: Cloud M19 profile not created"));
ensureCloudW17Target(db).catch((err) => app.log.warn({ err }, "delivery: Cloud W17 profile not created"));
try {
await app.listen({ port: config.PORT, host: "0.0.0.0" });
+36
View File
@@ -111,4 +111,40 @@ describe("EHF matches", () => {
expect(seen.some((u) => u.includes("/men/2026-27/matches/"))).toBe(true);
expect(seen.filter((u) => u.includes("GetMatches")).length).toBe(3);
});
it("reads a national standing list with the hall, the group and the kick-off", async () => {
const fetch: Fetch = async () => ({
ok: true,
status: 200,
json: async () => ({
matches: [
{
matchID: "202712010502014",
venue: {
date: { utc: "2026-11-27T19:00:00Z" },
place: { hallName: "Pavilhão da Associação Atlética de Águas Santas", cityName: "Àguas Santas" },
},
homeTeam: { team: { nationAbbreviation: "POR" } },
guestTeam: { team: { nationAbbreviation: "ITA" } },
comp: { round: { name: "Qualification Tournaments" }, group: { name: "C" } },
},
],
}),
text: async () => "",
arrayBuffer: async () => new ArrayBuffer(0),
});
const rows = await new EhfProvider(fetch, 0).euroCupMenMatches("comp", "139009");
expect(rows).toEqual([
{
matchId: "202712010502014",
startsAt: new Date("2026-11-27T19:00:00Z"),
homeNation: "POR",
awayNation: "ITA",
venue: "Pavilhão da Associação Atlética de Águas Santas",
city: "Àguas Santas",
round: "Qualification Tournaments",
group: "C",
},
]);
});
});
+10
View File
@@ -8,6 +8,8 @@ import {
nationalNamesMatch,
nationalSideFromTexts,
nationalTeamExternalId,
youthEuroRound,
youthNationalTeam,
} from "./national.js";
describe("national call-up", () => {
@@ -76,4 +78,12 @@ describe("nationalTeamExternalId", () => {
expect(nationalTeamExternalId("Roménia", "w18")).toBe("ROU-W18");
expect(nationalCountryLabel("Switzerland")).toBe("Suíça");
});
it("maps the W17 qualification nations onto youth sides", () => {
expect(youthNationalTeam("POR", "w17")).toEqual({ externalId: "W17", name: "Portugal", abbreviation: "POR" });
expect(youthNationalTeam("ITA", "w17")).toEqual({ externalId: "ITA-W17", name: "Itália", abbreviation: "ITA" });
expect(youthNationalTeam("SLO", "w17")?.externalId).toBe("SLO-W17");
expect(youthNationalTeam("FAR", "w17")?.name).toBe("Ilhas Faroé");
expect(youthEuroRound("Qualification Tournaments", "C")).toBe("Qualificação C");
});
});
+64
View File
@@ -171,6 +171,19 @@ export const EHF_EURO_CUP_MEN = {
sheetWindowMs: 3 * 86400_000,
} as const;
/**
* Women's under-17 EHF EURO 2027 qualification (Águas Santas, 27–29 Nov 2026, and the same page
* for the rest of that tournament). Same standing list and match sheet as the men's Euro Cup.
*/
export const EHF_W17_EURO = {
competitionId: "DrPEklHxLKeDu_IajXOQvA",
contentId: "139009",
externalId: "W17-EURO",
name: "W17 EHF EURO",
gender: "F" as const,
side: "w17",
} as const;
const fold = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
/** Same athlete across FPA call-up spelling and EHF sheet ("Iturriza" / "Iturizza", "Miguel Oliveira" / "Miguel Moreira de Oliveira"). */
@@ -231,6 +244,21 @@ export function nationalCountryLabel(raw: string): string | null {
if (/^(fra|fr|franca|france)$/.test(n)) return "França";
if (/^(ger|deu|alemanha|germany)$/.test(n)) return "Alemanha";
if (/^(swe|suecia|sweden)$/.test(n)) return "Suécia";
if (/^(ita|italy|italia)$/.test(n)) return "Itália";
if (/^(slo|svn|slovenia|eslovenia)$/.test(n)) return "Eslovénia";
if (/^(ukr|ukraine|ucrania)$/.test(n)) return "Ucrânia";
if (/^(isl|iceland|islandia)$/.test(n)) return "Islândia";
if (/^(far|fro|faroe|faroe islands|ilhas faroe)$/.test(n)) return "Ilhas Faroé";
if (/^(tur|turkey|turkiye|turquia)$/.test(n)) return "Turquia";
if (/^(isr|israel)$/.test(n)) return "Israel";
if (/^(mkd|north macedonia|macedonia do norte)$/.test(n)) return "Macedónia do Norte";
if (/^(ltu|lithuania|lituania)$/.test(n)) return "Lituânia";
if (/^(kos|kosovo)$/.test(n)) return "Kosovo";
if (/^(gre|greece|grecia)$/.test(n)) return "Grécia";
if (/^(aut|austria)$/.test(n)) return "Áustria";
if (/^(pol|poland|polonia)$/.test(n)) return "Polónia";
if (/^(fin|finland|finlandia)$/.test(n)) return "Finlândia";
if (/^(lux|luxembourg|luxemburgo)$/.test(n)) return "Luxemburgo";
return null;
}
@@ -248,6 +276,15 @@ const YOUTH_CODE: Record<string, string> = {
hungria: "HUN",
noruega: "NOR",
italia: "ITA",
ucrania: "UKR",
"ilhas faroe": "FAR",
turquia: "TUR",
israel: "ISR",
"macedonia do norte": "MKD",
lituania: "LTU",
kosovo: "KOS",
grecia: "GRE",
luxemburgo: "LUX",
polonia: "POL",
chequia: "CZE",
montenegro: "MNE",
@@ -261,6 +298,33 @@ const YOUTH_CODE: Record<string, string> = {
"paises baixos": "NED",
};
/**
* A youth national side from an EHF nation code or an English/Portuguese country name.
* Portugal's under-17 women are "W17"; Italy is "ITA-W17".
*/
export function youthNationalTeam(
nation: string | null | undefined,
side: string,
): { externalId: string; name: string; abbreviation: string } | null {
if (!nation) return null;
const name = nationalCountryLabel(nation);
if (!name) return null;
const externalId = nationalTeamExternalId(name, side);
if (!externalId) return null;
const abbreviation = YOUTH_CODE[fold(name)];
if (!abbreviation) return null;
return { externalId, name, abbreviation };
}
/** "Qualification Tournaments" + group "C" is what the picker shows as "Qualificação C". */
export function youthEuroRound(round: string | null, group: string | null): string | null {
let name = round;
if (name === "Qualification Tournaments") name = "Qualificação";
if (name && group) return `${name} ${group}`;
if (name) return name;
return group;
}
/** Which national sports team externalId fits this country + side key. */
export function nationalTeamExternalId(country: string, side: string): string | null {
const label = nationalCountryLabel(country) ?? country;
+5 -2
View File
@@ -1538,7 +1538,7 @@ export class EhfProvider {
async euroCupMenMatches(
competitionId: string,
contentId: string,
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[]> {
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null; round: string | null; group: string | null }[]> {
const data = await get(
this.fetcher,
`https://www.eurohandball.com/umbraco/api/competitionapi/GetStandingMatches?contentId=${encodeURIComponent(contentId)}&competitionId=${encodeURIComponent(competitionId)}`,
@@ -1546,7 +1546,7 @@ export class EhfProvider {
"json",
);
const rows = Array.isArray(obj(data).matches) ? (obj(data).matches as unknown[]) : [];
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[] = [];
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null; round: string | null; group: string | null }[] = [];
for (const row of rows) {
const m = obj(row);
const matchId = str(m.matchID);
@@ -1557,6 +1557,7 @@ export class EhfProvider {
if (Number.isNaN(at.getTime())) continue;
const hall = str(place.hallName);
const city = str(place.cityName);
const comp = obj(m.comp);
out.push({
matchId,
startsAt: at,
@@ -1564,6 +1565,8 @@ export class EhfProvider {
awayNation: str(obj(obj(m.guestTeam).team).nationAbbreviation) ?? str(obj(obj(m.guestTeam).team).countryAbbreviation),
venue: hall,
city,
round: str(obj(comp.round).name),
group: str(obj(comp.group).name),
});
}
return out;
+161
View File
@@ -17,6 +17,7 @@ import { type ClubCandidate, type JogaClient, chooseClub, jogaCompetitionId, jog
import { sameListedPerson } from "./people.js";
import {
EHF_EURO_CUP_MEN,
EHF_W17_EURO,
ESP_M19_2026,
M19_POR_2026,
NATIONAL_SIDES,
@@ -24,6 +25,8 @@ import {
SUI_EURO_CUP_2026,
nationToSnamTeam,
nationalNamesMatch,
youthEuroRound,
youthNationalTeam,
type NationalCallUp,
} from "./national.js";
import { tallyOf, tallySquadPhotos } from "./squadPhotos.js";
@@ -615,6 +618,7 @@ export class SportsService {
const espHave = await this.deps.db.sportsPlayer.count({ where: { teamId: espM19Id, season, goneAt: null } });
if (espHave === 0) result.players += await this.saveNationalCallUp(espM19Id, season, ESP_M19_2026);
await this.applyEuroCupSheets(now, season, result);
await this.applyYouthEuros(now, season, result);
// People + reference faces: only when an event syncs these teams (`syncEventSquads`), not on every FPA refresh.
await this.fillNationalPhotos(snamId, season);
await this.fillNationalPhotos(suiId, season);
@@ -687,6 +691,20 @@ export class SportsService {
this.deps.log.info({ side: camp.side, players: camp.players.length, source: camp.sourceUrl }, "sports: youth call-up");
}
for (const game of camp.games) {
if (camp.side === EHF_W17_EURO.side) {
const homeTeamId = await this.upsertTeam("FPA", {
externalId: game.homeExternalId,
name: game.homeCountry,
abbreviation: youthAbbrev(game.homeExternalId, camp.side),
});
const awayTeamId = await this.upsertTeam("FPA", {
externalId: game.awayExternalId,
name: game.awayCountry,
abbreviation: youthAbbrev(game.awayExternalId, camp.side),
});
const listed = await this.hasOfficialYouthFixture(homeTeamId, awayTeamId, game.startsAt, EHF_W17_EURO.externalId);
if (listed) continue;
}
const comp = await this.youthCompetition(season, camp.side);
result.fixtures += await this.saveFixture(comp, "FPA", {
externalId: game.externalId,
@@ -806,6 +824,149 @@ export class SportsService {
}
}
/** The FPA camp and the EHF page can disagree by an hour and still be the same match. */
private sameKickoff(startsAt: Date) {
const slackMs = 2 * 60 * 60 * 1000;
return {
gte: new Date(startsAt.getTime() - slackMs),
lte: new Date(startsAt.getTime() + slackMs),
};
}
/** The official under-17 EURO already has this kick-off, so the camp must not add it again as a friendly. */
private async hasOfficialYouthFixture(homeTeamId: string, awayTeamId: string, startsAt: Date, competitionExternalId: string): Promise<boolean> {
const row = await this.deps.db.sportsFixture.findFirst({
where: {
homeTeamId,
awayTeamId,
startsAt: this.sameKickoff(startsAt),
competition: { externalId: competitionExternalId },
},
select: { id: true },
});
return row !== null;
}
/**
* The FPA post lists the same under-17 game as a friendly ("Sub-17 feminina"). One match, one row.
* An event already opened on the friendly keeps that row when it can become the official one.
*/
private async foldYouthFriendly(
officialCompetitionId: string,
officialExternalId: string,
homeTeamId: string,
awayTeamId: string,
startsAt: Date,
): Promise<void> {
const friendly = await this.deps.db.sportsFixture.findFirst({
where: {
homeTeamId,
awayTeamId,
startsAt: this.sameKickoff(startsAt),
competition: { provider: "FPA", externalId: { endsWith: "-AMIG" } },
},
select: { id: true },
});
if (!friendly) return;
const official = await this.deps.db.sportsFixture.findUnique({
where: { competitionId_externalId: { competitionId: officialCompetitionId, externalId: officialExternalId } },
select: { id: true },
});
if (!official) {
await this.deps.db.sportsFixture.update({
where: { id: friendly.id },
data: { competitionId: officialCompetitionId, externalId: officialExternalId },
});
return;
}
if (official.id === friendly.id) return;
await this.deps.db.event.updateMany({
where: { fixtureId: friendly.id },
data: { fixtureId: official.id },
});
await this.deps.db.sportsFixture.delete({ where: { id: friendly.id } });
}
/**
* Women's under-17 EHF EURO qualification on eurohandball.com. The whole tournament is stored so the
* picker can open Portugal–Italy (and the rest of the weekend) before the nominated sheet is published.
* The sheet, when it is out, writes shirt numbers and headshots onto W17 / ITA-W17 / …
*/
private async applyYouthEuros(now: Date, season: string, result: RefreshResult): Promise<void> {
const { db, log } = this.deps;
let matches: Awaited<ReturnType<EhfProvider["euroCupMenMatches"]>>;
try {
matches = await this.ehf.euroCupMenMatches(EHF_W17_EURO.competitionId, EHF_W17_EURO.contentId);
} catch (err) {
result.errors.push(`ehf w17: ${(err as Error).message}`);
return;
}
const listed = matches.flatMap((m) => {
const home = youthNationalTeam(m.homeNation, EHF_W17_EURO.side);
const away = youthNationalTeam(m.awayNation, EHF_W17_EURO.side);
if (!home || !away) return [];
return [{ match: m, home, away }];
});
if (!listed.length) return;
const comp = await db.sportsCompetition.upsert({
where: { provider_externalId: { provider: "FPA", externalId: EHF_W17_EURO.externalId } },
create: {
provider: "FPA",
externalId: EHF_W17_EURO.externalId,
sport: "andebol",
name: EHF_W17_EURO.name,
gender: EHF_W17_EURO.gender,
season,
},
update: { name: EHF_W17_EURO.name, gender: EHF_W17_EURO.gender, season },
});
for (const row of listed) {
const homeTeamId = await this.upsertTeam("FPA", row.home);
const awayTeamId = await this.upsertTeam("FPA", row.away);
await this.foldYouthFriendly(comp.id, row.match.matchId, homeTeamId, awayTeamId, row.match.startsAt);
result.fixtures += await this.saveFixture(comp, "FPA", {
externalId: row.match.matchId,
competition: EHF_W17_EURO.externalId,
season,
home: row.home,
away: row.away,
startsAt: row.match.startsAt,
timeKnown: true,
round: youthEuroRound(row.match.round, row.match.group),
venue: row.match.venue,
city: row.match.city,
});
}
const due = listed.filter((row) => Math.abs(row.match.startsAt.getTime() - now.getTime()) <= EHF_EURO_CUP_MEN.sheetWindowMs);
for (const row of due) {
if (this.deps.ehfDelayMs) await new Promise((r) => setTimeout(r, this.deps.ehfDelayMs));
let sheet: Awaited<ReturnType<EhfProvider["nationalSheet"]>>;
try {
sheet = await this.ehf.nationalSheet(row.match.matchId);
} catch (err) {
result.errors.push(`ehf w17 sheet ${row.match.matchId}: ${(err as Error).message}`);
continue;
}
if (!sheet) continue;
const sides = [
{ nation: sheet.homeNation, players: sheet.home },
{ nation: sheet.awayNation, players: sheet.away },
];
for (const side of sides) {
const team = youthNationalTeam(side.nation, EHF_W17_EURO.side);
if (!team) continue;
const teamId = await this.upsertTeam("FPA", team);
const field = side.players.filter((p) => p.position !== "Equipa técnica");
result.players += await this.mergeNationalSheet(teamId, season, field, []);
await this.fillNationalPhotos(teamId, season);
}
log.info(
{ matchId: row.match.matchId, home: sheet.homeNation, away: sheet.awayNation, players: sheet.home.length + sheet.away.length },
"sports: w17 sheet",
);
}
}
/**
* Write EHF sheet players onto a national team. For Portugal, keep the CIPA from the FPA call-up when the
* name matches; still take the shirt number and headshot from the sheet.
+2 -1
View File
@@ -16,7 +16,7 @@ import { RenderPool, RenderProcess } from "./develop/engine.js";
import { DevelopService, RenderWorker } from "./develop/service.js";
import { FaceProcess, GrowingFacePool } from "./faces/process.js";
import { AutopilotService, AutopilotWorker } from "./autopilot/service.js";
import { ensureCloudM19Target } from "./delivery/fpa-m19.js";
import { ensureCloudM19Target, ensureCloudW17Target } from "./delivery/fpa-m19.js";
import { jogaClientFromConfig } from "./sports/joga.js";
import { SportsService, SportsWorker } from "./sports/service.js";
import { ArchiveService, ArchiveWorker, localDirs } from "./archive/service.js";
@@ -177,6 +177,7 @@ const sports = config.SPORTS_SYNC === "on"
: undefined;
ensureCloudM19Target(db).catch((err) => log.warn({ err }, "delivery: Cloud M19 profile not created"));
ensureCloudW17Target(db).catch((err) => log.warn({ err }, "delivery: Cloud W17 profile not created"));
scanner.start();
if (secrets) archive.start();
autopilot.start();
+21
View File
@@ -1,4 +1,7 @@
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { buildApp } from "../src/app.js";
import { loadConfig } from "../src/config.js";
import { createDb } from "../src/db.js";
import { bearer, createTestApp, login, PASSWORD, resetDb, seedUser, type TestContext } from "./helpers.js";
let ctx: TestContext;
@@ -16,6 +19,24 @@ describe("health", () => {
const res = await ctx.app.inject({ method: "GET", url: "/health" });
expect(res.json()).toEqual({ status: "ok", version: "dev" });
});
it("returns 503 degraded when the database is unreachable", async () => {
const config = loadConfig({
NODE_ENV: "test",
DATABASE_URL: "postgresql://[email protected]:1/photoreport_test",
JWT_SECRET: "test-secret-test-secret-test-secret-123",
});
const db = createDb(config.DATABASE_URL);
const app = await buildApp({ config, db });
try {
const res = await app.inject({ method: "GET", url: "/health" });
expect(res.statusCode).toBe(503);
expect(res.json()).toEqual({ status: "degraded", version: "dev" });
} finally {
await app.close();
await db.$disconnect();
}
});
});
describe("login", () => {
+24 -6
View File
@@ -40,22 +40,40 @@ describe("capacity", () => {
});
describe("dbConnectionBudget", () => {
it("stays under what the API's cluster, a deploy's reload overlap, the superuser reserve, the broadcaster and headroom leave of max_connections", () => {
// 100 - 3 superuser reserved - ((2 api instances + 1 reload overlap) * (10 pool + 3 realtime)) - 1 broadcaster - 10 headroom = 47.
expect(dbConnectionBudget(500)).toBe(47);
it("stays under what the API's cluster, a deploy's reload overlaps, the superuser reserve, the broadcaster and headroom leave of max_connections", () => {
// 100 - 3 superuser reserved - ((2 api + 1 reload) * (10 pool + 3 realtime)) - 10 headroom = 48.
// Divide by (1 + 1 worker overlap) = 24, minus 1 broadcaster = 23.
expect(dbConnectionBudget(500)).toBe(23);
expect(dbConnectionBudget(10)).toBe(10);
});
it("follows a differently sized API cluster or Postgres limit", () => {
expect(dbConnectionBudget(500, { max: 200, apiInstances: 4, apiPoolSize: 15 })).toBe(96);
// 200 - 3 - ((4 + 1) * (15 + 3)) - 10 = 200 - 3 - 90 - 10 = 97; floor(97 / 2) - 1 = 47.
expect(dbConnectionBudget(500, { max: 200, apiInstances: 4, apiPoolSize: 15 })).toBe(47);
// 40 - 3 - ((2 + 1) * (10 + 3)) - 10 = 40 - 3 - 39 - 10 = -12; floor(-12 / 2) - 1 = -7; clamped to 1.
expect(dbConnectionBudget(500, { max: 40, apiInstances: 2, apiPoolSize: 10 })).toBe(1);
});
it("can be told a deploy never overlaps instances (e.g. a non-cluster or single-instance API)", () => {
expect(dbConnectionBudget(500, { apiReloadOverlap: 0 })).toBe(60);
it("can be told a deploy never overlaps API instances (e.g. a non-cluster or single-instance API)", () => {
// 100 - 3 - (2 * 13) - 10 = 61; floor(61 / 2) - 1 = 29.
expect(dbConnectionBudget(500, { apiReloadOverlap: 0 })).toBe(29);
});
it("can be told the worker never overlaps during a deploy", () => {
// 100 - 3 - (3 * 13) - 10 = 48; floor(48 / 1) - 1 = 47 (the old steady-state budget, BIT-31550 era).
expect(dbConnectionBudget(500, { workerReloadOverlap: 0 })).toBe(47);
});
it("never goes below 1, even if the API and headroom already exceed max_connections", () => {
expect(dbConnectionBudget(50, { max: 20, apiInstances: 2, apiPoolSize: 10 })).toBe(1);
});
it("keeps the total at or below max_connections during a worker deploy overlap", () => {
const max = 100;
const budget = dbConnectionBudget(500, { max });
// Two workers (old draining + new), each with `budget` Prisma + 1 broadcaster, plus API at deploy overlap.
const apiConnections = 3 * (10 + 3);
const total = apiConnections + 2 * (budget + 1) + 3 + 10;
expect(total).toBeLessThanOrEqual(max);
});
});
+26
View File
@@ -851,6 +851,32 @@ describe("delivery", () => {
expect(broadcaster.sent.filter((s) => s.message.type === "delivery.updated").map((s) => (s.message as { item: { status: string } }).item.status)).toEqual(["QUEUED", "QUEUED", "FAILED", "DONE"]);
});
it("retry is idempotent when the item leaves FAILED between render and click (BIT-33418)", async () => {
const { orgId, token, target } = await setup();
const id = await photo("race.jpg", "2026:09:23 21:10:00");
await delivery.enqueue({ organizationId: orgId, targetId: target.id, photoIds: [id], again: false, requestedById: (await ctx.db.user.findFirstOrThrow()).id });
const [claimed] = await delivery.claim(5);
nc.status = 401;
expect(await delivery.process(claimed!)).toMatchObject({ status: "FAILED", attempts: 1 });
nc.status = undefined;
// Between the desktop rendering the FAILED row and the user clicking "Repetir", the queue worker
// requeued the item (autopilot, queueEdited, queueOrphanRetracts, …) so it is no longer FAILED.
const itemId = (await ctx.db.deliveryItem.findFirstOrThrow({ where: { photoId: id, targetId: target.id } })).id;
await ctx.db.deliveryItem.update({ where: { id: itemId }, data: { status: "QUEUED", attempts: 0, nextAttemptAt: new Date(), lastError: null } });
// The retry must not 404 — it returns the current state, so the desktop's promise resolves and no
// unhandledrejection reaches the error hub.
const retry = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/${itemId}/retry`, headers: bearer(token) });
expect(retry.statusCode).toBe(200);
expect(retry.json()).toMatchObject({ id: itemId, status: "QUEUED", attempts: 0 });
// A truly missing item still 404s.
const ghost = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/00000000-0000-4000-8000-000000000000/retry`, headers: bearer(token) });
expect(ghost.statusCode).toBe(404);
expect(ghost.json()).toMatchObject({ error: "item_not_found" });
});
it("writes long venues whole in IIM and XMP, flagged as UTF-8", async () => {
const src = path.join(dir, "src.jpg");
await writeFile(src, await sharp({ create: { width: 300, height: 200, channels: 3, background: "#123456" } }).jpeg().toBuffer());
+1
View File
@@ -105,6 +105,7 @@ describe("errors to errors.bitreport.pt", () => {
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");
log.error({ err: mk("Raw query failed. Code: `53300`. Message: `remaining connection slots are reserved for roles with the SUPERUSER attribute`", "P2010") }, "health: query failed");
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();
+140
View File
@@ -733,6 +733,28 @@ describe("sports data service", () => {
log: quiet,
fetch: (async (url, init) => {
const u = String(url);
if (u.includes("GetStandingMatches") && u.includes("contentId=139009"))
return {
ok: true,
status: 200,
json: async () => ({
matches: [
{
matchID: "202712010502014",
venue: {
date: { utc: kick.toISOString() },
place: { hallName: "Pavilhão da Associação Atlética de Águas Santas", cityName: "Àguas Santas" },
},
homeTeam: { team: { nationAbbreviation: "POR" } },
guestTeam: { team: { nationAbbreviation: "ITA" } },
comp: { round: { name: "Qualification Tournaments" }, group: { name: "C" } },
},
],
rounds: [],
}),
text: async () => "",
arrayBuffer: async () => new ArrayBuffer(0),
};
if (u.includes("GetStandingMatches"))
return {
ok: true,
@@ -751,6 +773,45 @@ describe("sports data service", () => {
text: async () => "",
arrayBuffer: async () => new ArrayBuffer(0),
};
if (u.includes("GetMatchDetails") && u.includes("202712010502014"))
return {
ok: true,
status: 200,
json: async () => ({
matchDetails: {
details: {
homeTeam: {
team: { nationAbbreviation: "POR" },
players: [
{
id: "ehf-w17-costa",
shirtNumber: "7",
playingPosition: "Centre Back",
person: { firstName: "Maria", lastName: "Costa", nationAbbreviation: "POR" },
newPhoto: { w512: "https://res.ehf.eu/photo/w17-costa.jpg" },
},
],
officials: [],
},
guestTeam: {
team: { nationAbbreviation: "ITA" },
players: [
{
id: "ehf-w17-rossi",
shirtNumber: "9",
playingPosition: "Left Wing",
person: { firstName: "Giulia", lastName: "Rossi", nationAbbreviation: "ITA" },
newPhoto: { w512: "https://res.ehf.eu/photo/w17-rossi.jpg" },
},
],
officials: [],
},
},
},
}),
text: async () => "",
arrayBuffer: async () => new ArrayBuffer(0),
};
if (u.includes("GetMatchDetails") && u.includes("202811130101002"))
return {
ok: true,
@@ -848,6 +909,85 @@ describe("sports data service", () => {
expect(friendly?.startsAt.toISOString()).toBe("2026-11-05T20:00:00.000Z");
expect(friendly?.venue).toBe("Pavilhão Municipal Fernando Lima");
expect(friendly?.city).toBe("Caminha");
const w17 = await ctx.db.sportsFixture.findFirst({
where: { externalId: "202712010502014" },
include: { homeTeam: true, awayTeam: true, competition: true },
});
expect(w17?.competition.name).toBe("W17 EHF EURO");
expect(w17?.competition.gender).toBe("F");
expect(w17?.round).toBe("Qualificação C");
expect(w17?.venue).toBe("Pavilhão da Associação Atlética de Águas Santas");
expect(w17?.city).toBe("Àguas Santas");
expect(w17?.homeTeam.externalId).toBe("W17");
expect(w17?.homeTeam.name).toBe("Portugal");
expect(w17?.awayTeam.externalId).toBe("ITA-W17");
expect(w17?.awayTeam.name).toBe("Itália");
expect(await ctx.db.sportsPlayer.findFirstOrThrow({ where: { teamId: w17!.homeTeam.id, name: "Maria Costa" } })).toMatchObject({
number: "7",
photoUrl: "https://res.ehf.eu/photo/w17-costa.jpg",
});
expect(await ctx.db.sportsPlayer.findFirstOrThrow({ where: { teamId: w17!.awayTeam.id, name: "Giulia Rossi" } })).toMatchObject({
number: "9",
externalId: "ehf-w17-rossi",
});
const { org } = await seedUser(ctx.db, "[email protected]", { org: "w17dup", role: "OWNER" });
const friendlyComp = await ctx.db.sportsCompetition.create({
data: { provider: "FPA", externalId: "W17-AMIG", sport: "andebol", name: "Sub-17 feminina", gender: "F", season: w17!.season },
});
const duplicate = await ctx.db.sportsFixture.create({
data: {
competitionId: friendlyComp.id,
externalId: "w17-por-ita-20261127",
season: w17!.season,
homeTeamId: w17!.homeTeam.id,
awayTeamId: w17!.awayTeam.id,
startsAt: w17!.startsAt,
timeKnown: true,
round: "Particular",
},
});
const opened = await ctx.db.event.create({
data: {
organizationId: org!.id,
home: "Portugal",
away: "Itália",
startsAt: w17!.startsAt,
ingestFrom: w17!.startsAt,
ingestUntil: w17!.startsAt,
iptcTemplate: {},
fixtureId: duplicate.id,
},
});
await sports.syncNationalCallUps(kick);
const paired = await ctx.db.sportsFixture.findMany({
where: { homeTeamId: w17!.homeTeam.id, awayTeamId: w17!.awayTeam.id, startsAt: w17!.startsAt },
});
expect(paired.map((row) => row.externalId)).toEqual(["202712010502014"]);
expect((await ctx.db.event.findUniqueOrThrow({ where: { id: opened.id } })).fixtureId).toBe(w17!.id);
await ctx.db.sportsFixture.delete({ where: { id: w17!.id } });
const campOnly = await ctx.db.sportsFixture.create({
data: {
competitionId: friendlyComp.id,
externalId: "w17-por-ita-20261127",
season: w17!.season,
homeTeamId: w17!.homeTeam.id,
awayTeamId: w17!.awayTeam.id,
startsAt: w17!.startsAt,
timeKnown: true,
round: "Particular",
},
});
await ctx.db.event.update({ where: { id: opened.id }, data: { fixtureId: campOnly.id } });
await sports.syncNationalCallUps(kick);
const adopted = await ctx.db.sportsFixture.findMany({
where: { homeTeamId: w17!.homeTeam.id, awayTeamId: w17!.awayTeam.id, startsAt: w17!.startsAt },
include: { competition: true },
});
expect(adopted).toHaveLength(1);
expect(adopted[0]).toMatchObject({ id: campOnly.id, externalId: "202712010502014", competition: { name: "W17 EHF EURO" } });
expect((await ctx.db.event.findUniqueOrThrow({ where: { id: opened.id } })).fixtureId).toBe(campOnly.id);
});
});
+57 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { AutopilotSettings } from "@photoreport/contracts";
import { exportTargets, galleryReceivers, picksNeeded } from "../src/autopilot/targets.js";
import { assignBurstExports, exportSlots, exportTargets, galleryReceivers, picksNeeded, type BurstExportSlot } from "../src/autopilot/targets.js";
const a = "11111111-1111-4111-8111-111111111111";
const b = "22222222-2222-4222-8222-222222222222";
@@ -17,6 +17,62 @@ describe("exportTargets", () => {
});
});
function slot(targetId: string, extra: Partial<BurstExportSlot> = {}): BurstExportSlot {
return {
targetId,
alsoTargetIds: [],
count: null,
originals: false,
sent: 0,
...extra,
};
}
describe("exportSlots", () => {
it("keeps a copy on the same frame and out of the pick list", () => {
const settings = AutopilotSettings.parse({
enabled: true,
deliverExports: [
{ targetId: a, alsoTargetIds: [b], count: 50, originals: false },
{ targetId: c, alsoTargetIds: [], count: null, originals: true },
],
});
expect(exportSlots(settings)).toEqual([
{ targetId: a, alsoTargetIds: [b], count: 50, originals: false },
{ targetId: c, alsoTargetIds: [], count: null, originals: true },
]);
});
});
describe("assignBurstExports", () => {
const three = [slot(a), slot(b), slot(c)];
it("gives one different frame to each destination when the burst has enough", () => {
expect(assignBurstExports(three, 0, 3).map((row) => row.targetId)).toEqual([a, b, c]);
});
it("rotates the only frame so a short burst does not always feed the first destination", () => {
expect(assignBurstExports(three, 0, 1).map((row) => row.targetId)).toEqual([a]);
expect(assignBurstExports(three, 1, 1).map((row) => row.targetId)).toEqual([b]);
expect(assignBurstExports(three, 2, 1).map((row) => row.targetId)).toEqual([c]);
expect(assignBurstExports(three, 3, 1).map((row) => row.targetId)).toEqual([a]);
});
it("stops a destination that already has its total and keeps filling the others", () => {
const slots = [slot(a, { count: 20, sent: 20 }), slot(b, { count: 80, sent: 20 }), slot(c)];
expect(assignBurstExports(slots, 0, 2).map((row) => row.targetId)).toEqual([b, c]);
});
it("sends the same frame's copy alongside, without taking a second frame", () => {
const slots = [slot(a, { alsoTargetIds: [b] }), slot(c)];
const plan = assignBurstExports(slots, 0, 2);
expect(plan).toEqual([
{ targetId: a, alsoTargetIds: [b], originals: false, rank: 0 },
{ targetId: c, alsoTargetIds: [], originals: false, rank: 1 },
]);
});
});
describe("picksNeeded", () => {
it("matches the number of exports when set", () => {
const s = AutopilotSettings.parse({ enabled: true, deliverTargetIds: [a, b, c] });
+1 -1
View File
@@ -3,7 +3,7 @@ import { defineConfig } from "vitest/config";
/** Pure tests. The default config migrates a database, which these do not need. */
export default defineConfig({
test: {
include: ["src/**/*.test.ts", "test/compose.test.ts"],
include: ["src/**/*.test.ts", "test/capacity.test.ts", "test/compose.test.ts"],
fileParallelism: false,
},
});
+9 -1
View File
@@ -578,6 +578,14 @@ export const t = {
noPicks: "Não escolher",
minLongEdge: "Resolução mínima do recorte",
deliver: "Enviar as escolhidas para",
exportAdd: "Acrescentar envio",
exportRemove: "Tirar",
exportAlso: "A mesma foto também para",
exportCount: "Total neste jogo",
exportOriginals: "Originais, sem edição",
exportHelp:
"Há tantos escolhidos por sequência quantos os envios: uma foto diferente para cada um. Se a sequência não chegar para todos, a que houver vai rodando, para no fim cada destino chegar ao total que pediste. Vazio nesse total: uma por sequência, até ao fim. «Também para» manda a mesma foto aos dois (Cofina Direto e Cofina Arquivo) e não conta como outra escolha. Originais sai o ficheiro da câmara, sem o recorte nem o tom.",
exportPlayers: "Um destino com «Esperar pelas caras» sai com os jogadores no ficheiro. Se os nomes chegarem depois, o ficheiro volta a ser enviado.",
noDelivery: "Não enviar",
selection: "O que enviar",
selectionBursts: "As escolhidas de cada sequência",
@@ -713,7 +721,7 @@ export const t = {
startsAt: "Início",
photographers: "Fotógrafos",
pickMatch: "Escolher o jogo",
pickMatchHelp: "Jogos da Liga Portugal, FPF, FPA, EHF Euro Cup (seleções) e UEFA (Champions, Liga Europa, Conference, Champions feminina e de futsal) dos próximos dias (ao pesquisar, também os dos últimos 10 dias). Preenche o evento e junta os plantéis às pessoas. As fotos de 2 h antes até 4 h depois do apito vão para este evento.",
pickMatchHelp: "Jogos da Liga Portugal, FPF, FPA, EHF Euro Cup (seleções), W17 EHF EURO (qualificação de sub-17 feminina) e UEFA (Champions, Liga Europa, Conference, Champions feminina e de futsal) dos próximos dias (ao pesquisar, também os dos últimos 10 dias). Preenche o evento e junta os plantéis às pessoas. As fotos de 2 h antes até 4 h depois do apito vão para este evento.",
squadFromMatch: "Usar o plantel de um jogo",
squadFromMatchHelp: "Treino ou sessão: fica com os jogadores desse jogo, sem ser o jogo (legenda e hora são as tuas).",
searchMatch: "Equipa, competição ou pavilhão",
+170 -15
View File
@@ -4,6 +4,153 @@ import { useEffect, useState } from "react";
import { t } from "../i18n.js";
import { ZerozeroGamePicker } from "./ZerozeroGame.js";
type ExportRow = AutopilotSettings["deliverExports"][number];
/** As many burst exports as the photographer lists. One frame each; a copy shares that frame. */
function BurstExports(props: {
settings: AutopilotSettings;
targets: DeliveryTarget[];
canEdit: boolean;
onChange: (next: AutopilotSettings) => void;
}) {
const L = t.autopilot;
const rows = props.settings.deliverExports;
const used = new Set<string>();
for (const row of rows) {
used.add(row.targetId);
for (const id of row.alsoTargetIds) used.add(id);
}
const commit = (nextRows: ExportRow[]) => {
const primaries: string[] = [];
for (const row of nextRows) primaries.push(row.targetId);
props.onChange({
...props.settings,
deliverExports: nextRows,
deliverTargetIds: primaries,
deliverTargetId: primaries[0] ?? null,
});
};
const update = (index: number, row: ExportRow) => {
const next = rows.map((item) => ({ ...item, alsoTargetIds: [...item.alsoTargetIds] }));
next[index] = row;
commit(next);
};
const add = () => {
let free = "";
for (const target of props.targets) {
if (!used.has(target.id)) {
free = target.id;
break;
}
}
if (!free) return;
commit([...rows, { targetId: free, alsoTargetIds: [], count: null, originals: false }]);
};
const remove = (index: number) => {
commit(rows.filter((_, i) => i !== index));
};
return (
<div className="space-y-2">
<p className="text-faint">{L.exportHelp}</p>
{rows.map((row, index) => {
const also = row.alsoTargetIds[0] ?? "";
return (
<div key={`${row.targetId}-${index}`} className="space-y-1 border border-line p-1.5">
<label className="flex items-center justify-between gap-2">
<span>{index + 1}</span>
<span className="flex items-center gap-1">
<select
className="h-6 max-w-[160px] border border-black bg-cell px-1"
disabled={!props.canEdit}
value={row.targetId}
onChange={(e) => {
const value = e.target.value;
if (!value) return;
const alsoIds = row.alsoTargetIds.filter((id) => id !== value);
update(index, { ...row, targetId: value, alsoTargetIds: alsoIds });
}}
>
{props.targets.map((target) => {
if (used.has(target.id) && target.id !== row.targetId && target.id !== also) return null;
return (
<option key={target.id} value={target.id}>
{target.name}
</option>
);
})}
</select>
<button type="button" className="text-faint hover:text-ink" disabled={!props.canEdit} onClick={() => remove(index)}>
{L.exportRemove}
</button>
</span>
</label>
<label className="flex items-center justify-between gap-2">
<span className="text-faint">{L.exportAlso}</span>
<select
className="h-6 max-w-[160px] border border-black bg-cell px-1"
disabled={!props.canEdit}
value={also}
onChange={(e) => {
const value = e.target.value;
if (!value) update(index, { ...row, alsoTargetIds: [] });
else update(index, { ...row, alsoTargetIds: [value] });
}}
>
<option value="">{L.noDelivery}</option>
{props.targets.map((target) => {
if (target.id === row.targetId) return null;
if (used.has(target.id) && target.id !== also) return null;
return (
<option key={target.id} value={target.id}>
{target.name}
</option>
);
})}
</select>
</label>
<label className="flex items-center justify-between gap-2">
<span className="text-faint">{L.exportCount}</span>
<input
type="number"
min={1}
max={2000}
disabled={!props.canEdit}
value={row.count ?? ""}
placeholder="—"
onChange={(e) => {
const raw = e.target.value.trim();
let count: number | null = null;
if (raw) count = Math.max(1, Math.min(2000, Number(raw) || 1));
update(index, { ...row, count });
}}
className="h-6 w-20 border border-black bg-[#161617] px-1 text-ink"
/>
</label>
<label className="flex items-center gap-2">
<input
type="checkbox"
disabled={!props.canEdit}
checked={row.originals}
onChange={(e) => update(index, { ...row, originals: e.target.checked })}
/>
<span>{L.exportOriginals}</span>
</label>
</div>
);
})}
<button type="button" className="pr-quiet" disabled={!props.canEdit || used.size >= props.targets.length} onClick={add}>
{L.exportAdd}
</button>
<p className="text-faint">{L.exportPlayers}</p>
</div>
);
}
/**
* Autopilot for the open event (docs/photo-editing-rules.md): photos arriving by FTP or the desktop app's ingest
* are edited (tone, level, crop) and the best frames of each burst picked, and optionally delivered.
@@ -30,9 +177,12 @@ export function AutopilotButton(props: {
}, [props.autopilotAsk, props.event.id, props.onAsked]);
const save = async (next: AutopilotSettings) => {
// Keep deliverTargetIds in sync with the two legacy slots (N exports = ordered list).
const ids = [next.deliverTargetId, next.restTargetId].filter((x): x is string => !!x);
const synced = { ...next, deliverTargetIds: ids.length ? ids : next.deliverTargetIds ?? [] };
// Burst groups already name every destination. The two legacy slots must not wipe that list.
let synced = next;
if (next.selection !== "bursts" || next.deliverExports.length === 0) {
const ids = [next.deliverTargetId, next.restTargetId].filter((x): x is string => !!x);
if (ids.length > 0) synced = { ...next, deliverTargetIds: ids };
}
setS(synced);
setState("saving");
try {
@@ -59,7 +209,7 @@ export function AutopilotButton(props: {
{L.button}
</button>
{open && (
<div className="absolute right-0 top-7 z-30 w-[360px] space-y-3 border border-black bg-panel p-3 text-[12px] shadow-xl" role="dialog" aria-label={L.button}>
<div className="absolute right-0 top-7 z-30 w-[420px] space-y-3 border border-black bg-panel p-3 text-[12px] shadow-xl" role="dialog" aria-label={L.button}>
<label className="flex items-center justify-between gap-2">
<span className="font-semibold uppercase tracking-wide text-ink">{L.button}</span>
<input type="checkbox" disabled={!props.canEdit} checked={s.enabled} onChange={(e) => void save({ ...s, enabled: e.target.checked })} aria-label={L.enable} />
@@ -110,17 +260,22 @@ export function AutopilotButton(props: {
))}
</select>
</label>
<label className="flex items-center justify-between gap-2">
<span>{L.deliver}</span>
<select className="h-6 max-w-[180px] border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.deliverTargetId ?? ""} onChange={(e) => void save({ ...s, deliverTargetId: e.target.value || null })}>
<option value="">{L.noDelivery}</option>
{props.targets.map((x) => (
<option key={x.id} value={x.id}>
{x.name}
</option>
))}
</select>
</label>
{s.selection === "bursts" && (
<BurstExports settings={s} targets={props.targets} canEdit={props.canEdit && s.enabled} onChange={(next) => void save(next)} />
)}
{s.selection !== "bursts" && (
<label className="flex items-center justify-between gap-2">
<span>{L.deliver}</span>
<select className="h-6 max-w-[180px] border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.deliverTargetId ?? ""} onChange={(e) => void save({ ...s, deliverTargetId: e.target.value || null })}>
<option value="">{L.noDelivery}</option>
{props.targets.map((x) => (
<option key={x.id} value={x.id}>
{x.name}
</option>
))}
</select>
</label>
)}
<label className="flex items-center justify-between gap-2">
<span>{L.selection}</span>
<select className="h-6 max-w-[180px] border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.selection} onChange={(e) => void save({ ...s, selection: e.target.value as AutopilotSettings["selection"] })}>
+7
View File
@@ -139,6 +139,13 @@ const PRESETS = {
longEdge: 4000,
...DESTINATION_EXAMPLES.fpaM19,
},
fpaW17: {
label: "Cloud W17",
kind: "NEXTCLOUD",
baseUrl: "https://cloud.photoreport.pt",
longEdge: 4000,
...DESTINATION_EXAMPLES.fpaW17,
},
liga: {
label: "Estrutura Liga",
kind: "NEXTCLOUD",
+12 -1
View File
@@ -14,6 +14,17 @@ import { kv } from "./kv.js";
import { localPhotos } from "./local.js";
import { localId, offlineQueue } from "./queue.js";
/** One pick per export group, otherwise the event's own number. Matches the server. */
function picksFor(settings: AutopilotSettings): number {
if (settings.deliverExports.length > 0) {
return Math.min(10, settings.deliverExports.length);
}
if (settings.deliverTargetIds.length > 0) {
return Math.min(5, settings.deliverTargetIds.length);
}
return settings.picksPerBurst;
}
/** Same settle window as the server: a burst is decided once no new frame has arrived for this long. */
const BURST_SETTLE_MS = 15_000;
const PENDING_KEY = (orgId: string, eventId: string) => `autopilot:pending:${orgId}:${eventId}`;
@@ -98,7 +109,7 @@ export async function planLocalAutopilot(args: {
const pending = await loadPending(args.orgId, args.event.id);
const next = [...pending.filter((f) => f.sha256 !== frame.sha256), frame];
await savePending(args.orgId, args.event.id, next);
scheduleSettle(args.orgId, args.event.id, settings.picksPerBurst, settings.burstGapSec * 1000);
scheduleSettle(args.orgId, args.event.id, picksFor(settings), settings.burstGapSec * 1000);
}
const timers = new Map<string, ReturnType<typeof setTimeout>>();
+1 -1
View File
@@ -136,7 +136,7 @@ export function DeliveryPage() {
</td>
<td className="border-b border-line px-3 py-1.5 text-right">
{i.status === "FAILED" && (
<button className="pr-quiet" onClick={() => void api.retryDelivery(orgId, i.id).then(load)}>
<button className="pr-quiet" onClick={() => void api.retryDelivery(orgId, i.id).then(load, () => load())}>
{t.retry}
</button>
)}
+8 -2
View File
@@ -330,14 +330,20 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati
sides (`M19`, `ESP-M19`), and merges the Men's EHF EURO Cup match sheets from `www.eurohandball.com`
(`GetStandingMatches` / `GetMatchDetails` — same shape as club sheets, with shirt numbers and `res.ehf.eu`
headshots for the nominated 16). Portuguese CIPAs from the FPA call-up stay as `externalId` when the name
matches; photo/number come from the sheet. Youth camps (sub-17, sub-19, sub-20, men or women) come from
matches; photo/number come from the sheet. The same pass reads the Women's U17 EHF EURO qualification
(`W17-EURO`, content `139009`: Portugal–Italy `202712010502014`, 27 Nov 2026 19:00 in Águas Santas, and the
rest of that tournament). Portugal is team `W17`; every other country is `<code>-W17` (Italy is `ITA-W17`). The nominated sheet
fills numbers and headshots once the EHF publishes it. The FPA camp lists that same match as a friendly
(`Sub-17 feminina`): it is folded into `W17-EURO`, and an event already opened on it stays on the one fixture.
Youth camps (sub-17, sub-19, sub-20, men or women) come from
recent posts on `portal.fpa.pt`: the call-up PDF (CIPA, no shirt number from the list order) and the
"Jogos Particulares" calendar. A sheet with a real squad replaces that age group; a post the site does not
return leaves the plantel we already have. The November 2026 M19 list and the Spain name list are only the
seed when that team is still empty. Those friendlies are fixtures (`m19-por-esp-20261105`,
`m19-esp-por-20261107`) so picking the game links that plantel, not the senior one. A folder or title that
says sub-19 / M19 (not "Encontro Nacional") is that age group. Cloud delivery for these games is the
destination "Cloud M19" (`/FPA/Fotos/{season}/Seleções Nacionais/M19/…`), created from the organisation's
destination "Cloud M19" (`/FPA/Fotos/{season}/Seleções Nacionais/M19/…`) and "Cloud W17"
(`…/Seleções Nacionais/W17/…`), each created from the organisation's
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`.
+22
View File
@@ -61,6 +61,22 @@ export const AutopilotSettings = z.object({
* legacy pair below. Empty: use `deliverTargetId` / `restTargetId` when set.
*/
deliverTargetIds: z.array(z.string().uuid()).max(10).default([]),
/**
* One frame of each burst per row. `alsoTargetIds` receive that same frame (Cofina Direto and Arquivo) and
* are not a separate pick. `count` is how many photos that destination takes over the match (null: no cap).
* `originals`: the camera file, without the develop render. Empty: `deliverTargetIds`, one destination each.
*/
deliverExports: z
.array(
z.object({
targetId: z.string().uuid(),
alsoTargetIds: z.array(z.string().uuid()).max(4).default([]),
count: z.number().int().min(1).max(2000).nullable().default(null),
originals: z.boolean().default(false),
}),
)
.max(10)
.default([]),
/** Legacy first export (null: don't). Kept for older clients; folded into `deliverTargetIds` when that is empty. */
deliverTargetId: z.string().uuid().nullable().default(null),
/**
@@ -88,6 +104,12 @@ export const AutopilotSettings = z.object({
* to this one when `deliverTargetIds` is empty. Prefer `deliverTargetIds`.
*/
restTargetId: z.string().uuid().nullable().default(null),
/**
* With galleries and `restTargetId`: leftover picks go to the rest destination until this many minutes
* before kick-off. After that they still go, unless the frame is clearly only the away team. Omitted:
* galleries do not send leftovers (an older app leaves this out; the stored value is kept).
*/
restHomeFromMin: z.number().int().min(0).max(180).nullable().optional(),
});
export type AutopilotSettings = z.infer<typeof AutopilotSettings>;
+15
View File
@@ -238,6 +238,21 @@ describe("delivery paths", () => {
expect(renderFileName(DESTINATION_EXAMPLES.fpaM19.fileName, { ...m19, n: 3 }, "R1_0003.JPG")).toBe("PS_POR x ESP_3.jpg");
});
it("matches the women's under-17 cloud folder", () => {
const w17 = buildVars({
home: "Portugal",
away: "Itália",
homeShort: "POR",
awayShort: "ITA",
competition: "W17 EHF EURO",
startsAt: new Date("2026-11-27T19:00:00Z"),
});
expect(renderFolder(DESTINATION_EXAMPLES.fpaW17.folder, w17)).toBe(
"/FPA/Fotos/2026_2027/Seleções Nacionais/W17/20261127 - POR x ITA/",
);
expect(renderFileName(DESTINATION_EXAMPLES.fpaW17.fileName, { ...w17, n: 1 }, "R1_0001.JPG")).toBe("PS_POR x ITA_1.jpg");
});
it("matches the Liga folder and keeps the camera name", () => {
const liga = buildVars({ home: "Casa Pia", away: "Sporting", round: 1, matchNumber: 1, startsAt: new Date("2025-08-09T18:00:00Z") });
expect(renderFolder(DESTINATION_EXAMPLES.liga.folder, liga)).toBe("/LPBetclic 25-26/Jornada 1/1. Casa Pia x Sporting/");
+5
View File
@@ -82,6 +82,11 @@ export const DESTINATION_EXAMPLES = {
folder: "/FPA/Fotos/{season}/Seleções Nacionais/M19/{dateCompact} - {homeShort} x {awayShort}/",
fileName: "PS_{homeShort} x {awayShort}_{n}.jpg",
},
/** Women's under-17. Same account as the club cloud; its own folder under Seleções Nacionais. */
fpaW17: {
folder: "/FPA/Fotos/{season}/Seleções Nacionais/W17/{dateCompact} - {homeShort} x {awayShort}/",
fileName: "PS_{homeShort} x {awayShort}_{n}.jpg",
},
liga: {
folder: "/LPBetclic {seasonShort}/Jornada {round}/{matchNumber}. {home} x {away}/",
fileName: "{originalName}",