From 0d497018c759422ba9396a9a13132a2ca3c1bc19 Mon Sep 17 00:00:00 2001 From: Spinnich Date: Fri, 4 Sep 2026 19:28:41 +0000 Subject: [PATCH 1/5] fix(scan): let a complete rescan clear the ids it rematched A complete rescan is documented as wiping every external id and matching again from scratch, but it only wrote NULL for deselected sources. Selected ones were assumed to reset implicitly by staying out of rom_attrs, which merge then skips rather than nulling, so a provider that searched and found nothing left its old (wrong) id in place. Track the sources whose lookup actually ran and clear those too. A source skipped because the platform carries no id for it never enters the set, so hand-set ids on unmapped platforms survive, and a provider that raised or hit the ScreenScraper rate limit is discarded again since it ruled nothing out. SteamGridDB resolves after the reset block, so it clears its own id. Fixes #4346 Co-Authored-By: Claude Opus 5 --- backend/handler/scan_handler.py | 79 +++++-- .../handler/test_scan_complete_rescan_ids.py | 194 ++++++++++++++++++ 2 files changed, 254 insertions(+), 19 deletions(-) create mode 100644 backend/tests/handler/test_scan_complete_rescan_ids.py diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 1542df989..dec49ad97 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -595,6 +595,12 @@ async def scan_rom( } ) + is_complete_rescan = not newly_added and scan_type == ScanType.COMPLETE + + # Sources whose lookup actually ran. One skipped because the platform carries + # no id for it never enters the set, so a rescan can't clear what it can't redo. + attempted_sources: set[MetadataSource] = set() + @functools.cache def get_match_files() -> list[RomFile]: """Files used for hash-based metadata matching, fetched at most once.""" @@ -700,6 +706,7 @@ async def scan_rom( ) ) ): + attempted_sources.add(MetadataSource.IGDB) # Use Hasheous match to get the IGDB ID h_igdb_id = hasheous_rom.get("igdb_id") if h_igdb_id: @@ -746,6 +753,7 @@ async def scan_rom( and (not rom.gamelist_id or not rom.gamelist_metadata) ) ): + attempted_sources.add(MetadataSource.GAMELIST) return await meta_gamelist_handler.get_rom( rom_attrs["fs_name"], platform, rom ) @@ -767,6 +775,7 @@ async def scan_rom( ) ) ): + attempted_sources.add(MetadataSource.FLASHPOINT) if (scan_type == ScanType.UPDATE and rom.flashpoint_id) or ( scan_type == ScanType.UNMATCHED and rom.flashpoint_id @@ -791,6 +800,7 @@ async def scan_rom( or (scan_type == ScanType.UNMATCHED and not rom.libretro_id) ) ): + attempted_sources.add(MetadataSource.LIBRETRO) return await meta_libretro_handler.get_rom( rom_attrs["fs_name"], platform.slug ) @@ -811,6 +821,7 @@ async def scan_rom( ) ) ): + attempted_sources.add(MetadataSource.HLTB) # A refresh keeps the ID already on the ROM, often a manual match, # rather than trading it for a filename guess. COMPLETE rematches. if rom.hltb_id and ( @@ -833,6 +844,7 @@ async def scan_rom( and (not rom.demozoo_id or not rom.demozoo_metadata) ) ): + attempted_sources.add(MetadataSource.DEMOZOO) return await meta_demozoo_handler.get_rom( rom_attrs["fs_name"], platform.slug ) @@ -848,6 +860,7 @@ async def scan_rom( and (not rom.pouet_id or not rom.pouet_metadata) ) ): + attempted_sources.add(MetadataSource.POUET) if rom.pouet_id: return await meta_pouet_handler.get_rom_by_id(int(rom.pouet_id)) return await meta_pouet_handler.get_rom(rom_attrs["fs_name"], platform.slug) @@ -863,6 +876,7 @@ async def scan_rom( and (not rom.csdb_id or not rom.csdb_metadata) ) ): + attempted_sources.add(MetadataSource.CSDB) if rom.csdb_id: return await meta_csdb_handler.get_rom_by_id(int(rom.csdb_id)) return await meta_csdb_handler.get_rom(rom_attrs["fs_name"], platform.slug) @@ -882,6 +896,7 @@ async def scan_rom( ) ) ): + attempted_sources.add(MetadataSource.STEAM) return await resolve_steam_rom( rom=rom, fs_name=str(rom_attrs["fs_name"]), @@ -906,6 +921,7 @@ async def scan_rom( ) ) ): + attempted_sources.add(MetadataSource.MOBY) if scan_type == ScanType.UPDATE and rom.moby_id: return await meta_moby_handler.get_rom_by_id(rom.moby_id) @@ -938,6 +954,7 @@ async def scan_rom( ) ) ): + attempted_sources.add(MetadataSource.SS) # One refusal means the per-minute budget is already spent, so give # up on this ROM rather than spending another retried request (and # its backoff) on the fallback lookups. @@ -970,6 +987,7 @@ async def scan_rom( ) except ScreenScraperRateLimitError: note_rate_limited_rom(rom_attrs["fs_name"]) + attempted_sources.discard(MetadataSource.SS) return SSRom(ss_id=None) return SSRom(ss_id=None) @@ -987,6 +1005,7 @@ async def scan_rom( and rom.platform_slug in LAUNCHBOX_PLATFORM_LIST ) ): + attempted_sources.add(MetadataSource.LAUNCHBOX) launchbox_rom = await resolve_launchbox_rom( rom=rom, fs_name=str(rom_attrs["fs_name"]), @@ -1020,6 +1039,7 @@ async def scan_rom( ) ) ): + attempted_sources.add(MetadataSource.RA) # Use Hasheous match to get the RA ID h_ra_id = hasheous_rom.get("ra_id") if h_ra_id: @@ -1057,6 +1077,7 @@ async def scan_rom( ) ) ): + attempted_sources.add(MetadataSource.HASHEOUS) ( igdb_game, ra_game, @@ -1079,41 +1100,56 @@ async def scan_rom( # others' results for this ROM, so each failure falls back to an empty match. provider_fetches = ( ( + MetadataSource.IGDB, fetch_igdb_rom(playmatch_hash_match, hasheous_hash_match), IGDBRom(igdb_id=None), ), - (fetch_moby_rom(playmatch_hash_match), MobyGamesRom(moby_id=None)), - (fetch_ss_rom(playmatch_hash_match), SSRom(ss_id=None)), - (fetch_ra_rom(hasheous_hash_match), RAGameRom(ra_id=None)), ( + MetadataSource.MOBY, + fetch_moby_rom(playmatch_hash_match), + MobyGamesRom(moby_id=None), + ), + (MetadataSource.SS, fetch_ss_rom(playmatch_hash_match), SSRom(ss_id=None)), + (MetadataSource.RA, fetch_ra_rom(hasheous_hash_match), RAGameRom(ra_id=None)), + ( + MetadataSource.LAUNCHBOX, fetch_launchbox_rom(platform.slug, playmatch_hash_match), LaunchboxRom(launchbox_id=None), ), ( + MetadataSource.HASHEOUS, fetch_hasheous_rom(hasheous_hash_match), HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None), ), - (fetch_flashpoint_rom(), FlashpointRom(flashpoint_id=None)), - (fetch_hltb_rom(), HLTBRom(hltb_id=None)), - (fetch_demozoo_rom(), DemozooRom(demozoo_id=None)), - (fetch_pouet_rom(), PouetRom(pouet_id=None)), - (fetch_csdb_rom(), CsdbRom(csdb_id=None)), - (fetch_steam_rom(), SteamRom(steam_id=None)), - (fetch_gamelist_rom(), GamelistRom(gamelist_id=None)), - (fetch_libretro_rom(), LibretroRom(libretro_id=None)), + ( + MetadataSource.FLASHPOINT, + fetch_flashpoint_rom(), + FlashpointRom(flashpoint_id=None), + ), + (MetadataSource.HLTB, fetch_hltb_rom(), HLTBRom(hltb_id=None)), + (MetadataSource.DEMOZOO, fetch_demozoo_rom(), DemozooRom(demozoo_id=None)), + (MetadataSource.POUET, fetch_pouet_rom(), PouetRom(pouet_id=None)), + (MetadataSource.CSDB, fetch_csdb_rom(), CsdbRom(csdb_id=None)), + (MetadataSource.STEAM, fetch_steam_rom(), SteamRom(steam_id=None)), + (MetadataSource.GAMELIST, fetch_gamelist_rom(), GamelistRom(gamelist_id=None)), + (MetadataSource.LIBRETRO, fetch_libretro_rom(), LibretroRom(libretro_id=None)), ) fetch_results = await asyncio.gather( - *(coro for coro, _ in provider_fetches), return_exceptions=True + *(coro for _, coro, _ in provider_fetches), return_exceptions=True ) resolved: list[Any] = [] - for (_, fallback), result in zip(provider_fetches, fetch_results, strict=True): + for (source, _, fallback), result in zip( + provider_fetches, fetch_results, strict=True + ): if isinstance(result, BaseException): if not isinstance(result, Exception): raise result - provider = fallback.__class__.__name__ + # A provider that blew up ruled nothing out, so it no longer counts + # as attempted and a complete rescan keeps the id it already had. + attempted_sources.discard(source) log.error( - f"Error fetching {hl(provider)} metadata for {hl(rom_attrs['fs_name'])}: {result}", + f"Error fetching {hl(source)} metadata for {hl(rom_attrs['fs_name'])}: {result}", extra=LOGGER_MODULE_NAME, ) resolved.append(fallback) @@ -1291,11 +1327,11 @@ async def scan_rom( }, } - # For COMPLETE rescans, explicitly clear metadata IDs and metadata for unselected sources - # This ensures that when a source is no longer selected, its data is removed from the ROM - if not newly_added and scan_type == ScanType.COMPLETE: + # Reset the id and blob of every source this rescan could rematch: the ones it + # consulted, whose miss has to undo the old match, and the deselected ones. + if is_complete_rescan: for source, fields in metadata_handlers.items(): - if source not in metadata_sources: + if source in attempted_sources or source not in metadata_sources: rom_attrs[fields["id_field"]] = None if fields["metadata_field"]: rom_attrs[fields["metadata_field"]] = {} @@ -1453,6 +1489,7 @@ async def scan_rom( or (scan_type == ScanType.UPDATE and rom.sgdb_id) or (scan_type == ScanType.UNMATCHED and not rom.sgdb_id) ): + attempted_sources.add(MetadataSource.SGDB) if scan_type == ScanType.UPDATE and rom.sgdb_id: return await meta_sgdb_handler.get_rom_by_id(rom.sgdb_id) @@ -1500,6 +1537,10 @@ async def scan_rom( ) if ranked[0] == MetadataSource.SGDB: rom_attrs["url_cover"] = sgdb_cover + elif is_complete_rescan and MetadataSource.SGDB in attempted_sources: + # SteamGridDB resolves after the reset block above, so it has to clear + # its own stale id when its lookup came back empty. + rom_attrs["sgdb_id"] = None log.info( f"{hl(rom_attrs['fs_name'])} identified as {hl(rom_attrs['name'], color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}", diff --git a/backend/tests/handler/test_scan_complete_rescan_ids.py b/backend/tests/handler/test_scan_complete_rescan_ids.py new file mode 100644 index 000000000..c4fbfb874 --- /dev/null +++ b/backend/tests/handler/test_scan_complete_rescan_ids.py @@ -0,0 +1,194 @@ +"""What a complete rescan does to a ROM's external IDs. + +A complete rescan is documented as wiping every match and rematching from +scratch, but `add_rom` merges, and merge skips attributes the object doesn't +carry. An ID therefore only resets when the scan writes it out as NULL, which +it did for deselected sources but not for the ones it actually searched. (#4346) +""" + +from unittest.mock import AsyncMock, patch + +import pytest + +from handler.database import db_platform_handler, db_rom_handler +from handler.metadata.igdb_handler import IGDBRom +from handler.metadata.sgdb_handler import SGDBRom +from handler.scan_handler import MetadataSource, ScanType, scan_rom +from models.platform import Platform +from models.rom import Rom +from utils.context import initialize_context + +FS_NAME = "Some Homebrew Thing (Aftermarket).z64" +STALE_IGDB_ID = 1289 +STALE_MOBY_ID = 42 +STALE_SGDB_ID = 777 + +MISS = IGDBRom(igdb_id=None) +MATCH = IGDBRom(igdb_id=9999, name="A Real Game") + + +async def _complete_rescan( + sources: list[str], + *, + igdb_result: IGDBRom | Exception = MISS, + sgdb_result: SGDBRom | None = None, + platform_igdb_id: int | None = 4, +) -> Rom: + """Run a complete rescan over a ROM carrying hand-set IDs, and persist it.""" + platform = db_platform_handler.add_platform( + Platform( + id=1, + slug="n64", + fs_slug="n64", + name="Nintendo 64", + igdb_id=platform_igdb_id, + ) + ) + rom = db_rom_handler.add_rom( + Rom( + platform_id=platform.id, + fs_name=FS_NAME, + fs_name_no_tags="Some Homebrew Thing", + fs_name_no_ext="Some Homebrew Thing (Aftermarket)", + fs_extension="z64", + fs_path="n64", + name="Wrong Match", + igdb_id=STALE_IGDB_ID, + igdb_metadata={"total_rating": "9"}, + moby_id=STALE_MOBY_ID, + sgdb_id=STALE_SGDB_ID, + fs_size_bytes=1024, + tags=[], + ) + ) + + igdb_mock = ( + AsyncMock(side_effect=igdb_result) + if isinstance(igdb_result, Exception) + else AsyncMock(return_value=igdb_result) + ) + with ( + patch("handler.scan_handler.meta_igdb_handler.get_rom", new=igdb_mock), + patch("handler.scan_handler.meta_igdb_handler.get_rom_by_id", new=igdb_mock), + patch( + "handler.scan_handler.meta_sgdb_handler.get_details_by_names", + new=AsyncMock(return_value=sgdb_result or SGDBRom(sgdb_id=None)), + ), + ): + async with initialize_context(): + scanned = await scan_rom( + platform=platform, + scan_type=ScanType.COMPLETE, + rom=rom, + fs_rom={ + "fs_name": FS_NAME, + "flat": True, + "nested": False, + "files": [], + "crc_hash": "", + "md5_hash": "", + "sha1_hash": "", + "ra_hash": "", + }, + metadata_sources=sources, + newly_added=False, + ) + + return db_rom_handler.add_rom(scanned) + + +async def test_a_searched_source_that_misses_drops_its_stale_id(): + saved = await _complete_rescan([MetadataSource.IGDB]) + + assert saved.igdb_id is None + assert saved.igdb_metadata == {} + + +async def test_a_searched_source_that_matches_stores_the_new_id(): + saved = await _complete_rescan([MetadataSource.IGDB], igdb_result=MATCH) + + assert saved.igdb_id == 9999 + + +async def test_a_source_the_platform_cannot_use_keeps_its_id(): + """No `platform.igdb_id` means IGDB never ran, so it rules nothing out.""" + saved = await _complete_rescan([MetadataSource.IGDB], platform_igdb_id=None) + + assert saved.igdb_id == STALE_IGDB_ID + + +async def test_a_source_that_fails_keeps_its_id(): + saved = await _complete_rescan( + [MetadataSource.IGDB], igdb_result=RuntimeError("IGDB is down") + ) + + assert saved.igdb_id == STALE_IGDB_ID + + +async def test_a_deselected_source_still_drops_its_id(): + saved = await _complete_rescan([MetadataSource.IGDB]) + + assert saved.moby_id is None + + +async def test_steamgriddb_drops_its_stale_id_after_a_miss(): + """SteamGridDB resolves after the reset, so it clears its own ID.""" + saved = await _complete_rescan( + [MetadataSource.IGDB, MetadataSource.SGDB], igdb_result=MATCH + ) + + assert saved.sgdb_id is None + + +@pytest.mark.parametrize( + "scan_type", [ScanType.QUICK, ScanType.UPDATE, ScanType.UNMATCHED] +) +async def test_only_a_complete_rescan_drops_ids(scan_type: ScanType): + """Every other scan type carries the existing IDs forward untouched.""" + platform = db_platform_handler.add_platform( + Platform(id=1, slug="n64", fs_slug="n64", name="Nintendo 64", igdb_id=4) + ) + rom = db_rom_handler.add_rom( + Rom( + platform_id=platform.id, + fs_name=FS_NAME, + fs_name_no_tags="Some Homebrew Thing", + fs_name_no_ext="Some Homebrew Thing (Aftermarket)", + fs_extension="z64", + fs_path="n64", + name="Wrong Match", + igdb_id=STALE_IGDB_ID, + fs_size_bytes=1024, + tags=[], + ) + ) + with ( + patch( + "handler.scan_handler.meta_igdb_handler.get_rom", + new=AsyncMock(return_value=MISS), + ), + patch( + "handler.scan_handler.meta_igdb_handler.get_rom_by_id", + new=AsyncMock(return_value=MISS), + ), + ): + async with initialize_context(): + scanned = await scan_rom( + platform=platform, + scan_type=scan_type, + rom=rom, + fs_rom={ + "fs_name": FS_NAME, + "flat": True, + "nested": False, + "files": [], + "crc_hash": "", + "md5_hash": "", + "sha1_hash": "", + "ra_hash": "", + }, + metadata_sources=[MetadataSource.IGDB], + newly_added=False, + ) + + assert db_rom_handler.add_rom(scanned).igdb_id == STALE_IGDB_ID From 24bc4c221b263165d3825271e219be1c85eaee79 Mon Sep 17 00:00:00 2001 From: Spinnich Date: Fri, 4 Sep 2026 20:49:51 +0000 Subject: [PATCH 2/5] fix(scan): don't let a failed lookup clear the id it couldn't check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A complete rescan clears the id of every source it consulted that came back empty. That reads an outage as a conclusive miss for the providers that report a failure as an empty match, so a rescan run while one was down wiped the id it would otherwise have confirmed, hand-set ones included. Each of those now reports the failure and leaves the tolerance to the caller, which is what the gather loop's discard already assumed: - Pouët, CSDb and Demozoo stop swallowing the 503 their own `_request` raises, and Pouët's title search raises it rather than answering "no unique title". - SteamGridDB and Flashpoint stop catching `Exception` around a whole lookup; HLTB stops catching it around its search. - ScreenScraper answers empty for every remaining ROM once its daily-quota or credentials breaker trips, so the scan reads that state off the service and drops it from the sources the rescan may clear. SteamGridDB resolves outside the gather and so needs the discard at its call site. Search keeps degrading to no thumbnail, since its cover art sits on top of matches the other providers already produced. Co-Authored-By: Claude Opus 5 --- backend/adapters/services/screenscraper.py | 9 +++ backend/endpoints/search.py | 8 +- backend/handler/metadata/csdb_handler.py | 9 +-- backend/handler/metadata/demozoo_handler.py | 7 +- .../handler/metadata/flashpoint_handler.py | 4 +- backend/handler/metadata/hltb_handler.py | 2 +- backend/handler/metadata/pouet_handler.py | 24 +++--- backend/handler/metadata/sgdb_handler.py | 10 +-- backend/handler/scan_handler.py | 22 ++++- .../handler/metadata/test_csdb_handler.py | 18 +++++ .../handler/metadata/test_demozoo_handler.py | 18 +++++ .../metadata/test_flashpoint_handler.py | 43 ++++++++++ .../handler/metadata/test_hltb_handler.py | 17 ++++ .../handler/metadata/test_pouet_handler.py | 18 +++++ .../handler/metadata/test_sgdb_handler.py | 33 ++++++++ .../handler/test_scan_complete_rescan_ids.py | 81 +++++++++++++++++-- 16 files changed, 284 insertions(+), 39 deletions(-) create mode 100644 backend/tests/handler/metadata/test_flashpoint_handler.py diff --git a/backend/adapters/services/screenscraper.py b/backend/adapters/services/screenscraper.py index b43151d8b..20e781dad 100644 --- a/backend/adapters/services/screenscraper.py +++ b/backend/adapters/services/screenscraper.py @@ -224,6 +224,15 @@ def is_daily_quota_exhausted() -> bool: return _state.daily_quota_exhausted +def is_breaker_tripped() -> bool: + """Whether a breaker has taken ScreenScraper out for the rest of this scan. + + The lookups answer empty once one trips, which a caller must not read as + "ScreenScraper has nothing for this ROM". + """ + return _state.daily_quota_exhausted or _state.credentials_rejected is not None + + def _trip_daily_quota(reason: str) -> None: """Trip the daily-quota breaker, logging a single clear notice the first time.""" if not _state.daily_quota_exhausted: diff --git a/backend/endpoints/search.py b/backend/endpoints/search.py index 4ce865729..3216b8431 100644 --- a/backend/endpoints/search.py +++ b/backend/endpoints/search.py @@ -220,7 +220,13 @@ async def search_rom( } async def get_sgdb_rom(name: str) -> tuple[str, SGDBRom]: - return name, await meta_sgdb_handler.get_details_by_names([name]) + # Cover art on top of matches the other providers already produced, so + # an unreachable SteamGridDB costs a thumbnail rather than the results. + try: + return name, await meta_sgdb_handler.get_details_by_names([name]) + except Exception as exc: + log.error("Error fetching SteamGridDB covers for '%s': %s", name, exc) + return name, SGDBRom(sgdb_id=None) async def get_libretro_rom(name: str) -> tuple[str, LibretroRom]: return name, await meta_libretro_handler.get_rom(name, rom.platform.slug) diff --git a/backend/handler/metadata/csdb_handler.py b/backend/handler/metadata/csdb_handler.py index 834ed8cce..9e07454c1 100644 --- a/backend/handler/metadata/csdb_handler.py +++ b/backend/handler/metadata/csdb_handler.py @@ -203,12 +203,9 @@ class CsdbHandler(MetadataHandler): async def get_rom_by_id(self, csdb_id: int) -> CsdbRom: if not self.is_enabled() or not csdb_id: return CsdbRom(csdb_id=None) - try: - xml = await self._request( - f"{CSDB_WEBSERVICE}?type=release&id={int(csdb_id)}&depth=2" - ) - except HTTPException: - return CsdbRom(csdb_id=None) + xml = await self._request( + f"{CSDB_WEBSERVICE}?type=release&id={int(csdb_id)}&depth=2" + ) return production_from_xml(xml) async def get_rom(self, fs_name: str, platform_slug: str) -> CsdbRom: diff --git a/backend/handler/metadata/demozoo_handler.py b/backend/handler/metadata/demozoo_handler.py index ee70c75a7..28eaae3ab 100644 --- a/backend/handler/metadata/demozoo_handler.py +++ b/backend/handler/metadata/demozoo_handler.py @@ -545,12 +545,7 @@ class DemozooHandler(MetadataHandler): async def get_rom_by_id(self, demozoo_id: int) -> DemozooRom: if not self.is_enabled() or not demozoo_id: return DemozooRom(demozoo_id=None) - try: - data = await self._request( - f"{DEMOZOO_API_ROOT}/productions/{int(demozoo_id)}/" - ) - except HTTPException: - return DemozooRom(demozoo_id=None) + data = await self._request(f"{DEMOZOO_API_ROOT}/productions/{int(demozoo_id)}/") if not data.get("id"): return DemozooRom(demozoo_id=None) return production_to_rom(data) diff --git a/backend/handler/metadata/flashpoint_handler.py b/backend/handler/metadata/flashpoint_handler.py index 456c57401..18e45cd53 100644 --- a/backend/handler/metadata/flashpoint_handler.py +++ b/backend/handler/metadata/flashpoint_handler.py @@ -218,7 +218,7 @@ class FlashpointHandler(MetadataHandler): except Exception as exc: log.error("Error searching Flashpoint API: %s", exc) - return [] + raise def get_platform(self, slug: str) -> FlashpointPlatform: """ @@ -413,7 +413,7 @@ class FlashpointHandler(MetadataHandler): except Exception as exc: log.error("Error getting ROM by ID from Flashpoint API: %s", exc) - return FlashpointRom(flashpoint_id=None) + raise class SlugToFlashpointId(TypedDict): diff --git a/backend/handler/metadata/hltb_handler.py b/backend/handler/metadata/hltb_handler.py index 75fb0be28..89b816d71 100644 --- a/backend/handler/metadata/hltb_handler.py +++ b/backend/handler/metadata/hltb_handler.py @@ -527,7 +527,7 @@ class HLTBHandler(MetadataHandler): except Exception as exc: log.error("Error searching HowLongToBeat API: %s", exc) - return [] + raise def get_platform(self, slug: str) -> HLTBPlatform: if slug not in HLTB_PLATFORM_LIST: diff --git a/backend/handler/metadata/pouet_handler.py b/backend/handler/metadata/pouet_handler.py index bca39dc5c..7e6caeb72 100644 --- a/backend/handler/metadata/pouet_handler.py +++ b/backend/handler/metadata/pouet_handler.py @@ -296,6 +296,18 @@ def production_to_rom(prod: dict[str, Any]) -> PouetRom: ) +def _unavailable() -> HTTPException: + """The error every unreachable-Pouët path raises. + + A scan reads an empty match as "this production is gone" and drops the id it + had, so a lookup that failed must not answer with one. + """ + return HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="Can't connect to Pouët API, check your internet connection", + ) + + class PouetHandler(MetadataHandler): def __init__(self) -> None: self.min_similarity_score: Final = 0.88 @@ -314,10 +326,7 @@ class PouetHandler(MetadataHandler): body = await self._fetch_capped(url, headers=headers) except (httpx.HTTPStatusError, httpx.ConnectError, httpx.ReadTimeout) as exc: log.warning("Can't connect to Pouët API", extra={"exception": str(exc)}) - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Can't connect to Pouët API, check your internet connection", - ) from exc + raise _unavailable() from exc if body is None: return {} try: @@ -340,10 +349,7 @@ class PouetHandler(MetadataHandler): async def get_rom_by_id(self, pouet_id: int) -> PouetRom: if not self.is_enabled() or not pouet_id: return PouetRom(pouet_id=None) - try: - data = await self._request(f"{POUET_API_PROD}?id={int(pouet_id)}") - except HTTPException: - return PouetRom(pouet_id=None) + data = await self._request(f"{POUET_API_PROD}?id={int(pouet_id)}") prod = data.get("prod") if not data.get("success") or not isinstance(prod, dict) or not prod.get("id"): return PouetRom(pouet_id=None) @@ -375,7 +381,7 @@ class PouetHandler(MetadataHandler): return pouet_id_from_location(res.headers.get("location") or "") except (httpx.ConnectError, httpx.ReadTimeout) as exc: log.warning("Pouët title search failed: %s", exc) - return None + raise _unavailable() from exc async def get_rom(self, fs_name: str, platform_slug: str) -> PouetRom: """Tag first; otherwise unique-title 302. No HTML list parse.""" diff --git a/backend/handler/metadata/sgdb_handler.py b/backend/handler/metadata/sgdb_handler.py index e9f9a2cb3..16165202b 100644 --- a/backend/handler/metadata/sgdb_handler.py +++ b/backend/handler/metadata/sgdb_handler.py @@ -84,7 +84,7 @@ class SGDBBaseHandler(MetadataHandler): return result except Exception as e: log.warning(f"Failed to fetch ROM by SteamGridDB ID {sgdb_id}: {e}") - return SGDBRom(sgdb_id=None) + raise async def get_details(self, search_term: str) -> list[SGDBResult]: if not self.is_enabled(): @@ -113,9 +113,9 @@ class SGDBBaseHandler(MetadataHandler): async def get_details_by_names(self, game_names: list[str]) -> SGDBRom: """Get ROM details by candidate game names. - Returns an empty match if the lookup fails. The lookup is best-effort - and never raises to the caller, so an unreachable SteamGridDB can't - abort a scan. + Raises when the lookup fails, so a caller can tell an unreachable + SteamGridDB from a name it has no art for. Callers that would rather + carry on than fail decide that for themselves. """ if not self.is_enabled(): return SGDBRom(sgdb_id=None) @@ -168,7 +168,7 @@ class SGDBBaseHandler(MetadataHandler): log.error( f"Failed to fetch SteamGridDB details for '{', '.join(game_names)}': {e}" ) - return SGDBRom(sgdb_id=None) + raise log.debug(f"No good match found for '{', '.join(game_names)}' on SteamGridDB") return SGDBRom(sgdb_id=None) diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index dec49ad97..0d11e04ca 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -6,7 +6,10 @@ from typing import Any import pydash import socketio # type: ignore -from adapters.services.screenscraper import ScreenScraperRateLimitError +from adapters.services.screenscraper import ( + ScreenScraperRateLimitError, + is_breaker_tripped, +) from config.config_manager import config_manager as cm from endpoints.responses.rom import SimpleRomSchema from handler.database import db_platform_handler, db_rom_handler @@ -1156,6 +1159,11 @@ async def scan_rom( else: resolved.append(result) + # Once a ScreenScraper breaker trips, the remaining lookups answer empty + # without asking, so it has ruled nothing out for this rom either. + if is_breaker_tripped(): + attempted_sources.discard(MetadataSource.SS) + ( igdb_handler_rom, moby_handler_rom, @@ -1518,7 +1526,17 @@ async def scan_rom( return SGDBRom(sgdb_id=None) - sgdb_hander_rom = await fetch_sgdb_details(playmatch_hash_match) + try: + sgdb_hander_rom = await fetch_sgdb_details(playmatch_hash_match) + except Exception as exc: + # A failure ruled nothing out, so the id the rom already had stands. + attempted_sources.discard(MetadataSource.SGDB) + log.error( + f"Error fetching {hl(MetadataSource.SGDB)} metadata for {hl(rom_attrs['fs_name'])}: {exc}", + extra=LOGGER_MODULE_NAME, + ) + sgdb_hander_rom = SGDBRom(sgdb_id=None) + if sgdb_hander_rom.get("sgdb_id"): rom_attrs["sgdb_id"] = sgdb_hander_rom["sgdb_id"] diff --git a/backend/tests/handler/metadata/test_csdb_handler.py b/backend/tests/handler/metadata/test_csdb_handler.py index a7066501a..c795e5b75 100644 --- a/backend/tests/handler/metadata/test_csdb_handler.py +++ b/backend/tests/handler/metadata/test_csdb_handler.py @@ -1,6 +1,7 @@ from unittest.mock import AsyncMock, patch import pytest +from fastapi import HTTPException from handler.metadata.csdb_handler import ( CsdbHandler, @@ -110,3 +111,20 @@ async def test_request_returns_empty_when_over_the_cap(): handler = CsdbHandler() with patch.object(CsdbHandler, "_fetch_capped", AsyncMock(return_value=None)): assert await handler._request("https://csdb.dk/webservice/?id=1") == "" + + +@pytest.mark.asyncio +async def test_get_rom_by_id_propagates_an_unreachable_csdb(): + """A dead connection has to stay distinguishable from a missing release.""" + handler = CsdbHandler() + with ( + patch.object(CsdbHandler, "is_enabled", return_value=True), + patch.object( + CsdbHandler, + "_request", + new_callable=AsyncMock, + side_effect=HTTPException(status_code=503, detail="down"), + ), + pytest.raises(HTTPException), + ): + await handler.get_rom_by_id(75330) diff --git a/backend/tests/handler/metadata/test_demozoo_handler.py b/backend/tests/handler/metadata/test_demozoo_handler.py index 8186fdd63..328f6a38d 100644 --- a/backend/tests/handler/metadata/test_demozoo_handler.py +++ b/backend/tests/handler/metadata/test_demozoo_handler.py @@ -3,6 +3,7 @@ from unittest.mock import AsyncMock, patch import pytest +from fastapi import HTTPException from handler.metadata.demozoo_handler import ( DemozooHandler, @@ -355,3 +356,20 @@ async def test_request_returns_empty_when_over_the_cap(): handler = DemozooHandler() with patch.object(DemozooHandler, "_fetch_capped", AsyncMock(return_value=None)): assert await handler._request("https://demozoo.org/api/v1/x") == {} + + +@pytest.mark.asyncio +async def test_get_rom_by_id_propagates_an_unreachable_demozoo(): + """A dead connection has to stay distinguishable from a missing production.""" + handler = DemozooHandler() + with ( + patch.object(DemozooHandler, "is_enabled", return_value=True), + patch.object( + DemozooHandler, + "_request", + new_callable=AsyncMock, + side_effect=HTTPException(status_code=503, detail="down"), + ), + pytest.raises(HTTPException), + ): + await handler.get_rom_by_id(1234) diff --git a/backend/tests/handler/metadata/test_flashpoint_handler.py b/backend/tests/handler/metadata/test_flashpoint_handler.py new file mode 100644 index 000000000..c13394755 --- /dev/null +++ b/backend/tests/handler/metadata/test_flashpoint_handler.py @@ -0,0 +1,43 @@ +"""Tests for the Flashpoint handler's lookup failure reporting.""" + +from unittest.mock import AsyncMock, patch + +import pytest +from fastapi import HTTPException + +from handler.metadata.flashpoint_handler import FlashpointHandler + + +@pytest.mark.asyncio +async def test_search_games_propagates_an_unreachable_flashpoint(): + """A failed search has to stay distinguishable from a term with no hits.""" + handler = FlashpointHandler() + + with ( + patch.object(FlashpointHandler, "is_enabled", return_value=True), + patch.object( + FlashpointHandler, + "_request", + new_callable=AsyncMock, + side_effect=HTTPException(status_code=503, detail="down"), + ), + pytest.raises(HTTPException), + ): + await handler.search_games("Interactive Buddy") + + +@pytest.mark.asyncio +async def test_get_rom_by_id_propagates_an_unreachable_flashpoint(): + handler = FlashpointHandler() + + with ( + patch("handler.metadata.flashpoint_handler.FLASHPOINT_API_ENABLED", True), + patch.object( + FlashpointHandler, + "_request", + new_callable=AsyncMock, + side_effect=HTTPException(status_code=503, detail="down"), + ), + pytest.raises(HTTPException), + ): + await handler.get_rom_by_id("dc1f7d99-9a3d-4f3f-8f2a-000000000000") diff --git a/backend/tests/handler/metadata/test_hltb_handler.py b/backend/tests/handler/metadata/test_hltb_handler.py index 8510b79ed..af13d130c 100644 --- a/backend/tests/handler/metadata/test_hltb_handler.py +++ b/backend/tests/handler/metadata/test_hltb_handler.py @@ -828,3 +828,20 @@ async def test_an_unrelated_json_script_is_not_mistaken_for_the_payload( await handler.get_rom_by_id(7169) assert exc_info.value.status_code == status.HTTP_502_BAD_GATEWAY + + +@pytest.mark.asyncio +async def test_search_games_propagates_an_unreachable_hltb(): + """A failed search has to stay distinguishable from a term with no hits.""" + handler = _handler() + + with ( + patch.object( + handler, + "_request", + new_callable=AsyncMock, + side_effect=HTTPException(status_code=503, detail="down"), + ), + pytest.raises(HTTPException), + ): + await handler.search_games("Chrono Trigger", "snes") diff --git a/backend/tests/handler/metadata/test_pouet_handler.py b/backend/tests/handler/metadata/test_pouet_handler.py index 85713f038..2bc027dfc 100644 --- a/backend/tests/handler/metadata/test_pouet_handler.py +++ b/backend/tests/handler/metadata/test_pouet_handler.py @@ -3,6 +3,7 @@ from unittest.mock import AsyncMock, patch import pytest +from fastapi import HTTPException from handler.metadata.pouet_handler import ( PouetHandler, @@ -143,3 +144,20 @@ async def test_get_rom_uses_filename_tag(): assert "id=99" in req.await_args_list[0].args[0] assert result["pouet_id"] == 99 assert result["name"] == "State of the Art" + + +@pytest.mark.asyncio +async def test_get_rom_by_id_propagates_an_unreachable_pouet(): + """A dead connection has to stay distinguishable from a missing production.""" + handler = PouetHandler() + with ( + patch.object(PouetHandler, "is_enabled", return_value=True), + patch.object( + PouetHandler, + "_request", + new_callable=AsyncMock, + side_effect=HTTPException(status_code=503, detail="down"), + ), + pytest.raises(HTTPException), + ): + await handler.get_rom_by_id(99) diff --git a/backend/tests/handler/metadata/test_sgdb_handler.py b/backend/tests/handler/metadata/test_sgdb_handler.py index d35e6b044..d4a389e07 100644 --- a/backend/tests/handler/metadata/test_sgdb_handler.py +++ b/backend/tests/handler/metadata/test_sgdb_handler.py @@ -134,3 +134,36 @@ class TestGetDetailsContentFilters: assert kwargs["is_nsfw"] == "any" assert kwargs["is_humor"] == "any" assert kwargs["is_epilepsy"] == "any" + + +class TestLookupFailures: + @pytest.mark.asyncio + async def test_get_details_by_names_propagates_an_unreachable_sgdb(self): + """A failed lookup has to stay distinguishable from a name with no art.""" + handler = SGDBBaseHandler() + + with ( + patch.object( + handler.sgdb_service, + "search_games", + AsyncMock(side_effect=RuntimeError("SteamGridDB is down")), + ), + patch.object(SGDBBaseHandler, "is_enabled", return_value=True), + pytest.raises(RuntimeError), + ): + await handler.get_details_by_names(["Test Game"]) + + @pytest.mark.asyncio + async def test_get_rom_by_id_propagates_an_unreachable_sgdb(self): + handler = SGDBBaseHandler() + + with ( + patch.object( + handler.sgdb_service, + "get_game_by_id", + AsyncMock(side_effect=RuntimeError("SteamGridDB is down")), + ), + patch.object(SGDBBaseHandler, "is_enabled", return_value=True), + pytest.raises(RuntimeError), + ): + await handler.get_rom_by_id(7) diff --git a/backend/tests/handler/test_scan_complete_rescan_ids.py b/backend/tests/handler/test_scan_complete_rescan_ids.py index c4fbfb874..72138cb01 100644 --- a/backend/tests/handler/test_scan_complete_rescan_ids.py +++ b/backend/tests/handler/test_scan_complete_rescan_ids.py @@ -4,15 +4,22 @@ A complete rescan is documented as wiping every match and rematching from scratch, but `add_rom` merges, and merge skips attributes the object doesn't carry. An ID therefore only resets when the scan writes it out as NULL, which it did for deselected sources but not for the ones it actually searched. (#4346) + +The flip side matters just as much: a provider that failed answered nothing, so +its ID has to survive. Several report an outage as an empty match, which a +rescan would otherwise read as "this game is gone". """ from unittest.mock import AsyncMock, patch import pytest +from fastapi import HTTPException from handler.database import db_platform_handler, db_rom_handler from handler.metadata.igdb_handler import IGDBRom +from handler.metadata.pouet_handler import PouetRom from handler.metadata.sgdb_handler import SGDBRom +from handler.metadata.ss_handler import SSRom from handler.scan_handler import MetadataSource, ScanType, scan_rom from models.platform import Platform from models.rom import Rom @@ -22,17 +29,29 @@ FS_NAME = "Some Homebrew Thing (Aftermarket).z64" STALE_IGDB_ID = 1289 STALE_MOBY_ID = 42 STALE_SGDB_ID = 777 +STALE_POUET_ID = 106640 +STALE_SS_ID = 314 MISS = IGDBRom(igdb_id=None) MATCH = IGDBRom(igdb_id=9999, name="A Real Game") +UNREACHABLE = HTTPException(status_code=503, detail="provider is down") + + +def _lookup(result): + """A provider lookup that answers with `result`, or fails when it is one.""" + if isinstance(result, Exception): + return AsyncMock(side_effect=result) + return AsyncMock(return_value=result) async def _complete_rescan( sources: list[str], *, igdb_result: IGDBRom | Exception = MISS, - sgdb_result: SGDBRom | None = None, + sgdb_result: SGDBRom | Exception | None = None, + pouet_result: PouetRom | Exception | None = None, platform_igdb_id: int | None = 4, + ss_breaker_tripped: bool = False, ) -> Rom: """Run a complete rescan over a ROM carrying hand-set IDs, and persist it.""" platform = db_platform_handler.add_platform( @@ -42,6 +61,7 @@ async def _complete_rescan( fs_slug="n64", name="Nintendo 64", igdb_id=platform_igdb_id, + ss_id=14, ) ) rom = db_rom_handler.add_rom( @@ -57,22 +77,35 @@ async def _complete_rescan( igdb_metadata={"total_rating": "9"}, moby_id=STALE_MOBY_ID, sgdb_id=STALE_SGDB_ID, + pouet_id=STALE_POUET_ID, + ss_id=STALE_SS_ID, fs_size_bytes=1024, tags=[], ) ) - igdb_mock = ( - AsyncMock(side_effect=igdb_result) - if isinstance(igdb_result, Exception) - else AsyncMock(return_value=igdb_result) - ) + igdb_mock = _lookup(igdb_result) + pouet_mock = _lookup(pouet_result or PouetRom(pouet_id=None)) with ( patch("handler.scan_handler.meta_igdb_handler.get_rom", new=igdb_mock), patch("handler.scan_handler.meta_igdb_handler.get_rom_by_id", new=igdb_mock), patch( "handler.scan_handler.meta_sgdb_handler.get_details_by_names", - new=AsyncMock(return_value=sgdb_result or SGDBRom(sgdb_id=None)), + new=_lookup(sgdb_result or SGDBRom(sgdb_id=None)), + ), + patch("handler.scan_handler.meta_pouet_handler.get_rom", new=pouet_mock), + patch("handler.scan_handler.meta_pouet_handler.get_rom_by_id", new=pouet_mock), + patch( + "handler.scan_handler.meta_ss_handler.lookup_rom", + new=AsyncMock(return_value=(SSRom(ss_id=None), False)), + ), + patch( + "handler.scan_handler.meta_ss_handler.get_rom", + new=AsyncMock(return_value=SSRom(ss_id=None)), + ), + patch( + "handler.scan_handler.is_breaker_tripped", + return_value=ss_breaker_tripped, ), ): async with initialize_context(): @@ -125,6 +158,30 @@ async def test_a_source_that_fails_keeps_its_id(): assert saved.igdb_id == STALE_IGDB_ID +async def test_a_source_that_could_not_be_reached_keeps_its_id(): + """Pouët reports an outage as an empty match, so the handler has to raise.""" + saved = await _complete_rescan( + [MetadataSource.IGDB, MetadataSource.POUET], pouet_result=UNREACHABLE + ) + + assert saved.pouet_id == STALE_POUET_ID + + +async def test_a_screenscraper_breaker_keeps_its_id(): + """An exhausted quota answers empty for every remaining ROM.""" + saved = await _complete_rescan( + [MetadataSource.IGDB, MetadataSource.SS], ss_breaker_tripped=True + ) + + assert saved.ss_id == STALE_SS_ID + + +async def test_a_selected_screenscraper_that_misses_still_drops_its_id(): + saved = await _complete_rescan([MetadataSource.IGDB, MetadataSource.SS]) + + assert saved.ss_id is None + + async def test_a_deselected_source_still_drops_its_id(): saved = await _complete_rescan([MetadataSource.IGDB]) @@ -140,6 +197,16 @@ async def test_steamgriddb_drops_its_stale_id_after_a_miss(): assert saved.sgdb_id is None +async def test_steamgriddb_keeps_its_stale_id_when_it_could_not_be_reached(): + saved = await _complete_rescan( + [MetadataSource.IGDB, MetadataSource.SGDB], + igdb_result=MATCH, + sgdb_result=UNREACHABLE, + ) + + assert saved.sgdb_id == STALE_SGDB_ID + + @pytest.mark.parametrize( "scan_type", [ScanType.QUICK, ScanType.UPDATE, ScanType.UNMATCHED] ) From 8b2931a56d27b2f1dc1d6f74aeb3a1cc36801827 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Fri, 4 Sep 2026 20:58:18 -0400 Subject: [PATCH 3/5] fix(scan): don't let a Hasheous outage read as a conclusive miss `_request` swallowed a non-404 HTTP error and a timeout into an empty dict, which `lookup_rom` then reported as conclusive: Hasheous answered and knows nothing about these hashes. A 500 or a timeout therefore de-verified a rom on a rehash and cleared its id on a complete rescan. Both paths now raise, so the conclusive flag already carried by `lookup_rom` tells the two empty matches apart on its own. Co-Authored-By: Claude Opus 5 (1M context) --- backend/handler/metadata/hasheous_handler.py | 22 +++++----- .../handler/metadata/test_hasheous_handler.py | 40 ++++++++++++++++++- 2 files changed, 52 insertions(+), 10 deletions(-) diff --git a/backend/handler/metadata/hasheous_handler.py b/backend/handler/metadata/hasheous_handler.py index cbdb42bb9..5d81fad58 100644 --- a/backend/handler/metadata/hasheous_handler.py +++ b/backend/handler/metadata/hasheous_handler.py @@ -126,6 +126,14 @@ def extract_metadata_from_igdb_rom(rom: dict[str, Any]) -> IGDBMetadata: ) +def _unavailable() -> HTTPException: + """The error every unreachable-Hasheous path raises.""" + return HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail="Can't connect to Hasheous, check your internet connection", + ) + + class HasheousHandler(MetadataHandler): def __init__(self) -> None: self.BASE_URL = HASHEOUS_API_URL @@ -222,21 +230,17 @@ class HasheousHandler(MetadataHandler): exc.response.status_code, exc.response.text, ) - pass + raise _unavailable() from exc except httpx.NetworkError as exc: log.critical("Connection error: can't connect to Hasheous") - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Can't connect to Hasheous, check your internet connection", - ) from exc + raise _unavailable() from exc except json.decoder.JSONDecodeError as exc: # Log the error and return an empty dict if the response is not valid JSON log.error(exc) return {} - except httpx.TimeoutException: - pass - - return {} + except httpx.TimeoutException as exc: + log.error("Hasheous API timed out: %s", exc) + raise _unavailable() from exc def get_platform(self, slug: str) -> HasheousPlatform: if slug not in HASHEOUS_PLATFORM_LIST: diff --git a/backend/tests/handler/metadata/test_hasheous_handler.py b/backend/tests/handler/metadata/test_hasheous_handler.py index 048858abd..b49dd7699 100644 --- a/backend/tests/handler/metadata/test_hasheous_handler.py +++ b/backend/tests/handler/metadata/test_hasheous_handler.py @@ -1,4 +1,13 @@ -from handler.metadata.hasheous_handler import extract_metadata_from_igdb_rom +from unittest.mock import AsyncMock, patch + +import httpx +import pytest +from fastapi import HTTPException + +from handler.metadata.hasheous_handler import ( + HasheousHandler, + extract_metadata_from_igdb_rom, +) # The proxy keys expanded collections by id and returns `company` as a bare id, # unlike IGDB's own list-of-objects shape. @@ -37,3 +46,32 @@ def test_involvements_are_optional(): assert metadata["publishers"] == [] assert metadata["developers"] == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "failure", + [ + httpx.HTTPStatusError( + "boom", + request=httpx.Request("POST", "https://hasheous.org/api"), + response=httpx.Response( + 500, request=httpx.Request("POST", "https://hasheous.org/api") + ), + ), + httpx.TimeoutException("too slow"), + ], + ids=["server_error", "timeout"], +) +async def test_request_propagates_an_unreachable_hasheous(failure: Exception): + """A failed request has to stay distinguishable from a game Hasheous lacks.""" + handler = HasheousHandler() + client = AsyncMock() + client.request = AsyncMock(side_effect=failure) + + with ( + patch("handler.metadata.hasheous_handler.ctx_httpx_client") as ctx, + pytest.raises(HTTPException), + ): + ctx.get.return_value = client + await handler._request("https://hasheous.org/api") From 3b2a9e304304cc4c5cab5220da8298d5aa9c49b8 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Fri, 4 Sep 2026 20:58:27 -0400 Subject: [PATCH 4/5] refactor(scan): share one failure path across the provider lookups Every gathered provider already resolved through a single loop that logs the failure, drops the source from the attempted set and falls back to an empty match. SteamGridDB, which searches on the names the other providers produce and so cannot join that gather, hand-wrote the same three steps again, and the search endpoint hand-wrote a third copy. Extract the loop body into `resolve_fetch` and route SteamGridDB through it. In the search endpoint the cover gathers now tolerate exceptions instead, so a failed lookup costs a thumbnail rather than the whole result set. That also covers Libretro, whose lookup had no guard at all and could fail the request. On the test side, the platform, rom and `fs_rom` scaffolding was written out three times across the two scan tests; it now lives in `tests/handler/scan_stubs.py`. Co-Authored-By: Claude Opus 5 (1M context) --- backend/adapters/services/screenscraper.py | 6 +- backend/endpoints/search.py | 38 ++-- backend/handler/metadata/pouet_handler.py | 6 +- backend/handler/metadata/sgdb_handler.py | 7 +- backend/handler/scan_handler.py | 65 +++---- backend/tests/handler/scan_stubs.py | 61 +++++++ .../handler/test_scan_complete_rescan_ids.py | 165 +++++------------- backend/tests/handler/test_scan_hltb_match.py | 51 ++---- 8 files changed, 179 insertions(+), 220 deletions(-) create mode 100644 backend/tests/handler/scan_stubs.py diff --git a/backend/adapters/services/screenscraper.py b/backend/adapters/services/screenscraper.py index 20e781dad..90192b1ce 100644 --- a/backend/adapters/services/screenscraper.py +++ b/backend/adapters/services/screenscraper.py @@ -225,11 +225,7 @@ def is_daily_quota_exhausted() -> bool: def is_breaker_tripped() -> bool: - """Whether a breaker has taken ScreenScraper out for the rest of this scan. - - The lookups answer empty once one trips, which a caller must not read as - "ScreenScraper has nothing for this ROM". - """ + """Whether a breaker has taken ScreenScraper out for the rest of this scan.""" return _state.daily_quota_exhausted or _state.credentials_rejected is not None diff --git a/backend/endpoints/search.py b/backend/endpoints/search.py index 3216b8431..207df6280 100644 --- a/backend/endpoints/search.py +++ b/backend/endpoints/search.py @@ -1,4 +1,5 @@ import asyncio +from typing import TypeVar from fastapi import HTTPException, Request, status @@ -37,12 +38,27 @@ from logger.logger import log from utils import emoji from utils.router import APIRouter +_CoverRomT = TypeVar("_CoverRomT", SGDBRom, LibretroRom) + router = APIRouter( prefix="/search", tags=["search"], ) +def _fetched_covers( + results: list[tuple[str, _CoverRomT] | BaseException], provider: str +) -> list[tuple[str, _CoverRomT]]: + """Drop the cover lookups that failed, keeping the ones that answered.""" + fetched = [] + for result in results: + if isinstance(result, BaseException): + log.error("Error fetching %s covers: %s", provider, result) + else: + fetched.append(result) + return fetched + + @protected_route(router.get, "/roms", [Scope.ROMS_READ]) async def search_rom( request: Request, @@ -220,24 +236,24 @@ async def search_rom( } async def get_sgdb_rom(name: str) -> tuple[str, SGDBRom]: - # Cover art on top of matches the other providers already produced, so - # an unreachable SteamGridDB costs a thumbnail rather than the results. - try: - return name, await meta_sgdb_handler.get_details_by_names([name]) - except Exception as exc: - log.error("Error fetching SteamGridDB covers for '%s': %s", name, exc) - return name, SGDBRom(sgdb_id=None) + return name, await meta_sgdb_handler.get_details_by_names([name]) async def get_libretro_rom(name: str) -> tuple[str, LibretroRom]: return name, await meta_libretro_handler.get_rom(name, rom.platform.slug) + # These two only add cover art to matches the other providers already + # produced, so an unreachable one costs a thumbnail rather than the results. merged_names = list(merged_dict.keys()) sgdb_roms, libretro_roms = await asyncio.gather( - asyncio.gather(*[get_sgdb_rom(name) for name in merged_names]), - asyncio.gather(*[get_libretro_rom(name) for name in merged_names]), + asyncio.gather( + *[get_sgdb_rom(name) for name in merged_names], return_exceptions=True + ), + asyncio.gather( + *[get_libretro_rom(name) for name in merged_names], return_exceptions=True + ), ) - for name, sgdb_rom in sgdb_roms: + for name, sgdb_rom in _fetched_covers(sgdb_roms, "SteamGridDB"): if sgdb_rom["sgdb_id"]: merged_dict[name] = { **merged_dict[name], @@ -245,7 +261,7 @@ async def search_rom( "sgdb_url_cover": sgdb_rom.get("url_cover", ""), } - for name, libretro_rom in libretro_roms: + for name, libretro_rom in _fetched_covers(libretro_roms, "Libretro"): if libretro_rom["libretro_id"]: merged_dict[name] = { **merged_dict[name], diff --git a/backend/handler/metadata/pouet_handler.py b/backend/handler/metadata/pouet_handler.py index 7e6caeb72..c10da251d 100644 --- a/backend/handler/metadata/pouet_handler.py +++ b/backend/handler/metadata/pouet_handler.py @@ -297,11 +297,7 @@ def production_to_rom(prod: dict[str, Any]) -> PouetRom: def _unavailable() -> HTTPException: - """The error every unreachable-Pouët path raises. - - A scan reads an empty match as "this production is gone" and drops the id it - had, so a lookup that failed must not answer with one. - """ + """The error every unreachable-Pouët path raises.""" return HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Can't connect to Pouët API, check your internet connection", diff --git a/backend/handler/metadata/sgdb_handler.py b/backend/handler/metadata/sgdb_handler.py index 16165202b..f723ff591 100644 --- a/backend/handler/metadata/sgdb_handler.py +++ b/backend/handler/metadata/sgdb_handler.py @@ -111,12 +111,7 @@ class SGDBBaseHandler(MetadataHandler): return list(filter(None, results)) async def get_details_by_names(self, game_names: list[str]) -> SGDBRom: - """Get ROM details by candidate game names. - - Raises when the lookup fails, so a caller can tell an unreachable - SteamGridDB from a name it has no art for. Callers that would rather - carry on than fail decide that for themselves. - """ + """Get ROM details by candidate game names, raising when the lookup fails.""" if not self.is_enabled(): return SGDBRom(sgdb_id=None) diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 0d11e04ca..dcc17cb81 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -604,6 +604,22 @@ async def scan_rom( # no id for it never enters the set, so a rescan can't clear what it can't redo. attempted_sources: set[MetadataSource] = set() + def resolve_fetch(source: MetadataSource, result: Any, fallback: Any) -> Any: + """Unwrap a gathered lookup, falling back to an empty match when it failed.""" + if not isinstance(result, BaseException): + return result + if not isinstance(result, Exception): + raise result + + # A provider that blew up ruled nothing out, so it no longer counts as + # attempted and a complete rescan keeps the id it already had. + attempted_sources.discard(source) + log.error( + f"Error fetching {hl(source)} metadata for {hl(rom_attrs['fs_name'])}: {result}", + extra=LOGGER_MODULE_NAME, + ) + return fallback + @functools.cache def get_match_files() -> list[RomFile]: """Files used for hash-based metadata matching, fetched at most once.""" @@ -1141,23 +1157,12 @@ async def scan_rom( *(coro for _, coro, _ in provider_fetches), return_exceptions=True ) - resolved: list[Any] = [] - for (source, _, fallback), result in zip( - provider_fetches, fetch_results, strict=True - ): - if isinstance(result, BaseException): - if not isinstance(result, Exception): - raise result - # A provider that blew up ruled nothing out, so it no longer counts - # as attempted and a complete rescan keeps the id it already had. - attempted_sources.discard(source) - log.error( - f"Error fetching {hl(source)} metadata for {hl(rom_attrs['fs_name'])}: {result}", - extra=LOGGER_MODULE_NAME, - ) - resolved.append(fallback) - else: - resolved.append(result) + resolved: list[Any] = [ + resolve_fetch(source, result, fallback) + for (source, _, fallback), result in zip( + provider_fetches, fetch_results, strict=True + ) + ] # Once a ScreenScraper breaker trips, the remaining lookups answer empty # without asking, so it has ruled nothing out for this rom either. @@ -1526,16 +1531,18 @@ async def scan_rom( return SGDBRom(sgdb_id=None) - try: - sgdb_hander_rom = await fetch_sgdb_details(playmatch_hash_match) - except Exception as exc: - # A failure ruled nothing out, so the id the rom already had stands. - attempted_sources.discard(MetadataSource.SGDB) - log.error( - f"Error fetching {hl(MetadataSource.SGDB)} metadata for {hl(rom_attrs['fs_name'])}: {exc}", - extra=LOGGER_MODULE_NAME, - ) - sgdb_hander_rom = SGDBRom(sgdb_id=None) + # SteamGridDB searches on the names the other providers just produced, so it + # can't join the gather above, but it resolves the same way. + (sgdb_result,) = await asyncio.gather( + fetch_sgdb_details(playmatch_hash_match), return_exceptions=True + ) + sgdb_hander_rom = resolve_fetch( + MetadataSource.SGDB, sgdb_result, SGDBRom(sgdb_id=None) + ) + + # Resolving this late means missing the reset block above, so clear its id here. + if is_complete_rescan and MetadataSource.SGDB in attempted_sources: + rom_attrs["sgdb_id"] = None if sgdb_hander_rom.get("sgdb_id"): rom_attrs["sgdb_id"] = sgdb_hander_rom["sgdb_id"] @@ -1555,10 +1562,6 @@ async def scan_rom( ) if ranked[0] == MetadataSource.SGDB: rom_attrs["url_cover"] = sgdb_cover - elif is_complete_rescan and MetadataSource.SGDB in attempted_sources: - # SteamGridDB resolves after the reset block above, so it has to clear - # its own stale id when its lookup came back empty. - rom_attrs["sgdb_id"] = None log.info( f"{hl(rom_attrs['fs_name'])} identified as {hl(rom_attrs['name'], color=BLUE)} {emoji.EMOJI_ALIEN_MONSTER}", diff --git a/backend/tests/handler/scan_stubs.py b/backend/tests/handler/scan_stubs.py new file mode 100644 index 000000000..b842eb630 --- /dev/null +++ b/backend/tests/handler/scan_stubs.py @@ -0,0 +1,61 @@ +"""Scaffolding shared by the tests that drive `scan_rom` end to end.""" + +from typing import Any + +from handler.database import db_platform_handler, db_rom_handler +from handler.scan_handler import ScanType, scan_rom +from models.platform import Platform +from models.rom import Rom +from utils.context import initialize_context + + +def add_n64_platform(**overrides: Any) -> Platform: + """Persist the N64 platform the scan tests match against.""" + return db_platform_handler.add_platform( + Platform(id=1, slug="n64", fs_slug="n64", name="Nintendo 64", **overrides) + ) + + +def add_rom(platform: Platform, fs_name: str, title: str, **overrides: Any) -> Rom: + """Persist a single-file ROM whose filename tags are already split out.""" + stem, _, extension = fs_name.rpartition(".") + attrs: dict[str, Any] = { + "platform_id": platform.id, + "fs_name": fs_name, + "fs_name_no_tags": title, + "fs_name_no_ext": stem, + "fs_extension": extension, + "fs_path": platform.fs_slug, + "name": title, + "fs_size_bytes": 1024, + "tags": [], + } + return db_rom_handler.add_rom(Rom(**{**attrs, **overrides})) + + +async def run_scan( + platform: Platform, + rom: Rom, + *, + scan_type: ScanType, + metadata_sources: list[str], +) -> Rom: + """Scan `rom` with no files on disk, so only the name-based lookups run.""" + async with initialize_context(): + return await scan_rom( + platform=platform, + scan_type=scan_type, + rom=rom, + fs_rom={ + "fs_name": rom.fs_name, + "flat": True, + "nested": False, + "files": [], + "crc_hash": "", + "md5_hash": "", + "sha1_hash": "", + "ra_hash": "", + }, + metadata_sources=metadata_sources, + newly_added=False, + ) diff --git a/backend/tests/handler/test_scan_complete_rescan_ids.py b/backend/tests/handler/test_scan_complete_rescan_ids.py index 72138cb01..fa6d51858 100644 --- a/backend/tests/handler/test_scan_complete_rescan_ids.py +++ b/backend/tests/handler/test_scan_complete_rescan_ids.py @@ -1,29 +1,22 @@ -"""What a complete rescan does to a ROM's external IDs. +"""What a scan does to a ROM's external IDs. -A complete rescan is documented as wiping every match and rematching from -scratch, but `add_rom` merges, and merge skips attributes the object doesn't -carry. An ID therefore only resets when the scan writes it out as NULL, which -it did for deselected sources but not for the ones it actually searched. (#4346) - -The flip side matters just as much: a provider that failed answered nothing, so -its ID has to survive. Several report an outage as an empty match, which a -rescan would otherwise read as "this game is gone". +A complete rescan clears every ID it could rematch; a provider that failed +answered nothing, so the ID it could not check has to survive. """ from unittest.mock import AsyncMock, patch import pytest from fastapi import HTTPException +from tests.handler.scan_stubs import add_n64_platform, add_rom, run_scan -from handler.database import db_platform_handler, db_rom_handler +from handler.database import db_rom_handler from handler.metadata.igdb_handler import IGDBRom from handler.metadata.pouet_handler import PouetRom from handler.metadata.sgdb_handler import SGDBRom from handler.metadata.ss_handler import SSRom -from handler.scan_handler import MetadataSource, ScanType, scan_rom -from models.platform import Platform +from handler.scan_handler import MetadataSource, ScanType from models.rom import Rom -from utils.context import initialize_context FS_NAME = "Some Homebrew Thing (Aftermarket).z64" STALE_IGDB_ID = 1289 @@ -33,6 +26,8 @@ STALE_POUET_ID = 106640 STALE_SS_ID = 314 MISS = IGDBRom(igdb_id=None) +SGDB_MISS = SGDBRom(sgdb_id=None) +POUET_MISS = PouetRom(pouet_id=None) MATCH = IGDBRom(igdb_id=9999, name="A Real Game") UNREACHABLE = HTTPException(status_code=503, detail="provider is down") @@ -44,54 +39,39 @@ def _lookup(result): return AsyncMock(return_value=result) -async def _complete_rescan( +async def _rescan( sources: list[str], *, + scan_type: ScanType = ScanType.COMPLETE, igdb_result: IGDBRom | Exception = MISS, - sgdb_result: SGDBRom | Exception | None = None, - pouet_result: PouetRom | Exception | None = None, + sgdb_result: SGDBRom | Exception = SGDB_MISS, + pouet_result: PouetRom | Exception = POUET_MISS, platform_igdb_id: int | None = 4, ss_breaker_tripped: bool = False, ) -> Rom: - """Run a complete rescan over a ROM carrying hand-set IDs, and persist it.""" - platform = db_platform_handler.add_platform( - Platform( - id=1, - slug="n64", - fs_slug="n64", - name="Nintendo 64", - igdb_id=platform_igdb_id, - ss_id=14, - ) - ) - rom = db_rom_handler.add_rom( - Rom( - platform_id=platform.id, - fs_name=FS_NAME, - fs_name_no_tags="Some Homebrew Thing", - fs_name_no_ext="Some Homebrew Thing (Aftermarket)", - fs_extension="z64", - fs_path="n64", - name="Wrong Match", - igdb_id=STALE_IGDB_ID, - igdb_metadata={"total_rating": "9"}, - moby_id=STALE_MOBY_ID, - sgdb_id=STALE_SGDB_ID, - pouet_id=STALE_POUET_ID, - ss_id=STALE_SS_ID, - fs_size_bytes=1024, - tags=[], - ) + """Rescan a ROM carrying hand-set IDs, and persist the result.""" + platform = add_n64_platform(igdb_id=platform_igdb_id, ss_id=14) + rom = add_rom( + platform, + FS_NAME, + "Some Homebrew Thing", + name="Wrong Match", + igdb_id=STALE_IGDB_ID, + igdb_metadata={"total_rating": "9"}, + moby_id=STALE_MOBY_ID, + sgdb_id=STALE_SGDB_ID, + pouet_id=STALE_POUET_ID, + ss_id=STALE_SS_ID, ) igdb_mock = _lookup(igdb_result) - pouet_mock = _lookup(pouet_result or PouetRom(pouet_id=None)) + pouet_mock = _lookup(pouet_result) with ( patch("handler.scan_handler.meta_igdb_handler.get_rom", new=igdb_mock), patch("handler.scan_handler.meta_igdb_handler.get_rom_by_id", new=igdb_mock), patch( "handler.scan_handler.meta_sgdb_handler.get_details_by_names", - new=_lookup(sgdb_result or SGDBRom(sgdb_id=None)), + new=_lookup(sgdb_result), ), patch("handler.scan_handler.meta_pouet_handler.get_rom", new=pouet_mock), patch("handler.scan_handler.meta_pouet_handler.get_rom_by_id", new=pouet_mock), @@ -108,50 +88,35 @@ async def _complete_rescan( return_value=ss_breaker_tripped, ), ): - async with initialize_context(): - scanned = await scan_rom( - platform=platform, - scan_type=ScanType.COMPLETE, - rom=rom, - fs_rom={ - "fs_name": FS_NAME, - "flat": True, - "nested": False, - "files": [], - "crc_hash": "", - "md5_hash": "", - "sha1_hash": "", - "ra_hash": "", - }, - metadata_sources=sources, - newly_added=False, - ) + scanned = await run_scan( + platform, rom, scan_type=scan_type, metadata_sources=sources + ) return db_rom_handler.add_rom(scanned) async def test_a_searched_source_that_misses_drops_its_stale_id(): - saved = await _complete_rescan([MetadataSource.IGDB]) + saved = await _rescan([MetadataSource.IGDB]) assert saved.igdb_id is None assert saved.igdb_metadata == {} async def test_a_searched_source_that_matches_stores_the_new_id(): - saved = await _complete_rescan([MetadataSource.IGDB], igdb_result=MATCH) + saved = await _rescan([MetadataSource.IGDB], igdb_result=MATCH) assert saved.igdb_id == 9999 async def test_a_source_the_platform_cannot_use_keeps_its_id(): """No `platform.igdb_id` means IGDB never ran, so it rules nothing out.""" - saved = await _complete_rescan([MetadataSource.IGDB], platform_igdb_id=None) + saved = await _rescan([MetadataSource.IGDB], platform_igdb_id=None) assert saved.igdb_id == STALE_IGDB_ID async def test_a_source_that_fails_keeps_its_id(): - saved = await _complete_rescan( + saved = await _rescan( [MetadataSource.IGDB], igdb_result=RuntimeError("IGDB is down") ) @@ -160,7 +125,7 @@ async def test_a_source_that_fails_keeps_its_id(): async def test_a_source_that_could_not_be_reached_keeps_its_id(): """Pouët reports an outage as an empty match, so the handler has to raise.""" - saved = await _complete_rescan( + saved = await _rescan( [MetadataSource.IGDB, MetadataSource.POUET], pouet_result=UNREACHABLE ) @@ -169,7 +134,7 @@ async def test_a_source_that_could_not_be_reached_keeps_its_id(): async def test_a_screenscraper_breaker_keeps_its_id(): """An exhausted quota answers empty for every remaining ROM.""" - saved = await _complete_rescan( + saved = await _rescan( [MetadataSource.IGDB, MetadataSource.SS], ss_breaker_tripped=True ) @@ -177,28 +142,26 @@ async def test_a_screenscraper_breaker_keeps_its_id(): async def test_a_selected_screenscraper_that_misses_still_drops_its_id(): - saved = await _complete_rescan([MetadataSource.IGDB, MetadataSource.SS]) + saved = await _rescan([MetadataSource.IGDB, MetadataSource.SS]) assert saved.ss_id is None async def test_a_deselected_source_still_drops_its_id(): - saved = await _complete_rescan([MetadataSource.IGDB]) + saved = await _rescan([MetadataSource.IGDB]) assert saved.moby_id is None async def test_steamgriddb_drops_its_stale_id_after_a_miss(): """SteamGridDB resolves after the reset, so it clears its own ID.""" - saved = await _complete_rescan( - [MetadataSource.IGDB, MetadataSource.SGDB], igdb_result=MATCH - ) + saved = await _rescan([MetadataSource.IGDB, MetadataSource.SGDB], igdb_result=MATCH) assert saved.sgdb_id is None async def test_steamgriddb_keeps_its_stale_id_when_it_could_not_be_reached(): - saved = await _complete_rescan( + saved = await _rescan( [MetadataSource.IGDB, MetadataSource.SGDB], igdb_result=MATCH, sgdb_result=UNREACHABLE, @@ -212,50 +175,6 @@ async def test_steamgriddb_keeps_its_stale_id_when_it_could_not_be_reached(): ) async def test_only_a_complete_rescan_drops_ids(scan_type: ScanType): """Every other scan type carries the existing IDs forward untouched.""" - platform = db_platform_handler.add_platform( - Platform(id=1, slug="n64", fs_slug="n64", name="Nintendo 64", igdb_id=4) - ) - rom = db_rom_handler.add_rom( - Rom( - platform_id=platform.id, - fs_name=FS_NAME, - fs_name_no_tags="Some Homebrew Thing", - fs_name_no_ext="Some Homebrew Thing (Aftermarket)", - fs_extension="z64", - fs_path="n64", - name="Wrong Match", - igdb_id=STALE_IGDB_ID, - fs_size_bytes=1024, - tags=[], - ) - ) - with ( - patch( - "handler.scan_handler.meta_igdb_handler.get_rom", - new=AsyncMock(return_value=MISS), - ), - patch( - "handler.scan_handler.meta_igdb_handler.get_rom_by_id", - new=AsyncMock(return_value=MISS), - ), - ): - async with initialize_context(): - scanned = await scan_rom( - platform=platform, - scan_type=scan_type, - rom=rom, - fs_rom={ - "fs_name": FS_NAME, - "flat": True, - "nested": False, - "files": [], - "crc_hash": "", - "md5_hash": "", - "sha1_hash": "", - "ra_hash": "", - }, - metadata_sources=[MetadataSource.IGDB], - newly_added=False, - ) + saved = await _rescan([MetadataSource.IGDB], scan_type=scan_type) - assert db_rom_handler.add_rom(scanned).igdb_id == STALE_IGDB_ID + assert saved.igdb_id == STALE_IGDB_ID diff --git a/backend/tests/handler/test_scan_hltb_match.py b/backend/tests/handler/test_scan_hltb_match.py index dfbbcc276..dad05c6c1 100644 --- a/backend/tests/handler/test_scan_hltb_match.py +++ b/backend/tests/handler/test_scan_hltb_match.py @@ -8,13 +8,11 @@ from types import SimpleNamespace from unittest.mock import AsyncMock, patch import pytest +from tests.handler.scan_stubs import add_n64_platform, add_rom, run_scan -from handler.database import db_platform_handler, db_rom_handler from handler.metadata.hltb_handler import HLTBMetadata, HLTBRom -from handler.scan_handler import MetadataSource, ScanType, scan_rom -from models.platform import Platform +from handler.scan_handler import MetadataSource, ScanType from models.rom import Rom -from utils.context import initialize_context FS_NAME = "Mario Kart 64 (USA).z64" PINNED = HLTBRom(hltb_id=2255, name="Mario Kart 64") @@ -43,43 +41,18 @@ async def _scan( hltb_id: int | None = None, hltb_metadata: HLTBMetadata | None = None, ) -> Rom: - platform = db_platform_handler.add_platform( - Platform(id=1, slug="n64", fs_slug="n64", name="Nintendo 64") - ) - rom = db_rom_handler.add_rom( - Rom( - platform_id=platform.id, - fs_name=FS_NAME, - fs_name_no_tags="Mario Kart 64", - fs_name_no_ext="Mario Kart 64 (USA)", - fs_extension="z64", - fs_path="n64", - name="Mario Kart 64", - hltb_id=hltb_id, - hltb_metadata=dict(hltb_metadata or {}), - fs_size_bytes=1024, - tags=[], - ) + platform = add_n64_platform() + rom = add_rom( + platform, + FS_NAME, + "Mario Kart 64", + hltb_id=hltb_id, + hltb_metadata=dict(hltb_metadata or {}), ) - async with initialize_context(): - return await scan_rom( - platform=platform, - scan_type=scan_type, - rom=rom, - fs_rom={ - "fs_name": FS_NAME, - "flat": True, - "nested": False, - "files": [], - "crc_hash": "", - "md5_hash": "", - "sha1_hash": "", - "ra_hash": "", - }, - metadata_sources=[MetadataSource.HLTB], - newly_added=False, - ) + return await run_scan( + platform, rom, scan_type=scan_type, metadata_sources=[MetadataSource.HLTB] + ) async def test_no_stored_id_uses_the_file_name_lookup(lookups): From 6dd33538555c9c806d4c7a82be1389272a579d60 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Fri, 4 Sep 2026 21:16:07 -0400 Subject: [PATCH 5/5] refactor(metadata): give the unreachable-provider error one home The same 503 was built inline at seven sites across the metadata handlers, and the previous commits added two more copies of it as per-handler `_unavailable` helpers. `base_handler.unavailable(provider)` now builds it for all of them. Also renames the search endpoint's cover filter to say what it does and types the scan test's lookup factory. Co-Authored-By: Claude Opus 5 (1M context) --- backend/endpoints/search.py | 8 ++++---- backend/handler/metadata/base_handler.py | 10 +++++++++- backend/handler/metadata/csdb_handler.py | 8 ++------ backend/handler/metadata/demozoo_handler.py | 8 ++------ backend/handler/metadata/flashpoint_handler.py | 8 ++------ backend/handler/metadata/hasheous_handler.py | 18 +++++------------- backend/handler/metadata/hltb_handler.py | 12 +++--------- backend/handler/metadata/playmatch_handler.py | 9 +++------ backend/handler/metadata/pouet_handler.py | 15 +++------------ .../handler/test_scan_complete_rescan_ids.py | 3 ++- 10 files changed, 35 insertions(+), 64 deletions(-) diff --git a/backend/endpoints/search.py b/backend/endpoints/search.py index 207df6280..2bcce1d09 100644 --- a/backend/endpoints/search.py +++ b/backend/endpoints/search.py @@ -46,10 +46,10 @@ router = APIRouter( ) -def _fetched_covers( +def _without_failures( results: list[tuple[str, _CoverRomT] | BaseException], provider: str ) -> list[tuple[str, _CoverRomT]]: - """Drop the cover lookups that failed, keeping the ones that answered.""" + """Drop the cover lookups that failed.""" fetched = [] for result in results: if isinstance(result, BaseException): @@ -253,7 +253,7 @@ async def search_rom( ), ) - for name, sgdb_rom in _fetched_covers(sgdb_roms, "SteamGridDB"): + for name, sgdb_rom in _without_failures(sgdb_roms, "SteamGridDB"): if sgdb_rom["sgdb_id"]: merged_dict[name] = { **merged_dict[name], @@ -261,7 +261,7 @@ async def search_rom( "sgdb_url_cover": sgdb_rom.get("url_cover", ""), } - for name, libretro_rom in _fetched_covers(libretro_roms, "Libretro"): + for name, libretro_rom in _without_failures(libretro_roms, "Libretro"): if libretro_rom["libretro_id"]: merged_dict[name] = { **merged_dict[name], diff --git a/backend/handler/metadata/base_handler.py b/backend/handler/metadata/base_handler.py index 74471aca5..e56857a4b 100644 --- a/backend/handler/metadata/base_handler.py +++ b/backend/handler/metadata/base_handler.py @@ -7,6 +7,7 @@ from pathlib import Path from typing import TYPE_CHECKING, Final, Mapping, NotRequired, TypedDict from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse +from fastapi import HTTPException, status from strsimpy.jaro_winkler import JaroWinkler from handler.redis_handler import async_cache @@ -23,7 +24,6 @@ if TYPE_CHECKING: jarowinkler = JaroWinkler() - METADATA_FIXTURES_DIR: Final = Path(__file__).parent / "fixtures" # Providers are third parties; a response is read only this far before it is dropped. @@ -58,6 +58,14 @@ NON_WORD_SPACE_PATTERN = re.compile(r"[^\w\s]") MULTIPLE_SPACE_PATTERN = re.compile(r"\s+") +def unavailable(provider: str) -> HTTPException: + """The error a provider raises when it can't be reached.""" + return HTTPException( + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, + detail=f"Can't connect to {provider}, check your internet connection", + ) + + class BaseRom(TypedDict): name: NotRequired[str] name_sort_key: NotRequired[str | None] diff --git a/backend/handler/metadata/csdb_handler.py b/backend/handler/metadata/csdb_handler.py index 9e07454c1..abddcfad0 100644 --- a/backend/handler/metadata/csdb_handler.py +++ b/backend/handler/metadata/csdb_handler.py @@ -14,14 +14,13 @@ from urllib.parse import parse_qs, urlparse import httpx from defusedxml import ElementTree as ET -from fastapi import HTTPException, status from config import CSDB_API_ENABLED from logger.logger import log from utils import get_version, int_or_none from utils.rate_limiter import RateLimiter -from .base_handler import BaseRom, MetadataHandler +from .base_handler import BaseRom, MetadataHandler, unavailable from .demozoo_handler import build_scene_summary, http_url CSDB_TAG_REGEX = re.compile(r"\(csdb-(\d+)\)", re.IGNORECASE) @@ -180,10 +179,7 @@ class CsdbHandler(MetadataHandler): log.warning( "Can't connect to CSDb webservice", extra={"exception": str(exc)} ) - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Can't connect to CSDb, check your internet connection", - ) from exc + raise unavailable("CSDb") from exc if body is None: return "" return body.decode("utf-8", errors="replace") diff --git a/backend/handler/metadata/demozoo_handler.py b/backend/handler/metadata/demozoo_handler.py index 28eaae3ab..408a002a1 100644 --- a/backend/handler/metadata/demozoo_handler.py +++ b/backend/handler/metadata/demozoo_handler.py @@ -15,7 +15,6 @@ from typing import Any, Final, NotRequired, TypedDict from urllib.parse import parse_qs, urlencode, urlparse import httpx -from fastapi import HTTPException, status from config import DEMOZOO_API_ENABLED from logger.logger import log @@ -23,7 +22,7 @@ from utils import get_version, int_or_none, valid_youtube_id from utils.platform_slugs import UniversalPlatformSlug as UPS from utils.rate_limiter import RateLimiter -from .base_handler import BaseRom, MetadataHandler +from .base_handler import BaseRom, MetadataHandler, unavailable DEMOZOO_TAG_REGEX = re.compile(r"\(demozoo-(\d+)\)", re.IGNORECASE) DEMOZOO_PROD_ID_RE = re.compile( @@ -517,10 +516,7 @@ class DemozooHandler(MetadataHandler): body = await self._fetch_capped(url, headers=headers) except (httpx.HTTPStatusError, httpx.ConnectError, httpx.ReadTimeout) as exc: log.warning("Can't connect to Demozoo API", extra={"exception": str(exc)}) - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Can't connect to Demozoo API, check your internet connection", - ) from exc + raise unavailable("Demozoo API") from exc if body is None: return {} try: diff --git a/backend/handler/metadata/flashpoint_handler.py b/backend/handler/metadata/flashpoint_handler.py index 18e45cd53..19147b544 100644 --- a/backend/handler/metadata/flashpoint_handler.py +++ b/backend/handler/metadata/flashpoint_handler.py @@ -5,7 +5,6 @@ from typing import Final, NotRequired, TypedDict import httpx import pydash import yarl -from fastapi import HTTPException, status from config import FLASHPOINT_API_ENABLED from logger.logger import log @@ -13,7 +12,7 @@ from utils import get_version, is_valid_uuid from utils.context import ctx_httpx_client from utils.platform_slugs import UniversalPlatformSlug as UPS -from .base_handler import MetadataHandler +from .base_handler import MetadataHandler, unavailable class FlashpointPlatform(TypedDict): @@ -147,10 +146,7 @@ class FlashpointHandler(MetadataHandler): log.warning( "Connection error: can't connect to Flashpoint API", exc_info=True ) - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Can't connect to Flashpoint API, check your internet connection", - ) from exc + raise unavailable("Flashpoint API") from exc except json.JSONDecodeError as exc: log.error("Error decoding JSON response from Flashpoint API: %s", exc) return {} diff --git a/backend/handler/metadata/hasheous_handler.py b/backend/handler/metadata/hasheous_handler.py index 5d81fad58..b80052777 100644 --- a/backend/handler/metadata/hasheous_handler.py +++ b/backend/handler/metadata/hasheous_handler.py @@ -5,7 +5,7 @@ from typing import Any, NotRequired, TypedDict import httpx import pydash import yarl -from fastapi import HTTPException, status +from fastapi import status from config import DEV_MODE, HASHEOUS_API_ENABLED, HASHEOUS_API_URL from logger.logger import log @@ -14,7 +14,7 @@ from utils import get_version from utils.context import ctx_httpx_client from utils.platform_slugs import UniversalPlatformSlug as UPS -from .base_handler import BaseRom, MetadataHandler +from .base_handler import BaseRom, MetadataHandler, unavailable from .igdb_handler import ( IGDB_AGE_RATINGS, IGDBMetadata, @@ -126,14 +126,6 @@ def extract_metadata_from_igdb_rom(rom: dict[str, Any]) -> IGDBMetadata: ) -def _unavailable() -> HTTPException: - """The error every unreachable-Hasheous path raises.""" - return HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Can't connect to Hasheous, check your internet connection", - ) - - class HasheousHandler(MetadataHandler): def __init__(self) -> None: self.BASE_URL = HASHEOUS_API_URL @@ -230,17 +222,17 @@ class HasheousHandler(MetadataHandler): exc.response.status_code, exc.response.text, ) - raise _unavailable() from exc + raise unavailable("Hasheous") from exc except httpx.NetworkError as exc: log.critical("Connection error: can't connect to Hasheous") - raise _unavailable() from exc + raise unavailable("Hasheous") from exc except json.decoder.JSONDecodeError as exc: # Log the error and return an empty dict if the response is not valid JSON log.error(exc) return {} except httpx.TimeoutException as exc: log.error("Hasheous API timed out: %s", exc) - raise _unavailable() from exc + raise unavailable("Hasheous") from exc def get_platform(self, slug: str) -> HasheousPlatform: if slug not in HASHEOUS_PLATFORM_LIST: diff --git a/backend/handler/metadata/hltb_handler.py b/backend/handler/metadata/hltb_handler.py index 89b816d71..9a51a76e4 100644 --- a/backend/handler/metadata/hltb_handler.py +++ b/backend/handler/metadata/hltb_handler.py @@ -25,7 +25,7 @@ from utils.hltb_search import ( from utils.platform_slugs import UniversalPlatformSlug as UPS from utils.rate_limiter import RateLimiter -from .base_handler import BaseRom, MetadataHandler +from .base_handler import BaseRom, MetadataHandler, unavailable # Regex to detect HLTB ID tags in filenames like (hltb-12345) HLTB_TAG_REGEX = re.compile(r"\(hltb-(\d+)\)", re.IGNORECASE) @@ -483,10 +483,7 @@ class HLTBHandler(MetadataHandler): "Connection error: can't connect to HowLongToBeat API", exc_info=True, ) - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Can't connect to HowLongToBeat API, check your internet connection", - ) from exc + raise unavailable("HowLongToBeat API") from exc except json.JSONDecodeError as exc: log.error( "Error decoding JSON response from HowLongToBeat API: %s", exc @@ -728,10 +725,7 @@ class HLTBHandler(MetadataHandler): log.warning( "Connection error: can't connect to HowLongToBeat", exc_info=True ) - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Can't connect to HowLongToBeat API, check your internet connection", - ) from exc + raise unavailable("HowLongToBeat API") from exc match = NEXT_DATA_REGEX.search(res.text) if not match: diff --git a/backend/handler/metadata/playmatch_handler.py b/backend/handler/metadata/playmatch_handler.py index 84aef3846..648ca8fc4 100644 --- a/backend/handler/metadata/playmatch_handler.py +++ b/backend/handler/metadata/playmatch_handler.py @@ -6,10 +6,10 @@ from typing import Final, NotRequired, TypedDict import httpx import yarl -from fastapi import HTTPException, status +from fastapi import status from config import PLAYMATCH_API_ENABLED, PLAYMATCH_API_URL -from handler.metadata.base_handler import MetadataHandler +from handler.metadata.base_handler import MetadataHandler, unavailable from logger.logger import log from models.rom import Rom, RomFile from utils import get_version @@ -201,10 +201,7 @@ class PlaymatchHandler(MetadataHandler): log.warning( "Connection error: can't connect to Playmatch", exc_info=True ) - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Can't connect to Playmatch, check your internet connection", - ) from exc + raise unavailable("Playmatch") from exc except json.JSONDecodeError as exc: log.error("Error decoding JSON response from Playmatch: %s", exc) return {} diff --git a/backend/handler/metadata/pouet_handler.py b/backend/handler/metadata/pouet_handler.py index c10da251d..f3c11e550 100644 --- a/backend/handler/metadata/pouet_handler.py +++ b/backend/handler/metadata/pouet_handler.py @@ -13,7 +13,6 @@ from typing import Any, Final, NotRequired, TypedDict from urllib.parse import parse_qs, urlencode, urlparse import httpx -from fastapi import HTTPException, status from config import POUET_API_ENABLED from logger.logger import log @@ -21,7 +20,7 @@ from utils import get_version, int_or_none from utils.context import ctx_httpx_client from utils.rate_limiter import RateLimiter -from .base_handler import BaseRom, MetadataHandler +from .base_handler import BaseRom, MetadataHandler, unavailable from .demozoo_handler import ( DEMOZOO_PROD_PAGE, _append_unique, @@ -296,14 +295,6 @@ def production_to_rom(prod: dict[str, Any]) -> PouetRom: ) -def _unavailable() -> HTTPException: - """The error every unreachable-Pouët path raises.""" - return HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Can't connect to Pouët API, check your internet connection", - ) - - class PouetHandler(MetadataHandler): def __init__(self) -> None: self.min_similarity_score: Final = 0.88 @@ -322,7 +313,7 @@ class PouetHandler(MetadataHandler): body = await self._fetch_capped(url, headers=headers) except (httpx.HTTPStatusError, httpx.ConnectError, httpx.ReadTimeout) as exc: log.warning("Can't connect to Pouët API", extra={"exception": str(exc)}) - raise _unavailable() from exc + raise unavailable("Pouët API") from exc if body is None: return {} try: @@ -377,7 +368,7 @@ class PouetHandler(MetadataHandler): return pouet_id_from_location(res.headers.get("location") or "") except (httpx.ConnectError, httpx.ReadTimeout) as exc: log.warning("Pouët title search failed: %s", exc) - raise _unavailable() from exc + raise unavailable("Pouët API") from exc async def get_rom(self, fs_name: str, platform_slug: str) -> PouetRom: """Tag first; otherwise unique-title 302. No HTML list parse.""" diff --git a/backend/tests/handler/test_scan_complete_rescan_ids.py b/backend/tests/handler/test_scan_complete_rescan_ids.py index fa6d51858..f0b72fddc 100644 --- a/backend/tests/handler/test_scan_complete_rescan_ids.py +++ b/backend/tests/handler/test_scan_complete_rescan_ids.py @@ -4,6 +4,7 @@ A complete rescan clears every ID it could rematch; a provider that failed answered nothing, so the ID it could not check has to survive. """ +from typing import Any from unittest.mock import AsyncMock, patch import pytest @@ -32,7 +33,7 @@ MATCH = IGDBRom(igdb_id=9999, name="A Real Game") UNREACHABLE = HTTPException(status_code=503, detail="provider is down") -def _lookup(result): +def _lookup(result: Any) -> AsyncMock: """A provider lookup that answers with `result`, or fails when it is one.""" if isinstance(result, Exception): return AsyncMock(side_effect=result)