From 5d286299f84fbc77388fe4d9d4eb11c5b2436d7a Mon Sep 17 00:00:00 2001 From: spark Date: Mon, 19 Oct 2026 00:45:00 +0000 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1 --- apps/api/src/archive/match.ts | 36 ++++++++++++++++++++++- apps/api/src/archive/viewer.ts | 17 +++++++---- apps/api/src/delivery/zerozero.ts | 9 ++++-- apps/api/test/archive.test.ts | 6 +++- apps/site/src/app/arquivo/[id]/Browse.tsx | 19 ++++++++++-- apps/site/src/app/arquivo/[id]/api.ts | 2 ++ 6 files changed, 75 insertions(+), 14 deletions(-) diff --git a/apps/api/src/archive/match.ts b/apps/api/src/archive/match.ts index 0eb013e..f78ed4b 100644 --- a/apps/api/src/archive/match.ts +++ b/apps/api/src/archive/match.ts @@ -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"; /** @@ -433,6 +433,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(); + 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); diff --git a/apps/api/src/archive/viewer.ts b/apps/api/src/archive/viewer.ts index cdedd58..04c3c91 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -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, teamMatcher } from "./match.js"; import type { FaceService } from "../faces/service.js"; import { faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js"; import { registerArchiveDownloadRoutes } from "./downloads.js"; @@ -386,21 +386,22 @@ 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; names: Map }>(); + const canonicalNames = new Map string>; names: Map }>(); 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; 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; galleries: number }>(); const byKey = new Map(); const fold = (x: string) => x.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim(); @@ -410,7 +411,7 @@ export async function registerArchiveViewerRoutes( 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(); @@ -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((r) => setTimeout(() => r(null), DIRECTORY_WAIT_MS).unref())]); + if (!teams) return { teams: [], preparing: true }; return { teams }; }); diff --git a/apps/api/src/delivery/zerozero.ts b/apps/api/src/delivery/zerozero.ts index 7cc2fae..37e5f0f 100644 --- a/apps/api/src/delivery/zerozero.ts +++ b/apps/api/src/delivery/zerozero.ts @@ -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))))); diff --git a/apps/api/test/archive.test.ts b/apps/api/test/archive.test.ts index 1d69d6e..290541f 100644 --- a/apps/api/test/archive.test.ts +++ b/apps/api/test/archive.test.ts @@ -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, exhibitionName, isExhibition, isInitials, isTeam, lisbonDay, parseFolder, pickFixture, teamLabel, teamMatcher, type FixtureCandidate } from "../src/archive/match.js"; import { parseMultistatus } from "../src/archive/nextcloud.js"; import { ArchiveService, localDirs } from "../src/archive/service.js"; import { SecretBox } from "../src/delivery/secrets.js"; @@ -224,6 +224,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", () => { diff --git a/apps/site/src/app/arquivo/[id]/Browse.tsx b/apps/site/src/app/arquivo/[id]/Browse.tsx index 198f456..59aca2a 100644 --- a/apps/site/src/app/arquivo/[id]/Browse.tsx +++ b/apps/site/src/app/arquivo/[id]/Browse.tsx @@ -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(null); + const [teamsTry, setTeamsTry] = useState(0); const [players, setPlayers] = useState | null>(null); const [people, setPeople] = useState(null); const [club, setClub] = useState(null); @@ -86,16 +87,28 @@ export function Browse({ useEffect(() => { let cancel = false; + let retry: ReturnType | undefined; setFailed(false); if (tab === "teams") { - cached(`/v1/archive/${sourceId}/directory`, token, (body) => !cancel && setTeams(body.teams)).catch((err) => !cancel && guard(err)); + const url = `/v1/archive/${sourceId}/directory`; + cached(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(`/v1/archive/${sourceId}/directory/players`, token, (body) => !cancel && setPlayers(body.players ?? [])).catch(() => !cancel && setPlayers([])); } if (tab === "people") cached(`/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; diff --git a/apps/site/src/app/arquivo/[id]/api.ts b/apps/site/src/app/arquivo/[id]/api.ts index c407899..581b53e 100644 --- a/apps/site/src/app/arquivo/[id]/api.ts +++ b/apps/site/src/app/arquivo/[id]/api.ts @@ -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 { -- 2.47.3