refactor(scan): give the title id one resolver and one identity shape

The Tinfoil feed was left behind when `_switch_productid_format` changed
from taking a `re.Match` to taking a `str`, so `/feeds/tinfoil` raised a
TypeError for any Switch rom carrying a product id in its filename but no
titledb id. It went unnoticed because `feeds.py` sits outside the changed
files mypy sees.

That call site was reachable only because "prefer the id the scan read over
the one scraped from the filename" lived in a second helper above the lookup,
leaving each caller to remember it. The resolution now happens inside
`_switch_productid_format`, so the three providers and the feed all get it
without repeating a preamble.

Also:

- Move `SWITCH_PLATFORM_SLUGS` to the sigil adapter so `utils/switch.py`
  stops importing the metadata base handler. The cycle that import created
  was papered over with a function-local import, and `normalize_identity`
  now takes the fact it needs rather than the whole slug set.
- Merge a partial identity update onto the stored identity before
  normalizing it. Normalizing rewrites the whole triple, so a client sending
  only a title id was getting the derived base id next to its old save
  target.
- Add `RomIdentity.from_rom` so the triple has one home on the read side
  too, and drop `asdict` from `as_rom_attrs`.
- Hold the `SigilExtractionResult` on `TitleIdEmbedCandidate` instead of
  copying two of its fields.
- Drop a guard in `_rom_level_identity` that could not fire, derive once in
  `normalize_identity`, and return only the parse from `_rebuild_rom_files`,
  which already owns `fs_rom["fs_name"]`.
- Read the parsed config in the heartbeat rather than forcing a YAML
  re-parse per request, and make `SigilService.is_enabled` a classmethod
  like every other one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-04 10:57:36 -04:00
parent 8db38f3322
commit fbbadb7c86
15 changed files with 124 additions and 124 deletions

View File

