Files
romm/backend/handler/metadata/playmatch_handler.py
Sam Dornan 4542998510 fix(backend): make type ignores honest and replace mypy trunk-ignores with fixes (#4711)
* fix(backend): make type ignores match what mypy reports

Third in the staged series clearing the errors #4655 made visible.
Whole-project mypy: 91 errors in 26 files -> 64 in 23.

Twenty `# type: ignore[assignment]` comments in
endpoints/responses/rom.py never suppressed anything. The request-scoped
values `from_orm_with_request` attaches to a Rom (rom_user, has_notes,
user_saves and the rest) are not declared on the model, so mypy reports
`attr-defined`; it does so under 1.19 as well as 2.3, so the code was
wrong when the comments were written rather than drifting since. They
now name the error they were meant to silence.

Seventy-nine ignores across 24 files suppressed nothing at all under
`--warn-unused-ignores`, and are removed. One of them,
`utils/zip_cache.py`, keeps its `attr-defined` code for the private
`zipfile._get_compressor` and drops only `assignment`. The unused set is
identical under mypy 2.3.0 and 2.3.1, and removing them leaves the error
count unchanged under both, so none was quietly needed.

The two `filter` helpers typed as `[QueryT: Select | Update | Delete]`
bound the TypeVar to the union, so `query.filter(...)` returned the union
and could not be assigned back to `QueryT`. Constraining it to the three
types lets mypy check each one separately, and the callers are unchanged.

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

* fix(backend): replace mypy and ASYNC240 trunk-ignores with real fixes

A `trunk-ignore` only suppresses when Trunk runs the linter. Plain mypy
does not read them, so the 13 on mypy findings were all still errors to
`mypy .` and would fail a whole-project check. Each now has a fix.

endpoints/tasks.py: `common_data` was a plain dict literal unpacked into
eight TypedDict constructors, so mypy saw `dict[str, Any]` and could not
match its keys. It holds exactly the fields of BaseTaskStatusResponse and
is now annotated as one, so the unpacking is checked.

handler/metadata/gamelist_handler.py: both media maps were inferred as
`dict[str, str]`, so indexing the TypedDict with their keys was
unprovable. Their keys are now typed `GamelistMediaKey`, the Literal of
the TypedDict's fields. A misspelt map key is now an error at the entry;
before, only the index site could have noticed, and it was suppressed.

handler/metadata/playmatch_handler.py: `attr` was a bare `str`. A TypeIs
guard narrows it to the five lookup attributes, and the frozenset is
derived from that Literal so the names live in one place. mypy now checks
that each name is a real PlaymatchRomMatch key. It does not check that
each takes an int, since mypy is lenient about value types on a union key;
that still rests on which five names are listed.

endpoints/search.py: the per-source tuples mixed ROM-list and handler
types, which mypy joined to `object`. The dict is now annotated with what
the loop uses: Mapping rows and the MetadataHandler base.

tests/handler/metadata/test_launchbox_handler.py: `Path.stat()` inside an
async test (ASYNC240) now goes through `anyio.Path`, as the rest of the
codebase already does.

Whole-project mypy: 64 errors in 23 files -> 51 in 20, identical under
2.3.0 and 2.3.1.

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

* fix(backend): keep gamelist media keys in one place

Review pointed out that `GamelistMediaKey` repeated all fourteen fields
of GamelistMetadataMedia. Python has no `keyof`, so any Literal of a
TypedDict's keys is a second declaration of them, and a field added to
the TypedDict would be left out of it without any error.

The three index sites go back to suppressing `literal-required`, now as
`# type: ignore[literal-required]` so plain mypy reads it as well as
Trunk. The TypedDict stays the only declaration of the key set.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-22 16:02:39 -05:00

350 lines
12 KiB
Python

import asyncio
import json
from collections.abc import Iterable
from enum import Enum
from typing import 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):
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) -> dict:
"""
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
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)