diff --git a/backend/config/__init__.py b/backend/config/__init__.py index 61ca3c4c6..03a3939e0 100644 --- a/backend/config/__init__.py +++ b/backend/config/__init__.py @@ -48,6 +48,8 @@ ROMM_TMP_PATH: Final[str | None] = _get_env("ROMM_TMP_PATH") LIBRARY_BASE_PATH: Final[str] = f"{ROMM_BASE_PATH}/library" RESOURCES_BASE_PATH: Final[str] = f"{ROMM_BASE_PATH}/resources" ASSETS_BASE_PATH: Final[str] = f"{ROMM_BASE_PATH}/assets" +# Scheduled tasks rebuild the metadata dumps here; nginx refuses to serve this folder. +METADATA_DUMPS_PATH: Final[str] = f"{RESOURCES_BASE_PATH}/metadata" CACHE_BASE_PATH: Final[str] = ( f"{ROMM_TMP_PATH or '/tmp/romm'}/cache" # trunk-ignore(bandit/B108) ) diff --git a/backend/handler/dump_cache.py b/backend/handler/dump_cache.py deleted file mode 100644 index 574c9b3a5..000000000 --- a/backend/handler/dump_cache.py +++ /dev/null @@ -1,81 +0,0 @@ -"""Storage codec for the metadata dumps that live only in the cache. - -Values are compressed one at a time because the stores are read by exact key. -""" - -import json -from compression import zstd -from typing import Any, Final - -from handler.redis_handler import async_binary_cache - -# Level 3 costs less per read than the `json.loads` that follows it. -COMPRESSION_LEVEL: Final[int] = 3 - -# Below this a frame header and a poor ratio cost more than they save, which is -# what leaves the id-valued title and product id indexes as plain JSON. -COMPRESS_MIN_BYTES: Final[int] = 256 - -# Zstandard frame magic, from RFC 8878 section 3.1.1. -_ZSTD_MAGIC: Final[bytes] = b"\x28\xb5\x2f\xfd" - -_compressor = zstd.ZstdCompressor(level=COMPRESSION_LEVEL) - - -def serialize(value: Any) -> bytes: - """Serialize a dump record, which is what the size threshold applies to. - - Args: - value: The record to store, as JSON-serializable data. - - Returns: - The payload, before any compression. - """ - return json.dumps(value, separators=(",", ":")).encode() - - -def encode(value: Any) -> bytes: - """Serialize a dump record, compressing it when it is large enough to pay off. - - Args: - value: The record to store, as JSON-serializable data. - - Returns: - The bytes to write into the store. - """ - payload = serialize(value) - if len(payload) < COMPRESS_MIN_BYTES: - return payload - - return _compressor.compress(payload, zstd.ZstdCompressor.FLUSH_FRAME) - - -def decode(raw: bytes | str | None) -> Any: - """Deserialize a dump record, whether or not it was stored compressed. - - Args: - raw: The stored value, or None when the field is absent. - - Returns: - The record, or None when there was nothing stored. - """ - if not raw: - return None - - if isinstance(raw, bytes) and raw.startswith(_ZSTD_MAGIC): - raw = zstd.decompress(raw) - - return json.loads(raw) - - -async def hget_json(key: str, field: str) -> Any: - """Read one record out of a dump store. - - Args: - key: The store's cache key. - field: The field to read. - - Returns: - The record, or None when the field is absent. - """ - return decode(await async_binary_cache.hget(key, field)) diff --git a/backend/handler/dump_store.py b/backend/handler/dump_store.py new file mode 100644 index 000000000..571cb9d51 --- /dev/null +++ b/backend/handler/dump_store.py @@ -0,0 +1,264 @@ +"""Read-only SQLite files of key-value tables, for lookups an import rebuilds whole. + +A build renames a finished file over the old one, so readers never see a partial store. +""" + +import json +import os +import sqlite3 +import threading +import time +import uuid +import weakref +from collections.abc import Iterator +from compression import zstd +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Final + +from logger.logger import log + +# Level 3 costs less per read than the `json.loads` that follows it. +COMPRESSION_LEVEL: Final[int] = 3 + +# Below this size, a frame header and a poor ratio cost more than they save, so +# the title and product id indexes, which hold only ids, stay plain JSON. +COMPRESS_MIN_BYTES: Final[int] = 256 + +# Zstandard frame magic, from RFC 8878 section 3.1.1. +_ZSTD_MAGIC: Final[bytes] = b"\x28\xb5\x2f\xfd" + +WRITE_BATCH_SIZE: Final[int] = 2000 + +# A build writes constantly, so a temporary file idle this long is one a killed +# process left behind. +STALE_BUILD_SECONDS: Final[int] = 3600 + +_compressor = zstd.ZstdCompressor(level=COMPRESSION_LEVEL) + +_stores: "weakref.WeakSet[DumpStore]" = weakref.WeakSet() + + +def _reset_stores_after_fork() -> None: + # A forked child must not use the parent's connection, nor a lock another + # thread held at the moment of the fork. + for store in _stores: + store._lock = threading.Lock() + store._conn = None + + +os.register_at_fork(after_in_child=_reset_stores_after_fork) + + +class EmptyDumpError(RuntimeError): + """A build finished without a single row in the store's required table.""" + + +def encode(value: Any) -> bytes: + """Serialize a dump record, compressing it when it is large enough to pay off. + + Args: + value: The record to store, as JSON-serializable data. + + Returns: + The bytes to write into the store. + """ + payload = json.dumps(value, separators=(",", ":")).encode() + if len(payload) < COMPRESS_MIN_BYTES: + return payload + + return _compressor.compress(payload, zstd.ZstdCompressor.FLUSH_FRAME) + + +def decode(raw: bytes | None) -> Any: + """Deserialize a dump record, whether or not it was stored compressed. + + Args: + raw: The stored value, or None when the key is absent. + + Returns: + The record, or None when there was nothing stored. + """ + if not raw: + return None + + if raw.startswith(_ZSTD_MAGIC): + raw = zstd.decompress(raw) + + return json.loads(raw) + + +class DumpWriter: + """Batches the rows of a store being built.""" + + def __init__(self, conn: sqlite3.Connection, tables: tuple[str, ...]) -> None: + self._conn = conn + self._pending: dict[str, list[tuple[str, bytes]]] = {t: [] for t in tables} + self._queued = 0 + + def put(self, table: str, key: str, value: Any) -> None: + """Queue a record, replacing any earlier one under the same key.""" + self._pending[table].append((key, encode(value))) + self._queued += 1 + if self._queued >= WRITE_BATCH_SIZE: + self.flush() + + def flush(self) -> None: + for table, rows in self._pending.items(): + if rows: + self._conn.executemany( + f"INSERT OR REPLACE INTO {table} (key, value) VALUES (?, ?)", # nosec B608 + rows, + ) + rows.clear() + self._queued = 0 + + +class DumpStore: + """One read-only SQLite file of key-value tables, swapped in whole by a build. + + Args: + revision: Part of the file name; bump it when a build changes what a table holds. + required_table: A build that leaves it empty fails and keeps the previous file. + """ + + def __init__( + self, + directory: Path, + name: str, + revision: str, + tables: tuple[str, ...], + required_table: str | None = None, + ) -> None: + if required_table is not None and required_table not in tables: + raise ValueError(f"{name} has no table {required_table!r}") + + self.directory = directory + self.name = name + self.revision = revision + self.tables = tables + self.required_table = required_table + # One connection per process, so a rebuild leaves at most one stale file open. + self._lock = threading.Lock() + self._conn: tuple[tuple[int, int], sqlite3.Connection] | None = None + _stores.add(self) + + @property + def path(self) -> Path: + return self.directory / f"{self.name}.{self.revision}.sqlite" + + def exists(self) -> bool: + return self.path.is_file() + + def get(self, table: str, key: str) -> Any: + """Read one record, or None when the key or the whole store is absent.""" + if table not in self.tables: + raise ValueError(f"{self.name} has no table {table!r}") + + with self._lock: + try: + conn = self._connection() + if conn is None: + return None + + row = conn.execute( + f"SELECT value FROM {table} WHERE key = ?", (key,) # nosec B608 + ).fetchone() + except sqlite3.DatabaseError as exc: + log.error(f"Could not read {self.path}: {exc}") + self._close() + return None + + return decode(row[0]) if row else None + + def _connection(self) -> sqlite3.Connection | None: + """The connection to the current file, reopened once a build swaps it. + + The caller holds `_lock`. + """ + try: + stat = os.stat(self.path) + except FileNotFoundError: + self._close() + return None + + identity = (stat.st_dev, stat.st_ino) + if self._conn is not None and self._conn[0] == identity: + return self._conn[1] + + self._close() + # The file is never written in place, so SQLite can skip locking it. + uri = f"{self.path.resolve().as_uri()}?mode=ro&immutable=1" + conn = sqlite3.connect(uri, uri=True, check_same_thread=False) + self._conn = (identity, conn) + return conn + + def _close(self) -> None: + """Close the open connection, releasing a replaced file. The caller holds `_lock`.""" + if self._conn is not None: + self._conn[1].close() + self._conn = None + + @contextmanager + def build(self) -> Iterator[DumpWriter]: + """Write a new file and swap it in once the block finishes without error.""" + self.directory.mkdir(parents=True, exist_ok=True) + self._drop_abandoned_builds() + + tmp_path = self.directory / f".{self.path.name}.{uuid.uuid4().hex}.tmp" + # Nothing else opens the file, and locks can fail on a network share. + conn = sqlite3.connect(f"{tmp_path.resolve().as_uri()}?nolock=1", uri=True) + try: + # A failed build throws its file away, so it needs no journal. + conn.execute("PRAGMA journal_mode = OFF") + conn.execute("PRAGMA synchronous = OFF") + # Rowid tables, since they pack large values densely in any key order. + for table in self.tables: + conn.execute( + f"CREATE TABLE {table} (key TEXT PRIMARY KEY, value BLOB NOT NULL)" + ) + + writer = DumpWriter(conn, self.tables) + yield writer + writer.flush() + if ( + self.required_table is not None + and not conn.execute( + f"SELECT 1 FROM {self.required_table} LIMIT 1" # nosec B608 + ).fetchone() + ): + raise EmptyDumpError( + f"{self.name} build wrote no {self.required_table} rows" + ) + conn.commit() + conn.close() + + with open(tmp_path, "rb") as f: + os.fsync(f.fileno()) + os.replace(tmp_path, self.path) + except BaseException: + conn.close() + tmp_path.unlink(missing_ok=True) + raise + + with self._lock: + self._close() + self.drop_other_revisions() + + def drop_other_revisions(self) -> list[Path]: + """Delete the files that earlier revisions of this store left, and return their paths.""" + dropped = [] + for path in self.directory.glob(f"{self.name}.*.sqlite"): + if path != self.path: + path.unlink(missing_ok=True) + dropped.append(path) + return dropped + + def _drop_abandoned_builds(self) -> None: + cutoff = time.time() - STALE_BUILD_SECONDS + for path in self.directory.glob(f".{self.name}.*.tmp"): + try: + if path.stat().st_mtime < cutoff: + path.unlink() + except FileNotFoundError: + continue diff --git a/backend/handler/fixture_store.py b/backend/handler/fixture_store.py new file mode 100644 index 000000000..889ea3576 --- /dev/null +++ b/backend/handler/fixture_store.py @@ -0,0 +1,71 @@ +"""The lookup indexes RomM ships as JSON, built on first use into a SQLite file +named after a hash of its sources.""" + +import hashlib +import json +from functools import cache +from pathlib import Path +from typing import Any, Final + +from config import CACHE_BASE_PATH +from handler.dump_store import DumpStore + +_METADATA_FIXTURES_DIR: Final = Path(__file__).parent / "metadata" / "fixtures" +_MODEL_FIXTURES_DIR: Final = Path(__file__).parents[1] / "models" / "fixtures" + +MAME_TABLE: Final = "mame" +SCUMMVM_TABLE: Final = "scummvm" +PS2_OPL_TABLE: Final = "ps2_opl" +PS1_SERIAL_TABLE: Final = "ps1_serial" +PS2_SERIAL_TABLE: Final = "ps2_serial" +PSP_SERIAL_TABLE: Final = "psp_serial" +KNOWN_BIOS_TABLE: Final = "known_bios" + +KNOWN_BIOS_FILE: Final = _MODEL_FIXTURES_DIR / "known_bios_files.json" + +FIXTURE_SOURCES: Final[dict[str, Path]] = { + MAME_TABLE: _METADATA_FIXTURES_DIR / "mame_index.json", + SCUMMVM_TABLE: _METADATA_FIXTURES_DIR / "scummvm_index.json", + PS2_OPL_TABLE: _METADATA_FIXTURES_DIR / "ps2_opl_index.json", + PS1_SERIAL_TABLE: _METADATA_FIXTURES_DIR / "ps1_serial_index.json", + PS2_SERIAL_TABLE: _METADATA_FIXTURES_DIR / "ps2_serial_index.json", + PSP_SERIAL_TABLE: _METADATA_FIXTURES_DIR / "psp_serial_index.json", + KNOWN_BIOS_TABLE: KNOWN_BIOS_FILE, +} + +FIXTURE_STORE_DIR: Final = Path(CACHE_BASE_PATH) / "fixtures" + + +def _sources_digest() -> str: + digest = hashlib.sha256() + for table, path in sorted(FIXTURE_SOURCES.items()): + digest.update(table.encode()) + digest.update(path.read_bytes()) + return digest.hexdigest()[:16] + + +@cache +def fixture_store() -> DumpStore: + """Return the fixture store for this image's sources, building it if no process has yet.""" + store = DumpStore( + FIXTURE_STORE_DIR, "fixtures", _sources_digest(), tuple(FIXTURE_SOURCES) + ) + if not store.exists(): + with store.build() as writer: + for table, path in FIXTURE_SOURCES.items(): + with path.open() as f: + for key, value in json.load(f).items(): + writer.put(table, key, value) + + return store + + +def fixture_get(table: str, key: str) -> Any: + """Read one fixture record, or None when the key is not in the index.""" + store = fixture_store() + if not store.exists(): + # A tmp cleaner can delete the file long after this process built it. + fixture_store.cache_clear() + store = fixture_store() + + return store.get(table, key) diff --git a/backend/handler/metadata/base_handler.py b/backend/handler/metadata/base_handler.py index bd9a35c67..2992d14c9 100644 --- a/backend/handler/metadata/base_handler.py +++ b/backend/handler/metadata/base_handler.py @@ -5,7 +5,6 @@ import unicodedata from collections.abc import Awaitable, Callable from dataclasses import dataclass from functools import lru_cache -from pathlib import Path from typing import TYPE_CHECKING, Any, Final, Mapping, NotRequired, TypedDict, cast from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse @@ -13,18 +12,24 @@ import httpx2 from strsimpy.jaro_winkler import JaroWinkler from adapters.services.provider_http import unavailable -from handler.dump_cache import hget_json -from handler.redis_handler import async_cache +from handler.fixture_store import ( + MAME_TABLE, + PS1_SERIAL_TABLE, + PS2_OPL_TABLE, + PS2_SERIAL_TABLE, + PSP_SERIAL_TABLE, + SCUMMVM_TABLE, + fixture_get, +) from logger.formatter import SENSITIVE_KEYS from logger.logger import log from tasks.scheduled.update_switch_titledb import ( - SWITCH_PRODUCT_ID_KEY, - SWITCH_TITLEDB_INDEX_KEY, + SWITCH_PRODUCT_ID_TABLE, SWITCH_TITLEDB_STORE, + SWITCH_TITLEDB_TABLE, ) from utils import get_version, int_or_none from utils.arcade_platforms import MAME_SHORTNAME_PLATFORMS -from utils.cache import is_cache_store_ready from utils.context import ctx_httpx_client from utils.switch import derive_base_title_id @@ -33,8 +38,6 @@ if TYPE_CHECKING: jarowinkler = JaroWinkler() -METADATA_FIXTURES_DIR: Final = Path(__file__).parent / "fixtures" - # An error status, or a request that never got an answer. HTTPX_REQUEST_ERRORS: Final = (httpx2.HTTPStatusError, httpx2.TransportError) @@ -42,28 +45,15 @@ HTTPX_REQUEST_ERRORS: Final = (httpx2.HTTPStatusError, httpx2.TransportError) MAX_RESPONSE_BYTES: Final[int] = 1_000_000 REQUEST_TIMEOUT: Final[int] = 25 -# These are loaded in cache in update_switch_titledb_task +# Matches are looked up in the store that update_switch_titledb_task builds. SWITCH_TITLEDB_REGEX: Final = re.compile(r"(70[0-9]{12})") SWITCH_PRODUCT_ID_REGEX: Final = re.compile(r"(0100[0-9A-F]{12})") - -# No regex needed for MAME -MAME_XML_KEY: Final = "romm:mame_xml" - -# ScummVM -SCUMMVM_INDEX_KEY: Final = "romm:scummvm_index" - -# PS2 OPL PS2_OPL_REGEX: Final = re.compile(r"^([A-Z]{4}_\d{3}\.\d{2})\..*$") -PS2_OPL_KEY: Final = "romm:ps2_opl_index" # Sony serial codes for PS1, PS2, PS3 and PSP SONY_SERIAL_REGEX: Final = re.compile(r".*([a-zA-Z]{4}-\d{5}).*$") -PS1_SERIAL_INDEX_KEY: Final = "romm:ps1_serial_index" -PS2_SERIAL_INDEX_KEY: Final = "romm:ps2_serial_index" -PSP_SERIAL_INDEX_KEY: Final = "romm:psp_serial_index" - LEADING_ARTICLE_PATTERN = re.compile(r"^(a|an|the)\b", re.IGNORECASE) COMMA_ARTICLE_PATTERN = re.compile(r",\s(a|an|the)\b(?=\s*[^\w\s]|$)", re.IGNORECASE) NON_WORD_SPACE_PATTERN = re.compile(r"[^\w\s]") @@ -110,8 +100,8 @@ def _fill_from_switch_entry(fallback_rom: BaseRom, index_entry: dict[str, Any]) async def mame_title(shortname: str) -> str | None: """MAME's full title for a set, region and revision tags included.""" - entry = await async_cache.hget(MAME_XML_KEY, shortname) - return json.loads(entry).get("description") if entry else None + entry = fixture_get(MAME_TABLE, shortname) + return entry.get("description") if entry else None class CoverResource(TypedDict): @@ -407,17 +397,15 @@ class MetadataHandler(abc.ABC): async def _ps2_opl_format(self, match: re.Match[str], search_term: str) -> str: serial_code = match.group(1) - index_entry = await async_cache.hget(PS2_OPL_KEY, serial_code) + index_entry = fixture_get(PS2_OPL_TABLE, serial_code) if index_entry: - index_entry = json.loads(index_entry) search_term = index_entry["Name"] return search_term - async def _sony_serial_format(self, index_key: str, serial_code: str) -> str | None: - index_entry = await async_cache.hget(index_key, serial_code.upper()) + async def _sony_serial_format(self, table: str, serial_code: str) -> str | None: + index_entry = fixture_get(table, serial_code.upper()) if index_entry: - index_entry = json.loads(index_entry) return cast(str | None, index_entry["title"]) return None @@ -425,22 +413,19 @@ class MetadataHandler(abc.ABC): async def _ps1_serial_format(self, match: re.Match[str], search_term: str) -> str: serial_code = match.group(1) return ( - await self._sony_serial_format(PS1_SERIAL_INDEX_KEY, serial_code) - or search_term + await self._sony_serial_format(PS1_SERIAL_TABLE, serial_code) or search_term ) async def _ps2_serial_format(self, match: re.Match[str], search_term: str) -> str: serial_code = match.group(1) return ( - await self._sony_serial_format(PS2_SERIAL_INDEX_KEY, serial_code) - or search_term + await self._sony_serial_format(PS2_SERIAL_TABLE, serial_code) or search_term ) async def _psp_serial_format(self, match: re.Match[str], search_term: str) -> str: serial_code = match.group(1) return ( - await self._sony_serial_format(PSP_SERIAL_INDEX_KEY, serial_code) - or search_term + await self._sony_serial_format(PSP_SERIAL_TABLE, serial_code) or search_term ) async def _switch_titledb_format( @@ -449,7 +434,7 @@ class MetadataHandler(abc.ABC): title_id = match.group(1) if not await self._is_switch_titledb_current(): - log.error("Could not find a current Switch titleID index in cache") + log.error("Could not find a current Switch TitleDB store") return search_term, None index_entry = await self._switch_titledb_entry(title_id) @@ -476,7 +461,7 @@ class MetadataHandler(abc.ABC): product_id = derive_base_title_id(product_id) or product_id if not await self._is_switch_titledb_current(): - log.error("Could not find a current Switch productID index in cache") + log.error("Could not find a current Switch TitleDB store") return search_term, None index_entry = await self._switch_product_id_entry(product_id) @@ -487,21 +472,20 @@ class MetadataHandler(abc.ABC): @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 - ) + """Whether an import has built the store this release reads.""" + return SWITCH_TITLEDB_STORE.exists() @staticmethod async def _switch_titledb_entry(title_id: str) -> dict[str, Any] | None: return cast( - dict[str, Any] | None, await hget_json(SWITCH_TITLEDB_INDEX_KEY, title_id) + dict[str, Any] | None, + SWITCH_TITLEDB_STORE.get(SWITCH_TITLEDB_TABLE, title_id), ) @classmethod async def _switch_product_id_entry(cls, product_id: str) -> dict[str, Any] | None: """Resolve a Switch product id to the titleID entry its index points at.""" - title_id = await hget_json(SWITCH_PRODUCT_ID_KEY, product_id) + title_id = SWITCH_TITLEDB_STORE.get(SWITCH_PRODUCT_ID_TABLE, product_id) if not title_id: return None @@ -519,9 +503,8 @@ class MetadataHandler(abc.ABC): from handler.filesystem import fs_rom_handler search_term = fs_rom_handler.get_file_name_with_no_extension(search_term) - index_entry = await async_cache.hget(SCUMMVM_INDEX_KEY, search_term) + index_entry = fixture_get(SCUMMVM_TABLE, search_term) if index_entry: - index_entry = json.loads(index_entry) search_term = index_entry["name"] return search_term diff --git a/backend/handler/metadata/launchbox_handler/handler.py b/backend/handler/metadata/launchbox_handler/handler.py index bbb7acef8..60e3c34bb 100644 --- a/backend/handler/metadata/launchbox_handler/handler.py +++ b/backend/handler/metadata/launchbox_handler/handler.py @@ -3,11 +3,9 @@ from typing import Any 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 import safe_int from utils.arcade_platforms import MAME_SHORTNAME_PLATFORMS -from utils.cache import is_cache_store_ready from utils.platform_slugs import UniversalPlatformSlug as UPS from ..base_handler import ( @@ -20,8 +18,6 @@ from .platforms import get_platform from .remote_source import RemoteSource from .types import ( DASH_COLON_REGEX, - LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, - LAUNCHBOX_METADATA_NAME_KEY, LAUNCHBOX_METADATA_STORE, LAUNCHBOX_PLATFORMS_DIR, LAUNCHBOX_TAG_REGEX, @@ -49,13 +45,7 @@ class LaunchboxHandler(MetadataHandler): @staticmethod async def is_remote_store_populated() -> bool: - return await is_cache_store_ready( - async_cache, LAUNCHBOX_METADATA_STORE, LAUNCHBOX_METADATA_NAME_KEY - ) - - @staticmethod - async def is_remote_store_importing() -> bool: - return bool(await async_cache.exists(LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY)) + return LAUNCHBOX_METADATA_STORE.exists() async def heartbeat(self) -> bool: if self.is_local_enabled(): @@ -64,15 +54,8 @@ class LaunchboxHandler(MetadataHandler): if not self.is_cloud_enabled(): return False - # A first import commits in batches, so the store starts answering for a - # handful of names long before it holds the whole dump. Until that run - # finishes, most lookups still miss. - if await self.is_remote_store_importing(): - return False - - # Cloud lookups read from a cache the metadata update task fills. Until - # it has run, every lookup returns nothing, so reporting healthy here - # would be a lie. + # Until the metadata update task has built the store, every cloud lookup + # returns nothing. return await self.is_remote_store_populated() def get_platform(self, slug: str) -> LaunchboxPlatform: @@ -105,11 +88,7 @@ class LaunchboxHandler(MetadataHandler): if remote is None: local_title = (local.get("Title") or "").strip() if local_title: - remote = await self._remote.get_rom( - local_title, - platform_slug, - assume_cache_present=True, - ) + remote = await self._remote.get_rom(local_title, platform_slug) platform_name = get_platform(platform_slug).get("name") remote_images = await self._remote.fetch_images( remote=remote, remote_enabled=remote_available @@ -185,11 +164,7 @@ class LaunchboxHandler(MetadataHandler): search_term = await self._scummvm_format(search_term) fallback_rom = LaunchboxRom(launchbox_id=None, name=search_term) - index_entry = await self._remote.get_rom( - search_term, - platform_slug, - assume_cache_present=True, - ) + index_entry = await self._remote.get_rom(search_term, platform_slug) if not index_entry: return fallback_rom diff --git a/backend/handler/metadata/launchbox_handler/remote_source.py b/backend/handler/metadata/launchbox_handler/remote_source.py index b87277ada..3decd43fc 100644 --- a/backend/handler/metadata/launchbox_handler/remote_source.py +++ b/backend/handler/metadata/launchbox_handler/remote_source.py @@ -1,20 +1,15 @@ from typing import Any, cast -from handler.dump_cache import hget_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 ( - LAUNCHBOX_FILES_KEY, - LAUNCHBOX_MAME_KEY, - LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, - LAUNCHBOX_METADATA_DATABASE_ID_KEY, - LAUNCHBOX_METADATA_FOLDED_NAME_KEY, - LAUNCHBOX_METADATA_IMAGE_KEY, - LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_ALTERNATE_NAME_TABLE, + LAUNCHBOX_FILES_TABLE, + LAUNCHBOX_FOLDED_NAME_TABLE, + LAUNCHBOX_IMAGE_TABLE, + LAUNCHBOX_MAME_TABLE, LAUNCHBOX_METADATA_STORE, + LAUNCHBOX_METADATA_TABLE, + LAUNCHBOX_NAME_TABLE, ) from .utils import deinvert_article, file_name_forms, fold_title @@ -23,30 +18,20 @@ class RemoteSource: async def get_by_id(self, database_id: int | str) -> dict[str, Any] | None: return cast( dict[str, Any] | None, - await hget_json(LAUNCHBOX_METADATA_DATABASE_ID_KEY, str(database_id)), + LAUNCHBOX_METADATA_STORE.get(LAUNCHBOX_METADATA_TABLE, str(database_id)), ) - async def _lookup_title_index(self, key: str, field: str) -> dict[str, Any] | None: + async def _lookup_title_index(self, table: str, key: str) -> dict[str, Any] | None: """Read a title index hit and resolve the database id it holds.""" - database_id = await hget_json(key, field) + database_id = LAUNCHBOX_METADATA_STORE.get(table, key) if not database_id: return None return await self.get_by_id(database_id) async def get_rom( - self, - file_name: str, - platform_slug: str, - *, - assume_cache_present: bool = False, + self, file_name: str, platform_slug: str ) -> dict[str, Any] | None: - 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 a current Launchbox Metadata.xml in cache") - return None - lb_platform = get_platform(platform_slug) platform_name = lb_platform.get("name", None) if not platform_name: @@ -71,14 +56,14 @@ class RemoteSource: for candidate in candidates: entry = await self._lookup_title_index( - LAUNCHBOX_METADATA_NAME_KEY, f"{candidate}:{platform_name}" + LAUNCHBOX_NAME_TABLE, f"{candidate}:{platform_name}" ) if entry: return entry for candidate in candidates: entry = await self._lookup_title_index( - LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, candidate + LAUNCHBOX_ALTERNATE_NAME_TABLE, candidate ) if not entry: continue @@ -97,7 +82,7 @@ class RemoteSource: if not folded: continue entry = await self._lookup_title_index( - LAUNCHBOX_METADATA_FOLDED_NAME_KEY, f"{folded}:{platform_name}" + LAUNCHBOX_FOLDED_NAME_TABLE, f"{folded}:{platform_name}" ) if entry: return entry @@ -118,7 +103,9 @@ class RemoteSource: return None for candidate in file_name_forms(file_name): - entry = await hget_json(LAUNCHBOX_FILES_KEY, f"{candidate}:{platform_name}") + entry = LAUNCHBOX_METADATA_STORE.get( + LAUNCHBOX_FILES_TABLE, f"{candidate}:{platform_name}" + ) if not entry: continue @@ -126,9 +113,7 @@ class RemoteSource: if not game_name: continue - index_entry = await self.get_rom( - game_name, platform_slug, assume_cache_present=True - ) + index_entry = await self.get_rom(game_name, platform_slug) if index_entry: return index_entry @@ -154,7 +139,7 @@ class RemoteSource: candidates.append(stem) for candidate in candidates: - entry = await hget_json(LAUNCHBOX_MAME_KEY, candidate) + entry = LAUNCHBOX_METADATA_STORE.get(LAUNCHBOX_MAME_TABLE, candidate) if entry: return cast(dict[str, Any], entry) @@ -179,5 +164,5 @@ class RemoteSource: return cast( list[dict[str, Any]] | None, - await hget_json(LAUNCHBOX_METADATA_IMAGE_KEY, str(resolved_id)), + LAUNCHBOX_METADATA_STORE.get(LAUNCHBOX_IMAGE_TABLE, str(resolved_id)), ) diff --git a/backend/handler/metadata/launchbox_handler/types.py b/backend/handler/metadata/launchbox_handler/types.py index 3eea52c1f..d6f6e7f23 100644 --- a/backend/handler/metadata/launchbox_handler/types.py +++ b/backend/handler/metadata/launchbox_handler/types.py @@ -3,41 +3,33 @@ from dataclasses import dataclass from pathlib import Path from typing import Any, Final, NotRequired, TypedDict -from config import ROMM_BASE_PATH -from utils.cache import VersionedCacheStore +from config import METADATA_DUMPS_PATH, ROMM_BASE_PATH +from handler.dump_store import DumpStore from ..base_handler import BaseRom, provider_tag_regex -LAUNCHBOX_PLATFORMS_KEY: Final[str] = "romm:launchbox_platforms" -LAUNCHBOX_METADATA_DATABASE_ID_KEY: Final[str] = "romm:launchbox_metadata_database_id" -LAUNCHBOX_METADATA_NAME_KEY: Final[str] = "romm:launchbox_metadata_name" -LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY: Final[str] = ( - "romm:launchbox_metadata_alternate_name" -) -LAUNCHBOX_METADATA_FOLDED_NAME_KEY: Final[str] = "romm:launchbox_metadata_folded_name" -LAUNCHBOX_METADATA_IMAGE_KEY: Final[str] = "romm:launchbox_metadata_image" -LAUNCHBOX_MAME_KEY: Final[str] = "romm:launchbox_mame" -LAUNCHBOX_FILES_KEY: Final[str] = "romm:launchbox_files" -# Set while the store is being filled for the first time -LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY: Final[str] = ( - "romm:launchbox_metadata_initial_import" -) +LAUNCHBOX_METADATA_TABLE: Final[str] = "metadata" +LAUNCHBOX_NAME_TABLE: Final[str] = "names" +LAUNCHBOX_ALTERNATE_NAME_TABLE: Final[str] = "alternate_names" +LAUNCHBOX_FOLDED_NAME_TABLE: Final[str] = "folded_names" +LAUNCHBOX_IMAGE_TABLE: Final[str] = "images" +LAUNCHBOX_MAME_TABLE: Final[str] = "mame" +LAUNCHBOX_FILES_TABLE: Final[str] = "files" -# Every hash the Metadata.zip import fills, dropped together on a schema bump. -# Version 2 stores each record compressed. -LAUNCHBOX_METADATA_STORE: Final[VersionedCacheStore] = VersionedCacheStore( - schema_key="romm:launchbox_metadata_schema", - version=2, - 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_METADATA_STORE: Final[DumpStore] = DumpStore( + Path(METADATA_DUMPS_PATH), + "launchbox", + "v1", + ( + LAUNCHBOX_METADATA_TABLE, + LAUNCHBOX_NAME_TABLE, + LAUNCHBOX_ALTERNATE_NAME_TABLE, + LAUNCHBOX_FOLDED_NAME_TABLE, + LAUNCHBOX_IMAGE_TABLE, + LAUNCHBOX_MAME_TABLE, + LAUNCHBOX_FILES_TABLE, ), + required_table=LAUNCHBOX_METADATA_TABLE, ) LAUNCHBOX_LOCAL_DIR: Final[Path] = Path(ROMM_BASE_PATH) / "launchbox" @@ -57,8 +49,8 @@ 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. +# What each table keeps of its dump element: the fields its reader reads, and +# never one the key already carries. LAUNCHBOX_IMAGE_FIELDS: Final[frozenset[str]] = frozenset( {"FileName", "Type", "Region"} ) diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py index 298cfdb4d..cf3213e95 100644 --- a/backend/handler/redis_handler.py +++ b/backend/handler/redis_handler.py @@ -147,19 +147,6 @@ sync_cache = __get_sync_cache() async_cache = __get_async_cache() -def __get_async_binary_cache() -> AsyncRedis: - """A client that leaves values as bytes, since `async_cache` decodes every - response as UTF-8 and a zstd frame is not.""" - if IS_PYTEST_RUN: - # The fake does not decode responses, which is what this client wants. - return async_cache - - return AsyncRedis.from_url(REDIS_URL, **REDIS_CLIENT_OPTIONS) - - -async_binary_cache = __get_async_binary_cache() - - @asynccontextmanager async def redis_lock( key: str, diff --git a/backend/models/firmware.py b/backend/models/firmware.py index f78fd1482..56cfbd267 100644 --- a/backend/models/firmware.py +++ b/backend/models/firmware.py @@ -2,13 +2,12 @@ from __future__ import annotations import json from functools import cache, cached_property -from pathlib import Path from typing import TYPE_CHECKING, Final from sqlalchemy import BigInteger, ForeignKey, String from sqlalchemy.orm import Mapped, mapped_column, relationship -from handler.redis_handler import sync_cache +from handler.fixture_store import KNOWN_BIOS_FILE, KNOWN_BIOS_TABLE, fixture_get from models.base import ( FILE_EXTENSION_MAX_LENGTH, FILE_NAME_MAX_LENGTH, @@ -22,10 +21,6 @@ from utils.platform_slugs import UniversalPlatformSlug as UPS if TYPE_CHECKING: from models.platform import Platform -FIRMWARE_FIXTURES_DIR: Final = Path(__file__).parent / "fixtures" -KNOWN_BIOS_KEY = "romm:known_bios_files" -KNOWN_BIOS_FILE: Final = FIRMWARE_FIXTURES_DIR / "known_bios_files.json" - # The known BIOS list files every arcade BIOS, Neo Geo's included, under Arcade. ARCADE_BIOS_PLATFORMS: Final = ARCADE_PLATFORMS | {UPS.NEOGEOAES, UPS.NEOGEOMVS} @@ -86,15 +81,17 @@ class Firmware(FileNamePartsMixin, BaseModel): bios_slug = ( UPS.ARCADE if platform_slug in ARCADE_BIOS_PLATFORMS else platform_slug ) - cache_entry = sync_cache.hget(KNOWN_BIOS_KEY, f"{bios_slug}:{file_name}") - if cache_entry: - cache_json = json.loads(cache_entry) - if file_size_bytes == int(cache_json.get("size", 0)) and ( - md5_hash == cache_json.get("md5") - or sha1_hash == cache_json.get("sha1") - or crc_hash == cache_json.get("crc") - ): - return True + known = fixture_get(KNOWN_BIOS_TABLE, f"{bios_slug}:{file_name}") + if ( + known + and file_size_bytes == int(known.get("size", 0)) + and ( + md5_hash == known.get("md5") + or sha1_hash == known.get("sha1") + or crc_hash == known.get("crc") + ) + ): + return True # A renamed or relocated dump still verifies by content. CRC32 is left # out here because without the name match it is too weak on its own. diff --git a/backend/startup.py b/backend/startup.py index 44a3f7d1a..c80684216 100644 --- a/backend/startup.py +++ b/backend/startup.py @@ -1,7 +1,7 @@ """Startup script to run tasks before the main application is started.""" import asyncio -from typing import cast +from typing import Final, NamedTuple, cast from opentelemetry import trace from rq.exceptions import DuplicateJobError, NoSuchJobError @@ -17,15 +17,8 @@ from config import ( ) from config.config_manager import config_manager as cm from handler.database import db_save_handler -from handler.metadata.base_handler import ( - MAME_XML_KEY, - METADATA_FIXTURES_DIR, - PS1_SERIAL_INDEX_KEY, - PS2_OPL_KEY, - PS2_SERIAL_INDEX_KEY, - PSP_SERIAL_INDEX_KEY, - SCUMMVM_INDEX_KEY, -) +from handler.dump_store import DumpStore +from handler.fixture_store import fixture_store from handler.metadata.launchbox_handler.types import LAUNCHBOX_METADATA_STORE from handler.redis_handler import ( async_cache, @@ -36,7 +29,6 @@ from handler.redis_handler import ( ) from handler.scan_jobs import drop_stale_scheduled_scans from logger.logger import log -from models.firmware import KNOWN_BIOS_FILE, KNOWN_BIOS_KEY from models.rom import sort_articles from tasks.manual.recompute_name_sort_keys import ( applied_sort_articles, @@ -44,7 +36,6 @@ from tasks.manual.recompute_name_sort_keys import ( ) from tasks.registry import enqueue_task from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE -from utils.cache import conditionally_set_cache, drop_stale_cache_store from utils.context import initialize_context from utils.platform_aliases import unknown_binding_warnings from utils.sentry import init_sentry @@ -138,17 +129,60 @@ 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 = ( - ( +# Cache keys earlier releases kept the metadata stores under. +LEGACY_LAUNCHBOX_CACHE_KEYS: Final = ( + "romm:launchbox_platforms", + "romm:launchbox_metadata_database_id", + "romm:launchbox_metadata_name", + "romm:launchbox_metadata_alternate_name", + "romm:launchbox_metadata_folded_name", + "romm:launchbox_metadata_image", + "romm:launchbox_mame", + "romm:launchbox_files", + "romm:launchbox_metadata_schema", + "romm:launchbox_metadata_initial_import", +) +LEGACY_SWITCH_TITLEDB_CACHE_KEYS: Final = ( + "romm:switch_titledb", + "romm:switch_product_id", + "romm:switch_titledb_schema", +) +LEGACY_FIXTURE_CACHE_KEYS: Final = tuple( + f"romm:{name}{suffix}" + for name in ( + "mame_xml", + "scummvm_index", + "ps2_opl_index", + "ps1_serial_index", + "ps2_serial_index", + "psp_serial_index", + "known_bios_files", + ) + for suffix in ("", ":file_hash") +) + + +class MetadataDumpStore(NamedTuple): + store: DumpStore + legacy_keys: tuple[str, ...] + task_name: str + job_id: str + # A provider that is off reclaims its store without queueing a download + # nothing would read. + rebuild: bool + + +METADATA_DUMP_STORES: Final[tuple[MetadataDumpStore, ...]] = ( + MetadataDumpStore( LAUNCHBOX_METADATA_STORE, + LEGACY_LAUNCHBOX_CACHE_KEYS, "update_launchbox_metadata", UPDATE_LAUNCHBOX_METADATA_JOB_ID, LAUNCHBOX_API_ENABLED, ), - ( + MetadataDumpStore( SWITCH_TITLEDB_STORE, + LEGACY_SWITCH_TITLEDB_CACHE_KEYS, "update_switch_titledb", UPDATE_SWITCH_TITLEDB_JOB_ID, True, @@ -157,13 +191,17 @@ VERSIONED_METADATA_STORES = ( 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): + """Drop what an older release left of the metadata stores and queue a rebuild.""" + await async_cache.unlink(*LEGACY_FIXTURE_CACHE_KEYS) + + for store, legacy_keys, task_name, job_id, rebuild in METADATA_DUMP_STORES: + dropped_legacy = bool(await async_cache.unlink(*legacy_keys)) + dropped_files = store.drop_other_revisions() + if not (dropped_legacy or dropped_files): continue log.info(f"Dropped the {task_name} store left by an older release") - if rebuild: + if rebuild and not store.exists(): _enqueue_backfill(task_name, job_id) @@ -249,34 +287,10 @@ async def main() -> None: 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" - ) - await conditionally_set_cache( - async_cache, - SCUMMVM_INDEX_KEY, - METADATA_FIXTURES_DIR / "scummvm_index.json", - ) - await conditionally_set_cache( - async_cache, PS2_OPL_KEY, METADATA_FIXTURES_DIR / "ps2_opl_index.json" - ) - await conditionally_set_cache( - async_cache, - PS1_SERIAL_INDEX_KEY, - METADATA_FIXTURES_DIR / "ps1_serial_index.json", - ) - await conditionally_set_cache( - async_cache, - PS2_SERIAL_INDEX_KEY, - METADATA_FIXTURES_DIR / "ps2_serial_index.json", - ) - await conditionally_set_cache( - async_cache, - PSP_SERIAL_INDEX_KEY, - METADATA_FIXTURES_DIR / "psp_serial_index.json", - ) - await conditionally_set_cache(async_cache, KNOWN_BIOS_KEY, KNOWN_BIOS_FILE) + try: + fixture_store() + except Exception: + log.exception("Failed to build the fixture store") log.info("Startup tasks completed") diff --git a/backend/tasks/registry.py b/backend/tasks/registry.py index 0a145c965..168d31f7b 100644 --- a/backend/tasks/registry.py +++ b/backend/tasks/registry.py @@ -74,8 +74,8 @@ UPDATE_LAUNCHBOX_METADATA_SPEC: Final = TaskSpec( enabled=ENABLE_SCHEDULED_UPDATE_LAUNCHBOX_METADATA, cron_string=SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON, manual_run=True, - # The store lives only in the cache, so with LaunchBox on admins must be - # able to fill it even while the scheduled update is off. + # Only this task builds the store, so when LaunchBox is enabled, admins must + # be able to fill it even while the scheduled update is off. manual_run_when_disabled=LAUNCHBOX_API_ENABLED, # Downloading ~100MB and parsing it takes far longer than an ordinary task. timeout=max(TASK_TIMEOUT, 30 * 60), diff --git a/backend/tasks/scheduled/update_launchbox_metadata.py b/backend/tasks/scheduled/update_launchbox_metadata.py index 9fb289d31..dad254d34 100644 --- a/backend/tasks/scheduled/update_launchbox_metadata.py +++ b/backend/tasks/scheduled/update_launchbox_metadata.py @@ -1,63 +1,33 @@ import zipfile -from collections.abc import Iterator +from collections.abc import Callable, Iterator from io import BytesIO -from typing import Any, Final +from typing import IO, Any, Final from defusedxml import ElementTree as ET -from redis.asyncio.client import Pipeline -from handler.dump_cache import encode +from handler.dump_store import DumpWriter from handler.metadata import meta_launchbox_handler from handler.metadata.launchbox_handler.types import ( + LAUNCHBOX_ALTERNATE_NAME_TABLE, LAUNCHBOX_FILE_FIELDS, - LAUNCHBOX_FILES_KEY, + LAUNCHBOX_FILES_TABLE, + LAUNCHBOX_FOLDED_NAME_TABLE, LAUNCHBOX_IMAGE_FIELDS, + LAUNCHBOX_IMAGE_TABLE, LAUNCHBOX_MAME_FIELDS, - LAUNCHBOX_MAME_KEY, - LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, - LAUNCHBOX_METADATA_DATABASE_ID_KEY, - LAUNCHBOX_METADATA_FOLDED_NAME_KEY, - LAUNCHBOX_METADATA_IMAGE_KEY, - LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, - LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_MAME_TABLE, LAUNCHBOX_METADATA_STORE, - LAUNCHBOX_PLATFORMS_KEY, + LAUNCHBOX_METADATA_TABLE, + LAUNCHBOX_NAME_TABLE, ) from handler.metadata.launchbox_handler.utils import fold_title -from handler.redis_handler import async_binary_cache, async_cache from logger.logger import log from tasks.registry import UPDATE_LAUNCHBOX_METADATA_SPEC from tasks.tasks import RemoteFilePullTask -from utils.cache import drop_stale_cache_store, stamp_cache_schema from utils.context import initialize_context from . import UpdateStats -# The dump is ~500MB across 600k+ entries. Buffering it into one pipeline peaks -# well over a gigabyte of memory and discards everything if the job dies, so -# writes go out in batches instead. -CACHE_WRITE_BATCH_SIZE: Final[int] = 2000 - - -class BatchedCacheWriter: - """Queues cache writes on a pipeline, flushing every `batch_size` entries.""" - - def __init__(self, pipe: Pipeline, batch_size: int | None = None) -> None: - self._pipe = pipe - self._batch_size = batch_size or CACHE_WRITE_BATCH_SIZE - self._queued = 0 - - async def hset(self, key: str, field: str, value: Any) -> None: - await self._pipe.hset(key, mapping={field: encode(value)}) - self._queued += 1 - if self._queued >= self._batch_size: - await self.flush() - - async def flush(self) -> None: - if self._queued: - await self._pipe.execute() - self._queued = 0 - def _element_to_dict(elem: Any, fields: frozenset[str] | None = None) -> dict[str, Any]: if fields is None: @@ -92,6 +62,110 @@ def _iter_elements(source: Any) -> Iterator[Any]: root.clear() +def _import_metadata(source: IO[bytes], writer: DumpWriter) -> None: + current_game_image_db_id: str | None = None + current_game_images: list[dict[str, Any]] = [] + + for elem in _iter_elements(source): + if elem.tag == "Game": + database_id = (elem.findtext("DatabaseID") or "").strip() + if database_id: + writer.put( + LAUNCHBOX_METADATA_TABLE, database_id, _element_to_dict(elem) + ) + + name = (elem.findtext("Name") or "").strip() + platform_name = (elem.findtext("Platform") or "").strip() + if database_id and name and platform_name: + # The title indexes hold the id, not a second copy of the record. + writer.put( + LAUNCHBOX_NAME_TABLE, + f"{name.lower()}:{platform_name}", + database_id, + ) + + folded = fold_title(name) + if folded: + writer.put( + LAUNCHBOX_FOLDED_NAME_TABLE, + f"{folded}:{platform_name}", + database_id, + ) + + elif elem.tag == "GameAlternateName": + alternate_name = (elem.findtext("AlternateName") or "").strip() + alternate_id = (elem.findtext("DatabaseID") or "").strip() + if alternate_name and alternate_id: + writer.put( + LAUNCHBOX_ALTERNATE_NAME_TABLE, + alternate_name.lower(), + alternate_id, + ) + + elif elem.tag == "GameImage": + image_id = (elem.findtext("DatabaseID") or "").strip() + if not image_id: + continue + + # A game's images are contiguous in the dump. + if ( + current_game_image_db_id is not None + and image_id != current_game_image_db_id + ): + writer.put( + LAUNCHBOX_IMAGE_TABLE, + current_game_image_db_id, + current_game_images, + ) + current_game_images = [] + + current_game_image_db_id = image_id + current_game_images.append(_element_to_dict(elem, LAUNCHBOX_IMAGE_FIELDS)) + + if current_game_image_db_id is not None: + writer.put(LAUNCHBOX_IMAGE_TABLE, current_game_image_db_id, current_game_images) + + +def _import_mame(source: IO[bytes], writer: DumpWriter) -> None: + for elem in _iter_elements(source): + if elem.tag != "MameFile": + continue + + file_name = (elem.findtext("FileName") or "").strip() + if file_name: + writer.put( + LAUNCHBOX_MAME_TABLE, + file_name, + _element_to_dict(elem, LAUNCHBOX_MAME_FIELDS), + ) + + +def _import_files(source: IO[bytes], writer: DumpWriter) -> None: + for elem in _iter_elements(source): + if elem.tag != "File": + continue + + file_name = (elem.findtext("FileName") or "").strip() + platform_name = (elem.findtext("Platform") or "").strip() + if file_name and platform_name: + # The same dump filename exists on several platforms, so the key + # has to carry the platform too. + writer.put( + LAUNCHBOX_FILES_TABLE, + f"{file_name.lower()}:{platform_name}", + _element_to_dict(elem, LAUNCHBOX_FILE_FIELDS), + ) + + +# Keys are stored the way lookups build them: stripped, and lowercased wherever +# the lookup lowercases. +ARCHIVE_IMPORTERS: Final[dict[str, Callable[[IO[bytes], DumpWriter], None]]] = { + "Metadata.xml": _import_metadata, + "Mame.xml": _import_mame, + "Files.xml": _import_files, +} + + class UpdateLaunchboxMetadataTask(RemoteFilePullTask): def __init__(self) -> None: super().__init__( @@ -109,198 +183,25 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): content = await super().run() - # A refresh keeps serving the previous dump, but a first import only - # holds the batches committed so far, so flag it to keep the provider - # from reporting healthy off a fraction of the entries. - if not await meta_launchbox_handler.is_remote_store_populated(): - await async_cache.set(LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, "1") + # Only archive errors are wrapped; a failure writing the store keeps its own. + with LAUNCHBOX_METADATA_STORE.build() as writer: + try: + with zipfile.ZipFile(BytesIO(content)) as z: + file_list = z.namelist() + update_stats.update(processed=0, total=len(file_list)) - # An import merges into its hashes, so an older release's rows go first. - await drop_stale_cache_store(async_cache, LAUNCHBOX_METADATA_STORE) + for processed_files, file in enumerate(file_list, start=1): + importer = ARCHIVE_IMPORTERS.get(file) + if importer is not None: + with z.open(file, "r") as f: + importer(f, writer) - try: - zip_file_bytes = BytesIO(content) - with zipfile.ZipFile(zip_file_bytes) as z: - file_list = z.namelist() - total_files = len(file_list) - processed_files = 0 + update_stats.update(processed=processed_files) - # Update initial progress - update_stats.update(processed=processed_files, total=total_files) - - # Keys are stored the way lookups build them: stripped, and - # lowercased wherever the lookup lowercases. - for file in file_list: - if file == "Platforms.xml": - with z.open(file, "r") as f: - async with async_binary_cache.pipeline() as pipe: - writer = BatchedCacheWriter(pipe) - - for elem in _iter_elements(f): - if elem.tag == "Platform": - name_elem = elem.find("Name") - if name_elem is not None and name_elem.text: - await writer.hset( - LAUNCHBOX_PLATFORMS_KEY, - name_elem.text.strip(), - _element_to_dict(elem), - ) - - await writer.flush() - processed_files += 1 - update_stats.update(processed=processed_files) - - elif file == "Metadata.xml": - with z.open(file, "r") as f: - async with async_binary_cache.pipeline() as pipe: - writer = BatchedCacheWriter(pipe) - - current_game_image_db_id = None - current_game_images: list[dict[str, Any]] = [] - - for elem in _iter_elements(f): - if elem.tag == "Game": - database_id = ( - elem.findtext("DatabaseID") or "" - ).strip() - if database_id: - await writer.hset( - LAUNCHBOX_METADATA_DATABASE_ID_KEY, - database_id, - _element_to_dict(elem), - ) - - 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.lower()}:{platform_name}", - database_id, - ) - - folded = fold_title(name) - if folded: - await writer.hset( - LAUNCHBOX_METADATA_FOLDED_NAME_KEY, - f"{folded}:{platform_name}", - database_id, - ) - - elif elem.tag == "GameAlternateName": - 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.lower(), - alternate_id, - ) - - elif elem.tag == "GameImage": - id_elem = elem.find("DatabaseID") - if id_elem is not None and id_elem.text: - image_id = id_elem.text.strip() - - if ( - current_game_image_db_id is not None - and image_id != current_game_image_db_id - ): - # Store the previous game's images - await writer.hset( - LAUNCHBOX_METADATA_IMAGE_KEY, - current_game_image_db_id, - current_game_images, - ) - current_game_images = [] - - current_game_image_db_id = image_id - current_game_images.append( - _element_to_dict( - elem, LAUNCHBOX_IMAGE_FIELDS - ) - ) - - # Store the last game's images - if current_game_image_db_id is not None: - await writer.hset( - LAUNCHBOX_METADATA_IMAGE_KEY, - current_game_image_db_id, - current_game_images, - ) - await writer.flush() - processed_files += 1 - update_stats.update(processed=processed_files) - - elif file == "Mame.xml": - with z.open(file, "r") as f: - async with async_binary_cache.pipeline() as pipe: - writer = BatchedCacheWriter(pipe) - - for elem in _iter_elements(f): - if elem.tag == "MameFile": - filename_elem = elem.find("FileName") - if ( - filename_elem is not None - and filename_elem.text - ): - await writer.hset( - LAUNCHBOX_MAME_KEY, - filename_elem.text.strip(), - _element_to_dict( - elem, LAUNCHBOX_MAME_FIELDS - ), - ) - - await writer.flush() - processed_files += 1 - update_stats.update(processed=processed_files) - - elif file == "Files.xml": - with z.open(file, "r") as f: - async with async_binary_cache.pipeline() as pipe: - writer = BatchedCacheWriter(pipe) - - for elem in _iter_elements(f): - if elem.tag == "File": - filename_elem = elem.find("FileName") - platform_elem = elem.find("Platform") - if ( - filename_elem is not None - and filename_elem.text - and platform_elem is not None - and platform_elem.text - ): - # The same dump filename exists on several platforms, - # so the key has to carry the platform too. - await writer.hset( - LAUNCHBOX_FILES_KEY, - f"{filename_elem.text.strip().lower()}" - f":{platform_elem.text.strip()}", - _element_to_dict( - elem, LAUNCHBOX_FILE_FIELDS - ), - ) - - await writer.flush() - processed_files += 1 - update_stats.update(processed=processed_files) - - except (zipfile.BadZipFile, RuntimeError, OSError) as exc: - raise RuntimeError("Could not read the LaunchBox metadata archive") from exc - - 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) + except (zipfile.BadZipFile, RuntimeError, OSError) as exc: + raise RuntimeError( + "Could not read the LaunchBox metadata archive" + ) from exc log.info("Scheduled launchbox metadata update completed!") diff --git a/backend/tasks/scheduled/update_switch_titledb.py b/backend/tasks/scheduled/update_switch_titledb.py index e767f564b..65e95c77f 100644 --- a/backend/tasks/scheduled/update_switch_titledb.py +++ b/backend/tasks/scheduled/update_switch_titledb.py @@ -1,28 +1,26 @@ import json -from itertools import batched +from pathlib import Path from typing import Any, Final -from handler.dump_cache import encode -from handler.redis_handler import async_binary_cache, async_cache +from config import METADATA_DUMPS_PATH +from handler.dump_store import DumpStore from logger.logger import log from tasks.registry import UPDATE_SWITCH_TITLEDB_SPEC from tasks.tasks import RemoteFilePullTask -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" -# Version 2 stores each entry compressed. -SWITCH_TITLEDB_STORE: Final = VersionedCacheStore( - schema_key="romm:switch_titledb_schema", - version=2, - keys=(SWITCH_TITLEDB_INDEX_KEY, SWITCH_PRODUCT_ID_KEY), +PROGRESS_INTERVAL: Final = 2000 + +SWITCH_TITLEDB_TABLE: Final = "titles" +SWITCH_PRODUCT_ID_TABLE: Final = "product_ids" +SWITCH_TITLEDB_STORE: Final = DumpStore( + Path(METADATA_DUMPS_PATH), + "switch_titledb", + "v1", + (SWITCH_TITLEDB_TABLE, SWITCH_PRODUCT_ID_TABLE), + required_table=SWITCH_TITLEDB_TABLE, ) @@ -39,41 +37,23 @@ class UpdateSwitchTitleDBTask(RemoteFilePullTask): content = await super().run() - # 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) - processed_items = 0 + update_stats.update(processed=0, total=len(relevant_data)) - # Update initial progress - update_stats.update(processed=processed_items, total=total_items) + with SWITCH_TITLEDB_STORE.build() as writer: + for processed_items, (title_id, entry) in enumerate( + relevant_data.items(), start=1 + ): + writer.put(SWITCH_TITLEDB_TABLE, title_id, entry) + # Maps to the title id rather than to a second copy of the entry. + if entry.get("id"): + writer.put(SWITCH_PRODUCT_ID_TABLE, entry["id"], title_id) - async with async_binary_cache.pipeline() as pipe: - for data_batch in batched(relevant_data.items(), 2000, strict=False): - await pipe.hset( - SWITCH_TITLEDB_INDEX_KEY, - mapping={title_id: encode(v) for title_id, v in data_batch}, - ) + if processed_items % PROGRESS_INTERVAL == 0: + update_stats.update(processed=processed_items) - # A second copy of each entry here costs ~60MB of cache. - product_map = { - v["id"]: encode(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) + update_stats.update(processed=len(relevant_data)) log.info("Scheduled switch titledb update completed!") return update_stats.to_dict() diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 0056fa5cd..1b2d1caf9 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -53,6 +53,7 @@ from handler.database import ( db_user_handler, ) from handler.database.base_handler import sync_engine +from handler.metadata.launchbox_handler.types import LAUNCHBOX_METADATA_STORE from logger.formatter import SENSITIVE_KEYS from models import load_all_models from models.assets import MemoryCard, MemoryCardVersion @@ -61,6 +62,7 @@ from models.permission import PermissionGroup, PermissionGroupGrant, SystemGroup from models.platform import Platform from models.rom import Rom, RomFile from models.user import Role, User +from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE from utils.database import get_db_url engine = create_engine(get_db_url(), pool_pre_ping=True) @@ -172,6 +174,15 @@ def raise_on_response_mismatch(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(response_validation, "RAISE_ON_MISMATCH", True) +@pytest.fixture(autouse=True) +def metadata_dump_dir(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path: + """Point the metadata dump stores at an empty folder of the test's own.""" + directory = tmp_path / "metadata" + for store in (LAUNCHBOX_METADATA_STORE, SWITCH_TITLEDB_STORE): + monkeypatch.setattr(store, "directory", directory) + return directory + + @pytest.fixture def lenient(monkeypatch: pytest.MonkeyPatch) -> MagicMock: """Production mode: mismatches log to the returned mock instead of raising.""" diff --git a/backend/tests/handler/metadata/conftest.py b/backend/tests/handler/metadata/conftest.py deleted file mode 100644 index e1496aad8..000000000 --- a/backend/tests/handler/metadata/conftest.py +++ /dev/null @@ -1,13 +0,0 @@ -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 d223be5bd..0abd0b5eb 100644 --- a/backend/tests/handler/metadata/test_base_handler.py +++ b/backend/tests/handler/metadata/test_base_handler.py @@ -1,4 +1,3 @@ -import json import re from collections.abc import AsyncIterator from unittest.mock import AsyncMock, patch @@ -6,19 +5,20 @@ from urllib.parse import parse_qsl, urlparse import httpx2 import pytest -from tests.handler.metadata.conftest import schema_stamp_get +from handler.fixture_store import ( + MAME_TABLE, + PS1_SERIAL_TABLE, + PS2_OPL_TABLE, + PS2_SERIAL_TABLE, + PSP_SERIAL_TABLE, +) from handler.metadata import base_handler from handler.metadata.base_handler import ( LEADING_ARTICLE_PATTERN, - MAME_XML_KEY, MULTIPLE_SPACE_PATTERN, NON_WORD_SPACE_PATTERN, - PS1_SERIAL_INDEX_KEY, - PS2_OPL_KEY, PS2_OPL_REGEX, - PS2_SERIAL_INDEX_KEY, - PSP_SERIAL_INDEX_KEY, SONY_SERIAL_REGEX, SWITCH_PRODUCT_ID_REGEX, SWITCH_TITLEDB_REGEX, @@ -31,13 +31,12 @@ from handler.metadata.base_handler import ( strip_sensitive_query_params, tag_id_from_filename, ) -from handler.redis_handler import async_cache from models.platform import Platform from models.rom import Rom from tasks.scheduled.update_switch_titledb import ( - SWITCH_PRODUCT_ID_KEY, - SWITCH_TITLEDB_INDEX_KEY, + SWITCH_PRODUCT_ID_TABLE, SWITCH_TITLEDB_STORE, + SWITCH_TITLEDB_TABLE, ) from utils.context import ctx_httpx_client from utils.platform_slugs import UniversalPlatformSlug @@ -159,21 +158,21 @@ class TestMetadataHandlerMethods: @pytest.mark.asyncio async def test_ps2_opl_format_found(self, handler: MetadataHandler): """Test PS2 OPL format when serial is found.""" - with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget: - mock_hget.return_value = json.dumps({"Name": "Test Game Name"}) + with patch.object(base_handler, "fixture_get") as mock_get: + mock_get.return_value = {"Name": "Test Game Name"} match = re.match(PS2_OPL_REGEX, "SLUS_123.45.iso") assert match is not None result = await handler._ps2_opl_format(match, "original_name") - mock_hget.assert_called_once_with(PS2_OPL_KEY, "SLUS_123.45") + mock_get.assert_called_once_with(PS2_OPL_TABLE, "SLUS_123.45") assert result == "Test Game Name" @pytest.mark.asyncio async def test_ps2_opl_format_not_found(self, handler: MetadataHandler): """Test PS2 OPL format when serial is not found.""" - with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget: - mock_hget.return_value = None + with patch.object(base_handler, "fixture_get") as mock_get: + mock_get.return_value = None match = re.match(PS2_OPL_REGEX, "SLUS_123.45.iso") assert match is not None @@ -184,19 +183,19 @@ class TestMetadataHandlerMethods: @pytest.mark.asyncio async def test_sony_serial_format_found(self, handler: MetadataHandler): """Test Sony serial format when found.""" - with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget: - mock_hget.return_value = json.dumps({"title": "Found Game Title"}) + with patch.object(base_handler, "fixture_get") as mock_get: + mock_get.return_value = {"title": "Found Game Title"} result = await handler._sony_serial_format("test_key", "SLUS-12345") - mock_hget.assert_called_once_with("test_key", "SLUS-12345") + mock_get.assert_called_once_with("test_key", "SLUS-12345") assert result == "Found Game Title" @pytest.mark.asyncio async def test_sony_serial_format_not_found(self, handler: MetadataHandler): """Test Sony serial format when not found.""" - with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget: - mock_hget.return_value = None + with patch.object(base_handler, "fixture_get") as mock_get: + mock_get.return_value = None result = await handler._sony_serial_format("test_key", "SLUS-12345") @@ -205,12 +204,12 @@ class TestMetadataHandlerMethods: @pytest.mark.asyncio async def test_sony_serial_format_normalizes_casing(self, handler: MetadataHandler): """Test Sony serial format uppercases the serial before lookup.""" - with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget: - mock_hget.return_value = json.dumps({"title": "Found Game Title"}) + with patch.object(base_handler, "fixture_get") as mock_get: + mock_get.return_value = {"title": "Found Game Title"} result = await handler._sony_serial_format("test_key", "slus-12345") - mock_hget.assert_called_once_with("test_key", "SLUS-12345") + mock_get.assert_called_once_with("test_key", "SLUS-12345") assert result == "Found Game Title" @pytest.mark.asyncio @@ -225,7 +224,7 @@ class TestMetadataHandlerMethods: assert match is not None result = await handler._ps1_serial_format(match, "original") - mock_sony.assert_called_once_with(PS1_SERIAL_INDEX_KEY, "SLUS-12345") + mock_sony.assert_called_once_with(PS1_SERIAL_TABLE, "SLUS-12345") assert result == "PS1 Game Title" @pytest.mark.asyncio @@ -254,7 +253,7 @@ class TestMetadataHandlerMethods: if match: result = await handler._ps2_serial_format(match, "original") - mock_sony.assert_called_once_with(PS2_SERIAL_INDEX_KEY, "SLUS-12345") + mock_sony.assert_called_once_with(PS2_SERIAL_TABLE, "SLUS-12345") assert result == "PS2 Game Title" @pytest.mark.asyncio @@ -269,21 +268,17 @@ class TestMetadataHandlerMethods: if match: result = await handler._psp_serial_format(match, "original") - mock_sony.assert_called_once_with(PSP_SERIAL_INDEX_KEY, "ULUS-12345") + mock_sony.assert_called_once_with(PSP_SERIAL_TABLE, "ULUS-12345") assert result == "PSP Game Title" @pytest.mark.asyncio async def test_switch_titledb_format_cache_exists(self, handler: MetadataHandler): """Test Switch TitleDB format when cache exists.""" 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, + patch.object(SWITCH_TITLEDB_STORE, "exists", return_value=True), + patch.object(SWITCH_TITLEDB_STORE, "get") as mock_get, ): - mock_exists.return_value = True - mock_hget.return_value = json.dumps( - {"name": "Switch Game", "publisher": "Nintendo"} - ) + mock_get.return_value = {"name": "Switch Game", "publisher": "Nintendo"} match = re.match(SWITCH_TITLEDB_REGEX, "70123456789012") assert match is not None @@ -291,7 +286,7 @@ class TestMetadataHandlerMethods: match, "original" ) - mock_hget.assert_called_once() + mock_get.assert_called_once() assert index_name == "Switch Game" assert index_entry is not None assert index_entry["publisher"] == "Nintendo" @@ -300,11 +295,10 @@ class TestMetadataHandlerMethods: async def test_switch_titledb_format_not_found(self, handler: MetadataHandler): """Test Switch TitleDB format when title ID not found.""" with ( - patch.object(async_cache, "exists", new_callable=AsyncMock) as mock_exists, - patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget, + patch.object(SWITCH_TITLEDB_STORE, "exists", return_value=True), + patch.object(SWITCH_TITLEDB_STORE, "get") as mock_get, ): - mock_exists.return_value = True - mock_hget.return_value = None + mock_get.return_value = None match = re.match(SWITCH_TITLEDB_REGEX, "70123456789012") assert match is not None @@ -330,23 +324,21 @@ class TestMetadataHandlerMethods: """Only the base application has a titledb entry, so updates and DLC are resolved to it before the lookup.""" 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, + patch.object(SWITCH_TITLEDB_STORE, "exists", return_value=True), + patch.object(SWITCH_TITLEDB_STORE, "get") as mock_get, ): - mock_exists.return_value = True - mock_hget.side_effect = [ - json.dumps("70010000000025"), - json.dumps({"name": "Product Game"}), + mock_get.side_effect = [ + "70010000000025", + {"name": "Product Game"}, ] rom = Rom(fs_name="Game.nsp", title_id=product_id) result = await handler._switch_productid_format(rom, "Game.nsp", "original") # 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 [call.args for call in mock_get.call_args_list] == [ + (SWITCH_PRODUCT_ID_TABLE, "0100ABCD12340000"), + (SWITCH_TITLEDB_TABLE, "70010000000025"), ] assert result[0] == "Product Game" @@ -375,27 +367,23 @@ class TestMetadataHandlerMethods: rom = Rom(fs_name=fs_name, title_id=title_id) 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, + patch.object(SWITCH_TITLEDB_STORE, "exists", return_value=True), + patch.object(SWITCH_TITLEDB_STORE, "get") as mock_get, ): - mock_exists.return_value = True - mock_hget.return_value = None + mock_get.return_value = None await handler._switch_productid_format(rom, fs_name, "original") if expected is None: - mock_hget.assert_not_called() + mock_get.assert_not_called() else: - mock_hget.assert_called_once_with(SWITCH_PRODUCT_ID_KEY, expected) + mock_get.assert_called_once_with(SWITCH_PRODUCT_ID_TABLE, expected) @pytest.mark.asyncio async def test_mame_format_found(self, handler: MetadataHandler): """Test MAME format when entry is found.""" - with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget: - mock_hget.return_value = json.dumps( - {"description": "Test MAME Game (Version 1.0)"} - ) + with patch.object(base_handler, "fixture_get") as mock_get: + mock_get.return_value = {"description": "Test MAME Game (Version 1.0)"} # Mock the fs_rom_handler import from handler.filesystem with patch("handler.filesystem.fs_rom_handler") as mock_fs_handler: @@ -405,7 +393,7 @@ class TestMetadataHandlerMethods: result = await handler._mame_format("test_rom") - mock_hget.assert_called_once_with(MAME_XML_KEY, "test_rom") + mock_get.assert_called_once_with(MAME_TABLE, "test_rom") mock_fs_handler.get_file_name_with_no_tags.assert_called_once_with( "Test MAME Game (Version 1.0)" ) @@ -414,8 +402,8 @@ class TestMetadataHandlerMethods: @pytest.mark.asyncio async def test_mame_format_not_found(self, handler: MetadataHandler): """Test MAME format when entry is not found.""" - with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget: - mock_hget.return_value = None + with patch.object(base_handler, "fixture_get") as mock_get: + mock_get.return_value = None result = await handler._mame_format("test_rom") @@ -590,10 +578,10 @@ class TestResolveIndexedTitle: @pytest.mark.asyncio async def test_other_platform_is_left_alone(self, handler: MetadataHandler): - with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget: + with patch.object(base_handler, "fixture_get") as mock_get: term, fallback_rom = await self._resolve(handler, "SLUS-12345.bin", 99) - mock_hget.assert_not_called() + mock_get.assert_not_called() assert term == "original" assert fallback_rom == BaseRom() @@ -963,38 +951,6 @@ class TestBaseRomTypedDict: assert len(rom) == 5 -class TestConstants: - """Test module constants.""" - - def test_redis_keys_format(self): - """Test that Redis keys follow expected format.""" - expected_prefix = "romm:" - - redis_keys = [ - MAME_XML_KEY, - PS2_OPL_KEY, - PS1_SERIAL_INDEX_KEY, - PS2_SERIAL_INDEX_KEY, - PSP_SERIAL_INDEX_KEY, - ] - - for key in redis_keys: - assert key.startswith(expected_prefix) - assert len(key) > len(expected_prefix) - - def test_key_uniqueness(self): - """Test that all Redis keys are unique.""" - keys = [ - MAME_XML_KEY, - PS2_OPL_KEY, - PS1_SERIAL_INDEX_KEY, - PS2_SERIAL_INDEX_KEY, - PSP_SERIAL_INDEX_KEY, - ] - - assert len(keys) == len(set(keys)) - - class _CappedHandler(base_handler.MetadataHandler): @classmethod def is_enabled(cls) -> bool: diff --git a/backend/tests/handler/metadata/test_igdb_handler.py b/backend/tests/handler/metadata/test_igdb_handler.py index a93d72e8a..1fa222ad2 100644 --- a/backend/tests/handler/metadata/test_igdb_handler.py +++ b/backend/tests/handler/metadata/test_igdb_handler.py @@ -1,6 +1,5 @@ """Tests for the IGDB metadata handler.""" -import json from collections.abc import AsyncIterator from typing import Any, cast from unittest.mock import AsyncMock, MagicMock, patch @@ -24,8 +23,8 @@ from adapters.services.igdb_types import ( GameLocalization, GameType, ) +from handler.fixture_store import PS1_SERIAL_TABLE from handler.metadata import igdb_handler -from handler.metadata.base_handler import PS1_SERIAL_INDEX_KEY from handler.metadata.igdb_handler import ( FAMICOM_IGDB_ID, NES_IGDB_ID, @@ -881,15 +880,15 @@ class TestSonySerialFilenames: "handler.metadata.igdb_handler.IGDBHandler.is_enabled", return_value=True, ), - patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget, + patch("handler.metadata.base_handler.fixture_get") as mock_get, patch.object( IGDBHandler, "_search_rom", new_callable=AsyncMock, return_value=None ), ): - mock_hget.return_value = json.dumps({"title": "Gran Turismo"}) + mock_get.return_value = {"title": "Gran Turismo"} result = await handler.get_rom(MagicMock(), "SCUS-94163.bin", PS1_IGDB_ID) - mock_hget.assert_awaited_once_with(PS1_SERIAL_INDEX_KEY, "SCUS-94163") + mock_get.assert_called_once_with(PS1_SERIAL_TABLE, "SCUS-94163") assert result.get("name") == "Gran Turismo" assert result["igdb_id"] is None diff --git a/backend/tests/handler/metadata/test_launchbox_handler.py b/backend/tests/handler/metadata/test_launchbox_handler.py index 33794f4c9..c924941a8 100644 --- a/backend/tests/handler/metadata/test_launchbox_handler.py +++ b/backend/tests/handler/metadata/test_launchbox_handler.py @@ -9,7 +9,6 @@ Covers: - handler.py: LaunchboxHandler orchestration """ -import json from pathlib import Path from typing import Any from unittest.mock import AsyncMock, MagicMock, patch @@ -17,9 +16,8 @@ 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.dump_cache import _ZSTD_MAGIC, encode +from handler.dump_store import _ZSTD_MAGIC, encode from handler.metadata.launchbox_handler.handler import LaunchboxHandler from handler.metadata.launchbox_handler.local_source import LocalSource from handler.metadata.launchbox_handler.media import ( @@ -36,15 +34,14 @@ from handler.metadata.launchbox_handler.media import ( from handler.metadata.launchbox_handler.platforms import get_platform from handler.metadata.launchbox_handler.remote_source import RemoteSource from handler.metadata.launchbox_handler.types import ( - LAUNCHBOX_FILES_KEY, - LAUNCHBOX_MAME_KEY, - LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, - LAUNCHBOX_METADATA_DATABASE_ID_KEY, - LAUNCHBOX_METADATA_FOLDED_NAME_KEY, - LAUNCHBOX_METADATA_IMAGE_KEY, - LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, - LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_ALTERNATE_NAME_TABLE, + LAUNCHBOX_FILES_TABLE, + LAUNCHBOX_FOLDED_NAME_TABLE, + LAUNCHBOX_IMAGE_TABLE, + LAUNCHBOX_MAME_TABLE, LAUNCHBOX_METADATA_STORE, + LAUNCHBOX_METADATA_TABLE, + LAUNCHBOX_NAME_TABLE, LaunchboxImage, LaunchboxMetadata, MediaRequest, @@ -58,7 +55,6 @@ from handler.metadata.launchbox_handler.utils import ( parse_release_date, sanitize_filename, ) -from handler.redis_handler import async_cache # --------------------------------------------------------------------------- # Sample XML that mirrors a real LaunchBox platform file @@ -513,18 +509,15 @@ class TestRemoteSourceGetById: return RemoteSource() async def test_cache_miss_returns_none(self, source: RemoteSource): - with patch.object( - async_cache, "hget", new_callable=AsyncMock, return_value=None - ): + with patch.object(LAUNCHBOX_METADATA_STORE, "get", return_value=None): result = await source.get_by_id(1234) assert result is None async def test_cache_hit_returns_dict(self, source: RemoteSource): with patch.object( - async_cache, - "hget", - new_callable=AsyncMock, - return_value=json.dumps(REMOTE_ENTRY), + LAUNCHBOX_METADATA_STORE, + "get", + return_value=REMOTE_ENTRY, ): result = await source.get_by_id(1234) assert result is not None @@ -532,13 +525,12 @@ class TestRemoteSourceGetById: async def test_accepts_string_id(self, source: RemoteSource): with patch.object( - async_cache, - "hget", - new_callable=AsyncMock, - return_value=json.dumps(REMOTE_ENTRY), - ) as mock_hget: + LAUNCHBOX_METADATA_STORE, + "get", + return_value=REMOTE_ENTRY, + ) as mock_get: await source.get_by_id("1234") - mock_hget.assert_called_once_with(LAUNCHBOX_METADATA_DATABASE_ID_KEY, "1234") + mock_get.assert_called_once_with(LAUNCHBOX_METADATA_TABLE, "1234") class TestRemoteSourceGetRom: @@ -547,39 +539,29 @@ class TestRemoteSourceGetRom: return RemoteSource() async def test_no_cache_returns_none(self, source: RemoteSource): - with patch.object( - async_cache, "exists", new_callable=AsyncMock, return_value=False - ): - result = await source.get_rom("super mario bros.", "nes") + result = await source.get_rom("super mario bros.", "nes") assert result is None async def test_unknown_platform_returns_none(self, source: RemoteSource): - with patch.object( - async_cache, "hget", new_callable=AsyncMock, return_value=None - ): - result = await source.get_rom( - "game", "unknown-xyz", assume_cache_present=True - ) + with patch.object(LAUNCHBOX_METADATA_STORE, "get", return_value=None): + result = await source.get_rom("game", "unknown-xyz") assert result is None async def test_name_match_returns_entry(self, source: RemoteSource): with patch.object( - async_cache, - "hget", - new_callable=AsyncMock, - return_value=json.dumps(REMOTE_ENTRY), + LAUNCHBOX_METADATA_STORE, + "get", + return_value=REMOTE_ENTRY, ): - result = await source.get_rom( - "super mario bros.", "nes", assume_cache_present=True - ) + result = await source.get_rom("super mario bros.", "nes") 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"), + (LAUNCHBOX_NAME_TABLE, "super mario bros."), + (LAUNCHBOX_FOLDED_NAME_TABLE, "super mario bros"), ], ) async def test_title_index_follows_database_id( @@ -587,74 +569,60 @@ class TestRemoteSourceGetRom: ): """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) + def side_effect(table, _key): + if table == index_key: + return "1234" + if table == LAUNCHBOX_METADATA_TABLE: + return 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) + with patch.object(LAUNCHBOX_METADATA_STORE, "get", side_effect=side_effect): + result = await source.get_rom(file_name, "nes") 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") + def side_effect(table, _key): + if table == LAUNCHBOX_NAME_TABLE: + return "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 - ) + with patch.object(LAUNCHBOX_METADATA_STORE, "get", side_effect=side_effect): + result = await source.get_rom("super mario bros.", "nes") assert result is None - async def test_reads_a_compressed_store(self, source: RemoteSource): + async def test_reads_a_built_store(self, source: RemoteSource): """The records the import compresses are read back through the codec.""" assert encode(REMOTE_ENTRY).startswith(_ZSTD_MAGIC), "fixture is not compressed" - async def side_effect(key, _field): - if key == LAUNCHBOX_METADATA_NAME_KEY: - return encode("1234") - if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: - return encode(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 + with LAUNCHBOX_METADATA_STORE.build() as writer: + writer.put( + LAUNCHBOX_NAME_TABLE, + "super mario bros.:Nintendo Entertainment System", + "1234", ) + writer.put(LAUNCHBOX_METADATA_TABLE, "1234", REMOTE_ENTRY) + + result = await source.get_rom("super mario bros.", "nes") assert result is not None assert result.get("Name", None) == "Super Mario Bros." async def test_alternate_name_match(self, source: RemoteSource): alt_entry = {"DatabaseID": "1234"} - async def side_effect(key, _field): - if key == LAUNCHBOX_METADATA_NAME_KEY: + def side_effect(table, _key): + if table == LAUNCHBOX_NAME_TABLE: return None - if key == LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY: - return json.dumps(alt_entry) - if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: - return json.dumps(REMOTE_ENTRY) + if table == LAUNCHBOX_ALTERNATE_NAME_TABLE: + return alt_entry + if table == LAUNCHBOX_METADATA_TABLE: + return 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 - ) + with patch.object(LAUNCHBOX_METADATA_STORE, "get", side_effect=side_effect): + result = await source.get_rom("super mario bros.", "nes") assert result is not None assert result.get("Name", None) == "Super Mario Bros." @@ -665,21 +633,17 @@ class TestRemoteSourceGetRom: at a same-titled game on another system must not be returned.""" alt_entry = {"DatabaseID": "1234"} - async def side_effect(key, _field): - if key == LAUNCHBOX_METADATA_NAME_KEY: + def side_effect(table, _key): + if table == LAUNCHBOX_NAME_TABLE: return None - if key == LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY: - return json.dumps(alt_entry) - if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: - return json.dumps(REMOTE_ENTRY) + if table == LAUNCHBOX_ALTERNATE_NAME_TABLE: + return alt_entry + if table == LAUNCHBOX_METADATA_TABLE: + return 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.", "psx", assume_cache_present=True - ) + with patch.object(LAUNCHBOX_METADATA_STORE, "get", side_effect=side_effect): + result = await source.get_rom("super mario bros.", "psx") assert result is None async def test_inverted_article_match(self, source: RemoteSource): @@ -687,24 +651,21 @@ class TestRemoteSourceGetRom: entry = {"DatabaseID": "161", "Name": "The Legend of Zelda: Ocarina of Time"} queried: list[str] = [] - async def side_effect(key, field): - queried.append(field) + def side_effect(table, key): + queried.append(key) if ( - key == LAUNCHBOX_METADATA_NAME_KEY - and field == "the legend of zelda: ocarina of time:Nintendo 64" + table == LAUNCHBOX_NAME_TABLE + and key == "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 "161" + if table == LAUNCHBOX_METADATA_TABLE: + return entry return None - with patch.object( - async_cache, "hget", new_callable=AsyncMock, side_effect=side_effect - ): + with patch.object(LAUNCHBOX_METADATA_STORE, "get", side_effect=side_effect): result = await source.get_rom( "legend of zelda, the: ocarina of time", "n64", - assume_cache_present=True, ) assert result is not None @@ -732,17 +693,15 @@ class TestRemoteSourceGetRom: entry = {"DatabaseID": "77", "Name": dump_title} folded_field = f"{fold_title(dump_title)}:Sony Playstation 2" - 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) + def side_effect(table, key): + if table == LAUNCHBOX_FOLDED_NAME_TABLE and key == folded_field: + return "77" + if table == LAUNCHBOX_METADATA_TABLE: + return entry return None - with patch.object( - async_cache, "hget", new_callable=AsyncMock, side_effect=side_effect - ): - result = await source.get_rom(search_term, "ps2", assume_cache_present=True) + with patch.object(LAUNCHBOX_METADATA_STORE, "get", side_effect=side_effect): + result = await source.get_rom(search_term, "ps2") assert result is not None assert result.get("DatabaseID", None) == "77" @@ -779,36 +738,28 @@ class TestRemoteSourceGetRom: exact = {"DatabaseID": "1", "Name": "Burnout Revenge"} folded = {"DatabaseID": "2", "Name": "Burnout: Revenge"} - async def side_effect(key, field): - if key == LAUNCHBOX_METADATA_NAME_KEY: - return json.dumps("1") - if key == LAUNCHBOX_METADATA_FOLDED_NAME_KEY: - return json.dumps("2") - if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: - return json.dumps(exact if field == "1" else folded) + def side_effect(table, key): + if table == LAUNCHBOX_NAME_TABLE: + return "1" + if table == LAUNCHBOX_FOLDED_NAME_TABLE: + return "2" + if table == LAUNCHBOX_METADATA_TABLE: + return exact if key == "1" else folded return None - with patch.object( - async_cache, "hget", new_callable=AsyncMock, side_effect=side_effect - ): - result = await source.get_rom( - "burnout revenge", "ps2", assume_cache_present=True - ) + with patch.object(LAUNCHBOX_METADATA_STORE, "get", side_effect=side_effect): + result = await source.get_rom("burnout revenge", "ps2") assert result is not None assert result.get("DatabaseID", None) == "1" async def test_no_match_returns_none(self, source: RemoteSource): - with patch.object( - async_cache, "hget", new_callable=AsyncMock, return_value=None - ): - result = await source.get_rom( - "nonexistent game", "nes", assume_cache_present=True - ) + with patch.object(LAUNCHBOX_METADATA_STORE, "get", return_value=None): + result = await source.get_rom("nonexistent game", "nes") assert result is None async def test_empty_filename_returns_none(self, source: RemoteSource): - result = await source.get_rom("", "nes", assume_cache_present=True) + result = await source.get_rom("", "nes") assert result is None @@ -822,21 +773,19 @@ class TestRemoteSourceGetRomByFileName: async def test_file_name_resolves_to_title(self, source: RemoteSource): 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({"GameName": "1943: The Battle of Midway"}) + def side_effect(table, key): + if table == LAUNCHBOX_FILES_TABLE and key == "1943_v1.3:Commodore Amiga": + return {"GameName": "1943: The Battle of Midway"} if ( - key == LAUNCHBOX_METADATA_NAME_KEY - and field == "1943: The Battle of Midway:Commodore Amiga" + table == LAUNCHBOX_NAME_TABLE + and key == "1943: The Battle of Midway:Commodore Amiga" ): - return json.dumps("999") - if key == LAUNCHBOX_METADATA_DATABASE_ID_KEY: - return json.dumps(game_entry) + return "999" + if table == LAUNCHBOX_METADATA_TABLE: + return game_entry return None - with patch.object( - async_cache, "hget", new_callable=AsyncMock, side_effect=side_effect - ): + with patch.object(LAUNCHBOX_METADATA_STORE, "get", side_effect=side_effect): result = await source.get_rom_by_file_name("1943_v1.3.lha", "amiga") assert result is not None @@ -844,31 +793,27 @@ class TestRemoteSourceGetRomByFileName: async def test_unknown_platform_returns_none(self, source: RemoteSource): with patch.object( - async_cache, "hget", new_callable=AsyncMock, return_value=None - ) as mock_hget: + LAUNCHBOX_METADATA_STORE, "get", return_value=None + ) as mock_get: result = await source.get_rom_by_file_name("game.zip", "unknown-xyz") assert result is None - mock_hget.assert_not_called() + mock_get.assert_not_called() async def test_no_file_entry_returns_none(self, source: RemoteSource): - with patch.object( - async_cache, "hget", new_callable=AsyncMock, return_value=None - ): + with patch.object(LAUNCHBOX_METADATA_STORE, "get", return_value=None): result = await source.get_rom_by_file_name("game.zip", "nes") assert result is None async def test_file_entry_without_game_name_returns_none( self, source: RemoteSource ): - async def side_effect(key, _field): - if key == LAUNCHBOX_FILES_KEY: - return json.dumps({"FileName": "game"}) + def side_effect(table, _key): + if table == LAUNCHBOX_FILES_TABLE: + return {"FileName": "game"} return None - with patch.object( - async_cache, "hget", new_callable=AsyncMock, side_effect=side_effect - ): + with patch.object(LAUNCHBOX_METADATA_STORE, "get", side_effect=side_effect): result = await source.get_rom_by_file_name("game.zip", "nes") assert result is None @@ -879,9 +824,7 @@ class TestRemoteSourceGetMameEntry: return RemoteSource() async def test_cache_miss_returns_none(self, source: RemoteSource): - with patch.object( - async_cache, "hget", new_callable=AsyncMock, return_value=None - ): + with patch.object(LAUNCHBOX_METADATA_STORE, "get", return_value=None): result = await source.get_mame_entry("pacman.zip") assert result is None @@ -894,13 +837,12 @@ class TestRemoteSourceGetMameEntry: "Year": "1982", } with patch.object( - async_cache, - "hget", - new_callable=AsyncMock, - return_value=json.dumps(mame_entry), - ) as mock_hget: + LAUNCHBOX_METADATA_STORE, + "get", + return_value=mame_entry, + ) as mock_get: result = await source.get_mame_entry("wrlok_l3") - mock_hget.assert_called_once_with(LAUNCHBOX_MAME_KEY, "wrlok_l3") + mock_get.assert_called_once_with(LAUNCHBOX_MAME_TABLE, "wrlok_l3") assert result == mame_entry async def test_falls_back_to_stem_when_given_filename_with_ext( @@ -908,17 +850,17 @@ class TestRemoteSourceGetMameEntry: ): mame_entry = {"FileName": "wrlok_l3", "Name": "Warlok"} - async def fake_hget(_key, field): - return json.dumps(mame_entry) if field == "wrlok_l3" else None + def fake_hget(_table, key): + return mame_entry if key == "wrlok_l3" else None with patch.object( - async_cache, "hget", new_callable=AsyncMock, side_effect=fake_hget - ) as mock_hget: + LAUNCHBOX_METADATA_STORE, "get", side_effect=fake_hget + ) as mock_get: result = await source.get_mame_entry("wrlok_l3.zip") # First lookup by raw filename (miss), then by stem (hit). - assert mock_hget.call_count == 2 - assert mock_hget.call_args_list[0].args == (LAUNCHBOX_MAME_KEY, "wrlok_l3.zip") - assert mock_hget.call_args_list[1].args == (LAUNCHBOX_MAME_KEY, "wrlok_l3") + assert mock_get.call_count == 2 + assert mock_get.call_args_list[0].args == (LAUNCHBOX_MAME_TABLE, "wrlok_l3.zip") + assert mock_get.call_args_list[1].args == (LAUNCHBOX_MAME_TABLE, "wrlok_l3") assert result == mame_entry async def test_empty_input_returns_none(self, source: RemoteSource): @@ -927,11 +869,11 @@ class TestRemoteSourceGetMameEntry: async def test_whitespace_stripped(self, source: RemoteSource): with patch.object( - async_cache, "hget", new_callable=AsyncMock, return_value=None - ) as mock_hget: + LAUNCHBOX_METADATA_STORE, "get", return_value=None + ) as mock_get: await source.get_mame_entry(" wrlok_l3 ") # First call uses the trimmed filename. - assert mock_hget.call_args_list[0].args == (LAUNCHBOX_MAME_KEY, "wrlok_l3") + assert mock_get.call_args_list[0].args == (LAUNCHBOX_MAME_TABLE, "wrlok_l3") class TestRemoteSourceFetchImages: @@ -949,30 +891,26 @@ class TestRemoteSourceFetchImages: async def test_id_from_database_id_arg(self, source: RemoteSource): with patch.object( - async_cache, - "hget", - new_callable=AsyncMock, - return_value=json.dumps(REMOTE_IMAGES), - ) as mock_hget: + LAUNCHBOX_METADATA_STORE, + "get", + return_value=REMOTE_IMAGES, + ) as mock_get: result = await source.fetch_images(database_id=1234) - mock_hget.assert_called_once_with(LAUNCHBOX_METADATA_IMAGE_KEY, "1234") + mock_get.assert_called_once_with(LAUNCHBOX_IMAGE_TABLE, "1234") assert result == REMOTE_IMAGES async def test_id_from_remote_dict(self, source: RemoteSource): with patch.object( - async_cache, - "hget", - new_callable=AsyncMock, - return_value=json.dumps(REMOTE_IMAGES), - ) as mock_hget: + LAUNCHBOX_METADATA_STORE, + "get", + return_value=REMOTE_IMAGES, + ) as mock_get: result = await source.fetch_images(remote={"DatabaseID": "1234"}) - mock_hget.assert_called_once_with(LAUNCHBOX_METADATA_IMAGE_KEY, "1234") + mock_get.assert_called_once_with(LAUNCHBOX_IMAGE_TABLE, "1234") assert result == REMOTE_IMAGES async def test_cache_miss_returns_none(self, source: RemoteSource): - with patch.object( - async_cache, "hget", new_callable=AsyncMock, return_value=None - ): + with patch.object(LAUNCHBOX_METADATA_STORE, "get", return_value=None): result = await source.fetch_images(database_id=9999) assert result is None @@ -1559,10 +1497,7 @@ class TestRemoteMatchLocalImages: ) h._remote.fetch_images = AsyncMock(return_value=None) 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) - ) + monkeypatch.setattr(LAUNCHBOX_METADATA_STORE, "exists", lambda: True) with patch( "handler.metadata.launchbox_handler.handler.fs_rom_handler" @@ -1670,50 +1605,34 @@ class TestLaunchboxHandlerEnabled: class TestLaunchboxHandlerHeartbeat: - @staticmethod - def _cache_exists(*present: str) -> AsyncMock: - async def exists(key: str) -> int: - return 1 if key in present else 0 - - return AsyncMock(side_effect=exists) - - async def test_unhealthy_when_cloud_store_is_empty(self): + async def test_unhealthy_when_cloud_store_is_missing(self): handler = LaunchboxHandler() with ( patch.object(LaunchboxHandler, "is_cloud_enabled", return_value=True), patch.object(LaunchboxHandler, "is_local_enabled", return_value=False), - patch.object(async_cache, "exists", self._cache_exists()), ): assert await handler.heartbeat() is False - async def test_healthy_when_cloud_store_is_populated(self): + async def test_healthy_when_cloud_store_is_built(self): handler = LaunchboxHandler() + with LAUNCHBOX_METADATA_STORE.build() as writer: + writer.put(LAUNCHBOX_METADATA_TABLE, "1", {"Name": "Game"}) + with ( patch.object(LaunchboxHandler, "is_cloud_enabled", return_value=True), patch.object(LaunchboxHandler, "is_local_enabled", return_value=False), - 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 async def test_unhealthy_while_the_first_import_is_still_running(self): - """The store answers only for the batches committed so far.""" handler = LaunchboxHandler() with ( patch.object(LaunchboxHandler, "is_cloud_enabled", return_value=True), patch.object(LaunchboxHandler, "is_local_enabled", return_value=False), - patch.object( - async_cache, - "exists", - self._cache_exists( - LAUNCHBOX_METADATA_NAME_KEY, LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY - ), - ), + LAUNCHBOX_METADATA_STORE.build() as writer, ): + writer.put(LAUNCHBOX_METADATA_TABLE, "1", {"Name": "Game"}) + writer.flush() assert await handler.heartbeat() is False async def test_healthy_from_local_install_without_cloud_store(self): @@ -1721,7 +1640,6 @@ class TestLaunchboxHandlerHeartbeat: with ( patch.object(LaunchboxHandler, "is_cloud_enabled", return_value=False), patch.object(LaunchboxHandler, "is_local_enabled", return_value=True), - patch.object(async_cache, "exists", self._cache_exists()), ): assert await handler.heartbeat() is True @@ -1751,10 +1669,7 @@ class TestLaunchboxHandlerGetRom: h._remote.get_rom_by_file_name = AsyncMock(return_value=None) h._remote.fetch_images = AsyncMock(return_value=None) 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) - ) + monkeypatch.setattr(LAUNCHBOX_METADATA_STORE, "exists", lambda: True) return h async def test_disabled_returns_fallback( @@ -1768,7 +1683,7 @@ class TestLaunchboxHandlerGetRom: self, handler: LaunchboxHandler, monkeypatch ): local_data = {"Title": "Mario", "DatabaseID": "1234"} - monkeypatch.setattr(async_cache, "exists", AsyncMock(return_value=False)) + monkeypatch.setattr(LAUNCHBOX_METADATA_STORE, "exists", lambda: False) with patch.object( handler._local, "get_rom", new=AsyncMock(return_value=local_data) ): @@ -1806,13 +1721,13 @@ class TestLaunchboxHandlerGetRom: ): result = await handler.get_rom("game.nes", "nes") - mock_get_rom.assert_called_once_with("Mario", "nes", assume_cache_present=True) + mock_get_rom.assert_called_once_with("Mario", "nes") assert result.get("name", None) == "Mario" async def test_no_local_no_remote_returns_fallback( self, handler: LaunchboxHandler, monkeypatch ): - monkeypatch.setattr(async_cache, "exists", AsyncMock(return_value=False)) + monkeypatch.setattr(LAUNCHBOX_METADATA_STORE, "exists", lambda: False) result = await handler.get_rom("game.nes", "nes") assert result["launchbox_id"] is None @@ -1918,19 +1833,19 @@ class TestLaunchboxHandlerGetRom: } index = { ( - LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_NAME_TABLE, "the legend of zelda: a link to the past" ":Super Nintendo Entertainment System", - ): json.dumps("5678"), - (LAUNCHBOX_METADATA_DATABASE_ID_KEY, "5678"): json.dumps(entry), + ): "5678", + (LAUNCHBOX_METADATA_TABLE, "5678"): entry, } - async def hget(key, field): - return index.get((key, field)) + def hget(table, key): + return index.get((table, key)) with ( patch.object(handler._remote, "get_rom", new=RemoteSource().get_rom), - patch.object(async_cache, "hget", new=AsyncMock(side_effect=hget)), + patch.object(LAUNCHBOX_METADATA_STORE, "get", side_effect=hget), patch( "handler.metadata.launchbox_handler.handler.fs_rom_handler" ) as mock_fs, @@ -2106,10 +2021,7 @@ class TestLaunchboxHandlerSearch: h._remote.get_rom_by_file_name = AsyncMock(return_value=None) h._remote.fetch_images = AsyncMock(return_value=None) 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) - ) + monkeypatch.setattr(LAUNCHBOX_METADATA_STORE, "exists", lambda: True) return h async def test_get_matched_roms_by_name_disabled_returns_empty( diff --git a/backend/tests/handler/metadata/test_libretro_handler.py b/backend/tests/handler/metadata/test_libretro_handler.py index c92d11a45..52a7f2898 100644 --- a/backend/tests/handler/metadata/test_libretro_handler.py +++ b/backend/tests/handler/metadata/test_libretro_handler.py @@ -1,7 +1,6 @@ """Tests for the libretro thumbnails metadata handler.""" import hashlib -import json from unittest.mock import AsyncMock, patch import pytest @@ -9,7 +8,7 @@ import pytest from adapters.services.libretro_thumbnails import LibretroThumbnailsService from adapters.services.libretro_thumbnails_types import LibretroArtType from config.config_manager import MetadataMediaType -from handler.metadata.base_handler import MAME_XML_KEY +from handler.fixture_store import MAME_TABLE from handler.metadata.libretro_handler import ( LIBRETRO_PLATFORM_LIST, LibretroHandler, @@ -257,13 +256,12 @@ async def test_get_rom_matches_a_mame_shortname_by_its_full_title( return_value=[], ), patch( - "handler.metadata.base_handler.async_cache.hget", - AsyncMock(return_value=json.dumps(entry)), - ) as mock_hget, + "handler.metadata.base_handler.fixture_get", return_value=entry + ) as mock_get, ): result = await handler.get_rom("mvsc2.zip", "naomi") - mock_hget.assert_awaited_once_with(MAME_XML_KEY, "mvsc2") + mock_get.assert_called_once_with(MAME_TABLE, "mvsc2") assert result["libretro_id"] == libretro_id_for(NAOMI_LISTING[0]) @@ -277,13 +275,11 @@ async def test_get_rom_skips_the_mame_lookup_off_arcade(handler: LibretroHandler "handler.metadata.libretro_handler.get_preferred_media_types", return_value=[], ), - patch( - "handler.metadata.base_handler.async_cache.hget", AsyncMock() - ) as mock_hget, + patch("handler.metadata.base_handler.fixture_get") as mock_get, ): await handler.get_rom("Final Fantasy VII (USA).bin", "psx") - mock_hget.assert_not_awaited() + mock_get.assert_not_called() @pytest.mark.asyncio diff --git a/backend/tests/handler/metadata/test_moby_handler.py b/backend/tests/handler/metadata/test_moby_handler.py index a70256319..8ea04f49a 100644 --- a/backend/tests/handler/metadata/test_moby_handler.py +++ b/backend/tests/handler/metadata/test_moby_handler.py @@ -1,14 +1,13 @@ """Tests for the MobyGames metadata handler.""" -import json from typing import Any from unittest.mock import AsyncMock, patch import pytest from adapters.services.mobygames_types import MobyGame +from handler.fixture_store import PS1_SERIAL_TABLE from handler.metadata import moby_handler -from handler.metadata.base_handler import PS1_SERIAL_INDEX_KEY from handler.metadata.moby_handler import ( PS1_MOBY_ID, PS2_MOBY_ID, @@ -16,7 +15,6 @@ from handler.metadata.moby_handler import ( SWITCH_MOBY_ID, MobyGamesHandler, ) -from handler.redis_handler import async_cache from models.platform import Platform from models.rom import Rom @@ -38,7 +36,7 @@ class TestSonySerialFilenames: "handler.metadata.moby_handler.MobyGamesHandler.is_enabled", return_value=True, ), - patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget, + patch("handler.metadata.base_handler.fixture_get") as mock_get, patch.object( MobyGamesHandler, "_search_rom", @@ -46,12 +44,12 @@ class TestSonySerialFilenames: return_value=None, ), ): - mock_hget.return_value = json.dumps({"title": "Gran Turismo"}) + mock_get.return_value = {"title": "Gran Turismo"} result = await handler.get_rom( Rom(fs_name="SCUS-94163.bin"), "SCUS-94163.bin", PS1_MOBY_ID ) - mock_hget.assert_awaited_once_with(PS1_SERIAL_INDEX_KEY, "SCUS-94163") + mock_get.assert_called_once_with(PS1_SERIAL_TABLE, "SCUS-94163") assert result.get("name") == "Gran Turismo" assert result["moby_id"] is None @@ -286,7 +284,7 @@ class TestGetRom: ), } # The search drops the tags and is lowercased. - assert list_games.await_args_list[0].kwargs == { + assert list_games.call_args_list[0].kwargs == { "platform_ids": [SNES], "title": "zelda", } @@ -348,7 +346,7 @@ class TestGetRom: ) assert result["moby_id"] == 5 - assert [c.kwargs["title"] for c in list_games.await_args_list] == [ + assert [c.kwargs["title"] for c in list_games.call_args_list] == [ "zelda: link's awakening", "Link's Awakening", ] diff --git a/backend/tests/handler/metadata/test_ss_handler.py b/backend/tests/handler/metadata/test_ss_handler.py index 86edb1f65..ee0143b0d 100644 --- a/backend/tests/handler/metadata/test_ss_handler.py +++ b/backend/tests/handler/metadata/test_ss_handler.py @@ -1,13 +1,11 @@ """Tests for the ScreenScraper metadata handler.""" -import json from typing import Any, cast from unittest.mock import AsyncMock, MagicMock, patch 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, @@ -17,8 +15,8 @@ from adapters.services.screenscraper import ( ) from adapters.services.screenscraper_types import SSGame, SSGameRom from config.config_manager import Config, MetadataMediaType +from handler.fixture_store import PS1_SERIAL_TABLE from handler.metadata import ss_handler -from handler.metadata.base_handler import PS1_SERIAL_INDEX_KEY from handler.metadata.ss_handler import ( PS1_SS_ID, SCREENSAVER_PLATFORM_LIST, @@ -47,7 +45,6 @@ from handler.metadata.ss_handler import ( note_rate_limited_rom, reset_rate_limited_roms, ) -from handler.redis_handler import async_cache from models.rom import LookupHashes, Rom from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE from utils.platform_slugs import UniversalPlatformSlug as UPS @@ -1319,7 +1316,6 @@ class TestLookupRom: async def capture(**kwargs): captured.update(kwargs) - return None with patch.object(handler.ss_service, "get_game_info", side_effect=capture): result, is_not_game = await handler.lookup_rom( @@ -1457,7 +1453,6 @@ class TestLookupRom: async def capture(**kwargs): nonlocal called called = True - return None with patch.object(handler.ss_service, "get_game_info", side_effect=capture): result, is_not_game = await handler.lookup_rom( @@ -1503,7 +1498,6 @@ class TestLookupRom: async def capture(**kwargs): captured.update(kwargs) - return None with patch.object(handler.ss_service, "get_game_info", side_effect=capture): await handler.lookup_rom(MagicMock(platform_slug="n64"), 14, [mock_file]) @@ -1534,7 +1528,6 @@ class TestLookupRom: async def capture(**kwargs): captured.update(kwargs) - return None with patch.object(handler.ss_service, "get_game_info", side_effect=capture): await handler.lookup_rom(MagicMock(platform_slug="psx"), 57, [mock_file]) @@ -1569,7 +1562,6 @@ class TestLookupRom: async def capture(**kwargs): captured.update(kwargs) - return None with patch.object(handler.ss_service, "get_game_info", side_effect=capture): await handler.lookup_rom(MagicMock(platform_slug="psx"), 57, [mock_file]) @@ -1588,7 +1580,6 @@ class TestLookupRom: async def capture(**kwargs): captured.update(kwargs) - return None with patch.object(handler.ss_service, "get_game_info", side_effect=capture): await handler.lookup_rom(MagicMock(platform_slug="n64"), 14, [mock_file]) @@ -1604,7 +1595,6 @@ class TestLookupRom: async def capture(**kwargs): captured.update(kwargs) - return None with patch.object(handler.ss_service, "get_game_info", side_effect=capture): await handler.lookup_rom(MagicMock(platform_slug="n64"), 14, [mock_file]) @@ -1665,11 +1655,11 @@ class TestLookupRom: ) ), ), + pytest.raises(HTTPException), ): - with pytest.raises(HTTPException): - await handler.lookup_rom( - MagicMock(platform_slug="snes"), 3, [self._make_mock_file()] - ) + await handler.lookup_rom( + MagicMock(platform_slug="snes"), 3, [self._make_mock_file()] + ) class TestScreenScraperQuotaFallback: @@ -1792,9 +1782,9 @@ class TestScreenScraperCredentialFallback: side_effect=ScreenScraperCredentialsError(SSCredentialSet.USER) ), ), + pytest.raises(ScreenScraperExhaustedError) as exc_info, ): - with pytest.raises(ScreenScraperExhaustedError) as exc_info: - await handler.lookup_rom(rom, 1, [self._make_file()]) + await handler.lookup_rom(rom, 1, [self._make_file()]) assert exc_info.value.fallback["ss_id"] is None @@ -1812,9 +1802,9 @@ class TestScreenScraperCredentialFallback: side_effect=ScreenScraperCredentialsError(SSCredentialSet.USER) ), ), + pytest.raises(ScreenScraperExhaustedError) as exc_info, ): - with pytest.raises(ScreenScraperExhaustedError) as exc_info: - await handler.get_rom(rom, "Sonic.bin", platform_ss_id=3) + await handler.get_rom(rom, "Sonic.bin", platform_ss_id=3) assert exc_info.value.fallback["ss_id"] is None @@ -1831,9 +1821,9 @@ class TestScreenScraperCredentialFallback: side_effect=ScreenScraperCredentialsError(SSCredentialSet.USER) ), ), + pytest.raises(ScreenScraperExhaustedError) as exc_info, ): - with pytest.raises(ScreenScraperExhaustedError) as exc_info: - await handler.get_rom_by_id(MagicMock(), 1234) + await handler.get_rom_by_id(MagicMock(), 1234) assert exc_info.value.fallback["ss_id"] is None @@ -2196,15 +2186,15 @@ class TestSonySerialFilenames: "handler.metadata.ss_handler.SSHandler.is_enabled", return_value=True, ), - patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget, + patch("handler.metadata.base_handler.fixture_get") as mock_get, patch.object( SSHandler, "_search_rom", new_callable=AsyncMock, return_value=None ), ): - mock_hget.return_value = json.dumps({"title": "Gran Turismo"}) + mock_get.return_value = {"title": "Gran Turismo"} result = await handler.get_rom(MagicMock(), "SCUS-94163.bin", PS1_SS_ID) - mock_hget.assert_awaited_once_with(PS1_SERIAL_INDEX_KEY, "SCUS-94163") + mock_get.assert_called_once_with(PS1_SERIAL_TABLE, "SCUS-94163") assert result.get("name") == "Gran Turismo" assert result["ss_id"] is None @@ -2220,21 +2210,17 @@ class TestSonySerialFilenames: "handler.metadata.ss_handler.SSHandler.is_enabled", 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(SWITCH_TITLEDB_STORE, "exists", return_value=True), + patch.object(SWITCH_TITLEDB_STORE, "get") as mock_get, patch.object( SSHandler, "_search_rom", new_callable=AsyncMock, return_value=None ), ): - mock_exists.return_value = True - mock_hget.return_value = json.dumps( - { - "name": "Switch Game", - "description": "A game", - "iconUrl": "https://example.net/icon.png", - } - ) + mock_get.return_value = { + "name": "Switch Game", + "description": "A game", + "iconUrl": "https://example.net/icon.png", + } result = await handler.get_rom( Rom(fs_name="70123456789012.nsp"), "70123456789012.nsp", SWITCH_SS_ID ) diff --git a/backend/tests/handler/test_dump_cache.py b/backend/tests/handler/test_dump_cache.py deleted file mode 100644 index 335784c1b..000000000 --- a/backend/tests/handler/test_dump_cache.py +++ /dev/null @@ -1,92 +0,0 @@ -import json -from typing import Any - -import pytest - -from handler.dump_cache import ( - _ZSTD_MAGIC, - COMPRESS_MIN_BYTES, - decode, - encode, - hget_json, -) -from handler.redis_handler import async_binary_cache - -BIG_RECORD = {"Name": "Chrono Trigger", "Overview": "A long summary. " * 100} -SMALL_RECORD = "12345" -# BIG_RECORD as the `zstandard` 0.25 package wrote it, which Redis may still hold. -LEGACY_BIG_RECORD_FRAME = bytes.fromhex( - "28b52ffd60670505020074037b224e616d65223a224368726f6e6f2054726967676572222c" - "224f76657276696577223a2241206c6f6e672073756d6d6172792e20227d0100d5e2fc130a" -) - - -class TestEncode: - def test_compresses_a_record_worth_compressing(self): - stored = encode(BIG_RECORD) - - assert stored.startswith(_ZSTD_MAGIC) - assert len(stored) < len(json.dumps(BIG_RECORD).encode()) - - def test_leaves_a_short_value_as_plain_json(self): - stored = encode(SMALL_RECORD) - - assert stored == b'"12345"' - - @pytest.mark.parametrize("payload_size", [2, COMPRESS_MIN_BYTES - 1]) - def test_stores_a_payload_under_the_threshold_verbatim(self, payload_size: int): - # The threshold applies to the serialized payload, quotes included. - value = "x" * (payload_size - 2) - stored = encode(value) - - assert not stored.startswith(_ZSTD_MAGIC) - assert json.loads(stored) == value - - def test_compresses_a_payload_at_the_threshold(self): - value = "x" * (COMPRESS_MIN_BYTES - 2) - - assert encode(value).startswith(_ZSTD_MAGIC) - - def test_each_write_is_a_standalone_frame(self): - first, second = encode(BIG_RECORD), encode(BIG_RECORD) - - assert first == second - assert decode(second) == BIG_RECORD - - -class TestDecode: - @pytest.mark.parametrize("value", [BIG_RECORD, SMALL_RECORD, [], {}, 0]) - def test_round_trips_whatever_encode_wrote(self, value: Any): - assert decode(encode(value)) == value - - def test_reads_a_value_cached_by_the_previous_codec(self): - assert decode(LEGACY_BIG_RECORD_FRAME) == BIG_RECORD - - def test_reads_a_plain_json_value(self): - """A payload under the threshold is stored as JSON, so reads accept it.""" - stored = encode(SMALL_RECORD) - - assert not stored.startswith(_ZSTD_MAGIC) - assert decode(stored) == SMALL_RECORD - - def test_reads_a_value_handed_over_as_text(self): - """A client that decodes responses hands back `str`, which still parses.""" - assert decode(json.dumps(SMALL_RECORD)) == SMALL_RECORD - - @pytest.mark.parametrize("missing", [None, b"", ""]) - def test_returns_nothing_for_an_absent_field(self, missing: bytes | str | None): - assert decode(missing) is None - - -class TestHgetJson: - @pytest.mark.asyncio - async def test_reads_back_a_compressed_record(self): - await async_binary_cache.hset( - "romm:test_dump_cache", mapping={"1": encode(BIG_RECORD)} - ) - - assert await hget_json("romm:test_dump_cache", "1") == BIG_RECORD - - @pytest.mark.asyncio - async def test_returns_none_for_a_field_that_is_not_there(self): - assert await hget_json("romm:test_dump_cache", "absent") is None diff --git a/backend/tests/handler/test_dump_store.py b/backend/tests/handler/test_dump_store.py new file mode 100644 index 000000000..e59cd474e --- /dev/null +++ b/backend/tests/handler/test_dump_store.py @@ -0,0 +1,262 @@ +import json +import os +import sqlite3 +import threading +import time +from pathlib import Path +from typing import Any + +import pytest + +from handler import dump_store +from handler.dump_store import ( + _ZSTD_MAGIC, + COMPRESS_MIN_BYTES, + STALE_BUILD_SECONDS, + DumpStore, + EmptyDumpError, + decode, + encode, +) + +BIG_RECORD = {"Name": "Chrono Trigger", "Overview": "A long summary. " * 100} +SMALL_RECORD = "12345" + + +class TestEncode: + def test_compresses_a_record_worth_compressing(self): + stored = encode(BIG_RECORD) + + assert stored.startswith(_ZSTD_MAGIC) + assert len(stored) < len(json.dumps(BIG_RECORD).encode()) + + def test_leaves_a_short_value_as_plain_json(self): + stored = encode(SMALL_RECORD) + + assert stored == b'"12345"' + + @pytest.mark.parametrize("payload_size", [2, COMPRESS_MIN_BYTES - 1]) + def test_stores_a_payload_under_the_threshold_verbatim(self, payload_size: int): + # The threshold applies to the serialized payload, quotes included. + value = "x" * (payload_size - 2) + stored = encode(value) + + assert not stored.startswith(_ZSTD_MAGIC) + assert json.loads(stored) == value + + def test_compresses_a_payload_at_the_threshold(self): + value = "x" * (COMPRESS_MIN_BYTES - 2) + + assert encode(value).startswith(_ZSTD_MAGIC) + + def test_each_write_is_a_standalone_frame(self): + first, second = encode(BIG_RECORD), encode(BIG_RECORD) + + assert first == second + assert decode(second) == BIG_RECORD + + +class TestDecode: + @pytest.mark.parametrize("value", [BIG_RECORD, SMALL_RECORD, [], {}, 0]) + def test_round_trips_whatever_encode_wrote(self, value: Any): + assert decode(encode(value)) == value + + def test_reads_a_plain_json_value(self): + """A payload under the threshold is stored as JSON, so reads accept it.""" + stored = encode(SMALL_RECORD) + + assert not stored.startswith(_ZSTD_MAGIC) + assert decode(stored) == SMALL_RECORD + + @pytest.mark.parametrize("missing", [None, b""]) + def test_returns_nothing_for_an_absent_key(self, missing: bytes | None): + assert decode(missing) is None + + +@pytest.fixture +def store(tmp_path: Path) -> DumpStore: + return DumpStore(tmp_path, "games", "v2", ("titles", "ids")) + + +def _build(store: DumpStore, rows: dict[str, dict[str, Any]]) -> None: + with store.build() as writer: + for table, records in rows.items(): + for key, value in records.items(): + writer.put(table, key, value) + + +class TestDumpStoreReads: + def test_reads_back_what_a_build_wrote(self, store: DumpStore): + _build(store, {"titles": {"1": BIG_RECORD}, "ids": {"a": SMALL_RECORD}}) + + assert store.get("titles", "1") == BIG_RECORD + assert store.get("ids", "a") == SMALL_RECORD + + def test_a_missing_key_reads_as_none(self, store: DumpStore): + _build(store, {"titles": {"1": BIG_RECORD}}) + + assert store.get("titles", "2") is None + assert store.get("ids", "1") is None + + def test_a_store_never_built_reads_as_none(self, store: DumpStore): + assert not store.exists() + assert store.get("titles", "1") is None + + def test_a_file_that_cannot_be_opened_reads_as_none( + self, store: DumpStore, monkeypatch: pytest.MonkeyPatch + ): + _build(store, {"titles": {"1": SMALL_RECORD}}) + + def refuse(*_args: Any, **_kwargs: Any) -> None: + raise sqlite3.OperationalError("unable to open database file") + + monkeypatch.setattr(sqlite3, "connect", refuse) + + assert store.get("titles", "1") is None + + def test_an_unknown_table_is_refused(self, store: DumpStore): + with pytest.raises(ValueError, match="no table"): + store.get("users; DROP TABLE titles", "1") + + def test_a_later_write_of_a_key_wins(self, store: DumpStore): + _build(store, {"titles": {"1": "first"}}) + with store.build() as writer: + writer.put("titles", "1", "first") + writer.put("titles", "1", "second") + + assert store.get("titles", "1") == "second" + + def test_writes_span_several_batches( + self, store: DumpStore, monkeypatch: pytest.MonkeyPatch + ): + monkeypatch.setattr(dump_store, "WRITE_BATCH_SIZE", 3) + _build(store, {"titles": {str(i): i for i in range(10)}}) + + assert [store.get("titles", str(i)) for i in range(10)] == list(range(10)) + + def test_reads_from_another_thread(self, store: DumpStore): + _build(store, {"titles": {"1": SMALL_RECORD}}) + results: list[Any] = [] + + thread = threading.Thread( + target=lambda: results.append(store.get("titles", "1")) + ) + thread.start() + thread.join() + + assert results == [SMALL_RECORD] + assert store.get("titles", "1") == SMALL_RECORD + + +class TestDumpStoreBuild: + def test_a_rebuild_is_picked_up_by_an_open_reader(self, store: DumpStore): + _build(store, {"titles": {"1": "old"}}) + assert store.get("titles", "1") == "old" + + _build(store, {"titles": {"1": "new"}}) + + assert store.get("titles", "1") == "new" + + def test_a_rebuild_closes_the_replaced_file(self, store: DumpStore): + _build(store, {"titles": {"1": "old"}}) + store.get("titles", "1") + assert store._conn is not None + old_conn = store._conn[1] + + _build(store, {"titles": {"1": "new"}}) + + assert store._conn is None + with pytest.raises(sqlite3.ProgrammingError, match="closed"): + old_conn.execute("SELECT 1") + + def test_a_swap_by_another_process_closes_the_replaced_file( + self, store: DumpStore, tmp_path: Path + ): + _build(store, {"titles": {"1": "old"}}) + store.get("titles", "1") + assert store._conn is not None + old_conn = store._conn[1] + + other = DumpStore(tmp_path, "games", "v2", store.tables) + _build(other, {"titles": {"1": "new"}}) + + assert store.get("titles", "1") == "new" + with pytest.raises(sqlite3.ProgrammingError, match="closed"): + old_conn.execute("SELECT 1") + + def test_a_build_missing_its_required_rows_keeps_the_previous_file( + self, tmp_path: Path + ): + store = DumpStore(tmp_path, "games", "v2", ("titles", "ids"), "titles") + _build(store, {"titles": {"1": "old"}}) + + with pytest.raises(EmptyDumpError): + _build(store, {"ids": {"a": SMALL_RECORD}}) + + assert store.get("titles", "1") == "old" + assert store.get("ids", "a") is None + assert list(store.directory.iterdir()) == [store.path] + + def test_an_unknown_required_table_is_refused(self, tmp_path: Path): + with pytest.raises(ValueError, match="no table"): + DumpStore(tmp_path, "games", "v2", ("titles",), "ids") + + def test_the_file_appears_only_once_the_build_finishes(self, store: DumpStore): + with store.build() as writer: + writer.put("titles", "1", SMALL_RECORD) + writer.flush() + assert not store.exists() + + assert store.exists() + + def test_a_failed_build_keeps_the_previous_file(self, store: DumpStore): + _build(store, {"titles": {"1": "old"}}) + + with pytest.raises(RuntimeError), store.build() as writer: + writer.put("titles", "1", "new") + raise RuntimeError("dump went bad") + + assert store.get("titles", "1") == "old" + assert list(store.directory.iterdir()) == [store.path] + + def test_a_build_drops_the_files_of_other_revisions( + self, store: DumpStore, tmp_path: Path + ): + older = tmp_path / "games.v1.sqlite" + older.write_bytes(b"") + other_store = tmp_path / "gamesdb.v1.sqlite" + other_store.write_bytes(b"") + + _build(store, {"titles": {"1": SMALL_RECORD}}) + + assert not older.exists() + assert other_store.exists() + + def test_a_build_clears_abandoned_temporary_files( + self, store: DumpStore, tmp_path: Path + ): + abandoned = tmp_path / ".games.v2.sqlite.dead.tmp" + abandoned.write_bytes(b"") + stale = time.time() - STALE_BUILD_SECONDS - 1 + os.utime(abandoned, (stale, stale)) + recent = tmp_path / ".games.v2.sqlite.live.tmp" + recent.write_bytes(b"") + + _build(store, {"titles": {"1": SMALL_RECORD}}) + + assert not abandoned.exists() + assert recent.exists() + + +class TestDropOtherRevisions: + def test_returns_the_files_it_deleted(self, store: DumpStore, tmp_path: Path): + older = tmp_path / "games.v1.sqlite" + older.write_bytes(b"") + + assert store.drop_other_revisions() == [older] + assert not older.exists() + + def test_a_missing_directory_has_nothing_to_drop(self, tmp_path: Path): + store = DumpStore(tmp_path / "absent", "games", "v2", ("titles",)) + + assert store.drop_other_revisions() == [] diff --git a/backend/tests/handler/test_fixture_store.py b/backend/tests/handler/test_fixture_store.py new file mode 100644 index 000000000..7900291b4 --- /dev/null +++ b/backend/tests/handler/test_fixture_store.py @@ -0,0 +1,96 @@ +import json +from collections.abc import Iterator +from pathlib import Path + +import pytest + +from handler import fixture_store +from handler.fixture_store import ( + FIXTURE_SOURCES, + KNOWN_BIOS_FILE, + MAME_TABLE, + PS1_SERIAL_TABLE, + fixture_get, +) +from models.firmware import Firmware + + +@pytest.fixture +def isolated_fixture_store( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> Iterator[Path]: + """Build the fixture store from scratch in a folder of the test's own.""" + directory = tmp_path / "fixtures" + monkeypatch.setattr(fixture_store, "FIXTURE_STORE_DIR", directory) + fixture_store.fixture_store.cache_clear() + yield directory + fixture_store.fixture_store.cache_clear() + + +def test_every_index_is_read_from_the_shipped_json(): + for table, path in FIXTURE_SOURCES.items(): + with path.open() as f: + key, value = next(iter(json.load(f).items())) + assert fixture_get(table, key) == value, table + + +def test_a_serial_lookup_resolves_its_title(): + with FIXTURE_SOURCES[PS1_SERIAL_TABLE].open() as f: + serial, entry = next(iter(json.load(f).items())) + + assert fixture_get(PS1_SERIAL_TABLE, serial)["title"] == entry["title"] + + +def test_an_unknown_key_reads_as_none(): + assert fixture_get(MAME_TABLE, "not-a-real-set") is None + + +def test_a_known_bios_verifies_by_name_against_the_store(): + with KNOWN_BIOS_FILE.open() as f: + dump = json.load(f)["gb:gb_bios.bin"] + + assert Firmware.verify_file_hashes( + platform_slug="gb", + file_name="gb_bios.bin", + file_size_bytes=int(dump["size"]), + md5_hash="", + sha1_hash="", + crc_hash=dump["crc"], + ) + + +def test_the_store_is_built_once_and_named_after_its_sources( + isolated_fixture_store: Path, +): + store = fixture_store.fixture_store() + + assert store.path.parent == isolated_fixture_store + assert store.revision == fixture_store._sources_digest() + assert fixture_store.fixture_store() is store + + +def test_a_store_deleted_after_its_build_is_rebuilt_on_read( + isolated_fixture_store: Path, +): + fixture_store.fixture_store().path.unlink() + with FIXTURE_SOURCES[MAME_TABLE].open() as f: + key, value = next(iter(json.load(f).items())) + + assert fixture_get(MAME_TABLE, key) == value + + +def test_changed_sources_get_a_store_of_their_own( + isolated_fixture_store: Path, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +): + first = fixture_store.fixture_store() + + edited = tmp_path / "mame_index.json" + edited.write_text(json.dumps({"pacman": {"description": "Pac-Man (edited)"}})) + monkeypatch.setitem(FIXTURE_SOURCES, MAME_TABLE, edited) + fixture_store.fixture_store.cache_clear() + + second = fixture_store.fixture_store() + + assert second.path != first.path + assert not first.path.exists() + assert second.get(MAME_TABLE, "pacman") == {"description": "Pac-Man (edited)"} diff --git a/backend/tests/models/test_firmware.py b/backend/tests/models/test_firmware.py index 384bc4a0d..4ffe87925 100644 --- a/backend/tests/models/test_firmware.py +++ b/backend/tests/models/test_firmware.py @@ -3,7 +3,8 @@ from unittest.mock import patch import pytest -from models.firmware import KNOWN_BIOS_FILE, KNOWN_BIOS_KEY, Firmware +from handler.fixture_store import KNOWN_BIOS_FILE, KNOWN_BIOS_TABLE +from models.firmware import Firmware NAOMI_BIOS = {"size": 100, "md5": "abc", "sha1": "def", "crc": "123"} @@ -19,9 +20,9 @@ def _verify(platform_slug: str) -> bool: ) -def _known_bios(key: str, field: str) -> str | None: - assert key == KNOWN_BIOS_KEY - return json.dumps(NAOMI_BIOS) if field == "arcade:naomi.zip" else None +def _known_bios(table: str, key: str) -> dict[str, object] | None: + assert table == KNOWN_BIOS_TABLE + return NAOMI_BIOS if key == "arcade:naomi.zip" else None @pytest.mark.parametrize( @@ -30,12 +31,12 @@ def _known_bios(key: str, field: str) -> str | None: def test_an_arcade_platform_verifies_against_the_arcade_bios_list( platform_slug: str, ): - with patch("models.firmware.sync_cache.hget", side_effect=_known_bios): + with patch("models.firmware.fixture_get", side_effect=_known_bios): assert _verify(platform_slug) def test_a_non_arcade_platform_does_not_borrow_the_arcade_bios_list(): - with patch("models.firmware.sync_cache.hget", side_effect=_known_bios): + with patch("models.firmware.fixture_get", side_effect=_known_bios): assert not _verify("snes") @@ -49,7 +50,7 @@ def _verify_gb_bios( ) -> bool: with KNOWN_BIOS_FILE.open() as f: dump = json.load(f)["gb:gb_bios.bin"] - with patch("models.firmware.sync_cache.hget", return_value=None): + with patch("models.firmware.fixture_get", return_value=None): return Firmware.verify_file_hashes( platform_slug=platform_slug, file_name=file_name, diff --git a/backend/tests/tasks/test_update_launchbox_metadata.py b/backend/tests/tasks/test_update_launchbox_metadata.py index d75ccaf6b..a94b4d9d1 100644 --- a/backend/tests/tasks/test_update_launchbox_metadata.py +++ b/backend/tests/tasks/test_update_launchbox_metadata.py @@ -1,77 +1,90 @@ import os +import sqlite3 from dataclasses import replace -from typing import Any -from unittest.mock import AsyncMock, patch +from typing import IO, Any +from unittest.mock import patch -import anyio import pytest from config import LAUNCHBOX_API_ENABLED, TASK_TIMEOUT -from handler.dump_cache import decode +from handler.dump_store import DumpWriter, EmptyDumpError, decode from handler.metadata.launchbox_handler.handler import LaunchboxHandler from handler.metadata.launchbox_handler.types import ( - LAUNCHBOX_FILES_KEY, - LAUNCHBOX_MAME_KEY, - LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, - LAUNCHBOX_METADATA_DATABASE_ID_KEY, - LAUNCHBOX_METADATA_FOLDED_NAME_KEY, - LAUNCHBOX_METADATA_IMAGE_KEY, - LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY, - LAUNCHBOX_METADATA_NAME_KEY, + LAUNCHBOX_ALTERNATE_NAME_TABLE, + LAUNCHBOX_FILES_TABLE, + LAUNCHBOX_FOLDED_NAME_TABLE, + LAUNCHBOX_IMAGE_TABLE, + LAUNCHBOX_MAME_TABLE, LAUNCHBOX_METADATA_STORE, - LAUNCHBOX_PLATFORMS_KEY, + LAUNCHBOX_METADATA_TABLE, + LAUNCHBOX_NAME_TABLE, ) -from handler.redis_handler import async_cache from tasks.scheduled.update_launchbox_metadata import ( - BatchedCacheWriter, UpdateLaunchboxMetadataTask, update_launchbox_metadata_task, ) from tasks.tasks import RemoteFilePullTask +FIXTURES_DIR = os.path.join(os.path.dirname(__file__), "fixtures") + + +def _read_fixture(name: str) -> bytes: + with open(os.path.join(FIXTURES_DIR, name), "rb") as f: + return f.read() + + +def _rows(table: str) -> dict[str, Any]: + """Return every record of one table in the built store.""" + conn = sqlite3.connect(LAUNCHBOX_METADATA_STORE.path) + try: + return { + key: decode(value) + for key, value in conn.execute(f"SELECT key, value FROM {table}") + } + finally: + conn.close() + @pytest.fixture def task() -> UpdateLaunchboxMetadataTask: - """Create a task instance for testing""" return UpdateLaunchboxMetadataTask() @pytest.fixture def sample_zip_content() -> bytes: - test_dir = os.path.dirname(__file__) - sample_path = os.path.join(test_dir, "fixtures", "sample_metadata.zip") + return _read_fixture("sample_metadata.zip") - with open(sample_path, "rb") as f: - return f.read() + +@pytest.fixture +def empty_elements_zip_content() -> bytes: + return _read_fixture("sample_metadata_with_empty_elements.zip") @pytest.fixture def corrupt_zip_content() -> bytes: - """Create corrupt ZIP content for testing error handling""" return b"not a valid zip file" class TestUpdateLaunchboxMetadataTask: - """Test suite for UpdateLaunchboxMetadataTask""" - def test_task_initialization(self, task): - """Test task initialization with correct parameters""" assert task.spec.description == "Updates the LaunchBox metadata store" assert task.url == "https://gamesdb.launchbox-app.com/Metadata.zip" + def test_task_instance_creation(self): + assert isinstance(update_launchbox_metadata_task, UpdateLaunchboxMetadataTask) + @patch.object(RemoteFilePullTask, "run") async def test_run_when_launchbox_api_enabled( self, mock_super_run, task, sample_zip_content ): - """Test run method when Launchbox API is enabled""" mock_super_run.return_value = sample_zip_content await task.run() mock_super_run.assert_called_once_with() + assert LAUNCHBOX_METADATA_STORE.exists() async def test_run_when_launchbox_api_disabled(self, task, mocker): - """Test run method when Launchbox API is disabled""" mocker.patch.object(LaunchboxHandler, "is_cloud_enabled", return_value=False) mock_log = mocker.patch("tasks.scheduled.update_launchbox_metadata.log") @@ -80,6 +93,7 @@ class TestUpdateLaunchboxMetadataTask: mock_log.warning.assert_called_once_with( "Launchbox API is not enabled, skipping metadata update" ) + assert not LAUNCHBOX_METADATA_STORE.exists() @patch.object(RemoteFilePullTask, "run") async def test_a_failed_download_fails_the_run(self, mock_super_run, task): @@ -100,12 +114,13 @@ class TestUpdateLaunchboxMetadataTask: ): await task.run() + assert not LAUNCHBOX_METADATA_STORE.exists() + @patch.object(RemoteFilePullTask, "run") @patch("tasks.scheduled.update_launchbox_metadata.log") async def test_run_successful_completion( self, mock_log, mock_super_run, task, sample_zip_content ): - """Test successful completion of the task""" mock_super_run.return_value = sample_zip_content await task.run() @@ -115,399 +130,96 @@ class TestUpdateLaunchboxMetadataTask: ) @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_launchbox_metadata.async_binary_cache.pipeline") - async def test_xml_parsing( - self, - mock_async_cache_pipeline, - mock_super_run, - task, - sample_zip_content, - ): - """Test parsing of Platforms.xml file""" + async def test_builds_every_table(self, mock_super_run, task, sample_zip_content): mock_super_run.return_value = sample_zip_content - # Create a mock pipeline with async context manager support - mock_pipe = AsyncMock() - mock_async_cache_pipeline.return_value.__aenter__ = AsyncMock( - return_value=mock_pipe - ) - mock_async_cache_pipeline.return_value.__aexit__ = AsyncMock(return_value=None) - await task.run() - # Verify calls - assert mock_async_cache_pipeline.called - assert mock_async_cache_pipeline.call_count == 4 - assert mock_pipe.hset.called - assert mock_pipe.execute.called - - # Check hset call details - hset_calls = mock_pipe.hset.call_args_list - assert len(hset_calls) == 14 - - platform_calls = [ - call for call in hset_calls if call[0][0] == LAUNCHBOX_PLATFORMS_KEY - ] - assert len(platform_calls) == 2 - - metadata_id_calls = [ - call - for call in hset_calls - if call[0][0] == LAUNCHBOX_METADATA_DATABASE_ID_KEY - ] - metadata_name_calls = [ - call for call in hset_calls if call[0][0] == LAUNCHBOX_METADATA_NAME_KEY - ] - metadata_alt_calls = [ - call - for call in hset_calls - if call[0][0] == LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY - ] - metadata_image_calls = [ - call for call in hset_calls if call[0][0] == LAUNCHBOX_METADATA_IMAGE_KEY - ] - metadata_folded_calls = [ - call - for call in hset_calls - if call[0][0] == LAUNCHBOX_METADATA_FOLDED_NAME_KEY - ] - - assert len(metadata_id_calls) == 2 - assert len(metadata_name_calls) == 2 - assert len(metadata_alt_calls) == 1 - assert len(metadata_image_calls) == 1 - # Every named game is indexed under its folded title too. - assert len(metadata_folded_calls) == len(metadata_name_calls) - - mame_calls = [call for call in hset_calls if call[0][0] == LAUNCHBOX_MAME_KEY] - assert len(mame_calls) == 2 - - files_calls = [call for call in hset_calls if call[0][0] == LAUNCHBOX_FILES_KEY] - assert len(files_calls) == 2 - # The fixture pads one entry per index, as a pretty-printed dump does. # Keys come out normalized, and the Files key carries its platform, # since one dump filename exists on several systems. - def fields(calls) -> set[str]: - return {field for call in calls for field in call[1]["mapping"]} - - assert fields(files_calls) == { - "super mario 64 (usa):Nintendo 64", - "crash bandicoot (usa):PlayStation", - } - assert fields(platform_calls) == {"Nintendo 64", "PlayStation"} - assert fields(metadata_id_calls) == {"12345", "67890"} - assert fields(metadata_name_calls) == { - "super mario 64:Nintendo 64", - "crash bandicoot:PlayStation", - } - assert fields(metadata_alt_calls) == {"super mario 64 (usa)"} - assert fields(metadata_image_calls) == {"12345"} - assert fields(mame_calls) == {"mario.zip", "pacman.zip"} - - def values(calls) -> list[Any]: - return [ - decode(value) for call in calls for value in call[1]["mapping"].values() - ] + assert set(_rows(LAUNCHBOX_METADATA_TABLE)) == {"12345", "67890"} # 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"] + assert _rows(LAUNCHBOX_NAME_TABLE) == { + "super mario 64:Nintendo 64": "12345", + "crash bandicoot:PlayStation": "67890", + } + assert sorted(_rows(LAUNCHBOX_FOLDED_NAME_TABLE).values()) == [ + "12345", + "67890", + ] + assert _rows(LAUNCHBOX_ALTERNATE_NAME_TABLE) == { + "super mario 64 (usa)": "12345" + } # Images keep only the fields media selection reads. - assert values(metadata_image_calls) == [ - [ + assert _rows(LAUNCHBOX_IMAGE_TABLE) == { + "12345": [ {"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"}, - ] + # A table keeps its reader's field, never one the key already carries. + assert _rows(LAUNCHBOX_FILES_TABLE) == { + "super mario 64 (usa):Nintendo 64": {"GameName": "Super Mario 64"}, + "crash bandicoot (usa):PlayStation": {"GameName": "Crash Bandicoot"}, + } + assert _rows(LAUNCHBOX_MAME_TABLE) == { + "mario.zip": {"Name": "Super Mario Bros."}, + "pacman.zip": {"Name": "Pac-Man"}, + } @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_launchbox_metadata.async_binary_cache.pipeline") - async def test_empty_xml_elements_handling( - self, - mock_async_cache_pipeline, - mock_super_run, - task, + async def test_an_archive_without_records_keeps_the_previous_store( + self, mock_super_run, task, sample_zip_content, empty_elements_zip_content ): - """Test handling of XML elements with empty or missing text""" - test_dir = os.path.dirname(__file__) - sample_path = os.path.join( - test_dir, "fixtures", "sample_metadata_with_empty_elements.zip" - ) - - async with await anyio.open_file(sample_path, "rb") as f: - mock_super_run.return_value = await f.read() - - # Create a mock pipeline with async context manager support - mock_pipe = AsyncMock() - mock_async_cache_pipeline.return_value.__aenter__ = AsyncMock( - return_value=mock_pipe - ) - mock_async_cache_pipeline.return_value.__aexit__ = AsyncMock(return_value=None) - + """Records with empty elements are skipped, which leaves nothing to swap in.""" + mock_super_run.return_value = sample_zip_content await task.run() - # Verify calls - assert mock_async_cache_pipeline.called + mock_super_run.return_value = empty_elements_zip_content + with pytest.raises(EmptyDumpError): + await task.run() - # Check hset call details - hset_calls = mock_pipe.hset.call_args_list - assert len(hset_calls) == 1 - - platform_calls = [ - call for call in hset_calls if call[0][0] == LAUNCHBOX_PLATFORMS_KEY - ] - # Only one valid platform should be processed - assert len(platform_calls) == 1 + assert set(_rows(LAUNCHBOX_METADATA_TABLE)) == {"12345", "67890"} @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_launchbox_metadata.async_binary_cache.pipeline") - async def test_missing_xml_files_handling( - self, - mock_async_cache_pipeline, - mock_super_run, - task, + async def test_a_failed_run_keeps_the_previous_store( + self, mock_super_run, task, sample_zip_content, corrupt_zip_content ): - """Test handling when some XML files are missing from the ZIP""" - test_dir = os.path.dirname(__file__) - sample_path = os.path.join( - test_dir, "fixtures", "sample_metadata_with_empty_elements.zip" - ) - - async with await anyio.open_file(sample_path, "rb") as f: - mock_super_run.return_value = await f.read() - - # Create a mock pipeline with async context manager support - mock_pipe = AsyncMock() - mock_async_cache_pipeline.return_value.__aenter__ = AsyncMock( - return_value=mock_pipe - ) - mock_async_cache_pipeline.return_value.__aexit__ = AsyncMock(return_value=None) - + mock_super_run.return_value = sample_zip_content await task.run() - # Verify calls - assert mock_async_cache_pipeline.called - - # Check hset call details - hset_calls = mock_pipe.hset.call_args_list - assert len(hset_calls) == 1 - - def test_redis_keys_are_defined(self): - """Test that all Redis keys are properly defined""" - assert LAUNCHBOX_PLATFORMS_KEY == "romm:launchbox_platforms" - assert ( - LAUNCHBOX_METADATA_DATABASE_ID_KEY == "romm:launchbox_metadata_database_id" - ) - assert LAUNCHBOX_METADATA_NAME_KEY == "romm:launchbox_metadata_name" - assert ( - LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY - == "romm:launchbox_metadata_alternate_name" - ) - assert LAUNCHBOX_METADATA_IMAGE_KEY == "romm:launchbox_metadata_image" - assert LAUNCHBOX_MAME_KEY == "romm:launchbox_mame" - assert LAUNCHBOX_FILES_KEY == "romm:launchbox_files" - - def test_task_instance_creation(self): - """Test that the task instance is created correctly""" - assert isinstance(update_launchbox_metadata_task, UpdateLaunchboxMetadataTask) - - -class TestUpdateLaunchboxMetadataTaskIntegration: - """Integration tests for UpdateLaunchboxMetadataTask""" - - @pytest.fixture - def task(self): - return UpdateLaunchboxMetadataTask() - - @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_launchbox_metadata.async_binary_cache.pipeline") - async def test_full_workflow_integration( - self, mock_async_cache_pipeline, mock_super_run, task, sample_zip_content - ): - """Test the complete workflow from ZIP download to Redis storage""" - mock_super_run.return_value = sample_zip_content - - # Create a mock pipeline with async context manager support - mock_pipe = AsyncMock() - mock_async_cache_pipeline.return_value.__aenter__ = AsyncMock( - return_value=mock_pipe - ) - mock_async_cache_pipeline.return_value.__aexit__ = AsyncMock(return_value=None) - - await task.run() - - # Check hset call details - hset_calls = mock_pipe.hset.call_args_list - assert len(hset_calls) == 14 - - # Verify that all expected Redis keys were used - redis_keys_used = [call[0][0] for call in hset_calls] - - # 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" - - -class TestBatchedCacheWriter: - """The dump is far too large to buffer into a single pipeline.""" - - async def test_flushes_once_the_batch_is_full(self): - pipe = AsyncMock() - writer = BatchedCacheWriter(pipe, batch_size=3) - - for i in range(3): - await writer.hset("key", f"field-{i}", {"i": i}) - - assert pipe.execute.call_count == 1 - - async def test_does_not_flush_a_partial_batch_early(self): - pipe = AsyncMock() - writer = BatchedCacheWriter(pipe, batch_size=3) - - await writer.hset("key", "field", {"a": 1}) - - assert pipe.execute.call_count == 0 - - async def test_final_flush_writes_the_remainder(self): - pipe = AsyncMock() - writer = BatchedCacheWriter(pipe, batch_size=3) - - await writer.hset("key", "field", {"a": 1}) - await writer.flush() - - assert pipe.execute.call_count == 1 - - async def test_flush_is_a_noop_with_nothing_queued(self): - pipe = AsyncMock() - writer = BatchedCacheWriter(pipe, batch_size=3) - - await writer.flush() - - assert pipe.execute.call_count == 0 - - async def test_values_go_through_the_dump_codec(self): - pipe = AsyncMock() - writer = BatchedCacheWriter(pipe, batch_size=10) - record = {"Name": "Super Mario Bros."} - - await writer.hset("key", "field", record) - - stored = pipe.hset.call_args.kwargs["mapping"]["field"] - # Bytes, because a compressed value is not valid UTF-8. - assert isinstance(stored, bytes) - assert decode(stored) == record - - async def test_large_input_flushes_repeatedly(self, task, sample_zip_content): - """A real dump must not end up in one pipeline execute.""" - mock_pipe = AsyncMock() - - with ( - patch.object(RemoteFilePullTask, "run", return_value=sample_zip_content), - patch( - "tasks.scheduled.update_launchbox_metadata.CACHE_WRITE_BATCH_SIZE", 1 - ), - patch( - "tasks.scheduled.update_launchbox_metadata.async_cache.pipeline" - ) as mock_pipeline, - ): - mock_pipeline.return_value.__aenter__ = AsyncMock(return_value=mock_pipe) - mock_pipeline.return_value.__aexit__ = AsyncMock(return_value=None) - - await task.run() - - # One execute per queued write rather than one for the whole file. - assert mock_pipe.execute.call_count == mock_pipe.hset.call_count - - -class TestInitialImportFlag: - """The store is written in batches, so a half-filled one must not read as - ready to the provider heartbeat.""" - - @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_launchbox_metadata.async_binary_cache.pipeline") - async def test_first_import_flags_and_clears_on_completion( - self, mock_pipeline, mock_super_run, task, sample_zip_content - ): - mock_super_run.return_value = sample_zip_content - mock_pipeline.return_value.__aenter__ = AsyncMock(return_value=AsyncMock()) - mock_pipeline.return_value.__aexit__ = AsyncMock(return_value=None) - - 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() - - 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") - @patch("tasks.scheduled.update_launchbox_metadata.async_binary_cache.pipeline") - async def test_refresh_of_a_filled_store_is_not_flagged( - self, mock_pipeline, mock_super_run, task, sample_zip_content - ): - """An existing store keeps answering while it is refreshed in place.""" - mock_super_run.return_value = sample_zip_content - mock_pipeline.return_value.__aenter__ = AsyncMock(return_value=AsyncMock()) - mock_pipeline.return_value.__aexit__ = AsyncMock(return_value=None) - - 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() - - # 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( - self, mock_super_run, task, corrupt_zip_content - ): mock_super_run.return_value = corrupt_zip_content + with pytest.raises(RuntimeError): + await task.run() - with ( - patch.object(async_cache, "exists", AsyncMock(return_value=0)), - patch.object(async_cache, "set", AsyncMock()), - patch.object(async_cache, "delete", AsyncMock()) as mock_delete, - pytest.raises(RuntimeError), + assert set(_rows(LAUNCHBOX_METADATA_TABLE)) == {"12345", "67890"} + assert list(LAUNCHBOX_METADATA_STORE.directory.iterdir()) == [ + LAUNCHBOX_METADATA_STORE.path + ] + + @patch.object(RemoteFilePullTask, "run") + async def test_store_is_absent_until_the_import_finishes( + self, mock_super_run, task, sample_zip_content + ): + """The heartbeat reads a partial import as no store at all.""" + mock_super_run.return_value = sample_zip_content + seen_mid_import: list[bool] = [] + + def import_files(_source: IO[bytes], _writer: DumpWriter) -> None: + seen_mid_import.append(LAUNCHBOX_METADATA_STORE.exists()) + + with patch.dict( + "tasks.scheduled.update_launchbox_metadata.ARCHIVE_IMPORTERS", + {"Files.xml": import_files}, ): await task.run() - mock_delete.assert_not_awaited() + assert seen_mid_import == [False] + assert LAUNCHBOX_METADATA_STORE.exists() class TestManualRunGate: diff --git a/backend/tests/tasks/test_update_switch_titledb.py b/backend/tests/tasks/test_update_switch_titledb.py index bb35aba66..d84d131a5 100644 --- a/backend/tests/tasks/test_update_switch_titledb.py +++ b/backend/tests/tasks/test_update_switch_titledb.py @@ -1,13 +1,14 @@ import json from dataclasses import replace -from unittest.mock import AsyncMock, patch +from unittest.mock import patch import pytest -from handler.dump_cache import decode +from handler.dump_store import EmptyDumpError from tasks.scheduled.update_switch_titledb import ( - SWITCH_PRODUCT_ID_KEY, - SWITCH_TITLEDB_INDEX_KEY, + SWITCH_PRODUCT_ID_TABLE, + SWITCH_TITLEDB_STORE, + SWITCH_TITLEDB_TABLE, UpdateSwitchTitleDBTask, update_switch_titledb_task, ) @@ -65,110 +66,47 @@ class TestUpdateSwitchTitleDBTask: ) @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_switch_titledb.async_binary_cache.pipeline") - async def test_run_success( - self, - mock_async_cache_pipeline, - mock_super_run, - task, - sample_json_content, + async def test_run_builds_the_store( + self, mock_super_run, task, sample_titledb_data, sample_json_content ): - """Test successful run with valid data""" mock_super_run.return_value = sample_json_content - # Create mock pipeline with async context manager support - mock_pipe = AsyncMock() - mock_pipe.__aenter__ = AsyncMock(return_value=mock_pipe) - mock_pipe.__aexit__ = AsyncMock(return_value=None) - mock_async_cache_pipeline.return_value = mock_pipe - await task.run() - # Verify super().run was called mock_super_run.assert_called_once_with() - - # Verify pipeline was used - assert mock_async_cache_pipeline.called - assert mock_pipe.hset.called - assert mock_pipe.execute.called - - # Verify hset was called for both keys - hset_calls = mock_pipe.hset.call_args_list - - # Should have calls for both SWITCH_TITLEDB_INDEX_KEY and SWITCH_PRODUCT_ID_KEY - titledb_calls = [ - call for call in hset_calls if call[0][0] == SWITCH_TITLEDB_INDEX_KEY - ] - product_calls = [ - call for call in hset_calls if call[0][0] == SWITCH_PRODUCT_ID_KEY - ] - - assert len(titledb_calls) > 0 - assert len(product_calls) > 0 + assert SWITCH_TITLEDB_STORE.exists() + for title_id, entry in sample_titledb_data.items(): + if title_id and entry: + assert SWITCH_TITLEDB_STORE.get(SWITCH_TITLEDB_TABLE, title_id) == entry @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_switch_titledb.async_binary_cache.pipeline") async def test_run_filters_empty_data( - self, - mock_async_cache_pipeline, - mock_super_run, - task, - sample_json_content, + self, mock_super_run, task, sample_json_content ): - """Test that empty keys and None values are filtered out""" + """Empty keys and None values are left out.""" mock_super_run.return_value = sample_json_content - mock_pipe = AsyncMock() - mock_pipe.__aenter__ = AsyncMock(return_value=mock_pipe) - mock_pipe.__aexit__ = AsyncMock(return_value=None) - mock_async_cache_pipeline.return_value = mock_pipe - await task.run() - # Get all the mapping data that was passed to hset - hset_calls = mock_pipe.hset.call_args_list - - for call in hset_calls: - args, kwargs = call - if "mapping" in kwargs: - mapping = kwargs["mapping"] - # Verify no empty keys - assert "" not in mapping - # Verify no None values in the original data structure - for key in mapping.keys(): - assert key is not None and key != "" + assert SWITCH_TITLEDB_STORE.get(SWITCH_TITLEDB_TABLE, "") is None + assert SWITCH_TITLEDB_STORE.get(SWITCH_TITLEDB_TABLE, "70010000000052") is None + assert ( + SWITCH_TITLEDB_STORE.get(SWITCH_PRODUCT_ID_TABLE, "should_be_filtered") + is None + ) @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_switch_titledb.async_binary_cache.pipeline") - async def test_run_batches_data( - self, - mock_async_cache_pipeline, - mock_super_run, - task, - ): - """Test that data is properly batched""" - # Create a large dataset to test batching - large_dataset = {} - for i in range(5000): # More than 2000 to ensure batching - large_dataset[f"010000000{i:07d}"] = { - "id": f"010000000{i:07d}", - "name": f"Game {i}", - "publisher": "Test Publisher", - } - - large_json_content = json.dumps(large_dataset).encode("utf-8") - mock_super_run.return_value = large_json_content - - mock_pipe = AsyncMock() - mock_pipe.__aenter__ = AsyncMock(return_value=mock_pipe) - mock_pipe.__aexit__ = AsyncMock(return_value=None) - mock_async_cache_pipeline.return_value = mock_pipe + async def test_run_writes_more_than_one_batch(self, mock_super_run, task): + large_dataset = { + f"010000000{i:07d}": {"id": f"010000000{i:07d}", "name": f"Game {i}"} + for i in range(5000) + } + mock_super_run.return_value = json.dumps(large_dataset).encode("utf-8") await task.run() - # Should have multiple hset calls due to batching - hset_calls = mock_pipe.hset.call_args_list - assert len(hset_calls) > 2 # At least one batch for each key type + for title_id in ("0100000000000000", "0100000000004999"): + assert SWITCH_TITLEDB_STORE.get(SWITCH_TITLEDB_TABLE, title_id) is not None @patch.object(RemoteFilePullTask, "run") async def test_a_failed_download_fails_the_run(self, mock_super_run, task): @@ -178,93 +116,68 @@ class TestUpdateSwitchTitleDBTask: await task.run() @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_switch_titledb.async_binary_cache.pipeline") - async def test_run_invalid_json( - self, - mock_async_cache_pipeline, - mock_super_run, - task, - ): - """Test run with invalid JSON content""" + async def test_run_invalid_json(self, mock_super_run, task): mock_super_run.return_value = b"invalid json content" with pytest.raises(json.JSONDecodeError): await task.run() + assert not SWITCH_TITLEDB_STORE.exists() + @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_switch_titledb.async_binary_cache.pipeline") - async def test_run_empty_json( - self, - mock_async_cache_pipeline, - mock_super_run, - task, + async def test_an_empty_dump_keeps_the_previous_store( + self, mock_super_run, task, sample_json_content ): - """Test run with empty JSON object""" - mock_super_run.return_value = json.dumps({}).encode("utf-8") - - mock_pipe = AsyncMock() - mock_pipe.__aenter__ = AsyncMock(return_value=mock_pipe) - mock_pipe.__aexit__ = AsyncMock(return_value=None) - mock_async_cache_pipeline.return_value = mock_pipe - + mock_super_run.return_value = sample_json_content await task.run() - # Should still call execute even with empty data - assert mock_pipe.execute.called + mock_super_run.return_value = json.dumps({}).encode("utf-8") + with pytest.raises(EmptyDumpError): + await task.run() + + assert SWITCH_TITLEDB_STORE.get(SWITCH_TITLEDB_TABLE, "70010000000025") + + @patch.object(RemoteFilePullTask, "run") + async def test_a_refresh_replaces_the_previous_store( + self, mock_super_run, task, sample_json_content + ): + mock_super_run.return_value = sample_json_content + await task.run() + + mock_super_run.return_value = json.dumps( + {"70010000000099": {"id": "0100000000990000", "name": "New Game"}} + ).encode("utf-8") + await task.run() + + assert SWITCH_TITLEDB_STORE.get(SWITCH_TITLEDB_TABLE, "70010000000025") is None + assert SWITCH_TITLEDB_STORE.get(SWITCH_TITLEDB_TABLE, "70010000000099") == { + "id": "0100000000990000", + "name": "New Game", + } @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_switch_titledb.async_binary_cache.pipeline") async def test_product_id_mapping( - self, - mock_async_cache_pipeline, - mock_super_run, - task, - sample_titledb_data, - sample_json_content, + self, mock_super_run, task, sample_titledb_data, sample_json_content ): """The product id index points at its titleID index entry.""" mock_super_run.return_value = sample_json_content - mock_pipe = AsyncMock() - mock_pipe.__aenter__ = AsyncMock(return_value=mock_pipe) - mock_pipe.__aexit__ = AsyncMock(return_value=None) - mock_async_cache_pipeline.return_value = mock_pipe - await task.run() - hset_calls = mock_pipe.hset.call_args_list - product_mapping = { - product_id: decode(raw) - for call in hset_calls - if call[0][0] == SWITCH_PRODUCT_ID_KEY - for product_id, raw in call[1]["mapping"].items() - } - - assert product_mapping == { - entry["id"]: title_id - for title_id, entry in sample_titledb_data.items() - if title_id and entry - } + for title_id, entry in sample_titledb_data.items(): + if title_id and entry: + assert ( + SWITCH_TITLEDB_STORE.get(SWITCH_PRODUCT_ID_TABLE, entry["id"]) + == title_id + ) @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_switch_titledb.async_binary_cache.pipeline") @patch("tasks.scheduled.update_switch_titledb.log") async def test_completion_log( - self, - mock_log, - mock_async_cache_pipeline, - mock_super_run, - task, - sample_json_content, + self, mock_log, mock_super_run, task, sample_json_content ): - """Test that completion is logged""" mock_super_run.return_value = sample_json_content - mock_pipe = AsyncMock() - mock_pipe.__aenter__ = AsyncMock(return_value=mock_pipe) - mock_pipe.__aexit__ = AsyncMock(return_value=None) - mock_async_cache_pipeline.return_value = mock_pipe - await task.run() mock_log.info.assert_called_with("Scheduled switch titledb update completed!") diff --git a/backend/tests/test_nginx_cache_headers.py b/backend/tests/test_nginx_cache_headers.py index dd9a9e4dd..69708194f 100644 --- a/backend/tests/test_nginx_cache_headers.py +++ b/backend/tests/test_nginx_cache_headers.py @@ -61,6 +61,7 @@ class Location: def __init__(self, modifier: str, match: str, body: str): self.modifier = modifier self.match = match + self.body = body cache = re.search( r'add_header\s+Cache-Control\s+(?:"([^"]*)"|(\$[A-Za-z0-9_]+))', body, @@ -283,3 +284,18 @@ def test_root_files_revalidate(config, url): assert ( "no-cache" in cc or "must-revalidate" in cc ), f"{url} must revalidate so deploys/updates propagate, got: {cc!r}" + + +@pytest.mark.parametrize( + "url", + [ + "/assets/romm/resources/metadata/launchbox.v1.sqlite", + "/assets/romm/resources/metadata/.launchbox.v1.sqlite.abc.tmp", + # A case-insensitive volume would serve the file under any casing. + "/assets/romm/resources/Metadata/launchbox.v1.sqlite", + ], +) +def test_metadata_dumps_are_never_served(config, url): + locations, _ = config + loc = _resolve(locations, url) + assert loc is not None and re.search(r"\breturn\s+404\b", loc.body), url diff --git a/backend/tests/test_startup.py b/backend/tests/test_startup.py index d8db51892..0b2b514f4 100644 --- a/backend/tests/test_startup.py +++ b/backend/tests/test_startup.py @@ -1,6 +1,6 @@ """Tests for startup-time auto-enqueue of the recompute task.""" -from unittest.mock import AsyncMock +from pathlib import Path import pytest import startup @@ -9,12 +9,17 @@ from rq.job import JOB_ID_PATTERN, Job, JobStatus from config.config_manager import config_manager from handler.database import db_save_handler +from handler.dump_store import DumpStore from handler.metadata.launchbox_handler.types import LAUNCHBOX_METADATA_STORE -from handler.redis_handler import default_queue, high_prio_queue, low_prio_queue +from handler.redis_handler import ( + async_cache, + default_queue, + high_prio_queue, + low_prio_queue, +) from tasks.manual.recompute_name_sort_keys import articles_digest from tasks.registry import get_task from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE -from utils.cache import VersionedCacheStore @pytest.fixture @@ -191,28 +196,26 @@ class TestDropLegacySchedulerState: 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.""" + @staticmethod + async def _seed_legacy_keys(*keys: str) -> None: + for key in keys: + await async_cache.set(key, "1") - def patch_drop(*stale: VersionedCacheStore): - async def drop(_cache, store): - return store in stale + @staticmethod + def _write_store_file(store: DumpStore, revision: str) -> Path: + store.directory.mkdir(parents=True, exist_ok=True) + path = store.directory / f"{store.name}.{revision}.sqlite" + path.write_bytes(b"") + return path - 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 + async def test_launchbox_store_left_in_the_cache_is_dropped_and_rebuilt( + self, enqueue_task ): - mocker.patch.object(startup, "LAUNCHBOX_API_ENABLED", True) - drop_stale(LAUNCHBOX_METADATA_STORE) + await self._seed_legacy_keys(*startup.LEGACY_LAUNCHBOX_CACHE_KEYS) await startup._rebuild_outdated_metadata_stores() + assert not await async_cache.exists(*startup.LEGACY_LAUNCHBOX_CACHE_KEYS) enqueue_task.assert_called_once_with( "update_launchbox_metadata", job_id=startup.UPDATE_LAUNCHBOX_METADATA_JOB_ID, @@ -220,32 +223,33 @@ class TestRebuildOutdatedMetadataStores: ) async def test_launchbox_rebuild_waits_on_the_provider_being_enabled( - self, mocker, drop_stale, enqueue_task + self, mocker, 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", + "METADATA_DUMP_STORES", ( ( LAUNCHBOX_METADATA_STORE, + startup.LEGACY_LAUNCHBOX_CACHE_KEYS, "update_launchbox_metadata", startup.UPDATE_LAUNCHBOX_METADATA_JOB_ID, False, ), ), ) - drop_stale(LAUNCHBOX_METADATA_STORE) + await self._seed_legacy_keys(*startup.LEGACY_LAUNCHBOX_CACHE_KEYS) await startup._rebuild_outdated_metadata_stores() + assert not await async_cache.exists(*startup.LEGACY_LAUNCHBOX_CACHE_KEYS) enqueue_task.assert_not_called() - async def test_stale_switch_store_is_dropped_and_rebuilt( - self, drop_stale, enqueue_task + async def test_switch_store_left_in_the_cache_is_dropped_and_rebuilt( + self, enqueue_task ): - drop_stale(SWITCH_TITLEDB_STORE) + await self._seed_legacy_keys(*startup.LEGACY_SWITCH_TITLEDB_CACHE_KEYS) await startup._rebuild_outdated_metadata_stores() @@ -255,11 +259,41 @@ class TestRebuildOutdatedMetadataStores: unique=True, ) - async def test_current_stores_queue_nothing(self, drop_stale, enqueue_task): - drop_stale() + async def test_file_of_an_older_revision_is_deleted_and_rebuilt(self, enqueue_task): + old_file = self._write_store_file(SWITCH_TITLEDB_STORE, "v0") await startup._rebuild_outdated_metadata_stores() + assert not old_file.exists() + enqueue_task.assert_called_once_with( + "update_switch_titledb", + job_id=startup.UPDATE_SWITCH_TITLEDB_JOB_ID, + unique=True, + ) + + async def test_a_current_file_is_kept_and_not_rebuilt(self, enqueue_task): + current = self._write_store_file( + SWITCH_TITLEDB_STORE, SWITCH_TITLEDB_STORE.revision + ) + await self._seed_legacy_keys(*startup.LEGACY_SWITCH_TITLEDB_CACHE_KEYS) + + await startup._rebuild_outdated_metadata_stores() + + assert current.exists() + assert not await async_cache.exists(*startup.LEGACY_SWITCH_TITLEDB_CACHE_KEYS) + enqueue_task.assert_not_called() + + async def test_fixture_indexes_are_dropped_from_the_cache(self, enqueue_task): + await self._seed_legacy_keys(*startup.LEGACY_FIXTURE_CACHE_KEYS) + + await startup._rebuild_outdated_metadata_stores() + + assert not await async_cache.exists(*startup.LEGACY_FIXTURE_CACHE_KEYS) + enqueue_task.assert_not_called() + + async def test_nothing_to_drop_queues_nothing(self, enqueue_task): + 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 deleted file mode 100644 index 4934f08a5..000000000 --- a/backend/tests/utils/test_cache.py +++ /dev/null @@ -1,187 +0,0 @@ -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 ( - VersionedCacheStore, - conditionally_set_cache, - drop_stale_cache_store, - is_cache_schema_current, - is_cache_store_ready, - stamp_cache_schema, -) - - -class TestConditionallySetCache: - """Test the conditionally_set_cache function.""" - - async def test_cache_not_exists_loads_data(self, mocker): - """Test loading data when cache doesn't exist.""" - mock_cache_exists = mocker.patch.object( - async_cache, "exists", new_callable=AsyncMock, return_value=False - ) - mock_pipeline = AsyncMock() - mock_cache_pipeline = mocker.patch.object(async_cache, "pipeline") - mock_cache_pipeline.return_value.__aenter__.return_value = mock_pipeline - - await conditionally_set_cache( - async_cache, MAME_XML_KEY, METADATA_FIXTURES_DIR / "mame_index.json" - ) - - mock_cache_exists.assert_called_once_with(MAME_XML_KEY) - mock_cache_pipeline.return_value.__aenter__.assert_called_once() - mock_pipeline.hset.assert_called() - mock_pipeline.execute.assert_called_once() - - async def test_cache_exists_and_hash_does_not_match_loads_data(self, mocker): - """Test loading data when cache exists but file hash does not match.""" - mock_cache_exists = mocker.patch.object( - async_cache, "exists", new_callable=AsyncMock, return_value=True - ) - mock_pipeline = AsyncMock() - mock_cache_pipeline = mocker.patch.object(async_cache, "pipeline") - mock_cache_pipeline.return_value.__aenter__.return_value = mock_pipeline - - await conditionally_set_cache( - async_cache, MAME_XML_KEY, METADATA_FIXTURES_DIR / "mame_index.json" - ) - - mock_cache_exists.assert_called_once_with(MAME_XML_KEY) - mock_cache_pipeline.return_value.__aenter__.assert_called_once() - mock_pipeline.hset.assert_called() - mock_pipeline.execute.assert_called_once() - - async def test_cache_exists_and_hash_matches_skips_loading(self, mocker): - """Test skipping load when cache already exists and file hash matches.""" - fake_md5_hash = "d41d8cd98f00b204e9800998ecf8427e" - mocker.patch( - "hashlib.md5", - return_value=AsyncMock( - hexdigest=lambda: fake_md5_hash, - update=lambda x: None, - ), - ) - mock_cache_exists = mocker.patch.object( - async_cache, "exists", new_callable=AsyncMock, return_value=True - ) - mock_cache_get = mocker.patch.object( - async_cache, "get", new_callable=AsyncMock, return_value=fake_md5_hash - ) - mock_cache_pipeline = mocker.patch.object(async_cache, "pipeline") - - await conditionally_set_cache( - async_cache, MAME_XML_KEY, METADATA_FIXTURES_DIR / "mame_index.json" - ) - - mock_cache_exists.assert_called_once_with(MAME_XML_KEY) - mock_cache_get.assert_called_once_with(f"{MAME_XML_KEY}:file_hash") - mock_cache_pipeline.assert_not_called() - - async def test_exception_handling(self, mocker): - """Test exception handling when file loading fails.""" - mocker.patch.object( - async_cache, "exists", new_callable=AsyncMock, return_value=False - ) - mock_cache_pipeline = mocker.patch.object(async_cache, "pipeline") - - await conditionally_set_cache( - async_cache, MAME_XML_KEY, METADATA_FIXTURES_DIR / "nonexistent.json" - ) - - 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/tools/measure_dump_cache.py b/backend/tools/measure_dump_cache.py deleted file mode 100644 index ae42c0738..000000000 --- a/backend/tools/measure_dump_cache.py +++ /dev/null @@ -1,508 +0,0 @@ -"""Measure what the metadata dump stores cost in a real valkey, encoded or not. - -Usage: - uv run tools/measure_dump_cache.py \ - --metadata-zip Metadata.zip --titledb US.en.json \ - --redis-url redis://localhost:6379 -""" - -import argparse -import json -import statistics -import sys -import time -import unicodedata -import zipfile -from collections.abc import Callable, Iterator -from compression import zstd -from pathlib import Path -from typing import Any, Final, cast - -import redis -from defusedxml import ElementTree as ET - -sys.path.insert(0, str(Path(__file__).resolve().parents[1])) - -from handler.dump_cache import ( # noqa: E402 - COMPRESS_MIN_BYTES, - COMPRESSION_LEVEL, - decode, - encode, - serialize, -) - -# Mirrors the two stores' keys, which live behind `handler/metadata/__init__.py` -# and its provider handlers. The only keys this tool ever deletes. -LAUNCHBOX_PLATFORMS_KEY: Final = "romm:launchbox_platforms" -LAUNCHBOX_METADATA_DATABASE_ID_KEY: Final = "romm:launchbox_metadata_database_id" -LAUNCHBOX_METADATA_NAME_KEY: Final = "romm:launchbox_metadata_name" -LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY: Final = "romm:launchbox_metadata_alternate_name" -LAUNCHBOX_METADATA_FOLDED_NAME_KEY: Final = "romm:launchbox_metadata_folded_name" -LAUNCHBOX_METADATA_IMAGE_KEY: Final = "romm:launchbox_metadata_image" -LAUNCHBOX_MAME_KEY: Final = "romm:launchbox_mame" -LAUNCHBOX_FILES_KEY: Final = "romm:launchbox_files" -SWITCH_TITLEDB_INDEX_KEY: Final = "romm:switch_titledb" -SWITCH_PRODUCT_ID_KEY: Final = "romm:switch_product_id" - -DUMP_STORE_KEYS: Final[tuple[str, ...]] = ( - 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, - SWITCH_TITLEDB_INDEX_KEY, - SWITCH_PRODUCT_ID_KEY, -) - -# Mirrors the projections in `launchbox_handler/types.py`, behind the same -# package import. Each store keeps only the fields its reader reads. -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"}) - -WRITE_BATCH = 2000 - -Record = tuple[str, str, Any] - - -def fold_title(title: str) -> str: - """Mirror of `launchbox_handler.utils.fold_title`, behind the same package import.""" - kept: list[str] = [] - for char in unicodedata.normalize("NFKD", title.casefold()): - if unicodedata.category(char).startswith("M"): - if kept and "a" <= kept[-1] <= "z": - continue - kept.append(char) - elif char.isalnum(): - kept.append(char) - - return "".join(kept) - - -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 - } - - -def iter_elements(source: Any) -> Iterator[Any]: - """Yield each top-level record, dropping it once the caller moves on.""" - ctx = ET.iterparse(source, events=("start", "end")) - try: - _, root = next(iter(ctx)) - except StopIteration: - return - - depth = 0 - for event, elem in ctx: - if event == "start": - depth += 1 - continue - depth -= 1 - if depth > 0: - continue - yield elem - root.clear() - - -# Mirrors the record shapes `tasks/scheduled/update_launchbox_metadata.py` -# writes, duplicated because the writer fills a pipeline rather than yielding. -def iter_launchbox(metadata_zip: Path) -> Iterator[Record]: - with zipfile.ZipFile(metadata_zip) as z: - names = z.namelist() - - if "Platforms.xml" in names: - with z.open("Platforms.xml") as f: - for elem in iter_elements(f): - if elem.tag != "Platform": - continue - name = elem.find("Name") - if name is not None and name.text: - yield ( - LAUNCHBOX_PLATFORMS_KEY, - name.text.strip(), - element_to_dict(elem), - ) - - if "Metadata.xml" in names: - with z.open("Metadata.xml") as f: - image_id: str | None = None - images: list[dict[str, Any]] = [] - - 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 - ) - if database_id: - yield ( - LAUNCHBOX_METADATA_DATABASE_ID_KEY, - database_id, - 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 = platform_elem.text.strip() - title = name_elem.text.strip() - yield ( - LAUNCHBOX_METADATA_NAME_KEY, - f"{title.lower()}:{platform}", - database_id, - ) - folded = fold_title(title) - if folded: - yield ( - LAUNCHBOX_METADATA_FOLDED_NAME_KEY, - f"{folded}:{platform}", - database_id, - ) - - elif elem.tag == "GameAlternateName": - alt = (elem.findtext("AlternateName") or "").strip() - alt_id = (elem.findtext("DatabaseID") or "").strip() - if alt and alt_id: - yield ( - LAUNCHBOX_METADATA_ALTERNATE_NAME_KEY, - alt.lower(), - alt_id, - ) - - elif elem.tag == "GameImage": - id_elem = elem.find("DatabaseID") - if id_elem is None or not id_elem.text: - continue - current = id_elem.text.strip() - if image_id is not None and current != image_id: - yield LAUNCHBOX_METADATA_IMAGE_KEY, image_id, images - images = [] - image_id = current - images.append(element_to_dict(elem, LAUNCHBOX_IMAGE_FIELDS)) - - if image_id is not None: - yield LAUNCHBOX_METADATA_IMAGE_KEY, image_id, images - - if "Mame.xml" in names: - with z.open("Mame.xml") as f: - for elem in iter_elements(f): - if elem.tag != "MameFile": - continue - fn = elem.find("FileName") - if fn is not None and fn.text: - yield ( - LAUNCHBOX_MAME_KEY, - fn.text.strip(), - element_to_dict(elem, LAUNCHBOX_MAME_FIELDS), - ) - - if "Files.xml" in names: - with z.open("Files.xml") as f: - for elem in iter_elements(f): - if elem.tag != "File": - continue - fn = elem.find("FileName") - platform = elem.find("Platform") - if ( - fn is not None - and fn.text - and platform is not None - and platform.text - ): - field = f"{fn.text.strip().lower()}:{platform.text.strip()}" - yield ( - LAUNCHBOX_FILES_KEY, - field, - element_to_dict(elem, LAUNCHBOX_FILE_FIELDS), - ) - - -def iter_titledb(titledb: Path) -> Iterator[Record]: - data = json.loads(titledb.read_text()) - relevant = {k: v for k, v in data.items() if k and v} - del data - for title_id, entry in relevant.items(): - yield SWITCH_TITLEDB_INDEX_KEY, title_id, entry - for title_id, entry in relevant.items(): - product_id = entry.get("id") - if product_id: - yield SWITCH_PRODUCT_ID_KEY, product_id, title_id - - -def plain(value: Any) -> bytes: - """Serialize a record as the uncompressed baseline the report compares to.""" - return json.dumps(value).encode() - - -def load( - client: redis.Redis, - records: Iterator[Record], - serialize: Callable[[Any], bytes], -) -> None: - """Write every record into the store its key names.""" - pipe = client.pipeline(transaction=False) - queued = 0 - for key, field, value in records: - pipe.hset(key, mapping={field: serialize(value)}) - queued += 1 - if queued >= WRITE_BATCH: - pipe.execute() - queued = 0 - if queued: - pipe.execute() - - -def store_stats(client: redis.Redis) -> tuple[dict[str, int], dict[str, int]]: - """Field count and total value bytes per store, read back off the hashes.""" - # Not tallied while writing: the dump repeats a title on one platform and an - # alternate name across platforms, so ~9k records overwrite another's field. - counts: dict[str, int] = {} - value_bytes: dict[str, int] = {} - for key in DUMP_STORE_KEYS: - count = client.hlen(key) - if not count: - continue - counts[key] = count - value_bytes[key] = sum( - len(value) for _, value in client.hscan_iter(key, count=1000) - ) - return counts, value_bytes - - -def foreign_keys(client: redis.Redis) -> int: - """How many keys on the server are not this tool's own stores.""" - owned = {key.encode() for key in DUMP_STORE_KEYS} - return sum(1 for key in client.scan_iter(count=1000) if key not in owned) - - -def clear_stores(client: redis.Redis) -> int: - """Drop only this tool's stores, returning `used_memory` without them.""" - # Not `flushall`: the URL can point at a live RomM, whose sessions and RQ - # queues share the database with these stores. - client.delete(*DUMP_STORE_KEYS) - return int(client.info("memory")["used_memory"]) - - -def store_memory( - client: redis.Redis, keys: list[str] -) -> tuple[dict[str, int], int, int]: - sizes = {} - for key in keys: - # SAMPLES 0 walks every field rather than extrapolating from five. - size = client.execute_command("MEMORY", "USAGE", key, "SAMPLES", 0) - if size: - sizes[key] = int(size) - info = client.info("memory") - return sizes, int(info["used_memory"]), int(info["used_memory_rss"]) - - -def mb(value: float) -> str: - return f"{value / 1024 / 1024:>8.1f}M" - - -def sweep_threshold(metadata_zip: Path, limit: int) -> int: - """Print total stored bytes at each candidate COMPRESS_MIN_BYTES, on real - records, and return an exit code.""" - compressor = zstd.ZstdCompressor(level=COMPRESSION_LEVEL) - sample: list[bytes] = [] - for _, _, value in iter_launchbox(metadata_zip): - # The threshold applies to the payload `encode` builds, not the wider - # baseline the report uses for the old format. - sample.append(serialize(value)) - if len(sample) >= limit: - break - - if not sample: - print("no records in the zip; check --metadata-zip", file=sys.stderr) - return 1 - - raw = sum(len(payload) for payload in sample) - print(f"\nthreshold sweep over {len(sample):,} real records") - print(f"{'min bytes':>10} {'stored':>10} {'ratio':>7} {'compressed':>11}") - for threshold in (0, 64, 128, 192, 256, 384, 512, 1024, 1 << 30): - total = 0 - compressed = 0 - for payload in sample: - if len(payload) >= threshold: - total += len( - compressor.compress(payload, zstd.ZstdCompressor.FLUSH_FRAME) - ) - compressed += 1 - else: - total += len(payload) - label = "never" if threshold == 1 << 30 else f"{threshold}" - print( - f"{label:>10} {mb(total)} {raw / total:>6.2f}x " - f"{compressed / len(sample):>10.0%}" - ) - - return 0 - - -def bench_decode( - client: redis.Redis, key: str, rounds: int = 5 -) -> tuple[float, float] | None: - """Median `decode` latency, and mean stored size, on real stored records.""" - fields = cast(list[bytes], client.hrandfield(key, 2000)) - if not fields: - return None - blobs = [b for b in client.hmget(key, fields) if b] - if not blobs: - return None - - times = [] - for _ in range(rounds): - start = time.perf_counter() - for blob in blobs: - decode(blob) - times.append((time.perf_counter() - start) / len(blobs) * 1e6) - - return statistics.median(times), statistics.mean(len(b) for b in blobs) - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--metadata-zip", type=Path, required=True) - parser.add_argument("--titledb", type=Path) - parser.add_argument("--redis-url", default="redis://localhost:6379") - parser.add_argument( - "--sweep", - type=int, - default=0, - metavar="N", - help="sweep the compression threshold over N records and exit", - ) - parser.add_argument( - "--force", - action="store_true", - help="run even though the server holds data other than these stores", - ) - parser.add_argument( - "--only", - choices=("plain", "encoded"), - help="load one encoding and report it, for reading RSS off a server " - "started fresh for this pass", - ) - args = parser.parse_args() - - if args.sweep: - return sweep_threshold(args.metadata_zip, args.sweep) - - client = redis.Redis.from_url(args.redis_url) - - foreign = foreign_keys(client) - if foreign and not args.force: - # The URL is not echoed back: RomM builds it with the password inline. - print( - f"The target server holds {foreign:,} key(s) outside the metadata " - "dump stores, so it looks like a live instance. This tool drops and " - "rebuilds the dump stores, which a running RomM would then have to " - "re-import. Point it at a disposable server, or pass --force.", - file=sys.stderr, - ) - return 1 - - def records() -> Iterator[Record]: - yield from iter_launchbox(args.metadata_zip) - if args.titledb: - yield from iter_titledb(args.titledb) - - benched = ( - LAUNCHBOX_METADATA_DATABASE_ID_KEY, - LAUNCHBOX_METADATA_IMAGE_KEY, - SWITCH_TITLEDB_INDEX_KEY, - ) - results = {} - passes = [("plain", plain), ("encoded", encode)] - if args.only: - passes = [p for p in passes if p[0] == args.only] - - for label, encoding in passes: - base_used = clear_stores(client) - start = time.perf_counter() - load(client, records(), encoding) - elapsed = time.perf_counter() - start - counts, value_bytes = store_stats(client) - sizes, used, rss = store_memory(client, list(counts)) - # Net of anything else on the server. Only `used_memory` can be offset - # this way; RSS keeps the pages a delete frees, so it stays absolute. - used -= base_used - latency = {key: bench_decode(client, key) for key in benched} - results[label] = (counts, value_bytes, sizes, used, rss, latency) - print( - f"{label}: loaded in {elapsed:.0f}s, used_memory {mb(used)}, " - f"rss {mb(rss)}" - ) - - if args.only: - return 0 - - p_counts, p_values, p_sizes, p_used, p_rss, p_latency = results["plain"] - _, e_values, e_sizes, e_used, e_rss, e_latency = results["encoded"] - - if not p_sizes: - print("no records loaded; check --metadata-zip", file=sys.stderr) - return 1 - - print(f"\nCOMPRESS_MIN_BYTES = {COMPRESS_MIN_BYTES}\n") - header = f"{'store':<40} {'fields':>10} {'plain':>9} {'encoded':>9} {'saved':>7}" - print(header) - print("-" * len(header)) - for key in sorted(p_sizes, key=lambda k: -p_sizes[k]): - plain_size = p_sizes[key] - enc_size = e_sizes.get(key, 0) - saved = 1 - enc_size / plain_size if plain_size else 0 - print( - f"{key:<40} {p_counts[key]:>10,} {mb(plain_size)} {mb(enc_size)} " - f"{saved:>6.0%}" - ) - print("-" * len(header)) - print( - f"{'sum of stores':<40} {sum(p_counts.values()):>10,} " - f"{mb(sum(p_sizes.values()))} {mb(sum(e_sizes.values()))} " - f"{1 - sum(e_sizes.values()) / sum(p_sizes.values()):>6.0%}" - ) - print( - f"{'used_memory (dump stores)':<40} {'':>10} {mb(p_used)} {mb(e_used)} " - f"{1 - e_used / p_used:>6.0%}" - ) - # Only comparable between passes on a server restarted between them, - # which is what --only is for. - print(f"{'used_memory_rss (absolute)':<40} {'':>10} {mb(p_rss)} {mb(e_rss)}") - - p_value_total, e_value_total = sum(p_values.values()), sum(e_values.values()) - print( - f"\nstored value bytes: {mb(p_value_total)} -> {mb(e_value_total)} " - f"({p_value_total / e_value_total:.2f}x)" - ) - - print( - f"\n{'decode (us/record, mean stored bytes)':<40} {'plain':>16} {'encoded':>16}" - ) - for key in benched: - before, after = p_latency.get(key), e_latency.get(key) - if not before or not after: - continue - print( - f"{key:<40} {before[0]:>7.2f} {before[1]:>8,.0f} " - f"{after[0]:>7.2f} {after[1]:>8,.0f}" - ) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/backend/utils/cache.py b/backend/utils/cache.py deleted file mode 100644 index 675b3d007..000000000 --- a/backend/utils/cache.py +++ /dev/null @@ -1,103 +0,0 @@ -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 - -from logger.logger import log - - -async def conditionally_set_cache(cache: AsyncRedis, key: str, file_path: Path) -> None: - """Set the content of a JSON file to the cache, if it does not already exist or is outdated. - - The MD5 hash of the file is stored alongside the data to determine if the content has changed. - """ - - hash_key = f"{key}:file_hash" - - try: - # Calculate file's MD5 hash to determine if content has changed. - async with await open_file(file_path, "rb") as file: - file_content = await file.read() - md5_h = hashlib.md5(usedforsecurity=False) - md5_h.update(file_content) - file_hash = md5_h.hexdigest().lower() - - # If cache key exists, and hash matches, do nothing. - data_exists = await cache.exists(key) - cached_hash = await cache.get(hash_key) - if data_exists and cached_hash == file_hash: - log.debug(f"Cache is up to date, skipping initialization for {key}") - return - - # Set the content of the file to the cache, and update the hash. - index_data = json.loads(file_content) - async with cache.pipeline() as pipe: - # Clear existing data to avoid stale entries. - if data_exists: - await pipe.delete(key) - for data_batch in batched(index_data.items(), 2000, strict=False): - data_map = {k: json.dumps(v) for k, v in data_batch} - await pipe.hset(key, mapping=data_map) - await pipe.set(hash_key, file_hash) - await pipe.execute() - log.debug( - f"Cache successfully set for {key}, total items: {len(index_data)}" - ) - 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) diff --git a/docker/nginx/templates/default.conf.template b/docker/nginx/templates/default.conf.template index cde26fec4..c55df8401 100644 --- a/docker/nginx/templates/default.conf.template +++ b/docker/nginx/templates/default.conf.template @@ -97,6 +97,12 @@ server { try_files $uri $uri/ =404; } + # Metadata dumps the backend reads in place; they are not library resources. + # Case-insensitive, since the resources volume can be too. + location ~* ^/assets/romm/resources/metadata/ { + return 404; + } + location ^~ /assets/easyrpg/games/ { if ($easyrpg_backend_uri = "") { return 404; diff --git a/docker/s6-overlay/s6-rc.d/romm-valkey/run b/docker/s6-overlay/s6-rc.d/romm-valkey/run index 965c4f72e..3a4cfb505 100755 --- a/docker/s6-overlay/s6-rc.d/romm-valkey/run +++ b/docker/s6-overlay/s6-rc.d/romm-valkey/run @@ -18,14 +18,14 @@ fi info_log "Starting internal valkey" -# Snapshots rewrite hundreds of MB of rebuildable metadata, so take them hourly -# rather than valkey's every few minutes. An empty REDIS_SAVE_POLICY disables them. -REDIS_SAVE_POLICY="${REDIS_SAVE_POLICY="3600 1"}" - -declare -a save_flags=(--save "") -if [[ -n ${REDIS_SAVE_POLICY} ]]; then - # shellcheck disable=SC2206 # each " " token is its own argument - save_flags=(--save ${REDIS_SAVE_POLICY}) +# Unset keeps valkey's own snapshot policy; an empty REDIS_SAVE_POLICY disables snapshots. +declare -a save_flags=() +if [[ -v REDIS_SAVE_POLICY ]]; then + save_flags=(--save "") + if [[ -n ${REDIS_SAVE_POLICY} ]]; then + # shellcheck disable=SC2206 # each " " token is its own argument + save_flags=(--save ${REDIS_SAVE_POLICY}) + fi fi # Valkey otherwise ignores SIGTERM when its exit snapshot can't be written (say, diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index c56e5634d..034f38516 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -186,7 +186,8 @@ Running with a read-only root filesystem requires `/run` to be mounted **exec**, 1. alembic upgrade head # Run database migrations 2. startup.main() # Async startup tasks ├── Clear stale delayed scans and legacy scheduler keys - └── Load fixture caches into Redis (MAME, ScummVM, console serials, known BIOS) + ├── Drop metadata stores an older release left, and queue their rebuild + └── Build the fixture store (MAME, ScummVM, console serials, known BIOS) 3. uvicorn.run("main:app") # Start ASGI server └── FastAPI lifespan ├── Create aiohttp.ClientSession @@ -574,7 +575,7 @@ With a secret, a webhook adds `X-RomM-Signature: sha256= " pairs ("" to never snapshot) +REDIS_SAVE_POLICY="3600 1 300 100 60 10000" # Snapshot policy of the internal Valkey, as " " pairs ("" to never snapshot); valkey's own policy when unset # Authentication ROMM_AUTH_SECRET_KEY="" # App secret, generate with `openssl rand -hex 32` [REQUIRED]