From ea44dfd9cfd40edcca2e29e419f7faa928ad7dab Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 10 Sep 2026 13:17:44 -0400 Subject: [PATCH] refactor(metadata): fold the index follows into one lookup each The title index reader now takes the key and field it reads, so the two call sites lose their intermediate hit variable, and the alternate name path follows its id through `get_by_id` like the other two. The Switch titleID read is shared between the two lookups that do it. The LaunchBox import reads the `Game` fields with `findtext`, and the Switch import queues both indexes from one pass over the batches. The image projection moves next to the `LaunchboxImage` type it fills. Co-Authored-By: Claude Opus 5 (1M context) --- backend/handler/metadata/base_handler.py | 20 ++++---- .../launchbox_handler/remote_source.py | 39 ++++++---------- .../metadata/launchbox_handler/types.py | 8 ++++ .../scheduled/update_launchbox_metadata.py | 46 +++++++------------ .../tasks/scheduled/update_switch_titledb.py | 16 ++++--- .../handler/metadata/test_base_handler.py | 3 +- .../metadata/test_launchbox_handler.py | 34 +++++--------- 7 files changed, 72 insertions(+), 94 deletions(-) diff --git a/backend/handler/metadata/base_handler.py b/backend/handler/metadata/base_handler.py index d45e6bd7d..020c73589 100644 --- a/backend/handler/metadata/base_handler.py +++ b/backend/handler/metadata/base_handler.py @@ -277,9 +277,8 @@ class MetadataHandler(abc.ABC): log.error("Could not find the Switch titleID index file in cache") return search_term, None - index_entry = await async_cache.hget(SWITCH_TITLEDB_INDEX_KEY, title_id) + index_entry = await self._switch_titledb_entry(title_id) if index_entry: - index_entry = json.loads(index_entry) return index_entry["name"], index_entry return search_term, None @@ -312,12 +311,16 @@ class MetadataHandler(abc.ABC): return search_term, None @staticmethod - async def _switch_product_id_entry(product_id: str) -> dict | None: - """Resolve a Switch product id to its titleID index entry. + async def _switch_titledb_entry(title_id: str) -> dict | None: + entry = await async_cache.hget(SWITCH_TITLEDB_INDEX_KEY, title_id) + return json.loads(entry) if entry else None - The product id index holds the title id of the entry. A store imported - before it was de-duplicated holds the entry itself, so it keeps - answering until the next update rewrites it. + @classmethod + async def _switch_product_id_entry(cls, product_id: str) -> dict | None: + """Resolve a Switch product id to the title id its index entry holds. + + A store imported before the index was de-duplicated holds the titleID + entry itself, so it keeps answering until the next update. """ raw = await async_cache.hget(SWITCH_PRODUCT_ID_KEY, product_id) if not raw: @@ -327,8 +330,7 @@ class MetadataHandler(abc.ABC): if isinstance(value, dict): return value - entry = await async_cache.hget(SWITCH_TITLEDB_INDEX_KEY, value) - return json.loads(entry) if entry else None + return await cls._switch_titledb_entry(value) async def _mame_format(self, search_term: str) -> str: from handler.filesystem import fs_rom_handler diff --git a/backend/handler/metadata/launchbox_handler/remote_source.py b/backend/handler/metadata/launchbox_handler/remote_source.py index d2586b1d6..9880270db 100644 --- a/backend/handler/metadata/launchbox_handler/remote_source.py +++ b/backend/handler/metadata/launchbox_handler/remote_source.py @@ -25,14 +25,17 @@ class RemoteSource: return None return json.loads(entry) - async def _follow_title_index(self, entry: str) -> dict | None: - """Resolve a title index hit to the record it points at. + async def _lookup_title_index(self, key: str, field: str) -> dict | None: + """Read a title index hit and resolve the database id it holds. - A hit holds the database id of the record. A store imported before the - title indexes were de-duplicated holds the whole record instead, so it - keeps answering until the next import rewrites it. + A store imported before the title indexes were de-duplicated holds the + whole record instead, so it keeps answering until the next import. """ - value = json.loads(entry) + raw = await async_cache.hget(key, field) + if not raw: + return None + + value = json.loads(raw) if isinstance(value, dict): return value return await self.get_by_id(value) @@ -73,13 +76,9 @@ class RemoteSource: candidates = list(dict.fromkeys(candidates)) for candidate in candidates: - metadata_name_index_entry = await async_cache.hget( + entry = await self._lookup_title_index( LAUNCHBOX_METADATA_NAME_KEY, f"{candidate}:{platform_name}" ) - if not metadata_name_index_entry: - continue - - entry = await self._follow_title_index(metadata_name_index_entry) if entry: return entry @@ -90,19 +89,13 @@ class RemoteSource: if not metadata_alternate_name_index_entry: continue - metadata_alternate_name_index_entry = json.loads( - metadata_alternate_name_index_entry - ) - database_id = metadata_alternate_name_index_entry["DatabaseID"] - metadata_database_index_entry = await async_cache.hget( - LAUNCHBOX_METADATA_DATABASE_ID_KEY, database_id - ) - if not metadata_database_index_entry: + database_id = json.loads(metadata_alternate_name_index_entry)["DatabaseID"] + entry = await self.get_by_id(database_id) + if not entry: continue # The alternate name index is not keyed by platform, so a hit can # point at a same-titled game on a completely different system. - entry = json.loads(metadata_database_index_entry) if entry.get("Platform") == platform_name: return entry @@ -114,13 +107,9 @@ class RemoteSource: folded = fold_title(candidate) if not folded: continue - folded_index_entry = await async_cache.hget( + entry = await self._lookup_title_index( LAUNCHBOX_METADATA_FOLDED_NAME_KEY, f"{folded}:{platform_name}" ) - if not folded_index_entry: - continue - - entry = await self._follow_title_index(folded_index_entry) if entry: return entry diff --git a/backend/handler/metadata/launchbox_handler/types.py b/backend/handler/metadata/launchbox_handler/types.py index 75efa3713..aab000cf5 100644 --- a/backend/handler/metadata/launchbox_handler/types.py +++ b/backend/handler/metadata/launchbox_handler/types.py @@ -39,6 +39,14 @@ class LaunchboxImage(TypedDict): region: NotRequired[str] +# The fields an image list is imported with. `DatabaseID` repeats the field the +# list is stored under and `CRC32` has no reader, and the dump holds 1.3M +# images, so dropping the pair saves ~100MB of cache. +LAUNCHBOX_IMAGE_FIELDS: Final[frozenset[str]] = frozenset( + {"FileName", "Type", "Region"} +) + + class LaunchboxPlatform(TypedDict): slug: str launchbox_id: int | None diff --git a/backend/tasks/scheduled/update_launchbox_metadata.py b/backend/tasks/scheduled/update_launchbox_metadata.py index 0ca128e9b..b6d83218b 100644 --- a/backend/tasks/scheduled/update_launchbox_metadata.py +++ b/backend/tasks/scheduled/update_launchbox_metadata.py @@ -16,6 +16,7 @@ from config import ( from handler.metadata import meta_launchbox_handler from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_FILES_KEY, + LAUNCHBOX_IMAGE_FIELDS, LAUNCHBOX_MAME_KEY, LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, LAUNCHBOX_METADATA_DATABASE_ID_KEY, @@ -41,10 +42,6 @@ CACHE_WRITE_BATCH_SIZE: Final[int] = 2000 # Downloading ~100MB and parsing it takes far longer than an ordinary task. LAUNCHBOX_TASK_TIMEOUT: Final[int] = max(TASK_TIMEOUT, 30 * 60) -# `DatabaseID` repeats the field an image list is stored under and `CRC32` has -# no reader, and the dump holds 1.3M images, so dropping the pair saves ~100MB. -GAME_IMAGE_FIELDS: Final[frozenset[str]] = frozenset({"FileName", "Type", "Region"}) - class BatchedCacheWriter: """Queues cache writes on a pipeline, flushing every `batch_size` entries.""" @@ -67,9 +64,9 @@ class BatchedCacheWriter: def _element_to_dict(elem: Any, fields: frozenset[str] | None = None) -> dict[str, Any]: - return { - child.tag: child.text for child in elem if fields is None or child.tag in fields - } + if fields is None: + return {child.tag: child.text for child in elem} + return {child.tag: child.text for child in elem if child.tag in fields} def _iter_elements(source: Any) -> Iterator[Any]: @@ -182,12 +179,9 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): for elem in _iter_elements(f): if elem.tag == "Game": - id_elem = elem.find("DatabaseID") database_id = ( - id_elem.text.strip() - if id_elem is not None and id_elem.text - else None - ) + elem.findtext("DatabaseID") or "" + ).strip() if database_id: await writer.hset( LAUNCHBOX_METADATA_DATABASE_ID_KEY, @@ -195,28 +189,20 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): _element_to_dict(elem), ) - name_elem = elem.find("Name") - platform_elem = elem.find("Platform") - if ( - database_id - and name_elem is not None - and name_elem.text - and platform_elem is not None - and platform_elem.text - ): - platform_name = platform_elem.text.strip() - - # The title indexes hold the id of the - # record, not a second and third copy - # of it: each costs ~120MB of cache. + name = (elem.findtext("Name") or "").strip() + platform_name = ( + elem.findtext("Platform") or "" + ).strip() + if database_id and name and platform_name: + # Storing the id rather than the record: + # each copy costs ~120MB of cache. await writer.hset( LAUNCHBOX_METADATA_NAME_KEY, - f"{name_elem.text.strip().lower()}" - f":{platform_name}", + f"{name.lower()}:{platform_name}", database_id, ) - folded = fold_title(name_elem.text) + folded = fold_title(name) if folded: await writer.hset( LAUNCHBOX_METADATA_FOLDED_NAME_KEY, @@ -256,7 +242,7 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): current_game_image_db_id = image_id current_game_images.append( _element_to_dict( - elem, GAME_IMAGE_FIELDS + elem, LAUNCHBOX_IMAGE_FIELDS ) ) diff --git a/backend/tasks/scheduled/update_switch_titledb.py b/backend/tasks/scheduled/update_switch_titledb.py index d290d2781..419d11950 100644 --- a/backend/tasks/scheduled/update_switch_titledb.py +++ b/backend/tasks/scheduled/update_switch_titledb.py @@ -47,14 +47,13 @@ class UpdateSwitchTitleDBTask(RemoteFilePullTask): async with async_cache.pipeline() as pipe: for data_batch in batched(relevant_data.items(), 2000, strict=False): - titledb_map = {k: json.dumps(v) for k, v in dict(data_batch).items()} - await pipe.hset(SWITCH_TITLEDB_INDEX_KEY, mapping=titledb_map) - processed_items += len(data_batch) - update_stats.update(processed=processed_items) + await pipe.hset( + SWITCH_TITLEDB_INDEX_KEY, + mapping={title_id: json.dumps(v) for title_id, v in data_batch}, + ) - # The product id index points at the titleID index entry rather than - # holding a second copy of it, which costs ~60MB of cache. - for data_batch in batched(relevant_data.items(), 2000, strict=False): + # The product id index points at the titleID index entry rather + # than holding a second copy of it, which costs ~60MB of cache. product_map = { v["id"]: json.dumps(title_id) for title_id, v in data_batch @@ -62,6 +61,9 @@ class UpdateSwitchTitleDBTask(RemoteFilePullTask): } if product_map: await pipe.hset(SWITCH_PRODUCT_ID_KEY, mapping=product_map) + + processed_items += len(data_batch) + update_stats.update(processed=processed_items) await pipe.execute() # Final progress update diff --git a/backend/tests/handler/metadata/test_base_handler.py b/backend/tests/handler/metadata/test_base_handler.py index 421af5c77..8e3a63902 100644 --- a/backend/tests/handler/metadata/test_base_handler.py +++ b/backend/tests/handler/metadata/test_base_handler.py @@ -29,6 +29,7 @@ from handler.metadata.base_handler import ( ) from handler.redis_handler import async_cache from models.rom import Rom +from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_INDEX_KEY from utils.context import ctx_httpx_client from utils.platform_slugs import UniversalPlatformSlug @@ -356,7 +357,7 @@ class TestMetadataHandlerMethods: result = await handler._switch_productid_format(rom, "Game.nsp", "original") assert mock_hget.await_args_list[1].args == ( - "romm:switch_titledb", # SWITCH_TITLEDB_INDEX_KEY + SWITCH_TITLEDB_INDEX_KEY, "70010000000025", ) assert result[0] == "Product Game" diff --git a/backend/tests/handler/metadata/test_launchbox_handler.py b/backend/tests/handler/metadata/test_launchbox_handler.py index 6408f18f4..757056fd8 100644 --- a/backend/tests/handler/metadata/test_launchbox_handler.py +++ b/backend/tests/handler/metadata/test_launchbox_handler.py @@ -596,11 +596,20 @@ class TestRemoteSourceGetRom: assert result is not None assert result.get("DatabaseID", None) == "1234" - async def test_name_match_follows_database_id(self, source: RemoteSource): + @pytest.mark.parametrize( + ("index_key", "file_name"), + [ + (LAUNCHBOX_METADATA_NAME_KEY, "super mario bros."), + (LAUNCHBOX_METADATA_FOLDED_NAME_KEY, "super mario bros"), + ], + ) + async def test_title_index_follows_database_id( + self, source: RemoteSource, index_key: str, file_name: str + ): """A title index hit holds the id of the record, not the record.""" async def side_effect(key, _field): - if key == LAUNCHBOX_METADATA_NAME_KEY: + if key == index_key: return json.dumps("1234") if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: return json.dumps(REMOTE_ENTRY) @@ -609,26 +618,7 @@ class TestRemoteSourceGetRom: with patch.object( async_cache, "hget", new_callable=AsyncMock, side_effect=side_effect ): - result = await source.get_rom( - "super mario bros.", "nes", assume_cache_present=True - ) - assert result is not None - assert result.get("Name", None) == "Super Mario Bros." - - async def test_folded_name_match_follows_database_id(self, source: RemoteSource): - async def side_effect(key, _field): - if key == LAUNCHBOX_METADATA_FOLDED_NAME_KEY: - return json.dumps("1234") - if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: - return json.dumps(REMOTE_ENTRY) - return None - - with patch.object( - async_cache, "hget", new_callable=AsyncMock, side_effect=side_effect - ): - result = await source.get_rom( - "super mario bros", "nes", assume_cache_present=True - ) + result = await source.get_rom(file_name, "nes", assume_cache_present=True) assert result is not None assert result.get("Name", None) == "Super Mario Bros."