mirror of
https://github.com/rommapp/romm.git
synced 2026-12-05 05:07:31 +01:00
Merge pull request #4353 from Spinnich/fix/complete-rescan-clears-attempted-ids
fix(scan): let a complete rescan clear the ids it rematched
This commit is contained in:
@@ -224,6 +224,11 @@ 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."""
|
||||
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:
|
||||
|
||||
@@ -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 _without_failures(
|
||||
results: list[tuple[str, _CoverRomT] | BaseException], provider: str
|
||||
) -> list[tuple[str, _CoverRomT]]:
|
||||
"""Drop the cover lookups that failed."""
|
||||
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,
|
||||
@@ -225,13 +241,19 @@ async def search_rom(
|
||||
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 _without_failures(sgdb_roms, "SteamGridDB"):
|
||||
if sgdb_rom["sgdb_id"]:
|
||||
merged_dict[name] = {
|
||||
**merged_dict[name],
|
||||
@@ -239,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 _without_failures(libretro_roms, "Libretro"):
|
||||
if libretro_rom["libretro_id"]:
|
||||
merged_dict[name] = {
|
||||
**merged_dict[name],
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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")
|
||||
@@ -203,12 +199,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:
|
||||
|
||||
@@ -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:
|
||||
@@ -545,12 +541,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)
|
||||
|
||||
@@ -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 {}
|
||||
@@ -218,7 +214,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 +409,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):
|
||||
|
||||
@@ -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,
|
||||
@@ -222,21 +222,17 @@ class HasheousHandler(MetadataHandler):
|
||||
exc.response.status_code,
|
||||
exc.response.text,
|
||||
)
|
||||
pass
|
||||
raise unavailable("Hasheous") 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("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:
|
||||
pass
|
||||
|
||||
return {}
|
||||
except httpx.TimeoutException as exc:
|
||||
log.error("Hasheous API timed out: %s", exc)
|
||||
raise unavailable("Hasheous") from exc
|
||||
|
||||
def get_platform(self, slug: str) -> HasheousPlatform:
|
||||
if slug not in HASHEOUS_PLATFORM_LIST:
|
||||
|
||||
@@ -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
|
||||
@@ -527,7 +524,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:
|
||||
@@ -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:
|
||||
|
||||
@@ -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 {}
|
||||
|
||||
@@ -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,
|
||||
@@ -314,10 +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 HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Can't connect to Pouët API, check your internet connection",
|
||||
) from exc
|
||||
raise unavailable("Pouët API") from exc
|
||||
if body is None:
|
||||
return {}
|
||||
try:
|
||||
@@ -340,10 +336,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 +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)
|
||||
return None
|
||||
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."""
|
||||
|
||||
@@ -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():
|
||||
@@ -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.
|
||||
|
||||
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.
|
||||
"""
|
||||
"""Get ROM details by candidate game names, raising when the lookup fails."""
|
||||
if not self.is_enabled():
|
||||
return SGDBRom(sgdb_id=None)
|
||||
|
||||
@@ -168,7 +163,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)
|
||||
|
||||
@@ -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
|
||||
@@ -583,6 +586,28 @@ 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()
|
||||
|
||||
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."""
|
||||
@@ -688,6 +713,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:
|
||||
@@ -734,6 +760,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
|
||||
)
|
||||
@@ -755,6 +782,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
|
||||
@@ -779,6 +807,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
|
||||
)
|
||||
@@ -799,6 +828,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 (
|
||||
@@ -821,6 +851,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
|
||||
)
|
||||
@@ -836,6 +867,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)
|
||||
@@ -851,6 +883,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)
|
||||
@@ -870,6 +903,7 @@ async def scan_rom(
|
||||
)
|
||||
)
|
||||
):
|
||||
attempted_sources.add(MetadataSource.STEAM)
|
||||
return await resolve_steam_rom(
|
||||
rom=rom,
|
||||
fs_name=str(rom_attrs["fs_name"]),
|
||||
@@ -894,6 +928,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)
|
||||
|
||||
@@ -926,6 +961,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.
|
||||
@@ -958,6 +994,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)
|
||||
@@ -975,6 +1012,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"]),
|
||||
@@ -1008,6 +1046,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:
|
||||
@@ -1045,6 +1084,7 @@ async def scan_rom(
|
||||
)
|
||||
)
|
||||
):
|
||||
attempted_sources.add(MetadataSource.HASHEOUS)
|
||||
(
|
||||
igdb_game,
|
||||
ra_game,
|
||||
@@ -1067,46 +1107,55 @@ 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):
|
||||
if isinstance(result, BaseException):
|
||||
if not isinstance(result, Exception):
|
||||
raise result
|
||||
provider = fallback.__class__.__name__
|
||||
log.error(
|
||||
f"Error fetching {hl(provider)} 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.
|
||||
if is_breaker_tripped():
|
||||
attempted_sources.discard(MetadataSource.SS)
|
||||
|
||||
(
|
||||
igdb_handler_rom,
|
||||
@@ -1279,11 +1328,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"]] = {}
|
||||
@@ -1441,6 +1490,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)
|
||||
|
||||
@@ -1469,7 +1519,19 @@ async def scan_rom(
|
||||
|
||||
return SGDBRom(sgdb_id=None)
|
||||
|
||||
sgdb_hander_rom = await fetch_sgdb_details(playmatch_hash_match)
|
||||
# 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"]
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
43
backend/tests/handler/metadata/test_flashpoint_handler.py
Normal file
43
backend/tests/handler/metadata/test_flashpoint_handler.py
Normal file
@@ -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")
|
||||
@@ -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")
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
61
backend/tests/handler/scan_stubs.py
Normal file
61
backend/tests/handler/scan_stubs.py
Normal file
@@ -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,
|
||||
)
|
||||
181
backend/tests/handler/test_scan_complete_rescan_ids.py
Normal file
181
backend/tests/handler/test_scan_complete_rescan_ids.py
Normal file
@@ -0,0 +1,181 @@
|
||||
"""What a scan does to a ROM's external IDs.
|
||||
|
||||
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
|
||||
from fastapi import HTTPException
|
||||
from tests.handler.scan_stubs import add_n64_platform, add_rom, run_scan
|
||||
|
||||
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
|
||||
from models.rom import Rom
|
||||
|
||||
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)
|
||||
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")
|
||||
|
||||
|
||||
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)
|
||||
return AsyncMock(return_value=result)
|
||||
|
||||
|
||||
async def _rescan(
|
||||
sources: list[str],
|
||||
*,
|
||||
scan_type: ScanType = ScanType.COMPLETE,
|
||||
igdb_result: IGDBRom | Exception = MISS,
|
||||
sgdb_result: SGDBRom | Exception = SGDB_MISS,
|
||||
pouet_result: PouetRom | Exception = POUET_MISS,
|
||||
platform_igdb_id: int | None = 4,
|
||||
ss_breaker_tripped: bool = False,
|
||||
) -> Rom:
|
||||
"""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)
|
||||
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),
|
||||
),
|
||||
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,
|
||||
),
|
||||
):
|
||||
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 _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 _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 _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 _rescan(
|
||||
[MetadataSource.IGDB], igdb_result=RuntimeError("IGDB is down")
|
||||
)
|
||||
|
||||
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 _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 _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 _rescan([MetadataSource.IGDB, MetadataSource.SS])
|
||||
|
||||
assert saved.ss_id is None
|
||||
|
||||
|
||||
async def test_a_deselected_source_still_drops_its_id():
|
||||
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 _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 _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]
|
||||
)
|
||||
async def test_only_a_complete_rescan_drops_ids(scan_type: ScanType):
|
||||
"""Every other scan type carries the existing IDs forward untouched."""
|
||||
saved = await _rescan([MetadataSource.IGDB], scan_type=scan_type)
|
||||
|
||||
assert saved.igdb_id == STALE_IGDB_ID
|
||||
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user