Compare commits

..
Author SHA1 Message Date
spark 68588e0296 Merge main and read a slash between two club names as two teams.
ci / rust (pull_request) Successful in 12m19s
ci / typescript (pull_request) Successful in 15m22s
A folder such as "ALMADA AC / EXT. GIL EANES" was stored as one team in every archive. A slash with spaces is the two sides; a season written 2025/2026 stays a directory.
2026-10-19 08:54:26 +01:00
jos-alves c61d371819 Stop a not-yet-published Liga round from reaching the error hub as a warning
ci / rust (push) Successful in 4m1s
ci / typescript (push) Successful in 7m33s
Liga 400s competition/round/{n}/nominations until it publishes a round's referee
nominations, days before the match (providers.ts doc comment). syncEventSquadsNow
caught that but logged it at warn, and the pino->error-hub hook forwards any warn
carrying an `err` — so routine early reads of a round show up in the error hub as
warnings (ERRCLUSTER 9d79efd242be).

Give `get()` a typed ProviderHttpError carrying the HTTP status, and have the Liga
referees catch distinguish a 400 (not published yet, read again on the next refresh)
from a real failure: info instead of warn for the former, keeping it out of the hub.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31543
Paperclip-Run: 5f8f2566-36ea-4f72-9d15-cf0a107111c2
2026-10-19 06:01:31 +01:00
jos-alves 707420a579 Fix a race where matching a gallery onto an event could hit photos_event_id_fkey
ci / rust (push) Successful in 3m56s
ci / typescript (push) Successful in 7m28s
ArchiveService.dropIfEmpty() read an event's photo/folder/gallery/delivery
counts, then deleted it in a second, separate statement if they were all
zero. Between those two statements, another setFolderEvent() racing on the
same event (the normal concurrent paths: a scheduled rematch sweep and a
manual re-match, or two folders moving in the same sweep) could land a fresh
cloudFolder on it; dropIfEmpty's stale read never saw that and deleted the
event anyway, cascading SetNull back onto the folder that had just landed.
The other call then tried to move that folder's photos onto the
now-deleted event and hit `photos_event_id_fkey` (BIT-31531, same cluster
as the ERRSIG in the issue).

dropIfEmpty() now does the emptiness check and the delete as one
`deleteMany` with the relation-count conditions in its own WHERE, so
Postgres re-evaluates "is it still empty" against whatever just committed
instead of against a stale read. Added a regression test that holds the
delete open with a query extension while a second match lands on the
event, proving it survives instead of being dropped (confirmed the test
fails against the old read-then-delete code before restoring the fix).

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31531
Paperclip-Run: c48a8976-d063-4134-b393-fff6a124f0ce
2026-10-19 05:36:57 +01:00
jos-alves 92ceeee2fe Budget one extra API instance during a deploy's rolling reload
ci / rust (push) Successful in 3m52s
ci / typescript (push) Successful in 7m15s
dbConnectionBudget() sized the API cluster's connections at exactly
apiInstances (2), but pm2 startOrReload on the clustered photoreport-api
app brings a new instance online and confirms it healthy before stopping
an old one, so for a few seconds during every deploy there are
apiInstances + 1 processes alive, each with its own Prisma pool and
realtime connections. That transient extra instance (13 connections with
default pool/realtime sizes) was enough to push the cluster over the
budget BIT-31533 set and into Postgres' superuser_reserved_connections,
surfacing as the same "too many database connections ... reserved for
roles with the SUPERUSER attribute" error from the worker's ArchiveService
(BIT-31550, same cluster as BIT-31519/BIT-31533).

dbConnectionBudget() now takes apiReloadOverlap (default 1) and folds it
into the API cluster term so the worker's own pool is sized to leave room
for the overlap. Default worker budget on a 100-max_connections host drops
from 60 to 47.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31550
Paperclip-Run: 71ac411e-1cce-46e6-b745-7f380228cf79
2026-10-19 05:16:40 +01:00
jos-alves 81bd777e87 Stop a transient Nextcloud blip reading an archive original from reaching the error hub
ci / rust (push) Successful in 3m48s
ci / typescript (push) Successful in 7m9s
BIT-31513 already downgraded this exact self-healing retry to log.info inside
ArchiveService.index(), but DeliveryService.process() hits the same
CloudClient.download() through downloadOriginal() and unconditionally logged the
catch at warn with the raw err, so a 503/423 blip still fingerprinted into
errors.bitreport.pt and reopened the Error Loop (BIT-31522, same cluster pattern
as BIT-31491/BIT-31498/BIT-31505/BIT-31513). The retry behaviour was already
correct (the item is requeued with a backoff); only the log level was wrong.

Use the isTransient() check already imported in this file (and used at the two
other catch sites) to log at info instead of warn when the download blip is
transient, keeping warn for a real failure. Added a regression test mirroring
BIT-31513's.

