diff --git a/backend/handler/metadata/base_handler.py b/backend/handler/metadata/base_handler.py index e56857a4b..7f8af5caa 100644 --- a/backend/handler/metadata/base_handler.py +++ b/backend/handler/metadata/base_handler.py @@ -15,7 +15,9 @@ from logger.logger import log from tasks.scheduled.update_switch_titledb import ( SWITCH_PRODUCT_ID_KEY, SWITCH_TITLEDB_INDEX_KEY, + SWITCH_TITLEDB_STORE, ) +from utils.cache import is_cache_store_ready from utils.context import ctx_httpx_client from utils.switch import derive_base_title_id @@ -273,13 +275,12 @@ class MetadataHandler(abc.ABC): ) -> tuple[str, dict | None]: title_id = match.group(1) - if not (await async_cache.exists(SWITCH_TITLEDB_INDEX_KEY)): - log.error("Could not find the Switch titleID index file in cache") + if not await self._is_switch_titledb_current(): + log.error("Could not find a current Switch titleID index 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 @@ -301,17 +302,37 @@ class MetadataHandler(abc.ABC): # low 12 bits, and only the base has a titledb entry. product_id = derive_base_title_id(product_id) or product_id - if not (await async_cache.exists(SWITCH_PRODUCT_ID_KEY)): - log.error("Could not find the Switch productID index file in cache") + if not await self._is_switch_titledb_current(): + log.error("Could not find a current Switch productID index in cache") return search_term, None - index_entry = await async_cache.hget(SWITCH_PRODUCT_ID_KEY, product_id) + index_entry = await self._switch_product_id_entry(product_id) if index_entry: - index_entry = json.loads(index_entry) return index_entry["name"], index_entry return search_term, None + @staticmethod + async def _is_switch_titledb_current() -> bool: + """Whether the titleID index was written by the current import.""" + return await is_cache_store_ready( + async_cache, SWITCH_TITLEDB_STORE, SWITCH_TITLEDB_INDEX_KEY + ) + + @staticmethod + 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 + + @classmethod + async def _switch_product_id_entry(cls, product_id: str) -> dict | None: + """Resolve a Switch product id to the titleID entry its index points at.""" + title_id = await async_cache.hget(SWITCH_PRODUCT_ID_KEY, product_id) + if not title_id: + return None + + return await cls._switch_titledb_entry(json.loads(title_id)) + async def _mame_format(self, search_term: str) -> str: from handler.filesystem import fs_rom_handler diff --git a/backend/handler/metadata/launchbox_handler/handler.py b/backend/handler/metadata/launchbox_handler/handler.py index 5625b6e7b..27001675f 100644 --- a/backend/handler/metadata/launchbox_handler/handler.py +++ b/backend/handler/metadata/launchbox_handler/handler.py @@ -4,6 +4,7 @@ from config import LAUNCHBOX_API_ENABLED from handler.filesystem import fs_rom_handler from handler.redis_handler import async_cache from logger.logger import log +from utils.cache import is_cache_store_ready from utils.database import safe_int from utils.platform_slugs import UniversalPlatformSlug as UPS @@ -16,6 +17,7 @@ from .types import ( DASH_COLON_REGEX, LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_METADATA_STORE, LAUNCHBOX_PLATFORMS_DIR, LAUNCHBOX_TAG_REGEX, LaunchboxPlatform, @@ -42,7 +44,9 @@ class LaunchboxHandler(MetadataHandler): @staticmethod async def is_remote_store_populated() -> bool: - return bool(await async_cache.exists(LAUNCHBOX_METADATA_NAME_KEY)) + return await is_cache_store_ready( + async_cache, LAUNCHBOX_METADATA_STORE, LAUNCHBOX_METADATA_NAME_KEY + ) @staticmethod async def is_remote_store_importing() -> bool: diff --git a/backend/handler/metadata/launchbox_handler/remote_source.py b/backend/handler/metadata/launchbox_handler/remote_source.py index 7ee9f58ae..a1f75f35a 100644 --- a/backend/handler/metadata/launchbox_handler/remote_source.py +++ b/backend/handler/metadata/launchbox_handler/remote_source.py @@ -2,6 +2,7 @@ import json from handler.redis_handler import async_cache from logger.logger import log +from utils.cache import is_cache_store_ready from .platforms import get_platform from .types import ( @@ -12,6 +13,7 @@ from .types import ( LAUNCHBOX_METADATA_FOLDED_NAME_KEY, LAUNCHBOX_METADATA_IMAGE_KEY, LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_METADATA_STORE, ) from .utils import deinvert_article, file_name_forms, fold_title @@ -25,6 +27,14 @@ class RemoteSource: return None return json.loads(entry) + async def _lookup_title_index(self, key: str, field: str) -> dict | None: + """Read a title index hit and resolve the database id it holds.""" + database_id = await async_cache.hget(key, field) + if not database_id: + return None + + return await self.get_by_id(json.loads(database_id)) + async def get_rom( self, file_name: str, @@ -32,10 +42,10 @@ class RemoteSource: *, assume_cache_present: bool = False, ) -> dict | None: - if not assume_cache_present and not ( - await async_cache.exists(LAUNCHBOX_METADATA_NAME_KEY) + if not assume_cache_present and not await is_cache_store_ready( + async_cache, LAUNCHBOX_METADATA_STORE, LAUNCHBOX_METADATA_NAME_KEY ): - log.error("Could not find the Launchbox Metadata.xml file in cache") + log.error("Could not find a current Launchbox Metadata.xml in cache") return None lb_platform = get_platform(platform_slug) @@ -61,32 +71,21 @@ 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 metadata_name_index_entry: - return json.loads(metadata_name_index_entry) + if entry: + return entry for candidate in candidates: - metadata_alternate_name_index_entry = await async_cache.hget( + entry = await self._lookup_title_index( LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, candidate ) - 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: + 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 @@ -98,11 +97,11 @@ 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 folded_index_entry: - return json.loads(folded_index_entry) + if entry: + return entry return None diff --git a/backend/handler/metadata/launchbox_handler/types.py b/backend/handler/metadata/launchbox_handler/types.py index 75efa3713..018d24a14 100644 --- a/backend/handler/metadata/launchbox_handler/types.py +++ b/backend/handler/metadata/launchbox_handler/types.py @@ -4,6 +4,7 @@ from pathlib import Path from typing import Final, NotRequired, TypedDict from config import ROMM_BASE_PATH +from utils.cache import VersionedCacheStore from ..base_handler import BaseRom @@ -22,6 +23,22 @@ LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY: Final[str] = ( "romm:launchbox_metadata_initial_import" ) +# Every hash the Metadata.zip import fills, dropped together on a schema bump. +LAUNCHBOX_METADATA_STORE: Final[VersionedCacheStore] = VersionedCacheStore( + schema_key="romm:launchbox_metadata_schema", + version=1, + keys=( + LAUNCHBOX_PLATFORMS_KEY, + LAUNCHBOX_METADATA_DATABASE_ID_KEY, + LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, + LAUNCHBOX_METADATA_FOLDED_NAME_KEY, + LAUNCHBOX_METADATA_IMAGE_KEY, + LAUNCHBOX_MAME_KEY, + LAUNCHBOX_FILES_KEY, + ), +) + LAUNCHBOX_LOCAL_DIR: Final[Path] = Path(ROMM_BASE_PATH) / "launchbox" LAUNCHBOX_PLATFORMS_DIR: Final[Path] = LAUNCHBOX_LOCAL_DIR / "Data" / "Platforms" LAUNCHBOX_IMAGES_DIR: Final[Path] = LAUNCHBOX_LOCAL_DIR / "Images" @@ -39,6 +56,15 @@ class LaunchboxImage(TypedDict): region: NotRequired[str] +# What each store keeps of its dump element: the fields its reader reads, and +# never one the cache key already carries. +LAUNCHBOX_IMAGE_FIELDS: Final[frozenset[str]] = frozenset( + {"FileName", "Type", "Region"} +) +LAUNCHBOX_FILE_FIELDS: Final[frozenset[str]] = frozenset({"GameName"}) +LAUNCHBOX_MAME_FIELDS: Final[frozenset[str]] = frozenset({"Name"}) + + class LaunchboxPlatform(TypedDict): slug: str launchbox_id: int | None diff --git a/backend/startup.py b/backend/startup.py index c496bd7dd..79ce134d3 100644 --- a/backend/startup.py +++ b/backend/startup.py @@ -8,7 +8,11 @@ from rq.exceptions import DuplicateJobError from rq.job import Job from rq.utils import as_text -from config import ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP, SENTRY_DSN +from config import ( + ENABLE_SCHEDULED_CONVERT_IMAGES_TO_WEBP, + LAUNCHBOX_API_ENABLED, + SENTRY_DSN, +) from config.config_manager import config_manager as cm from handler.database import db_save_handler from handler.metadata.base_handler import ( @@ -20,6 +24,7 @@ from handler.metadata.base_handler import ( PSP_SERIAL_INDEX_KEY, SCUMMVM_INDEX_KEY, ) +from handler.metadata.launchbox_handler.types import LAUNCHBOX_METADATA_STORE from handler.redis_handler import ( async_cache, default_queue, @@ -31,14 +36,17 @@ from handler.scan_jobs import drop_stale_scheduled_scans from logger.logger import log from models.firmware import FIRMWARE_FIXTURES_DIR, KNOWN_BIOS_KEY from tasks.registry import enqueue_task +from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE from utils import get_version -from utils.cache import conditionally_set_cache +from utils.cache import conditionally_set_cache, drop_stale_cache_store from utils.context import initialize_context tracer = trace.get_tracer(__name__) RECOMPUTE_SAVE_HASHES_JOB_ID = "recompute_save_content_hashes_bootstrap" CONVERT_IMAGES_TO_WEBP_JOB_ID = "convert_images_to_webp_bootstrap" +UPDATE_LAUNCHBOX_METADATA_JOB_ID = "update_launchbox_metadata_bootstrap" +UPDATE_SWITCH_TITLEDB_JOB_ID = "update_switch_titledb_bootstrap" def _enqueue_backfill(task_name: str, job_id: str) -> None: @@ -87,6 +95,35 @@ def _enqueue_convert_images_to_webp() -> None: _enqueue_backfill("convert_images_to_webp", CONVERT_IMAGES_TO_WEBP_JOB_ID) +# A provider that is off reclaims its store's memory without queueing a +# download nothing would read. +VERSIONED_METADATA_STORES = ( + ( + LAUNCHBOX_METADATA_STORE, + "update_launchbox_metadata", + UPDATE_LAUNCHBOX_METADATA_JOB_ID, + LAUNCHBOX_API_ENABLED, + ), + ( + SWITCH_TITLEDB_STORE, + "update_switch_titledb", + UPDATE_SWITCH_TITLEDB_JOB_ID, + True, + ), +) + + +async def _rebuild_outdated_metadata_stores() -> None: + """Drop the metadata stores an older release wrote and queue their rebuild.""" + for store, task_name, job_id, rebuild in VERSIONED_METADATA_STORES: + if not await drop_stale_cache_store(async_cache, store): + continue + + log.info(f"Dropped the {task_name} store left by an older release") + if rebuild: + _enqueue_backfill(task_name, job_id) + + # Keys the rq-scheduler process left behind, now owned by the cron config. LEGACY_SCHEDULED_JOBS_KEY = "rq:scheduler:scheduled_jobs" LEGACY_SCHEDULER_KEYS = ( @@ -148,6 +185,11 @@ async def main() -> None: _enqueue_recompute_save_hashes_if_needed() + try: + await _rebuild_outdated_metadata_stores() + except Exception: + log.exception("Failed to check the metadata stores for an older shape") + log.info("Initializing cache with fixtures data") await conditionally_set_cache( async_cache, MAME_XML_KEY, METADATA_FIXTURES_DIR / "mame_index.json" diff --git a/backend/tasks/scheduled/update_launchbox_metadata.py b/backend/tasks/scheduled/update_launchbox_metadata.py index a1314a168..c1c4b1f61 100644 --- a/backend/tasks/scheduled/update_launchbox_metadata.py +++ b/backend/tasks/scheduled/update_launchbox_metadata.py @@ -15,7 +15,10 @@ from config import ( ) from handler.metadata import meta_launchbox_handler from handler.metadata.launchbox_handler.types import ( + LAUNCHBOX_FILE_FIELDS, LAUNCHBOX_FILES_KEY, + LAUNCHBOX_IMAGE_FIELDS, + LAUNCHBOX_MAME_FIELDS, LAUNCHBOX_MAME_KEY, LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, LAUNCHBOX_METADATA_DATABASE_ID_KEY, @@ -23,12 +26,14 @@ from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_METADATA_IMAGE_KEY, LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_METADATA_STORE, LAUNCHBOX_PLATFORMS_KEY, ) from handler.metadata.launchbox_handler.utils import fold_title from handler.redis_handler import async_cache from logger.logger import log from tasks.tasks import RemoteFilePullTask, TaskType +from utils.cache import drop_stale_cache_store, stamp_cache_schema from utils.context import initialize_context from . import UpdateStats @@ -62,8 +67,10 @@ class BatchedCacheWriter: self._queued = 0 -def _element_to_dict(elem: Any) -> dict[str, Any]: - return {child.tag: child.text for child in elem} +def _element_to_dict(elem: Any, fields: frozenset[str] | None = None) -> dict[str, Any]: + 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]: @@ -134,6 +141,9 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): if not await meta_launchbox_handler.is_remote_store_populated(): await async_cache.set(LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, "1") + # An import merges into its hashes, so an older release's rows go first. + await drop_stale_cache_store(async_cache, LAUNCHBOX_METADATA_STORE) + try: zip_file_bytes = BytesIO(content) with zipfile.ZipFile(zip_file_bytes) as z: @@ -176,51 +186,49 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): for elem in _iter_elements(f): if elem.tag == "Game": - id_elem = elem.find("DatabaseID") - if id_elem is not None and id_elem.text: + database_id = ( + elem.findtext("DatabaseID") or "" + ).strip() + if database_id: await writer.hset( LAUNCHBOX_METADATA_DATABASE_ID_KEY, - id_elem.text.strip(), + database_id, _element_to_dict(elem), ) - name_elem = elem.find("Name") - platform_elem = elem.find("Platform") - if ( - 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() - game = _element_to_dict(elem) - - # Use a unique combination of name and platform as the key + name = (elem.findtext("Name") or "").strip() + platform_name = ( + elem.findtext("Platform") or "" + ).strip() + if database_id and name and platform_name: + # A full copy of the record here + # costs ~120MB of cache. await writer.hset( LAUNCHBOX_METADATA_NAME_KEY, - f"{name_elem.text.strip().lower()}" - f":{platform_name}", - game, + 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, f"{folded}:{platform_name}", - game, + database_id, ) elif elem.tag == "GameAlternateName": - alternate_name_elem = elem.find("AlternateName") - if ( - alternate_name_elem is not None - and alternate_name_elem.text - ): + alternate_name = ( + elem.findtext("AlternateName") or "" + ).strip() + alternate_id = ( + elem.findtext("DatabaseID") or "" + ).strip() + if alternate_name and alternate_id: await writer.hset( LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, - alternate_name_elem.text.strip().lower(), - _element_to_dict(elem), + alternate_name.lower(), + alternate_id, ) elif elem.tag == "GameImage": @@ -242,7 +250,9 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): current_game_image_db_id = image_id current_game_images.append( - _element_to_dict(elem) + _element_to_dict( + elem, LAUNCHBOX_IMAGE_FIELDS + ) ) # Store the last game's images @@ -271,7 +281,9 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): await writer.hset( LAUNCHBOX_MAME_KEY, filename_elem.text.strip(), - _element_to_dict(elem), + _element_to_dict( + elem, LAUNCHBOX_MAME_FIELDS + ), ) await writer.flush() @@ -299,7 +311,9 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): LAUNCHBOX_FILES_KEY, f"{filename_elem.text.strip().lower()}" f":{platform_elem.text.strip()}", - _element_to_dict(elem), + _element_to_dict( + elem, LAUNCHBOX_FILE_FIELDS + ), ) await writer.flush() @@ -310,6 +324,8 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): log.error("Bad zip file in launchbox metadata update") return update_stats.to_dict() + await stamp_cache_schema(async_cache, LAUNCHBOX_METADATA_STORE) + # Also clears a flag left behind by an earlier run that died partway. await async_cache.delete(LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY) diff --git a/backend/tasks/scheduled/update_switch_titledb.py b/backend/tasks/scheduled/update_switch_titledb.py index 48142f697..7743fa4cb 100644 --- a/backend/tasks/scheduled/update_switch_titledb.py +++ b/backend/tasks/scheduled/update_switch_titledb.py @@ -9,12 +9,22 @@ from config import ( from handler.redis_handler import async_cache from logger.logger import log from tasks.tasks import RemoteFilePullTask, TaskType +from utils.cache import ( + VersionedCacheStore, + drop_stale_cache_store, + stamp_cache_schema, +) from utils.context import initialize_context from . import UpdateStats SWITCH_TITLEDB_INDEX_KEY: Final = "romm:switch_titledb" SWITCH_PRODUCT_ID_KEY: Final = "romm:switch_product_id" +SWITCH_TITLEDB_STORE: Final = VersionedCacheStore( + schema_key="romm:switch_titledb_schema", + version=1, + keys=(SWITCH_TITLEDB_INDEX_KEY, SWITCH_PRODUCT_ID_KEY), +) class UpdateSwitchTitleDBTask(RemoteFilePullTask): @@ -37,6 +47,9 @@ class UpdateSwitchTitleDBTask(RemoteFilePullTask): if content is None: return update_stats.to_dict() + # An import merges into its hashes, so an older release's rows go first. + await drop_stale_cache_store(async_cache, SWITCH_TITLEDB_STORE) + index_json = json.loads(content) relevant_data = {k: v for k, v in index_json.items() if k and v} total_items = len(relevant_data) @@ -47,21 +60,26 @@ 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}, + ) - for data_batch in batched(relevant_data.items(), 2000, strict=False): + # A second copy of each entry here costs ~60MB of cache. product_map = { - v["id"]: json.dumps(v) - for v in dict(data_batch).values() + v["id"]: json.dumps(title_id) + for title_id, v in data_batch if v.get("id") } 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() + await stamp_cache_schema(async_cache, SWITCH_TITLEDB_STORE) + # Final progress update update_stats.update(processed=processed_items) log.info("Scheduled switch titledb update completed!") diff --git a/backend/tests/handler/metadata/conftest.py b/backend/tests/handler/metadata/conftest.py new file mode 100644 index 000000000..e1496aad8 --- /dev/null +++ b/backend/tests/handler/metadata/conftest.py @@ -0,0 +1,13 @@ +from unittest.mock import AsyncMock + +from utils.cache import VersionedCacheStore + + +def schema_stamp_get(*stores: VersionedCacheStore) -> AsyncMock: + """Mock `async_cache.get` so the given stores read as currently stamped.""" + stamps = {store.schema_key: str(store.version) for store in stores} + + async def get(key: str) -> str | None: + return stamps.get(key) + + return AsyncMock(side_effect=get) diff --git a/backend/tests/handler/metadata/test_base_handler.py b/backend/tests/handler/metadata/test_base_handler.py index e657e9f5a..5925fcf5a 100644 --- a/backend/tests/handler/metadata/test_base_handler.py +++ b/backend/tests/handler/metadata/test_base_handler.py @@ -6,6 +6,7 @@ from urllib.parse import parse_qsl, urlparse import httpx import pytest +from tests.handler.metadata.conftest import schema_stamp_get from handler.metadata import base_handler from handler.metadata.base_handler import ( @@ -29,6 +30,11 @@ 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_PRODUCT_ID_KEY, + SWITCH_TITLEDB_INDEX_KEY, + SWITCH_TITLEDB_STORE, +) from utils.context import ctx_httpx_client from utils.platform_slugs import UniversalPlatformSlug @@ -268,6 +274,8 @@ class TestMetadataHandlerMethods: with patch.object( async_cache, "exists", new_callable=AsyncMock ) as mock_exists, patch.object( + async_cache, "get", schema_stamp_get(SWITCH_TITLEDB_STORE) + ), patch.object( async_cache, "hget", new_callable=AsyncMock ) as mock_hget: mock_exists.return_value = True @@ -323,18 +331,24 @@ class TestMetadataHandlerMethods: with patch.object( async_cache, "exists", new_callable=AsyncMock ) as mock_exists, patch.object( + async_cache, "get", schema_stamp_get(SWITCH_TITLEDB_STORE) + ), patch.object( async_cache, "hget", new_callable=AsyncMock ) as mock_hget: mock_exists.return_value = True - mock_hget.return_value = json.dumps({"name": "Product Game"}) + mock_hget.side_effect = [ + json.dumps("70010000000025"), + json.dumps({"name": "Product Game"}), + ] rom = Rom(fs_name="Game.nsp", title_id=product_id) result = await handler._switch_productid_format(rom, "Game.nsp", "original") - mock_hget.assert_called_once_with( - "romm:switch_product_id", # SWITCH_PRODUCT_ID_KEY - "0100ABCD12340000", - ) + # The product id index holds the title id of its titleID entry. + assert [call.args for call in mock_hget.await_args_list] == [ + (SWITCH_PRODUCT_ID_KEY, "0100ABCD12340000"), + (SWITCH_TITLEDB_INDEX_KEY, "70010000000025"), + ] assert result[0] == "Product Game" @pytest.mark.parametrize( @@ -364,6 +378,8 @@ class TestMetadataHandlerMethods: with patch.object( async_cache, "exists", new_callable=AsyncMock ) as mock_exists, patch.object( + async_cache, "get", schema_stamp_get(SWITCH_TITLEDB_STORE) + ), patch.object( async_cache, "hget", new_callable=AsyncMock ) as mock_hget: mock_exists.return_value = True @@ -374,10 +390,7 @@ class TestMetadataHandlerMethods: if expected is None: mock_hget.assert_not_called() else: - mock_hget.assert_called_once_with( - "romm:switch_product_id", # SWITCH_PRODUCT_ID_KEY - expected, - ) + mock_hget.assert_called_once_with(SWITCH_PRODUCT_ID_KEY, expected) @pytest.mark.asyncio async def test_mame_format_found(self, handler: MetadataHandler): diff --git a/backend/tests/handler/metadata/test_launchbox_handler.py b/backend/tests/handler/metadata/test_launchbox_handler.py index 750f510a9..ff0fc3c72 100644 --- a/backend/tests/handler/metadata/test_launchbox_handler.py +++ b/backend/tests/handler/metadata/test_launchbox_handler.py @@ -16,6 +16,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest from anyio import Path as AnyioPath from defusedxml import ElementTree as ET +from tests.handler.metadata.conftest import schema_stamp_get from handler.metadata.launchbox_handler.handler import LaunchboxHandler from handler.metadata.launchbox_handler.local_source import LocalSource @@ -40,6 +41,7 @@ from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_METADATA_IMAGE_KEY, LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_METADATA_STORE, LaunchboxImage, LaunchboxMetadata, MediaRequest, @@ -99,6 +101,7 @@ SAMPLE_N64_XML = """\ """ + REMOTE_ENTRY = { "DatabaseID": "1234", "Name": "Super Mario Bros.", @@ -596,6 +599,48 @@ class TestRemoteSourceGetRom: assert result is not None assert result.get("DatabaseID", None) == "1234" + @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 == index_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(file_name, "nes", assume_cache_present=True) + assert result is not None + assert result.get("Name", None) == "Super Mario Bros." + + async def test_title_index_pointing_at_missing_record(self, source: RemoteSource): + """A refresh that dropped the record leaves the index pointing nowhere.""" + + async def side_effect(key, _field): + if key == LAUNCHBOX_METADATA_NAME_KEY: + return json.dumps("1234") + 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 + ) + assert result is None + async def test_alternate_name_match(self, source: RemoteSource): alt_entry = {"DatabaseID": "1234"} @@ -652,6 +697,8 @@ class TestRemoteSourceGetRom: key == LAUNCHBOX_METADATA_NAME_KEY and field == "the legend of zelda: ocarina of time:Nintendo 64" ): + return json.dumps("161") + if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: return json.dumps(entry) return None @@ -691,6 +738,8 @@ class TestRemoteSourceGetRom: async def side_effect(key, field): if key == LAUNCHBOX_METADATA_FOLDED_NAME_KEY and field == folded_field: + return json.dumps("77") + if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: return json.dumps(entry) return None @@ -734,11 +783,13 @@ class TestRemoteSourceGetRom: exact = {"DatabaseID": "1", "Name": "Burnout Revenge"} folded = {"DatabaseID": "2", "Name": "Burnout: Revenge"} - async def side_effect(key, _field): + async def side_effect(key, field): if key == LAUNCHBOX_METADATA_NAME_KEY: - return json.dumps(exact) + return json.dumps("1") if key == LAUNCHBOX_METADATA_FOLDED_NAME_KEY: - return json.dumps(folded) + return json.dumps("2") + if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: + return json.dumps(exact if field == "1" else folded) return None with patch.object( @@ -773,20 +824,17 @@ class TestRemoteSourceGetRomByFileName: return RemoteSource() async def test_file_name_resolves_to_title(self, source: RemoteSource): - file_entry = { - "Platform": "Commodore Amiga", - "FileName": "1943_v1.3", - "GameName": "1943: The Battle of Midway", - } game_entry = {"DatabaseID": "999", "Name": "1943: The Battle of Midway"} async def side_effect(key, field): if key == LAUNCHBOX_FILES_KEY and field == "1943_v1.3:Commodore Amiga": - return json.dumps(file_entry) + return json.dumps({"GameName": "1943: The Battle of Midway"}) if ( key == LAUNCHBOX_METADATA_NAME_KEY and field == "1943: The Battle of Midway:Commodore Amiga" ): + return json.dumps("999") + if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: return json.dumps(game_entry) return None @@ -1300,6 +1348,9 @@ class TestRemoteMatchLocalImages: h._remote.fetch_images = AsyncMock(return_value=None) # type: ignore[method-assign] monkeypatch.setattr(LaunchboxHandler, "is_enabled", lambda *_: True) monkeypatch.setattr(async_cache, "exists", AsyncMock(return_value=True)) + monkeypatch.setattr( + async_cache, "get", schema_stamp_get(LAUNCHBOX_METADATA_STORE) + ) with patch( "handler.metadata.launchbox_handler.handler.fs_rom_handler" @@ -1431,6 +1482,9 @@ class TestLaunchboxHandlerHeartbeat: patch.object( async_cache, "exists", self._cache_exists(LAUNCHBOX_METADATA_NAME_KEY) ), + patch.object( + async_cache, "get", schema_stamp_get(LAUNCHBOX_METADATA_STORE) + ), ): assert await handler.heartbeat() is True @@ -1486,6 +1540,9 @@ class TestLaunchboxHandlerGetRom: h._remote.fetch_images = AsyncMock(return_value=None) # type: ignore[method-assign] monkeypatch.setattr(LaunchboxHandler, "is_enabled", lambda *_: True) monkeypatch.setattr(async_cache, "exists", AsyncMock(return_value=True)) + monkeypatch.setattr( + async_cache, "get", schema_stamp_get(LAUNCHBOX_METADATA_STORE) + ) return h async def test_disabled_returns_fallback( @@ -1652,7 +1709,8 @@ class TestLaunchboxHandlerGetRom: LAUNCHBOX_METADATA_NAME_KEY, "the legend of zelda: a link to the past" ":Super Nintendo Entertainment System", - ): json.dumps(entry) + ): json.dumps("5678"), + (LAUNCHBOX_METADATA_DATABASE_ID_KEY, "5678"): json.dumps(entry), } async def hget(key, field): @@ -1836,6 +1894,9 @@ class TestLaunchboxHandlerSearch: h._remote.fetch_images = AsyncMock(return_value=None) # type: ignore[method-assign] monkeypatch.setattr(LaunchboxHandler, "is_enabled", lambda *_: True) monkeypatch.setattr(async_cache, "exists", AsyncMock(return_value=True)) + monkeypatch.setattr( + async_cache, "get", schema_stamp_get(LAUNCHBOX_METADATA_STORE) + ) return h async def test_get_matched_roms_by_name_disabled_returns_empty( diff --git a/backend/tests/handler/metadata/test_ss_handler.py b/backend/tests/handler/metadata/test_ss_handler.py index 30fc5210d..e1aec435f 100644 --- a/backend/tests/handler/metadata/test_ss_handler.py +++ b/backend/tests/handler/metadata/test_ss_handler.py @@ -7,6 +7,7 @@ from urllib.parse import parse_qs, urlparse import pytest from fastapi import HTTPException, status +from tests.handler.metadata.conftest import schema_stamp_get from adapters.services.screenscraper import ( ScreenScraperCredentialsError, @@ -39,6 +40,7 @@ from handler.metadata.ss_handler import ( ) from handler.redis_handler import async_cache from models.rom import Rom +from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE def _make_config( @@ -1978,6 +1980,7 @@ class TestSonySerialFilenames: return_value=True, ), patch.object(async_cache, "exists", new_callable=AsyncMock) as mock_exists, + patch.object(async_cache, "get", schema_stamp_get(SWITCH_TITLEDB_STORE)), patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget, patch.object( SSHandler, "_search_rom", new_callable=AsyncMock, return_value=None diff --git a/backend/tests/tasks/fixtures/sample_metadata.zip b/backend/tests/tasks/fixtures/sample_metadata.zip index 1930545e3..89879a3c0 100644 Binary files a/backend/tests/tasks/fixtures/sample_metadata.zip and b/backend/tests/tasks/fixtures/sample_metadata.zip differ diff --git a/backend/tests/tasks/test_update_launchbox_metadata.py b/backend/tests/tasks/test_update_launchbox_metadata.py index 190aadcd6..219f77392 100644 --- a/backend/tests/tasks/test_update_launchbox_metadata.py +++ b/backend/tests/tasks/test_update_launchbox_metadata.py @@ -1,4 +1,6 @@ +import json import os +from typing import Any from unittest.mock import AsyncMock, patch import anyio @@ -15,6 +17,7 @@ from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_METADATA_IMAGE_KEY, LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_METADATA_STORE, LAUNCHBOX_PLATFORMS_KEY, ) from handler.redis_handler import async_cache @@ -210,6 +213,38 @@ class TestUpdateLaunchboxMetadataTask: assert fields(metadata_image_calls) == {"12345"} assert fields(mame_calls) == {"mario.zip", "pacman.zip"} + def values(calls) -> list[Any]: + return [ + json.loads(value) + for call in calls + for value in call[1]["mapping"].values() + ] + + # The title indexes point at the record, rather than repeating it. + assert sorted(values(metadata_name_calls)) == ["12345", "67890"] + assert sorted(values(metadata_folded_calls)) == ["12345", "67890"] + + # Images keep only the fields media selection reads. + assert values(metadata_image_calls) == [ + [ + {"FileName": "super_mario_64.jpg", "Type": "Cover"}, + {"FileName": "super_mario_64_screenshot.jpg", "Type": "Screenshot"}, + ] + ] + + # The alternate name index points at the record like the other two. + assert values(metadata_alt_calls) == ["12345"] + + # A store keeps its reader's field, never one the key already carries. + assert values(files_calls) == [ + {"GameName": "Super Mario 64"}, + {"GameName": "Crash Bandicoot"}, + ] + assert values(mame_calls) == [ + {"Name": "Super Mario Bros."}, + {"Name": "Pac-Man"}, + ] + @patch.object(RemoteFilePullTask, "run") @patch("tasks.scheduled.update_launchbox_metadata.async_cache.pipeline") async def test_empty_xml_elements_handling( @@ -333,18 +368,8 @@ class TestUpdateLaunchboxMetadataTaskIntegration: # Verify that all expected Redis keys were used redis_keys_used = [call[0][0] for call in hset_calls] - expected_keys = [ - LAUNCHBOX_PLATFORMS_KEY, - LAUNCHBOX_METADATA_DATABASE_ID_KEY, - LAUNCHBOX_METADATA_NAME_KEY, - LAUNCHBOX_METADATA_FOLDED_NAME_KEY, - LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, - LAUNCHBOX_METADATA_IMAGE_KEY, - LAUNCHBOX_MAME_KEY, - LAUNCHBOX_FILES_KEY, - ] - - for expected_key in expected_keys: + # The tuple the schema drop deletes has to name every key written. + for expected_key in LAUNCHBOX_METADATA_STORE.keys: assert ( expected_key in redis_keys_used ), f"Expected key {expected_key} not found in Redis operations" @@ -434,12 +459,19 @@ class TestInitialImportFlag: with ( patch.object(async_cache, "exists", AsyncMock(return_value=0)), + patch.object(async_cache, "get", AsyncMock(return_value=None)), patch.object(async_cache, "set", AsyncMock()) as mock_set, patch.object(async_cache, "delete", AsyncMock()) as mock_delete, ): await task.run(force=True) - mock_set.assert_awaited_once_with(LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, "1") + assert [call.args for call in mock_set.await_args_list] == [ + (LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, "1"), + ( + LAUNCHBOX_METADATA_STORE.schema_key, + str(LAUNCHBOX_METADATA_STORE.version), + ), + ] mock_delete.assert_awaited_once_with(LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY) @patch.object(RemoteFilePullTask, "run") @@ -454,12 +486,20 @@ class TestInitialImportFlag: with ( patch.object(async_cache, "exists", AsyncMock(return_value=1)), + patch.object( + async_cache, + "get", + AsyncMock(return_value=str(LAUNCHBOX_METADATA_STORE.version)), + ), patch.object(async_cache, "set", AsyncMock()) as mock_set, patch.object(async_cache, "delete", AsyncMock()), ): await task.run(force=True) - mock_set.assert_not_awaited() + # Only the schema stamp, never the initial-import flag. + mock_set.assert_awaited_once_with( + LAUNCHBOX_METADATA_STORE.schema_key, str(LAUNCHBOX_METADATA_STORE.version) + ) @patch.object(RemoteFilePullTask, "run") async def test_flag_survives_a_failed_run( diff --git a/backend/tests/tasks/test_update_switch_titledb.py b/backend/tests/tasks/test_update_switch_titledb.py index 8f5283f7b..987e1eab5 100644 --- a/backend/tests/tasks/test_update_switch_titledb.py +++ b/backend/tests/tasks/test_update_switch_titledb.py @@ -19,22 +19,24 @@ class TestUpdateSwitchTitleDBTask: @pytest.fixture def sample_titledb_data(self): + # The dump keys entries by title id and carries the application id as + # `id`, so the two indexes are keyed differently. return { - "0100000000010000": { + "70010000000025": { "id": "0100000000010000", "name": "Super Mario Odyssey", "publisher": "Nintendo", "region": "US", "version": "1.3.0", }, - "0100000000020000": { + "70010000000041": { "id": "0100000000020000", "name": "The Legend of Zelda: Breath of the Wild", "publisher": "Nintendo", "region": "US", "version": "1.6.0", }, - "0100000000030000": { + "70010000000046": { "id": "0100000000030000", "name": "Mario Kart 8 Deluxe", "publisher": "Nintendo", @@ -45,7 +47,7 @@ class TestUpdateSwitchTitleDBTask: "id": "should_be_filtered", "name": "Should not appear", }, - "0100000000040000": None, # None value to test filtering + "70010000000052": None, # None value to test filtering } @pytest.fixture @@ -218,9 +220,10 @@ class TestUpdateSwitchTitleDBTask: mock_async_cache_pipeline, mock_super_run, task, + sample_titledb_data, sample_json_content, ): - """Test that product ID mapping works correctly""" + """The product id index points at its titleID index entry.""" mock_super_run.return_value = sample_json_content mock_pipe = AsyncMock() @@ -230,22 +233,19 @@ class TestUpdateSwitchTitleDBTask: await task.run(force=True) - # Find product ID calls hset_calls = mock_pipe.hset.call_args_list - product_calls = [ - call for call in hset_calls if call[0][0] == SWITCH_PRODUCT_ID_KEY - ] + product_mapping = { + product_id: json.loads(raw) + for call in hset_calls + if call[0][0] == SWITCH_PRODUCT_ID_KEY + for product_id, raw in call[1]["mapping"].items() + } - assert len(product_calls) > 0 - - # Verify product mapping structure - for call in product_calls: - args, kwargs = call - if "mapping" in kwargs: - mapping = kwargs["mapping"] - for product_id, data_json in mapping.items(): - data = json.loads(data_json) - assert data.get("id") == product_id + assert product_mapping == { + entry["id"]: title_id + for title_id, entry in sample_titledb_data.items() + if title_id and entry + } @patch.object(RemoteFilePullTask, "run") @patch("tasks.scheduled.update_switch_titledb.async_cache.pipeline") diff --git a/backend/tests/test_startup.py b/backend/tests/test_startup.py index 6d049207a..f34825ad4 100644 --- a/backend/tests/test_startup.py +++ b/backend/tests/test_startup.py @@ -1,11 +1,16 @@ """Tests for startup-time auto-enqueue of the recompute task.""" +from unittest.mock import AsyncMock + import pytest import startup from rq.exceptions import DuplicateJobError from rq.job import JOB_ID_PATTERN +from handler.metadata.launchbox_handler.types import LAUNCHBOX_METADATA_STORE from tasks.registry import get_task +from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE +from utils.cache import VersionedCacheStore @pytest.fixture @@ -128,3 +133,78 @@ class TestDropLegacySchedulerState: redis.zrange.side_effect = RuntimeError("redis gone") startup._drop_legacy_scheduler_state() + + +class TestRebuildOutdatedMetadataStores: + """A store an older release wrote is dropped, and its rebuild queued.""" + + @pytest.fixture + def drop_stale(self, mocker): + """Report only the stores named as stale, whatever order they run in.""" + + def patch_drop(*stale: VersionedCacheStore): + async def drop(_cache, store): + return store in stale + + return mocker.patch.object( + startup, "drop_stale_cache_store", new=AsyncMock(side_effect=drop) + ) + + return patch_drop + + async def test_stale_launchbox_store_is_dropped_and_rebuilt( + self, mocker, drop_stale, enqueue_task + ): + mocker.patch.object(startup, "LAUNCHBOX_API_ENABLED", True) + drop_stale(LAUNCHBOX_METADATA_STORE) + + await startup._rebuild_outdated_metadata_stores() + + enqueue_task.assert_called_once_with( + "update_launchbox_metadata", + job_id=startup.UPDATE_LAUNCHBOX_METADATA_JOB_ID, + unique=True, + ) + + async def test_launchbox_rebuild_waits_on_the_provider_being_enabled( + self, mocker, drop_stale, enqueue_task + ): + """Dropping reclaims the memory; refilling it would serve nobody.""" + mocker.patch.object(startup, "LAUNCHBOX_API_ENABLED", False) + mocker.patch.object( + startup, + "VERSIONED_METADATA_STORES", + ( + ( + LAUNCHBOX_METADATA_STORE, + "update_launchbox_metadata", + startup.UPDATE_LAUNCHBOX_METADATA_JOB_ID, + False, + ), + ), + ) + drop_stale(LAUNCHBOX_METADATA_STORE) + + await startup._rebuild_outdated_metadata_stores() + + enqueue_task.assert_not_called() + + async def test_stale_switch_store_is_dropped_and_rebuilt( + self, drop_stale, enqueue_task + ): + drop_stale(SWITCH_TITLEDB_STORE) + + await startup._rebuild_outdated_metadata_stores() + + enqueue_task.assert_called_once_with( + "update_switch_titledb", + job_id=startup.UPDATE_SWITCH_TITLEDB_JOB_ID, + unique=True, + ) + + async def test_current_stores_queue_nothing(self, drop_stale, enqueue_task): + drop_stale() + + await startup._rebuild_outdated_metadata_stores() + + enqueue_task.assert_not_called() diff --git a/backend/tests/utils/test_cache.py b/backend/tests/utils/test_cache.py index cf39b8c7d..4934f08a5 100644 --- a/backend/tests/utils/test_cache.py +++ b/backend/tests/utils/test_cache.py @@ -1,8 +1,17 @@ from unittest.mock import AsyncMock +import pytest + from handler.metadata.base_handler import MAME_XML_KEY, METADATA_FIXTURES_DIR from handler.redis_handler import async_cache -from utils.cache import conditionally_set_cache +from utils.cache import ( + VersionedCacheStore, + conditionally_set_cache, + drop_stale_cache_store, + is_cache_schema_current, + is_cache_store_ready, + stamp_cache_schema, +) class TestConditionallySetCache: @@ -82,3 +91,97 @@ class TestConditionallySetCache: ) mock_cache_pipeline.assert_not_called() + + +class TestCacheSchema: + """A store is read only while its stamp matches the readers' shape.""" + + STORE = VersionedCacheStore( + schema_key="romm:store_schema", version=2, keys=("romm:a", "romm:b") + ) + + async def test_matching_stamp_is_current(self, mocker): + mocker.patch.object( + async_cache, "get", new_callable=AsyncMock, return_value="2" + ) + + assert await is_cache_schema_current(async_cache, self.STORE) is True + + @pytest.mark.parametrize("stamped", [None, "1", "not-a-version"]) + async def test_other_stamps_are_stale(self, mocker, stamped: str | None): + mocker.patch.object( + async_cache, "get", new_callable=AsyncMock, return_value=stamped + ) + + assert await is_cache_schema_current(async_cache, self.STORE) is False + + async def test_stamp_records_the_version(self, mocker): + mock_set = mocker.patch.object(async_cache, "set", new_callable=AsyncMock) + + await stamp_cache_schema(async_cache, self.STORE) + + mock_set.assert_awaited_once_with("romm:store_schema", "2") + + async def test_stale_store_is_dropped_with_its_stamp(self, mocker): + mocker.patch.object( + async_cache, "get", new_callable=AsyncMock, return_value="1" + ) + mock_unlink = mocker.patch.object( + async_cache, "unlink", new_callable=AsyncMock, return_value=2 + ) + + assert await drop_stale_cache_store(async_cache, self.STORE) is True + assert [call.args for call in mock_unlink.await_args_list] == [ + ("romm:a", "romm:b"), + ("romm:store_schema",), + ] + + async def test_current_store_is_left_alone(self, mocker): + mocker.patch.object( + async_cache, "get", new_callable=AsyncMock, return_value="2" + ) + mock_unlink = mocker.patch.object(async_cache, "unlink", new_callable=AsyncMock) + + assert await drop_stale_cache_store(async_cache, self.STORE) is False + mock_unlink.assert_not_awaited() + + async def test_store_that_was_never_filled_is_not_a_drop(self, mocker): + """An install that never imported has nothing to rebuild.""" + mocker.patch.object( + async_cache, "get", new_callable=AsyncMock, return_value=None + ) + mocker.patch.object( + async_cache, "unlink", new_callable=AsyncMock, return_value=0 + ) + + assert await drop_stale_cache_store(async_cache, self.STORE) is False + + +class TestCacheStoreReady: + """The reader gate: stamped with the current shape, and actually filled.""" + + STORE = VersionedCacheStore( + schema_key="romm:store_schema", version=2, keys=("romm:a",) + ) + + @pytest.mark.parametrize( + ("stamped", "present", "expected"), + [ + ("2", 1, True), + ("1", 1, False), + (None, 1, False), + # A hash an eviction policy reclaimed leaves the stamp behind. + ("2", 0, False), + ], + ids=["ready", "stale", "unstamped", "evicted"], + ) + async def test_gate(self, mocker, stamped, present, expected): + mocker.patch.object( + async_cache, "get", new_callable=AsyncMock, return_value=stamped + ) + mocker.patch.object( + async_cache, "exists", new_callable=AsyncMock, return_value=present + ) + + result = await is_cache_store_ready(async_cache, self.STORE, "romm:a") + assert result is expected diff --git a/backend/utils/cache.py b/backend/utils/cache.py index f2b825b24..675b3d007 100644 --- a/backend/utils/cache.py +++ b/backend/utils/cache.py @@ -2,6 +2,7 @@ import hashlib import json from itertools import batched from pathlib import Path +from typing import NamedTuple from anyio import open_file from redis.asyncio import Redis as AsyncRedis @@ -49,3 +50,54 @@ async def conditionally_set_cache(cache: AsyncRedis, key: str, file_path: Path) except Exception as e: # Log the error but don't fail - this allows migrations to run even if Redis is not available log.warning(f"Failed to initialize cache for {key}: {e}") + + +class VersionedCacheStore(NamedTuple): + """A group of cache keys filled together, stamped with the shape they hold. + + Bump `version` when an import changes that shape, so a store an older + release wrote is dropped rather than read as the current one. + """ + + schema_key: str + version: int + keys: tuple[str, ...] + + +async def is_cache_schema_current( + cache: AsyncRedis, store: VersionedCacheStore +) -> bool: + """Whether the store holds the shape its readers expect.""" + return await cache.get(store.schema_key) == str(store.version) + + +async def stamp_cache_schema(cache: AsyncRedis, store: VersionedCacheStore) -> None: + """Record the shape a completed import left the store in.""" + await cache.set(store.schema_key, str(store.version)) + + +async def is_cache_store_ready( + cache: AsyncRedis, store: VersionedCacheStore, data_key: str +) -> bool: + """Whether `data_key` holds entries an import wrote under the current shape. + + The stamp alone would trust a hash an eviction policy has since reclaimed. + """ + if not await is_cache_schema_current(cache, store): + return False + + return bool(await cache.exists(data_key)) + + +async def drop_stale_cache_store(cache: AsyncRedis, store: VersionedCacheStore) -> bool: + """Delete a store an older release wrote, returning whether one was there. + + `unlink` frees the hundreds of MB a metadata store holds off the main + thread, so a boot does not stall every other client. + """ + if await is_cache_schema_current(cache, store): + return False + + dropped = await cache.unlink(*store.keys) + await cache.unlink(store.schema_key) + return bool(dropped)