Files
romm/backend/handler/metadata/playmatch_handler.py
Sam Dornan 5a6c895d33 chore(mypy): give every generic its type arguments (#4818)
* chore(mypy): switch to strict mode with listed exceptions

Replace the hand-picked flags with `strict = True`, turning off only the
four flags that aren't clean yet (disallow_any_generics,
warn_return_any, disallow_untyped_calls, disallow_untyped_decorators).
Any other strict flag, including those future mypy releases add to the
preset, is on by default.

That turns on no_implicit_reexport, strict_equality and extra_checks:
- Import each name from the module that defines it. About 240 test
  sites patched a dependency through the module that imported it
  (`scan_module.fs_rom_handler`); they now import the same object from
  its source, so every patch targets what it did before. Tests that
  replace a module attribute are unchanged.
- handler.streaming.memory_cards re-exports store_memory_card_version
  explicitly, since endpoints call it there and tests patch it there.
- mutagen gets implicit_reexport, as it re-exports without __all__.
- Test comparisons build typed values (CoverResult, a typed expected
  dict, enum .value) and the CORS lookup casts for its identity check.
- One ss_handler ** spread keeps a coded ignore: extra_checks wants its
  NotRequired dump_* keys spelled out, and the media dict never has them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* chore(mypy): give every generic its type arguments

Drop disallow_any_generics from the strict-mode exceptions and fix the
347 bare generics it reports, 230 of them in app code.

- Bare `dict` becomes `dict[str, Any]`: update payloads, raw provider
  JSON and endpoint bodies map string keys to mixed values, so the Any is
  real and now written down. The OpenAPI document is unchanged.
- Rom query filters take and return RomSelect; _music_facet_joins and
  _exclude_hidden are generic over the Select they're given, and
  _build_hash_selects returns id-only selects.
- Redis clients are typed by what they return: the decoding caches are
  Redis[str], the RQ connection and binary cache Redis[bytes].
- The rest get explicit parameters: Row, Pattern, ColumnElement,
  QueryableAttribute, SpooledTemporaryFile, Task, Future and friends.

Precise types reached callers that had been getting Any, which surfaced:
- The LaunchBox cache writer is fed binary-cache pipelines.
- The flashpoint and IGDB request helpers return raw JSON of varying
  shape, not always a dict.
- The rom search endpoint returned dicts under a list[SearchRomSchema]
  annotation; it now validates them into that schema.
- The audit filter's id subquery selects strings.
- In tests the binary cache is the non-decoding fake shared with
  async_cache, so it is cast to Redis[bytes] rather than changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* test(upload): assert cleanup against the patched upload directory

The 409 test checked config's ROM_UPLOAD_TMP_BASE while the fixture patches
the endpoint's copy to tmp_path/uploads, so it passed even if cleanup failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* chore(mypy): keep the row type through the ROM filter helpers

filter_roms and its helpers also receive select(Rom.id) membership queries,
so they now take and return the caller's Select type instead of narrowing to
RomSelect. merged_ra_metadata mixes scalar and list values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 16:32:29 -05:00

359 lines
12 KiB
Python