Paperclip-Issue: BIT-31522
Paperclip-Run: fa16b650-eeb3-4067-81ff-879c78e4c0c1
2026-10-19 04:47:35 +01:00
jos-alves 0d6a9e27e0 Show a retry screen instead of a hard crash when a page render fails
ci / rust (push) Successful in 7m16s
ci / typescript (push) Successful in 10m59s
The site had no error.tsx or global-error.tsx anywhere, so any transient
failure in a Server Component (an API hiccup, a DB blip like the one fixed
in d6a7edd) took down the whole page with Next's generic "omitted in
production" message and no way to recover short of reloading. The real
error and stack still reach errors.bitreport.pt via instrumentation.ts's
onRequestError, which fires independently of these boundaries.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31537
Paperclip-Run: a91a9196-6082-4408-a3b1-9b3711e28f7b
2026-10-19 04:24:09 +01:00
spark 1652b6ba3c Merge pull request 'A slow Liga month no longer drops the rest of the season' (#42) from task/liga-sheet-faces into main
ci / rust (push) Successful in 10m31s
ci / typescript (push) Successful in 14m24s
2026-10-19 04:22:13 +01:00
tiago-neves d6a7edda38 Budget realtime connections per API instance and Postgres superuser reserve
ci / rust (push) Successful in 11m46s
ci / typescript (push) Successful in 15m42s
dbConnectionBudget() only subtracted the API's Prisma pool and the worker's
own 1-connection remote broadcaster, so it never counted the 3 connections
each API process opens for realtime (attachRealtime: a 2-connection publish
pool plus a dedicated LISTEN client), nor the connections Postgres reserves
for superuser roles below max_connections -- exactly what "remaining
connection slots are reserved for roles with the SUPERUSER attribute" means.
With 2 API instances that gap was 9 connections, enough for the worker and
API together to run the cluster right up against the ceiling.

dbConnectionBudget() now takes realtimePerInstance and superuserReserved
(new DB_SUPERUSER_RESERVED_CONNECTIONS env var, default 3) and subtracts
both explicitly instead of leaving them to be absorbed by headroom.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31533
Paperclip-Run: fc6639aa-bf73-43f0-b3f6-85835a1f809b
2026-10-19 04:13:14 +01:00
spark 8020574415 Merge pull request 'Keep every Liga season, because the fixture code is reused each year' (#41) from task/liga-sheet-faces into main
ci / rust (push) Successful in 11m56s
ci / typescript (push) Successful in 15m34s
2026-10-19 04:09:39 +01:00
tiago-neves c4c524c58b Stop reporting a self-healing Nextcloud download blip as a warning (BIT-31513)
ci / rust (push) Successful in 11m30s
ci / typescript (push) Successful in 14m59s
CloudClient.download already retries a transient 503/423 (BIT-31491), and ArchiveService.index
already requeues the file with its attempt given back when those retries run out (BIT-31505) —
a free retry, not a real failure. But the catch block still logged it with log.warn({ err, ... }),
and the reporter's pino hook (lib/reporter.ts logHooks) forwards any warn carrying an err to
errors.bitreport.pt. Each blip names a different file, so it fingerprints as a new ERRSIG under the
same ERRCLUSTER (ef937010320d) every time Nextcloud hiccups, reopening the Error Loop for a condition
that already self-heals — this is the third ticket on that cluster (BIT-31491, BIT-31498, BIT-31505).

Downgrade the transient case to log.info, which the reporter never forwards, and keep log.warn for a
real failure (permanent, or burning the attempt budget). Added a test asserting the transient path logs
at info with no warn call, alongside the existing BIT-31505 regression test for the requeue behaviour.

Paperclip-Issue: BIT-31513
Paperclip-Run: 4f183cb4-7ab1-4be3-ad64-f2af9e8d9742
2026-10-19 04:00:42 +01:00
spark 1aaa3857b0 Merge pull request 'Re-read a past Liga season whose calendar is only partly stored' (#40) from task/liga-sheet-faces into main
ci / typescript (push) Successful in 14m38s
ci / rust (push) Successful in 11m25s
2026-10-19 04:00:23 +01:00
spark 5ed0f94e04 Merge pull request 'Keep each Liga game in the season Liga named' (#39) from task/liga-sheet-faces into main
ci / rust (push) Successful in 10m32s
ci / typescript (push) Successful in 14m24s
2026-10-19 03:44:29 +01:00
tiago-neves 5df809eedf Add a regression test for the download-retry path reported by BIT-31505.
ci / rust (push) Successful in 11m46s
ci / typescript (push) Successful in 15m51s
CloudClient.download already retries a transient 503/423 (BIT-31491) and ArchiveService.index
already requeues a file as PENDING with its claimed attempt given back when the retries are
exhausted, instead of failing it outright or burning toward the permanent-failure limit. This
ERRSIG's stack trace runs through exactly that path; the fix is already in main, so this adds
a service-level test (claim -> blip past the retry budget -> requeued -> retried -> DONE) to
keep it covered on its own, the same way cfe9ecc covered the PROPFIND sibling.

Paperclip-Issue: BIT-31505
Paperclip-Run: 0c4396e8-3ed4-4145-821c-0f84468cf755
2026-10-19 03:43:59 +01:00
spark 999ab6d78d Merge pull request 'Liga names from every season, and one face review across games' (#38) from task/liga-sheet-faces into main
ci / rust (push) Successful in 11m10s
ci / typescript (push) Successful in 14m33s
2026-10-19 03:40:56 +01:00
tiago-neves 7b08b78b40 Budget worker DB connections against the APIs cluster, not just one pool
ci / rust (push) Successful in 7m0s
ci / typescript (push) Successful in 10m8s
The worker sized its pool to leave room for only the APIs 10 default pg
connections, but infra/pm2/api.config.cjs runs it as 2 cluster instances
(20 total) and the realtime broadcaster holds one more. On a busy host
the worker and API pools together could reach Postgres default
max_connections, which is why session.findFirst() -- run on every
authenticated request -- was the query that hit "too many clients
already".

dbConnectionBudget() now derives the worker pool cap from the APIs
actual cluster size and pool size, plus headroom for admin/migration
connections, instead of a hardcoded 80. Both are configurable
(API_DB_POOL_SIZE, API_INSTANCES, DB_MAX_CONNECTIONS) for installs that
tune Postgres or PM2 differently.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31519
Paperclip-Run: f5442a27-6b3b-4c5a-a1ab-8b2b4177be7c
2026-10-19 03:27:08 +01:00
spark a25d65c2c3 Merge pull request 'Keep Liga fixtures in the season Liga named' (#37) from task/liga-sheet-faces into main
ci / rust (push) Successful in 10m42s
ci / typescript (push) Successful in 15m22s
2026-10-19 03:18:23 +01:00
tiago-neves cfe9ecc59f Add a PROPFIND-specific regression test for the Nextcloud retry (BIT-31498).
ci / rust (push) Successful in 8m27s
ci / typescript (push) Successful in 14m37s
CloudClient.list() already retries transient statuses via the shared
call() method (fixed for downloads in BIT-31491), so the 503 reported here
is already covered by that retry logic. This test exercises the PROPFIND
path directly so the fix for this ERRSIG stays covered on its own.

Paperclip-Issue: BIT-31498
Paperclip-Run: 0564ac90-43c8-430b-9f93-b580f6775efa
2026-10-19 03:12:20 +01:00
spark 9d1bf4849b Merge pull request 'Index Liga bwin galleries and name faces from the match sheet' (#36) from task/liga-sheet-faces into main
ci / rust (push) Successful in 10m3s
ci / typescript (push) Successful in 14m32s
Index Liga bwin galleries and name faces from the match sheet
2026-10-19 03:04:51 +01:00
sparkandClaude Opus 5.5 5d286299f8 Archive teams: match folder names with prepared teams (6x faster), and say "preparing" instead of timing out.
Each known team's folded names, words and code are worked out once (teamMatcher, same answers as
canonicalTeam). The directory waits 10 s at most; meanwhile it answers { preparing: true } and the page asks
again, so the proxy never gives a 500.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1
2026-10-19 00:45:00 +00:00
19 changed files with 458 additions and 32 deletions

No files matched your search

+7
View File
@@ -3,6 +3,13 @@ PORT=3000
LOG_LEVEL=info
APP_VERSION=dev
DATABASE_URL=postgresql://photoreport:CHANGE_ME@pr-db:5432/photoreport
# The worker sizes its own pool from these three so the total stays under Postgres' max_connections. Leave unset
# unless this install's PM2 api instances, API pool size, or Postgres max_connections differ from the defaults
# (2, 10, 100).
# API_DB_POOL_SIZE=
# API_INSTANCES=
# DB_MAX_CONNECTIONS=
# DB_SUPERUSER_RESERVED_CONNECTIONS=
# At least 32 random characters, e.g. `openssl rand -base64 48`
JWT_SECRET=
ACCESS_TOKEN_TTL_SEC=900
+75 -5
View File
@@ -1,4 +1,4 @@
import { sameTeam } from "../delivery/zerozero.js";
import { sameTeam, sameWords, words } from "../delivery/zerozero.js";
import { officialSigla } from "../sports/fpa-siglas.js";
/**
@@ -55,15 +55,32 @@ function seasonIn(name: string): string | null {
return m ? toSeason(m[1]!, m[2]!) : null;
}
/** "SCP x ABC", "Sporting CP vs SC Braga", "A - B" (only after a date). */
/**
* "ALMADA AC / EXT. GIL EANES": a slash between two names, in any archive. A slash with no letters on a side
* ("2025/2026", "26/27") is a season, not two teams. The slash may be the ascii one or a lookalike the cloud kept
* in a folder name.
*/
export function slashSides(name: string): { home: string; away: string } | null {
const m = /^(.+?[A-Za-zÀ-ÿ].*?)\s+[//∕⁄]\s+(.+?[A-Za-zÀ-ÿ].+)$/.exec(name.trim());
if (!m) return null;
const side = (s: string) => s.replace(/\s+/g, " ").trim();
const home = side(m[1]!);
const away = side(m[2]!);
if (!/[A-Za-zÀ-ÿ]{2}/.test(home) || !/[A-Za-zÀ-ÿ]{2}/.test(away)) return null;
return { home, away };
}
/** "SCP x ABC", "Sporting CP vs SC Braga", "A - B" (only after a date), "ALMADA AC / EXT. GIL EANES". */
function teamsIn(name: string, dashOk = false): { home: string; away: string } | null {
// "A x B", "A vs B", "A va B" (a slip for vs); "A - B" only after a date or a game's number, or two codes
// ("MAD - SIR"): "Festa do Andebol 2025 - Externo" is not a game.
// ("MAD - SIR"): "Festa do Andebol 2025 - Externo" is not a game. "A / B" is two teams in every archive.
const dash = /^(.+?)\s+[-–]\s+(.+)$/.exec(name.trim());
const codes = dash && /^[A-Z]{2,6}$/.test(dash[1]!.trim()) && /^[A-Z]{2,6}$/.test(dash[2]!.trim());
const slash = slashSides(name);
const m =
/^(.+?)\s+(?:x|vs\.?|va|v)\s+(.+)$/i.exec(name.trim()) ??
(dashOk || codes ? dash : null) ??
(slash ? { 1: slash.home, 2: slash.away } : null) ??
// "POR_FRA", "PTxES": two codes. "CPACxRAFC", "1.GVFCxPSC": the Liga's old folders glue the siglas.
/^([A-Z]{2,3})(?:_|\s*x\s*)([A-Z]{2,3})$/.exec(name.trim()) ??
/^([A-Za-z]{2,6})x([A-Za-z]{2,6})$/.exec(name.trim());
@@ -79,6 +96,13 @@ function teamsIn(name: string, dashOk = false): { home: string; away: string } |
return home && away ? { home, away } : null;
}
/** A stored side that is really two clubs ("ALMADA AC / EXT. GIL EANES"): both names, for the teams directory. */
export function directorySides(name: string): string[] {
if (!slashSides(name)) return [name];
const teams = teamsIn(name, true);
return teams ? [teams.home, teams.away] : [name];
}
const foldName = (s: string) =>
s
.normalize("NFD")
@@ -166,8 +190,20 @@ export interface FolderPlace {
* Where a gallery folder sits: the occasion it belongs to (a game's halves and warm-up are the game; an athlete's
* folder in a photo session is the session, with that athlete named), and a name for it.
*/
/**
* Path segments. A slash with spaces on both sides is how a folder names two clubs ("ALMADA AC / EXT. GIL EANES"),
* not another directory. A slash without spaces stays a directory ("2025/2026", "/FPA/Fotos").
*/
export function pathParts(path: string): string[] {
const glued = path.replace(/([^\s/])\s+\/\s+([^\s/])/g, "$1\u0001$2");
return glued
.split("/")
.filter(Boolean)
.map((part) => part.replaceAll("\u0001", " / "));
}
export function describeFolder(path: string): FolderPlace {
const parts = path.split("/").filter(Boolean);
const parts = pathParts(path);
let section: string | null = null;
let people: FolderPerson[] = [];
// At most three levels up ("Torneio/_TEAM PORTUGAL_/PHOTOS MATCH/POR_FRA/M4 - ICONSPORT" stops at the game).
@@ -202,7 +238,7 @@ export function describeFolder(path: string): FolderPlace {
export function parseFolder(path: string): FolderGame | null {
// A game's photos may sit one or two levels down (a folder per photographer, "Selecionadas", the halves): the
// game is the nearest folder above whose name is one.
const parts = describeFolder(path).occasion.split("/").filter(Boolean);
const parts = pathParts(describeFolder(path).occasion);
for (let up = 0; up <= 2 && parts.length - up > 0; up++) {
const game = parseGameFolder(parts.slice(0, parts.length - up));
if (game) return game;
@@ -445,6 +481,40 @@ export function canonicalTeam(name: string, teams: readonly { name: string; abbr
return fits.length === 1 ? fits[0]!.name : label;
}
/**
* `canonicalTeam` for many names against the same teams: each team's folded names, words and code are worked out
* once, not once per name (thousands of folder names times every Liga team took minutes).
*/
export function teamMatcher(teams: readonly { name: string; abbreviation: string | null; slug: string }[]): (name: string) => string {
const prepared = teams.map((t) => {
const sigla = officialSigla(t.name);
return { t, variant: isVariantSide(t.name), abbr: fold(t.abbreviation ?? ""), slug: fold(t.slug), name: fold(t.name), words: words(t.name), sigla: sigla ? fold(sigla) : "" };
});
return (raw: string) => {
const label = teamLabel(raw);
if (!label) return raw.trim();
const n = fold(label);
if (!n) return label;
const variant = isVariantSide(label);
const nameWords = words(label);
const short = label.trim().length <= 6 && !/\s/.test(label.trim());
const fits = new Map<string, (typeof prepared)[number]["t"]>();
for (const p of prepared) {
// The same tests as isTeam, in the same order.
if (variant !== p.variant && p.abbr !== n) continue;
const fit =
(!!p.t.abbreviation && p.abbr === n) ||
p.slug === n ||
p.name === n ||
sameWords(nameWords, p.words) ||
(!!p.sigla && p.sigla === n) ||
(short && isInitials(label, p.t.name));
if (fit) fits.set(p.name, p.t);
}
return fits.size === 1 ? [...fits.values()][0]!.name : label;
};
}
export function pickFixture(game: FolderGame, fixtures: FixtureCandidate[], now = new Date()): FixtureCandidate | null {
// A game still to be played has no photos yet.
fixtures = fixtures.filter((f) => f.startsAt.getTime() <= now.getTime() + 6 * 3600_000);
+13 -5
View File
@@ -812,12 +812,17 @@ export class ArchiveService {
return moved;
}
/**
* One statement, not read-then-delete: a read-then-delete let another gallery just matched to this event (its
* `setFolderEvent` landing in the gap after the count was read) get silently taken back out by the delete, and
* then fail with a foreign key error moving its photos in here — the "empty" check now lives in the delete's own
* `WHERE`, so Postgres re-reads it against whatever just committed (BIT-31531).
*/
private async dropIfEmpty(eventId: string): Promise<void> {
const { db } = this.deps;
const event = await db.event.findUnique({ where: { id: eventId }, select: { archivedAt: true, _count: { select: { photos: true, cloudFolders: true, galleries: true, deliveries: true } } } });
if (!event?.archivedAt) return;
const c = event._count;
if (c.photos + c.cloudFolders + c.galleries + c.deliveries === 0) await db.event.delete({ where: { id: eventId } }).catch(() => undefined);
await db.event.deleteMany({
where: { id: eventId, archivedAt: { not: null }, photos: { none: {} }, cloudFolders: { none: {} }, galleries: { none: {} }, deliveries: { none: {} } },
});
}
// --- indexing --------------------------------------------------------------------------------------------------
@@ -969,7 +974,10 @@ export class ArchiveService {
await db.cloudFile.update({ where: { id: fileId }, data: { status: retry ? "PENDING" : "FAILED", error: message, ...(transient && { attempts: { decrement: 1 } }) } });
// A file moved since the walk: read its folder again next time.
if (gone) await db.cloudFolder.update({ where: { id: file.folderId }, data: { etag: null } });
log.warn({ err, fileId, path: file.path }, "archive: image not indexed");
// A transient blip is given a free retry and costs nothing (BIT-31513): logged at info so it never reaches
// the error hub as a warning, unlike a real decoding/matching failure or one burning the attempt budget.
if (transient) log.info({ err, fileId, path: file.path }, "archive: image download blipped, requeued for a free retry");
else log.warn({ err, fileId, path: file.path }, "archive: image not indexed");
} finally {
await rm(dir, { recursive: true, force: true });
}
+12 -7
View File
@@ -9,7 +9,7 @@ import type { SecretBox } from "../delivery/secrets.js";
import { AppError, badRequest, notFound, unauthorized } from "../lib/errors.js";
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
import { CloudClient, pollLogin, startLogin } from "./nextcloud.js";
import { canonicalTeam, describeFolder } from "./match.js";
import { describeFolder, directorySides, teamMatcher } from "./match.js";
import type { FaceService } from "../faces/service.js";
import { faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js";
import { registerArchiveDownloadRoutes } from "./downloads.js";
@@ -386,31 +386,32 @@ export async function registerArchiveViewerRoutes(
* team: thousands of games times every team blocked the API for minutes). One answer per name, kept for a while,
* shared by every viewer of the source.
*/
const canonicalNames = new Map<string, { at: number; known: Promise<{ name: string; abbreviation: string | null; slug: string }[]>; names: Map<string, string> }>();
const canonicalNames = new Map<string, { at: number; known: Promise<(name: string) => string>; names: Map<string, string> }>();
const CANONICAL_TTL_MS = 6 * 3600_000;
const DIRECTORY_WAIT_MS = 10_000;
const teamGroups = async (sourceId: string, games: Iterable<{ home: string; away: string }>): Promise<Map<string, { names: Set<string>; galleries: number }>> => {
let memo = canonicalNames.get(sourceId);
if (!memo || Date.now() - memo.at > CANONICAL_TTL_MS) {
const known = (async () => {
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { look: true, baseUrl: true } });
const liga = source?.look === "liga" || /liga/i.test(source?.baseUrl ?? "");
return db.sportsTeam.findMany({ where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } }, select: { name: true, abbreviation: true, slug: true } });
return teamMatcher(await db.sportsTeam.findMany({ where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } }, select: { name: true, abbreviation: true, slug: true } }));
})();
known.catch(() => canonicalNames.delete(sourceId));
memo = { at: Date.now(), known, names: new Map() };
canonicalNames.set(sourceId, memo);
}
const known = await memo.known;
const canonical = await memo.known;
const out = new Map<string, { names: Set<string>; galleries: number }>();
const byKey = new Map<string, string>();
const fold = (x: string) => x.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
let fresh = 0;
for (const g of games)
for (const raw of [g.home, g.away]) {
for (const raw of [g.home, g.away].flatMap((side) => (side ? directorySides(side) : []))) {
if (!raw) continue;
let name = memo.names.get(raw);
if (name === undefined) {
name = canonicalTeam(raw, known);
name = canonical(raw);
memo.names.set(raw, name);
// Let other requests in between the new names (the first reading of a big archive).
if (++fresh % 25 === 0) await new Promise((r) => setImmediate(r));
@@ -497,7 +498,7 @@ export async function registerArchiveViewerRoutes(
const { sourceId } = SourceParams.parse(req.params);
const v = viewerOf(req, sourceId);
const visible = await visibleFolders(v);
const teams = await remembered(sourceId, "teams", visible, async () => {
const reading = remembered(sourceId, "teams", visible, async () => {
const folders = await db.cloudFolder.findMany({ where: { ...folderWhere(v, visible), matchedBy: { not: "FOLDER" } }, select: { event: { select: { id: true, home: true, away: true } } } });
// Teams of games only (a session or a day of an event is named in "home" too), each game counted once.
const games = new Map<string, { home: string; away: string }>();
@@ -506,6 +507,10 @@ export async function registerArchiveViewerRoutes(
.map(([name, g]) => ({ name, galleries: g.galleries }))
.sort((a, b) => b.galleries - a.galleries || a.name.localeCompare(b.name));
});
// The first reading of a big archive can take a while: say so (the page asks again) rather than let the proxy
// time out. The reading goes on and is kept for the next ask.
const teams = await Promise.race([reading, new Promise<null>((r) => setTimeout(() => r(null), DIRECTORY_WAIT_MS).unref())]);
if (!teams) return { teams: [], preparing: true };
return { teams };
});
+8
View File
@@ -13,6 +13,14 @@ const Env = z.object({
.default("0")
.transform((v) => v === "1" || v === "true"),
DATABASE_URL: z.string().url(),
/** Prisma/pg pool size of one API process (infra/pm2/api.config.cjs runs API_INSTANCES of these). */
API_DB_POOL_SIZE: z.coerce.number().int().positive().default(10),
/** PM2 cluster instances for the API; mirror a pm2-api.override.json `instances` change here too. */
API_INSTANCES: z.coerce.number().int().positive().default(2),
/** Postgres' max_connections, so the worker leaves it enough room for the API and admin/migration connections. */
DB_MAX_CONNECTIONS: z.coerce.number().int().positive().default(100),
/** Postgres' superuser_reserved_connections: never available to the app, whatever max_connections says. */
DB_SUPERUSER_RESERVED_CONNECTIONS: z.coerce.number().int().nonnegative().default(3),
JWT_SECRET: z.string().min(32, "JWT_SECRET must have at least 32 characters"),
ACCESS_TOKEN_TTL_SEC: z.coerce.number().int().positive().default(900),
REFRESH_TOKEN_TTL_DAYS: z.coerce.number().int().positive().default(30),
+4 -1
View File
@@ -442,7 +442,10 @@ export class DeliveryService {
let cloud: { file: string; done: () => Promise<void> } | null = null;
if (!item.photo.originalStored && this.deps.originals) {
cloud = await this.deps.originals.downloadOriginal(item.photoId).catch((err) => {
log.warn({ err, itemId }, "delivery: original not read from the cloud");
// A transient cloud blip (BIT-31513) is retried below (QUEUED with a backoff), so it is logged at info,
// not warn, to keep it out of the error hub like the archive indexer's own download already is.
if (isTransient(err)) log.info({ err, itemId }, "delivery: original download blipped from the cloud, retrying");
else log.warn({ err, itemId }, "delivery: original not read from the cloud");
return null;
});
}
+6 -3
View File
@@ -301,7 +301,7 @@ export function zerozeroGameId(input: string): string | null {
}
const STOP = new Set(["fc", "sc", "cf", "cd", "ud", "sad", "ac", "ad", "gd", "cs", "sl", "sport", "clube", "club", "futebol", "football", "afc", "the", "de", "da", "do", "e", "fk", "sk"]);
const words = (name: string) =>
export const words = (name: string) =>
name
.normalize("NFD")
.replace(/[̀-ͯ]/g, "")
@@ -312,8 +312,11 @@ const words = (name: string) =>
/** Whether two names are the same team ("Torreense" / "SC Torreense", "Sporting CP" / "Sporting"). */
export function sameTeam(a: string, b: string): boolean {
const wa = words(a);
const wb = words(b);
return sameWords(words(a), words(b));
}
/** `sameTeam` on names already split into `words` (to compare one name with many teams). */
export function sameWords(wa: string[], wb: string[]): boolean {
if (!wa.length || !wb.length) return false;
const [short, long] = wa.length <= wb.length ? [wa, wb] : [wb, wa];
return short.every((w) => long.some((x) => x === w || (w.length >= 4 && (x.startsWith(w) || w.startsWith(x)))));
+37
View File
@@ -131,3 +131,40 @@ export class Pressure {
return Math.max(1, Math.floor(full * this.share(burst)));
}
}
/**
* How many Postgres connections the worker's pool may open for `wanted`, leaving room under `max` (Postgres'
* `max_connections`) for: the API's own Prisma pool, one per PM2 cluster instance; each of those instances'
* realtime connections (`attachRealtime` in `realtime.ts`: a 2-connection publish pool plus one dedicated
* `LISTEN` client, so 3 per instance — not just the worker's own 1-connection remote broadcaster); one extra
* 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.
*/
export function dbConnectionBudget(
wanted: number,
{
max = 100,
apiInstances = 2,
apiPoolSize = 10,
realtimePerInstance = 3,
apiReloadOverlap = 1,
superuserReserved = 3,
headroom = 10,
}: {
max?: number;
apiInstances?: number;
apiPoolSize?: number;
realtimePerInstance?: number;
apiReloadOverlap?: number;
superuserReserved?: number;
headroom?: number;
} = {},
): number {
const available = max - superuserReserved - (apiInstances + apiReloadOverlap) * (apiPoolSize + realtimePerInstance) - 1 - headroom;
return Math.max(1, Math.min(wanted, available));
}
+1 -1
View File
@@ -5,7 +5,7 @@ import { createDb } from "./db.js";
preferIpv4();
const config = loadConfig();
const db = createDb(config.DATABASE_URL);
const db = createDb(config.DATABASE_URL, config.API_DB_POOL_SIZE);
const reporter = reporterFor(config);
reporter.watchProcess("api");
const app = await buildApp({ config, db, realtime: "socket", reporter });
+11 -1
View File
@@ -70,9 +70,19 @@ export interface OfficialData {
const TIMEOUT_MS = 20_000;
/** An HTTP error from a federation's own API, with its status so callers can tell "not available yet" (4xx) from a real outage. */
export class ProviderHttpError extends Error {
constructor(
message: string,
readonly status: number,
) {
super(message);
}
}
async function get(fetcher: Fetch, url: string, headers: Record<string, string>, as: "json" | "text", timeoutMs = TIMEOUT_MS) {
const res = await fetcher(url, { headers, signal: AbortSignal.timeout(timeoutMs) });
if (!res.ok) throw new Error(`${new URL(url).host} ${new URL(url).pathname} ${res.status}`);
if (!res.ok) throw new ProviderHttpError(`${new URL(url).host} ${new URL(url).pathname} ${res.status}`, res.status);
return as === "json" ? res.json() : res.text();
}
+5 -1
View File
@@ -19,6 +19,7 @@ import {
LigaProvider,
type OfficialData,
type PlayerData,
ProviderHttpError,
type TeamData,
UEFA_COMPETITIONS,
UEFA_PITCH_OFFICIALS,
@@ -867,7 +868,10 @@ export class SportsService {
named = await this.liga.referees(fixture.competition.externalId, fixture.competition.season, fixture.round, fixture.externalId.replace(/^\d{8}-/, ""));
if (named.length) await db.sportsFixture.update({ where: { id: fixture.id }, data: { officials: named as unknown as object } });
} catch (err) {
log.warn({ err, fixture: fixture.id }, "sports: liga referees failed");
// Liga 400s a round's nominations until it publishes them, days before the match: expected, not an
// outage, so it is logged at info to keep it out of the error hub (it is read again on the next refresh).
if (err instanceof ProviderHttpError && err.status === 400) log.info({ err, fixture: fixture.id }, "sports: liga nominations not published yet for this round");
else log.warn({ err, fixture: fixture.id }, "sports: liga referees failed");
}
}
const officials = named.filter((o) => PEOPLE_OFFICIALS.includes(o.role));
+14 -3
View File
@@ -5,7 +5,7 @@ import { preferIpv4 } from "./lib/prefer-ipv4.js";
import { reporterFor } from "./lib/reporter.js";
import pino from "pino";
import { loadConfig } from "./config.js";
import { planCapacity, Pressure } from "./lib/capacity.js";
import { dbConnectionBudget, planCapacity, Pressure } from "./lib/capacity.js";
import { modelsDir } from "./lib/models.js";
import { createDb } from "./db.js";
import { closeRenderer } from "./delivery/render.js";
@@ -63,8 +63,19 @@ const capacity = planCapacity({
delivery: config.DELIVERY_CONCURRENCY,
});
log.info(capacity, "capacity");
// Enough connections for everything running at once, within Postgres' default 100 (the API keeps its own 10).
const db = createDb(config.DATABASE_URL, Math.min(80, 10 + Math.ceil((capacity.archiveDownloads + capacity.faces + capacity.ingest) / 2)));
// Enough connections for everything running at once, within what's left of Postgres' max_connections once the
// API's cluster (Prisma pool and realtime connections), the superuser-reserved slots, the realtime broadcaster
// and ad hoc connections (migrations, scripts, psql) have theirs.
const wanted = 10 + Math.ceil((capacity.archiveDownloads + capacity.faces + capacity.ingest) / 2);
const db = createDb(
config.DATABASE_URL,
dbConnectionBudget(wanted, {
max: config.DB_MAX_CONNECTIONS,
apiInstances: config.API_INSTANCES,
apiPoolSize: config.API_DB_POOL_SIZE,
superuserReserved: config.DB_SUPERUSER_RESERVED_CONNECTIONS,
}),
);
const storage = new LocalStorage(config.STORAGE_ROOT);
const broadcaster = createRemoteBroadcaster(config.DATABASE_URL, (err) => log.error({ err }, "realtime publish failed"));
+153 -1
View File
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import sharp from "sharp";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { canonicalTeam, describeFolder, exhibitionName, isExhibition, isInitials, isTeam, lisbonDay, parseFolder, pickFixture, teamLabel, type FixtureCandidate } from "../src/archive/match.js";
import { canonicalTeam, describeFolder, directorySides, exhibitionName, isExhibition, isInitials, isTeam, lisbonDay, parseFolder, pickFixture, teamLabel, teamMatcher, type FixtureCandidate } from "../src/archive/match.js";
import { CloudClient, parseMultistatus } from "../src/archive/nextcloud.js";
import { ArchiveService, localDirs } from "../src/archive/service.js";
import { SecretBox } from "../src/delivery/secrets.js";
@@ -52,6 +52,21 @@ describe("archive folder names", () => {
expect(pickFixture(parseFolder("/LPbwin - 22-23/JORNADA 11/CPACxRAFC")!, [fixture], new Date("2026-10-19T00:00:00Z"))?.id).toBe("cpac");
});
it("reads a slash between two clubs, in any archive, and leaves a season slash alone", () => {
expect(parseFolder("/FPA/Fotos/2025_2026/Competições Nacionais/PO09/20250913 - ALMADA AC / EXT. GIL EANES")).toMatchObject({
home: "ALMADA AC",
away: "EXT. GIL EANES",
day: "2025-09-13",
season: "20252026",
competition: "PO09",
});
expect(parseFolder("/Liga/04.11.23 ALMADA AC / EXT. GIL EANES")).toMatchObject({ home: "ALMADA AC", away: "EXT. GIL EANES", day: "2023-11-04" });
expect(directorySides("ALMADA AC / EXT. GIL EANES")).toEqual(["ALMADA AC", "EXT. GIL EANES"]);
expect(parseFolder("/x/20250913 - 2025/2026")).toBeNull();
expect(parseFolder("/x/20250913 - Final / Video")).toBeNull();
expect(directorySides("Sporting CP")).toEqual(["Sporting CP"]);
});
it("reads Liga folders: competition and season from the top, matchday, numbered games", () => {
expect(parseFolder("/LPBetclic 26-27/Jornada 5/03. Sporting CP x SC Braga")).toMatchObject({
home: "Sporting CP",
@@ -247,6 +262,10 @@ describe("archive folder names", () => {
expect(canonicalTeam("06_SPORTING CP", known)).toBe("Sporting CP");
expect(canonicalTeam("02.2024 Benfica B", known)).toBe("SL Benfica B");
expect(canonicalTeam("09.2023 Leiria", known)).toBe("U. Leiria");
// The prepared matcher (many names, same teams) answers the same.
const match = teamMatcher(known);
for (const name of ["01 SCP", "06_SPORTING CP", "02.2024 Benfica B", "09.2023 Leiria", "Benfica", "UDL", "SLB B", "FC Porto", "", "12"])
expect(match(name)).toBe(canonicalTeam(name, known));
});
it("picks the one fixture with those teams on that day", () => {
@@ -329,6 +348,26 @@ describe("CloudClient retries transient failures", () => {
await rm(dir, { recursive: true, force: true });
}
});
it("retries a 503 blip on a PROPFIND (BIT-31498) and succeeds, instead of failing the whole walk", async () => {
const multistatus = `<?xml version="1.0"?><d:multistatus xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
<d:response><d:href>/remote.php/dav/files/peter/FPA/Fotos/</d:href>
<d:propstat><d:prop><d:getetag>"abc"</d:getetag><d:resourcetype><d:collection/></d:resourcetype><oc:fileid>10</oc:fileid></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>
</d:response>
</d:multistatus>`;
let calls = 0;
const fetchImpl: typeof fetch = async (input) => {
const url = new URL(String(input));
const who = whoami(url);
if (who) return who;
calls++;
return calls <= 2 ? new Response(null, { status: 503 }) : new Response(multistatus, { status: 207 });
};
const client = new CloudClient({ baseUrl: "https://cloud.test", username: "peter", password: "pw" }, fetchImpl);
const { self } = await client.list("/FPA/Fotos");
expect(self.fileId).toBe("10");
expect(calls).toBe(3);
});
});
interface Node {
@@ -569,6 +608,70 @@ describe("archive from a Nextcloud", () => {
expect(after.lastScanAt).not.toBeNull();
});
it("requeues a photo instead of failing it when a download blip outlasts the cloud client's own retries (BIT-31505)", async () => {
const source = await connect();
cloud.authorised = true;
await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
await worker.scan(source.id);
const [id] = await worker.claim(1);
const claimed = await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } });
expect(claimed).toMatchObject({ status: "WORKING", attempts: 1 });
// Nextcloud stays unavailable for longer than CloudClient.call's own retry budget (BIT-31491): the GET for
// this file keeps answering 503 past the last retry, so download() gives up and throws.
const realFetch = cloud.fetch;
const name = claimed.path.split("/").pop()!;
cloud.fetch = async (input, init) => {
if ((init?.method ?? "GET") === "GET" && new URL(String(input)).pathname.endsWith(name)) return new Response(null, { status: 503 });
return realFetch(input, init);
};
await worker.index(id);
cloud.fetch = realFetch;
// Given back to the walk, not failed outright, and the claim's attempt is given back with it: a cloud blip
// never counts toward the permanent-failure limit the way a real decoding/matching error would.
const requeued = await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } });
expect(requeued).toMatchObject({ status: "PENDING", attempts: 0 });
expect(requeued.error).toContain("503");
const [again] = await worker.claim(1);
expect(again).toBe(id);
await worker.index(again);
expect(await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } })).toMatchObject({ status: "DONE" });
});
it("logs a download blip at info, not warn, so a free retry never reaches the error hub as a new error (BIT-31513)", async () => {
const source = await connect();
cloud.authorised = true;
await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
const calls: { level: "info" | "warn"; msg: string }[] = [];
const spy = {
info: (_obj: unknown, msg: string) => calls.push({ level: "info", msg }),
warn: (_obj: unknown, msg: string) => calls.push({ level: "warn", msg }),
};
const storage = new LocalStorage(storageRoot);
const ingest = new IngestService({ db: ctx.db, storage, signer: new UrlSigner("s".repeat(40), 3600), broadcaster: new MemoryBroadcaster(), ingestRoot: path.join(storageRoot, "ingest"), log: quiet });
const spied = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: spy, ingest, fetchImpl: fetchProxy });
await spied.scan(source.id);
const [id] = await spied.claim(1);
const claimed = await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } });
const realFetch = cloud.fetch;
const name = claimed.path.split("/").pop()!;
cloud.fetch = async (input, init) => {
if ((init?.method ?? "GET") === "GET" && new URL(String(input)).pathname.endsWith(name)) return new Response(null, { status: 503 });
return realFetch(input, init);
};
await spied.index(id);
cloud.fetch = realFetch;
// Same recoverable blip as BIT-31505: a free retry, not an error to page on, so logHooks (reporter.ts) must
// never see it as a "warn" carrying an err (it would otherwise reach errors.bitreport.pt and reopen the Loop).
expect(calls).toContainEqual({ level: "info", msg: "archive: image download blipped, requeued for a free retry" });
expect(calls.some((c) => c.level === "warn")).toBe(false);
});
it("puts a game's halves in one event with the clubs' names, and names a session's athletes on their photos", async () => {
const game = "/FPA/Fotos/2024_2025/Supertaça Kempa 2024/20240824 - SCP x ABC";
cloud.add(`${game}/1P/H_0001.jpg`, await jpeg(6));
@@ -628,6 +731,55 @@ describe("archive from a Nextcloud", () => {
expect(await ctx.db.event.findUnique({ where: { id: oldEvent } })).toBeNull();
});
it("never drops an event a match lands on while its own cleanup still thinks it is empty (BIT-31531)", async () => {
const source = await connect();
cloud.authorised = true;
await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
await worker.scan(source.id);
for (const id of await worker.claim(10)) await worker.index(id);
const gameFolder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "20250913 - SCP x ABC" } } });
const galaFolder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "Gala 20250614" } } });
const gameEventId = gameFolder.eventId!;
const galaEventId = galaFolder.eventId!;
// galaFolder is galaEventId's only folder, so moving it onto the game's event makes galaEventId empty and
// triggers dropIfEmpty(galaEventId) at the end of the move. Hold that cleanup open right at its delete — as if
// another match had just made it look empty a moment ago — while a second move lands gameFolder (and its
// photos) on galaEventId. Before BIT-31531 dropIfEmpty read "empty" and deleted on that stale read regardless
// of what arrived after; the fix folds the check into the delete's own WHERE, so it must see the new tenant.
let releaseDelete!: () => void;
const heldOpen = new Promise<void>((resolve) => (releaseDelete = resolve));
let reachedDelete!: () => void;
const deleteReached = new Promise<void>((resolve) => (reachedDelete = resolve));
const gated = ctx.db.$extends({
query: {
event: {
async deleteMany({ args, query }) {
if (args.where?.id === galaEventId) {
reachedDelete();
await heldOpen;
}
return query(args);
},
},
},
});
const slowWorker = new ArchiveService({ db: gated as unknown as TestContext["db"], secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy });
const held = slowWorker.setFolderEvent(galaFolder.id, { eventId: gameEventId });
await deleteReached;
await worker.setFolderEvent(gameFolder.id, { eventId: galaEventId });
releaseDelete();
await held;
const gameAfter = await ctx.db.cloudFolder.findUniqueOrThrow({ where: { id: gameFolder.id } });
expect(gameAfter.eventId).toBe(galaEventId);
expect(await ctx.db.event.findUnique({ where: { id: galaEventId } })).not.toBeNull();
const gamePhotos = await ctx.db.photo.findMany({ where: { originalName: { in: ["PS_0001.jpg", "PS_0002.jpg"] } } });
expect(gamePhotos.every((p) => p.eventId === galaEventId)).toBe(true);
});
it("asks again when the cloud revokes the app password", async () => {
const source = await connect();
cloud.authorised = true;
+22 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { planCapacity, Pressure, type Reading } from "../src/lib/capacity.js";
import { dbConnectionBudget, planCapacity, Pressure, type Reading } from "../src/lib/capacity.js";
const GB = 1e9;
@@ -38,3 +38,24 @@ describe("capacity", () => {
expect(at({ free: 6 * GB }).allow(36, true)).toBe(18);
});
});
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);
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);
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("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);
});
});
+32
View File
@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import sharp from "sharp";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { NextcloudError } from "../src/delivery/nextcloud.js";
import { closeRenderer } from "../src/delivery/render.js";
import { SecretBox } from "../src/delivery/secrets.js";
import { DeliveryService } from "../src/delivery/service.js";
@@ -705,6 +706,37 @@ describe("delivery", () => {
expect(await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } })).toMatchObject({ status: "WAITING", lastError: null });
});
it("logs a blip reading an archive original from the cloud at info, not warn, so it never reaches the error hub (BIT-31522)", async () => {
const { orgId, token } = await setup();
const created = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name: "Disco", kind: "LOCAL", baseUrl: "/Users/peter/Entregas", username: "mac-0001-peter", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}" },
});
const targetId = (created.json() as { id: string }).id;
const a = await photo("archived.jpg", "2026:09:23 21:10:00");
await ctx.db.photo.update({ where: { id: a }, data: { originalStored: false } });
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a] } });
const calls: { level: "info" | "warn"; msg: string }[] = [];
const spy = {
info: (_obj: unknown, msg: string) => calls.push({ level: "info", msg }),
warn: (_obj: unknown, msg: string) => calls.push({ level: "warn", msg }),
};
// A cloud "originals" source whose download always comes back as the Nextcloud 503 seen in BIT-31522 — the
// same self-healing blip BIT-31513 already stopped from reaching the error hub out of the archive indexer.
const originals = { downloadOriginal: async () => { throw new NextcloudError("GET /archived.jpg failed: 503", 503); } };
const spied = new DeliveryService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), secrets: new SecretBox(KEY), broadcaster, log: spy, fetchImpl: nc.fetch, originals });
const [claimed] = await delivery.claim(5);
await spied.process(claimed!);
expect(calls).toContainEqual({ level: "info", msg: "delivery: original download blipped from the cloud, retrying" });
expect(calls.some((c) => c.level === "warn")).toBe(false);
expect(await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } })).toMatchObject({ status: "QUEUED", lastError: "waiting_for_original" });
});
it("retries transient errors with back-off and stops at auth errors", async () => {
const { orgId, token, target } = await setup();
const id = await photo("a.jpg", "2026:09:23 21:10:00");
+16 -3
View File
@@ -1,7 +1,7 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { cached, call, fold, initials, prefetch, shortDay, Unauthorised, type Directory, type GalleryCard, type PeopleList } from "./api";
import { cached, call, fold, forget, initials, prefetch, shortDay, Unauthorised, type Directory, type GalleryCard, type PeopleList } from "./api";
import { Icon, Loading, PersonFace } from "./parts";
export type Tab = "galleries" | "people" | "teams" | "review";
@@ -37,6 +37,7 @@ export function Browse({
const [total, setTotal] = useState(0);
const [loadingMore, setLoadingMore] = useState(false);
const [teams, setTeams] = useState<Directory["teams"] | null>(null);
const [teamsTry, setTeamsTry] = useState(0);
const [players, setPlayers] = useState<NonNullable<Directory["players"]> | null>(null);
const [people, setPeople] = useState<PeopleList | null>(null);
const [club, setClub] = useState<string | null>(null);
@@ -86,16 +87,28 @@ export function Browse({
useEffect(() => {
let cancel = false;
let retry: ReturnType<typeof setTimeout> | undefined;
setFailed(false);
if (tab === "teams") {
cached<Directory>(`/v1/archive/${sourceId}/directory`, token, (body) => !cancel && setTeams(body.teams)).catch((err) => !cancel && guard(err));
const url = `/v1/archive/${sourceId}/directory`;
cached<Directory>(url, token, (body) => {
if (cancel) return;
// The server is still reading a big archive's teams: ask again in a moment (the list keeps loading).
if (body.preparing) {
forget(url);
retry = setTimeout(() => setTeamsTry((n) => n + 1), 4000);
return;
}
setTeams(body.teams);
}).catch((err) => !cancel && guard(err));
cached<Directory>(`/v1/archive/${sourceId}/directory/players`, token, (body) => !cancel && setPlayers(body.players ?? [])).catch(() => !cancel && setPlayers([]));
}
if (tab === "people") cached<PeopleList>(`/v1/archive/${sourceId}/people`, token, (body) => !cancel && setPeople(body)).catch((err) => !cancel && guard(err));
return () => {
cancel = true;
clearTimeout(retry);
};
}, [tab, sourceId, token, guard, attempt]);
}, [tab, sourceId, token, guard, attempt, teamsTry]);
const more = () => {
if (!list || loadingMore) return;
+2
View File
@@ -107,6 +107,8 @@ export interface Directory {
teams: { name: string; galleries: number }[];
/** Named on the photos (a session's folder per athlete, the editors' tags). */
players?: { name: string; club: string | null; photos: number }[];
/** The server is still reading the teams of a big archive: ask again shortly. */
preparing?: boolean;
}
export interface PeopleList {
+17
View File
@@ -0,0 +1,17 @@
"use client";
/**
* Catches render errors anywhere under the root layout (pages, nested layouts) so a transient API or DB
* hiccup shows a retry screen instead of a hard crash. The real error already reached errors.bitreport.pt
* via instrumentation.ts's onRequestError, which fires regardless of this boundary.
*/
export default function Error({ reset }: { error: Error & { digest?: string }; reset: () => void }) {
return (
<main className="wrap empty">
<p>Não foi possível carregar esta página. Tenta novamente.</p>
<button type="button" onClick={() => reset()}>
Tentar novamente
</button>
</main>
);
}
+23
View File
@@ -0,0 +1,23 @@
"use client";
import "./globals.css";
/**
* Catches errors thrown by the root layout itself (e.g. getSite() failing for a reason other than
* NotFound). Next only reaches this boundary for root-layout errors, so it must render its own
* html/body — the layout that would normally do that is what just failed.
*/
export default function GlobalError({ reset }: { error: Error & { digest?: string }; reset: () => void }) {
return (
<html lang="pt">
<body>
<main className="wrap empty">
<p>Não foi possível carregar esta página. Tenta novamente.</p>
<button type="button" onClick={() => reset()}>
Tentar novamente
</button>
</main>
</body>
</html>
);
}