diff --git a/backend/endpoints/search.py b/backend/endpoints/search.py index f50afb0ed..20ac31b5f 100644 --- a/backend/endpoints/search.py +++ b/backend/endpoints/search.py @@ -1,5 +1,5 @@ import asyncio -from collections.abc import Callable, Sequence +from collections.abc import Callable, Coroutine, Sequence from typing import Any, TypeVar from fastapi import HTTPException, Request, status @@ -60,24 +60,17 @@ def _without_failures( return fetched -# The order the provider lookups are gathered in, for reporting which one failed. -_ID_SEARCH_PROVIDERS = ("IGDB", "MobyGames", "ScreenScraper", "LaunchBox", "Demozoo") -_NAME_SEARCH_PROVIDERS = ( - "IGDB", - "MobyGames", - "ScreenScraper", - "Flashpoint", - "LaunchBox", - "Demozoo", -) - - -def _resolved( - results: Sequence[Any], providers: Sequence[str], fallback: Callable[[], Any] +async def _gathered( + lookups: Sequence[tuple[str, Coroutine[Any, Any, Any]]], + fallback: Callable[[], Any], ) -> list[Any]: - """Let a provider that could not answer cost only its own matches.""" + """Run provider lookups together, letting a failure cost only its own matches.""" + results = await asyncio.gather( + *(coro for _, coro in lookups), return_exceptions=True + ) + resolved: list[Any] = [] - for provider, result in zip(providers, results, strict=True): + for (provider, _), result in zip(lookups, results, strict=True): if isinstance(result, BaseException): log.error("Error searching %s: %s", provider, result) resolved.append(fallback()) @@ -153,13 +146,24 @@ async def search_rom( if search_by.lower() == "id": try: - gathered = await asyncio.gather( - meta_igdb_handler.get_matched_rom_by_id(rom, int(search_term)), - meta_moby_handler.get_matched_rom_by_id(int(search_term)), - meta_ss_handler.get_matched_rom_by_id(rom, int(search_term)), - meta_launchbox_handler.get_matched_rom_by_id(int(search_term)), - meta_demozoo_handler.get_rom_by_id(int(search_term)), - return_exceptions=True, + id_lookups = ( + ( + "IGDB", + meta_igdb_handler.get_matched_rom_by_id(rom, int(search_term)), + ), + ( + "MobyGames", + meta_moby_handler.get_matched_rom_by_id(int(search_term)), + ), + ( + "ScreenScraper", + meta_ss_handler.get_matched_rom_by_id(rom, int(search_term)), + ), + ( + "LaunchBox", + meta_launchbox_handler.get_matched_rom_by_id(int(search_term)), + ), + ("Demozoo", meta_demozoo_handler.get_rom_by_id(int(search_term))), ) except ValueError as exc: log.error(f"Search error: invalid ID '{search_term}'") @@ -168,8 +172,8 @@ async def search_rom( detail=f"Tried searching by ID, but '{search_term}' is not a valid ID", ) from exc else: - igdb_rom, moby_rom, ss_rom, lb_rom, dz_rom = _resolved( - gathered, _ID_SEARCH_PROVIDERS, lambda: None + igdb_rom, moby_rom, ss_rom, lb_rom, dz_rom = await _gathered( + id_lookups, lambda: None ) igdb_matched_roms = [igdb_rom] if igdb_rom else [] moby_matched_roms = [moby_rom] if moby_rom else [] @@ -186,29 +190,45 @@ async def search_rom( flashpoint_matched_roms, launchbox_matched_roms, demozoo_matched_roms, - ) = _resolved( - await asyncio.gather( - meta_igdb_handler.get_matched_roms_by_name( - rom, search_term, get_main_platform_igdb_id(rom.platform) + ) = await _gathered( + ( + ( + "IGDB", + meta_igdb_handler.get_matched_roms_by_name( + rom, search_term, get_main_platform_igdb_id(rom.platform) + ), ), - meta_moby_handler.get_matched_roms_by_name( - search_term, rom.platform.moby_id + ( + "MobyGames", + meta_moby_handler.get_matched_roms_by_name( + search_term, rom.platform.moby_id + ), ), - meta_ss_handler.get_matched_roms_by_name( - rom, search_term, rom.platform.ss_id + ( + "ScreenScraper", + meta_ss_handler.get_matched_roms_by_name( + rom, search_term, rom.platform.ss_id + ), ), - meta_flashpoint_handler.get_matched_roms_by_name( - search_term, rom.platform.slug + ( + "Flashpoint", + meta_flashpoint_handler.get_matched_roms_by_name( + search_term, rom.platform.slug + ), ), - meta_launchbox_handler.get_matched_roms_by_name( - search_term, rom.platform.slug + ( + "LaunchBox", + meta_launchbox_handler.get_matched_roms_by_name( + search_term, rom.platform.slug + ), ), - meta_demozoo_handler.get_matched_roms_by_name( - search_term, rom.platform.slug + ( + "Demozoo", + meta_demozoo_handler.get_matched_roms_by_name( + search_term, rom.platform.slug + ), ), - return_exceptions=True, ), - _NAME_SEARCH_PROVIDERS, list, ) diff --git a/backend/handler/metadata/ss_handler.py b/backend/handler/metadata/ss_handler.py index c0c7baf70..7650e404d 100644 --- a/backend/handler/metadata/ss_handler.py +++ b/backend/handler/metadata/ss_handler.py @@ -256,8 +256,8 @@ def _is_daily_quota_error(exc: HTTPException) -> bool: def _is_provider_exhausted(exc: HTTPException) -> bool: """True for the errors a breaker raises in ScreenScraper's place. - Both an exhausted daily quota and a refused credential set trip a breaker in - the service, so the request never went out and the answer is not ScreenScraper's. + An exhausted daily quota and a refused credential set both trip one, so the + request never went out and the answer is not ScreenScraper's. """ return _is_daily_quota_error(exc) or isinstance(exc, ScreenScraperCredentialsError) @@ -341,9 +341,8 @@ class SSRom(BaseRom): class ScreenScraperExhaustedError(Exception): """A breaker answered this lookup, so ScreenScraper itself never saw it. - Carries the match the lookup would otherwise have returned, which still holds - whatever the handler derived locally (a name from the Switch title database, - a MAME index, a PS2 OPL tag). + Carries the match the lookup would have returned, which still holds the name + the handler derived locally. """ def __init__(self, fallback: SSRom): diff --git a/backend/handler/scan_handler.py b/backend/handler/scan_handler.py index 88b76b166..fdeeab57a 100644 --- a/backend/handler/scan_handler.py +++ b/backend/handler/scan_handler.py @@ -1000,9 +1000,8 @@ async def scan_rom( short_circuited = True return exc.fallback except ScreenScraperRateLimitError: - # 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. + # The per-minute budget is already spent, so give up on this ROM + # rather than spending a retried request on the fallback lookups. note_rate_limited_rom(rom_attrs["fs_name"]) short_circuited = True return SSRom(ss_id=None) diff --git a/backend/tests/endpoints/test_search.py b/backend/tests/endpoints/test_search.py index 9516c6675..8155fb139 100644 --- a/backend/tests/endpoints/test_search.py +++ b/backend/tests/endpoints/test_search.py @@ -1,8 +1,7 @@ """What one unreachable provider costs a metadata search. The providers are gathered together, so an error from any one of them used to -take down the whole dialog: the user saw a 500 instead of the matches the other -providers had already found. +take the whole dialog down with it. """ from unittest.mock import AsyncMock, patch