@@ -15,6 +15,7 @@ from anyio import Path as AnyioPath
from adapters.services.sigil import (
SIGIL_PLATFORM_SLUGS,
SWITCH_PLATFORM_SLUGS,
SigilExtractionResult,
SigilService,
)
@@ -188,8 +189,7 @@ class TitleIdEmbedCandidate:
"""A parsed file whose name can carry the Switch title id read from it."""
rom_file: RomFile
title_id: str
version: int | None
extraction: SigilExtractionResult
# Renaming this file renames the rom, so the caller reconciles `fs_name`.
is_rom_level: bool
@@ -295,14 +295,11 @@ def _rom_level_identity(
if not extractions:
return RomIdentity()
chosen = extractions[0]
if platform_slug in switch.SWITCH_PLATFORM_SLUGS:
chosen = next(
(e for e in extractions if switch.is_base_title_id(e.title_id)), chosen
)
chosen = next(
(e for e in extractions if switch.is_base_title_id(e.title_id)), extractions[0]
)
return switch.normalize_identity(
platform_slug,
platform_slug in SWITCH_PLATFORM_SLUGS,
RomIdentity(
title_id=chosen.title_id,
save_target=chosen.save_target,
@@ -533,7 +530,7 @@ class FSRomsHandler(FSHandler):
# Title id extraction is independent of hashing support: it covers
# non-hashable platforms like Switch.
sigil_platform = extract_title_ids and rom.platform_slug in SIGIL_PLATFORM_SLUGS
is_switch = rom.platform_slug in switch.SWITCH_PLATFORM_SLUGS
is_switch = rom.platform_slug in SWITCH_PLATFORM_SLUGS
sigil_extractions: list[SigilExtractionResult] = []
embed_candidates: list[TitleIdEmbedCandidate] = []
sigil_service = SigilService()
@@ -562,8 +559,7 @@ class FSRomsHandler(FSHandler):
embed_candidates.append(
TitleIdEmbedCandidate(
rom_file=rom_file,
title_id=extraction.title_id,
version=extraction.version,
extraction=extraction,
is_rom_level=is_rom_level,
)
)
@@ -1035,8 +1031,8 @@ class FSRomsHandler(FSHandler):
rom_file = candidate.rom_file
new_name = await self._embed_switch_title_id_in_name(
Path(rom_file.file_path, rom_file.file_name),
candidate.title_id,
candidate.version,
candidate.extraction.title_id,
candidate.extraction.version,
)
if new_name is None:
continue

View File

@@ -17,6 +17,7 @@ from tasks.scheduled.update_switch_titledb import (
SWITCH_TITLEDB_INDEX_KEY,
)
from utils.context import ctx_httpx_client
from utils.switch import derive_base_title_id
if TYPE_CHECKING:
from models.rom import Rom
@@ -276,21 +277,18 @@ class MetadataHandler(abc.ABC):
return search_term, None
@staticmethod
def switch_product_id(rom: "Rom", fs_name: str) -> str | None:
"""The Switch product id to search by, preferring the one the scan read
out of the binary over one scraped from the filename."""
if rom.title_id and SWITCH_PRODUCT_ID_REGEX.fullmatch(rom.title_id.upper()):
return rom.title_id.upper()
match = SWITCH_PRODUCT_ID_REGEX.search(fs_name)
return match.group(1) if match else None
async def _switch_productid_format(
self, product_id: str, search_term: str
self, rom: "Rom", fs_name: str, search_term: str
) -> tuple[str, dict | None]:
# Imported here because utils.switch imports this module for the slugs.
from utils.switch import derive_base_title_id
"""Match by Switch product id, preferring the one the scan read out of
the binary over one scraped from the filename."""
if rom.title_id and SWITCH_PRODUCT_ID_REGEX.fullmatch(rom.title_id.upper()):
product_id = rom.title_id.upper()
else:
match = SWITCH_PRODUCT_ID_REGEX.search(fs_name)
if not match:
return search_term, None
product_id = match.group(1)
# Updates and DLC share the base application's product ID, off by the
# low 12 bits, and only the base has a titledb entry.

View File

@@ -830,19 +830,17 @@ class IGDBHandler(MetadataHandler):
# Support for switch productID filename format
if platform_igdb_id == SWITCH_IGDB_ID:
product_id = self.switch_product_id(rom, fs_name)
if product_id:
search_term, index_entry = await self._switch_productid_format(
product_id, search_term
search_term, index_entry = await self._switch_productid_format(
rom, fs_name, search_term
)
if index_entry:
fallback_rom = IGDBRom(
igdb_id=None,
name=index_entry["name"],
summary=index_entry.get("description", ""),
url_cover=index_entry.get("iconUrl", ""),
url_screenshots=index_entry.get("screenshots", None) or [],
)
if index_entry:
fallback_rom = IGDBRom(
igdb_id=None,
name=index_entry["name"],
summary=index_entry.get("description", ""),
url_cover=index_entry.get("iconUrl", ""),
url_screenshots=index_entry.get("screenshots", None) or [],
)
# Support for MAME arcade filename format
if platform_igdb_id in ARCADE_IGDB_IDS:

View File

@@ -216,19 +216,17 @@ class MobyGamesHandler(MetadataHandler):
# Support for switch productID filename format
if platform_moby_id == SWITCH_MOBY_ID:
product_id = self.switch_product_id(rom, fs_name)
if product_id:
search_term, index_entry = await self._switch_productid_format(
product_id, search_term
search_term, index_entry = await self._switch_productid_format(
rom, fs_name, search_term
)
if index_entry:
fallback_rom = MobyGamesRom(
moby_id=None,
name=index_entry["name"],
summary=index_entry.get("description", ""),
url_cover=index_entry.get("iconUrl", ""),
url_screenshots=index_entry.get("screenshots", None) or [],
)
if index_entry:
fallback_rom = MobyGamesRom(
moby_id=None,
name=index_entry["name"],
summary=index_entry.get("description", ""),
url_cover=index_entry.get("iconUrl", ""),
url_screenshots=index_entry.get("screenshots", None) or [],
)
# Support for MAME arcade filename format
if platform_moby_id in ARCADE_MOBY_IDS:

View File

@@ -958,19 +958,17 @@ class SSHandler(MetadataHandler):
# Support for switch productID filename format
if platform_ss_id == SWITCH_SS_ID:
product_id = self.switch_product_id(rom, file_name)
if product_id:
search_term, index_entry = await self._switch_productid_format(
product_id, search_term
search_term, index_entry = await self._switch_productid_format(
rom, file_name, search_term
)
if index_entry:
fallback_rom = SSRom(
ss_id=None,
name=index_entry["name"],
summary=index_entry.get("description", ""),
url_cover=index_entry.get("iconUrl", ""),
url_screenshots=index_entry.get("screenshots", None) or [],
)
if index_entry:
fallback_rom = SSRom(
ss_id=None,
name=index_entry["name"],
summary=index_entry.get("description", ""),
url_cover=index_entry.get("iconUrl", ""),
url_screenshots=index_entry.get("screenshots", None) or [],
)
# Support for MAME arcade filename format
if platform_ss_id in ARCADES_SS_IDS:

View File

@@ -74,7 +74,7 @@ from logger.logger import log
from models.assets import Save, Screenshot, State
from models.firmware import Firmware
from models.platform import Platform
from models.rom import Rom, RomFile, RomFileCategory
from models.rom import Rom, RomFile, RomFileCategory, RomIdentity
from models.user import User
from utils import emoji
from utils.audio_tags import persist_embedded_cover, remove_persisted_cover
@@ -519,9 +519,7 @@ async def scan_rom(
"md5_hash": rom.md5_hash,
"sha1_hash": rom.sha1_hash,
"ra_hash": rom.ra_hash,
"title_id": rom.title_id,
"save_target": rom.save_target,
"save_target_layout": rom.save_target_layout,
**RomIdentity.from_rom(rom).as_rom_attrs(),
"fs_size_bytes": rom.fs_size_bytes,
"is_physical": rom.is_physical,
"upc": rom.upc,