import asyncio
import json
from collections.abc import Iterable
from enum import Enum
from typing import Any, Final, Literal, NotRequired, TypedDict, TypeIs, get_args
import httpx
import yarl
from fastapi import status
from config import PLAYMATCH_API_ENABLED, PLAYMATCH_API_URL
from handler.metadata.base_handler import MetadataHandler, unavailable
from logger.logger import log
from models.rom import Rom, RomFile
from utils import get_version
from utils.context import ctx_httpx_client
from utils.rate_limiter import RateLimiter
# Playmatch caps clients at 4 req/s per IP
PLAYMATCH_MAX_REQUESTS_PER_SECOND: Final[float] = 4
PLAYMATCH_MAX_REQUEST_ATTEMPTS: Final[int] = 2
_rate_limiter = RateLimiter(PLAYMATCH_MAX_REQUESTS_PER_SECOND)
class PlaymatchProvider(str, Enum):
IGDB = "IGDB"
STEAM_GRID_DB = "SteamGridDB"
SCREEN_SCRAPER = "ScreenScraper"
MOBY_GAMES = "MobyGames"
LAUNCH_BOX = "LaunchBox"
EMU_READY = "EmuReady"
OPEN_VGDB = "OpenVGDB"
# Tag is the uppercased Playmatch MetadataProvider name.
# Playmatch parses it case-insensitively but spacing must match.
# Tags Playmatch doesn't yet know are kept so older RomM clients keep
# submitting the right tag once Playmatch adds support.
PLAYMATCH_TAG_TO_ATTR: Final[dict[str, str]] = {
"IGDB": "igdb_id",
"MOBYGAMES": "moby_id",
"SCREENSCRAPER": "ss_id",
"RETRO_ACHIEVEMENTS": "ra_id",
"LAUNCHBOX": "launchbox_id",
"HASHEOUS": "hasheous_id",
"TGDB": "tgdb_id",
"FLASHPOINT": "flashpoint_id",
"HOWLONGTOBEAT": "hltb_id",
"LIBRETRO": "libretro_id",
"STEAMGRIDDB": "sgdb_id",
"GAMELIST": "gamelist_id",
}
# Rom attrs the scan handler actually consumes from a Playmatch lookup.
# Other tags exist only for outbound suggestions.
PlaymatchLookupAttr = Literal["igdb_id", "moby_id", "ss_id", "launchbox_id", "sgdb_id"]
PLAYMATCH_LOOKUP_ROM_ATTRS: Final = frozenset(get_args(PlaymatchLookupAttr))
def _is_lookup_attr(attr: str | None) -> TypeIs[PlaymatchLookupAttr]:
return attr in PLAYMATCH_LOOKUP_ROM_ATTRS
# MetadataSource values (StrEnum) for which Playmatch can return ids. Typed as
# strings so this module stays free of scan_handler imports. EmuReady and
# OpenVGDB are in Playmatch's enum but have no RomM counterpart yet.
PLAYMATCH_SUPPORTED_SOURCES: frozenset[str] = frozenset(
{"igdb", "moby", "ss", "launchbox", "sgdb"}
)
def _select_lookup_file(files: Iterable[RomFile]) -> RomFile | None:
"""The single file a ROM is identified by: the biggest top-level one, which
is how Hasheous and ScreenScraper choose theirs.
Equally sized files break the tie on path, so a two-disc set resolves to
disc 1. The scanner walks the filesystem unsorted, so without that two
machines scanning the same library ask about different files.
"""
return min(
(file for file in files if file.file_size_bytes > 0 and file.is_top_level),
key=lambda file: (-file.file_size_bytes, file.full_path),
default=None,
)
class GameMatchType(str, Enum):
SHA256 = "SHA256"
SHA1 = "SHA1"
MD5 = "MD5"
CRC = "CRC"
FILE_NAME_AND_SIZE = "FileNameAndSize"
NO_MATCH = "NoMatch"
class PlaymatchExternalMetadata(TypedDict):
automaticMatchReason: NotRequired[str]
comment: NotRequired[str]
failedMatchReason: NotRequired[str]
manualMatchType: NotRequired[str]
matchType: NotRequired[str]
providerId: NotRequired[str]
providerName: NotRequired[str]
class PlaymatchRomMatch(TypedDict):
igdb_id: int | None
moby_id: int | None
ss_id: int | None
launchbox_id: int | None
sgdb_id: int | None
ra_id: int | None
hasheous_id: int | None
tgdb_id: int | None
flashpoint_id: str | None
hltb_id: int | None
gamelist_id: str | None
libretro_id: str | None
class PlaymatchHandler(MetadataHandler):
"""
Handler for [Playmatch](https://github.com/RetroRealm/playmatch), a service for matching ROMs by Hashes.
"""
def __init__(self) -> None:
self.base_url = PLAYMATCH_API_URL
self.identify_url = f"{self.base_url}/identify/ids"
self.healthcheck_url = f"{self.base_url}/health"
self.suggestion_url = f"{self.base_url}/suggestion/external/game"
@classmethod
def is_enabled(cls) -> bool:
return PLAYMATCH_API_ENABLED
async def heartbeat(self) -> bool:
if not self.is_enabled():
return False
# The /health endpoint returns a plain-text body ("Healthy"), not
# JSON, so any 2xx response is enough to consider the service up.
httpx_client = ctx_httpx_client.get()
try:
await _rate_limiter.acquire()
res = await httpx_client.get(
self.healthcheck_url,
headers={"user-agent": f"RomM/{get_version()}"},
timeout=60,
)
res.raise_for_status()
except Exception as e:
log.error("Error checking Playmatch API: %s", e)
return False
return True
async def _request(self, url: str, query: dict[str, Any]) -> dict[str, Any]:
"""
Sends a Request to Playmatch API.
:param url: The API endpoint URL.
:param query: A dictionary containing the query parameters.
:return: A dictionary with the json result.
:raises HTTPException: If the request fails or the service is unavailable.
"""
httpx_client = ctx_httpx_client.get()
filtered_query = {
key: value
for key, value in query.items()
if value is not None and value != "" # drop None and ""
}
url_with_query = yarl.URL(url).update_query(filtered_query)
log.debug(
"API request: URL=%s, Timeout=%s",
url_with_query,
60,
)
headers = {"user-agent": f"RomM/{get_version()}"}
for attempt in range(PLAYMATCH_MAX_REQUEST_ATTEMPTS):
await _rate_limiter.acquire()
try:
res = await httpx_client.get(
str(url_with_query), headers=headers, timeout=60
)
res.raise_for_status()
return res.json()
except (
httpx.HTTPStatusError,
httpx.ConnectError,
httpx.ReadTimeout,
) as exc:
if (
attempt == 0
and isinstance(exc, httpx.HTTPStatusError)
and exc.response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
):
log.warning("Playmatch: rate limit hit, retrying after 2s")
await asyncio.sleep(2)
continue
log.warning(
"Connection error: can't connect to Playmatch", exc_info=True
)
raise unavailable("Playmatch") from exc
except json.JSONDecodeError as exc:
log.error("Error decoding JSON response from Playmatch: %s", exc)
return {}
return {}
async def lookup_rom(self, files: list[RomFile]) -> PlaymatchRomMatch:
"""
Identify a ROM file using Playmatch API.
:param rom_attrs: A dictionary containing the ROM attributes.
:return: A PlaymatchRomMatch with the matched IDs, or an empty match if the
lookup fails. Playmatch is best-effort and never raises to the caller.
"""
fallback_rom = PlaymatchRomMatch(
igdb_id=None,
moby_id=None,
ss_id=None,
launchbox_id=None,
sgdb_id=None,
ra_id=None,
hasheous_id=None,
tgdb_id=None,
flashpoint_id=None,
hltb_id=None,
gamelist_id=None,
libretro_id=None,
)
if not self.is_enabled():
return fallback_rom
match_file = _select_lookup_file(files)
if match_file is None:
return fallback_rom
hashes = match_file.lookup_hashes
# Folder ROM members carry generic names (a Wii U title's 00000005.app),
# so name and size alone match an unrelated game.
if not any(hashes) and match_file.full_path != match_file.rom.full_path:
log.debug(
"Skipping Playmatch lookup for %s: no hashes to identify it by",
match_file.full_path,
)
return fallback_rom
try:
response = await self._request(
self.identify_url,
{
"fileName": match_file.file_name,
"fileSize": match_file.file_size_bytes,
"md5": hashes.md5,
"sha1": hashes.sha1,
"crc": hashes.crc,
},
)
except Exception as exc:
# We silently fail if the service is unavailable as this should not block the rest of RomM.
log.warning("Playmatch lookup failed, skipping: %s", exc)
return fallback_rom
game_match_type = response.get("gameMatchType", None)
if game_match_type == GameMatchType.NO_MATCH:
log.debug("No match found for the provided ROM file.")
return fallback_rom
externalMetadata = response.get("externalMetadata", [])
if len(externalMetadata) == 0:
log.debug("No external metadata found for the matched ROM file.")
return fallback_rom
result = fallback_rom
for metadata in externalMetadata:
provider_name = metadata.get("providerName", None)
provider_game_id = metadata.get("providerId", None)
if not provider_name or provider_game_id is None:
continue
attr = PLAYMATCH_TAG_TO_ATTR.get(provider_name.upper())
if not _is_lookup_attr(attr):
continue
try:
parsed_id = int(provider_game_id)
except TypeError, ValueError:
log.debug(
"Playmatch returned non-int ID for %s: %r",
provider_name,
provider_game_id,
)
continue
log.debug("Playmatch found %s match with id: %s", provider_name, parsed_id)
result[attr] = parsed_id
return result
@staticmethod
def is_manual_match(form_fields_set: set[str]) -> bool:
"""True if the submitted form contains any Playmatch-tracked provider id field."""
return any(attr in form_fields_set for attr in PLAYMATCH_TAG_TO_ATTR.values())
async def submit_manual_match_suggestion(self, rom: Rom) -> None:
"""
Fire-and-forget suggestion POST.
No-ops if disabled or no provider IDs are set.
"""
try:
if not self.is_enabled():
return
mappings = [
{"provider": tag, "providerId": str(getattr(rom, attr))}
for tag, attr in PLAYMATCH_TAG_TO_ATTR.items()
if getattr(rom, attr, None)
]
if not mappings:
return
# A suggestion writes a hash-to-game mapping into a public index.
# With no file to take one from, the ROM-level hash is a composite
# spanning every file or archive member, so there is nothing here
# worth contributing.
match_file = _select_lookup_file(rom.files)
if match_file is None:
return
hashes = match_file.lookup_hashes
payload = {
"md5": hashes.md5,
"sha1": hashes.sha1,
"sha256": None,
"fileName": match_file.file_name,
"fileSize": match_file.file_size_bytes,
"mappings": mappings,
}
httpx_client = ctx_httpx_client.get()
await _rate_limiter.acquire()
res = await httpx_client.post(
self.suggestion_url,
json=payload,
headers={"user-agent": f"RomM/{get_version()}"},
timeout=30,
)
res.raise_for_status()
except Exception:
log.debug("Playmatch match suggestion failed (ignored)", exc_info=True)