diff --git a/backend/handler/dump_cache.py b/backend/handler/dump_cache.py new file mode 100644 index 000000000..f4c486f59 --- /dev/null +++ b/backend/handler/dump_cache.py @@ -0,0 +1,71 @@ +"""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 typing import Any, Final + +import zstandard + +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 = zstandard.ZstdCompressor(level=COMPRESSION_LEVEL) +_decompressor = zstandard.ZstdDecompressor() + + +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) + + +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 = _decompressor.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/metadata/base_handler.py b/backend/handler/metadata/base_handler.py index 7f8af5caa..8d4fb2553 100644 --- a/backend/handler/metadata/base_handler.py +++ b/backend/handler/metadata/base_handler.py @@ -10,6 +10,7 @@ from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse from fastapi import HTTPException, status from strsimpy.jaro_winkler import JaroWinkler +from handler.dump_cache import hget_json from handler.redis_handler import async_cache from logger.logger import log from tasks.scheduled.update_switch_titledb import ( @@ -321,17 +322,16 @@ class MetadataHandler(abc.ABC): @staticmethod async def _switch_titledb_entry(title_id: str) -> dict | None: - entry = await async_cache.hget(SWITCH_TITLEDB_INDEX_KEY, title_id) - return json.loads(entry) if entry else None + return await hget_json(SWITCH_TITLEDB_INDEX_KEY, title_id) @classmethod async def _switch_product_id_entry(cls, product_id: str) -> dict | None: """Resolve a Switch product id to the titleID entry its index points at.""" - title_id = await async_cache.hget(SWITCH_PRODUCT_ID_KEY, product_id) + title_id = await hget_json(SWITCH_PRODUCT_ID_KEY, product_id) if not title_id: return None - return await cls._switch_titledb_entry(json.loads(title_id)) + return await cls._switch_titledb_entry(title_id) async def _mame_format(self, search_term: str) -> str: from handler.filesystem import fs_rom_handler diff --git a/backend/handler/metadata/launchbox_handler/remote_source.py b/backend/handler/metadata/launchbox_handler/remote_source.py index a1f75f35a..8f919dc6d 100644 --- a/backend/handler/metadata/launchbox_handler/remote_source.py +++ b/backend/handler/metadata/launchbox_handler/remote_source.py @@ -1,5 +1,4 @@ -import json - +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 @@ -20,20 +19,15 @@ from .utils import deinvert_article, file_name_forms, fold_title class RemoteSource: async def get_by_id(self, database_id: int | str) -> dict | None: - entry = await async_cache.hget( - LAUNCHBOX_METADATA_DATABASE_ID_KEY, str(database_id) - ) - if not entry: - return None - return json.loads(entry) + return await hget_json(LAUNCHBOX_METADATA_DATABASE_ID_KEY, str(database_id)) async def _lookup_title_index(self, key: str, field: str) -> dict | None: """Read a title index hit and resolve the database id it holds.""" - database_id = await async_cache.hget(key, field) + database_id = await hget_json(key, field) if not database_id: return None - return await self.get_by_id(json.loads(database_id)) + return await self.get_by_id(database_id) async def get_rom( self, @@ -119,13 +113,11 @@ class RemoteSource: return None for candidate in file_name_forms(file_name): - entry = await async_cache.hget( - LAUNCHBOX_FILES_KEY, f"{candidate}:{platform_name}" - ) + entry = await hget_json(LAUNCHBOX_FILES_KEY, f"{candidate}:{platform_name}") if not entry: continue - game_name = (json.loads(entry).get("GameName") or "").strip() + game_name = (entry.get("GameName") or "").strip() if not game_name: continue @@ -157,9 +149,9 @@ class RemoteSource: candidates.append(stem) for candidate in candidates: - entry = await async_cache.hget(LAUNCHBOX_MAME_KEY, candidate) + entry = await hget_json(LAUNCHBOX_MAME_KEY, candidate) if entry: - return json.loads(entry) + return entry return None @@ -180,11 +172,4 @@ class RemoteSource: if not resolved_id: return None - metadata_image_index_entry = await async_cache.hget( - LAUNCHBOX_METADATA_IMAGE_KEY, str(resolved_id) - ) - - if not metadata_image_index_entry: - return None - - return json.loads(metadata_image_index_entry) + return await hget_json(LAUNCHBOX_METADATA_IMAGE_KEY, str(resolved_id)) diff --git a/backend/handler/metadata/launchbox_handler/types.py b/backend/handler/metadata/launchbox_handler/types.py index 018d24a14..1a240937b 100644 --- a/backend/handler/metadata/launchbox_handler/types.py +++ b/backend/handler/metadata/launchbox_handler/types.py @@ -24,9 +24,10 @@ LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY: Final[str] = ( ) # 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=1, + version=2, keys=( LAUNCHBOX_PLATFORMS_KEY, LAUNCHBOX_METADATA_DATABASE_ID_KEY, diff --git a/backend/handler/redis_handler.py b/backend/handler/redis_handler.py index 33fda4e06..7ae82a13c 100644 --- a/backend/handler/redis_handler.py +++ b/backend/handler/redis_handler.py @@ -67,6 +67,20 @@ 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: + # Two fakeredis clients get two keyspaces, so the fake is shared. It + # does not decode responses, which is what this client wants anyway. + return async_cache + + return AsyncRedis.from_url(REDIS_URL) + + +async_binary_cache = __get_async_binary_cache() + + def get_job_func_name(job: Job, fallback: str = "") -> str: """Safely get the function name from an RQ job, handling DeserializationError. diff --git a/backend/tasks/scheduled/update_launchbox_metadata.py b/backend/tasks/scheduled/update_launchbox_metadata.py index c1c4b1f61..ca32013ca 100644 --- a/backend/tasks/scheduled/update_launchbox_metadata.py +++ b/backend/tasks/scheduled/update_launchbox_metadata.py @@ -1,4 +1,3 @@ -import json import zipfile from collections.abc import Iterator from io import BytesIO @@ -13,6 +12,7 @@ from config import ( SCHEDULED_UPDATE_LAUNCHBOX_METADATA_CRON, TASK_TIMEOUT, ) +from handler.dump_cache import encode from handler.metadata import meta_launchbox_handler from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_FILE_FIELDS, @@ -30,7 +30,7 @@ from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_PLATFORMS_KEY, ) from handler.metadata.launchbox_handler.utils import fold_title -from handler.redis_handler import async_cache +from handler.redis_handler import async_binary_cache, async_cache from logger.logger import log from tasks.tasks import RemoteFilePullTask, TaskType from utils.cache import drop_stale_cache_store, stamp_cache_schema @@ -56,7 +56,7 @@ class BatchedCacheWriter: self._queued = 0 async def hset(self, key: str, field: str, value: Any) -> None: - await self._pipe.hset(key, mapping={field: json.dumps(value)}) + await self._pipe.hset(key, mapping={field: encode(value)}) self._queued += 1 if self._queued >= self._batch_size: await self.flush() @@ -159,7 +159,7 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): for file in file_list: if file == "Platforms.xml": with z.open(file, "r") as f: - async with async_cache.pipeline() as pipe: + async with async_binary_cache.pipeline() as pipe: writer = BatchedCacheWriter(pipe) for elem in _iter_elements(f): @@ -178,7 +178,7 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): elif file == "Metadata.xml": with z.open(file, "r") as f: - async with async_cache.pipeline() as pipe: + async with async_binary_cache.pipeline() as pipe: writer = BatchedCacheWriter(pipe) current_game_image_db_id = None @@ -268,7 +268,7 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): elif file == "Mame.xml": with z.open(file, "r") as f: - async with async_cache.pipeline() as pipe: + async with async_binary_cache.pipeline() as pipe: writer = BatchedCacheWriter(pipe) for elem in _iter_elements(f): @@ -292,7 +292,7 @@ class UpdateLaunchboxMetadataTask(RemoteFilePullTask): elif file == "Files.xml": with z.open(file, "r") as f: - async with async_cache.pipeline() as pipe: + async with async_binary_cache.pipeline() as pipe: writer = BatchedCacheWriter(pipe) for elem in _iter_elements(f): diff --git a/backend/tasks/scheduled/update_switch_titledb.py b/backend/tasks/scheduled/update_switch_titledb.py index 7743fa4cb..aa993ff3d 100644 --- a/backend/tasks/scheduled/update_switch_titledb.py +++ b/backend/tasks/scheduled/update_switch_titledb.py @@ -6,7 +6,8 @@ from config import ( ENABLE_SCHEDULED_UPDATE_SWITCH_TITLEDB, SCHEDULED_UPDATE_SWITCH_TITLEDB_CRON, ) -from handler.redis_handler import async_cache +from handler.dump_cache import encode +from handler.redis_handler import async_binary_cache, async_cache from logger.logger import log from tasks.tasks import RemoteFilePullTask, TaskType from utils.cache import ( @@ -20,9 +21,10 @@ 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=1, + version=2, keys=(SWITCH_TITLEDB_INDEX_KEY, SWITCH_PRODUCT_ID_KEY), ) @@ -58,16 +60,16 @@ class UpdateSwitchTitleDBTask(RemoteFilePullTask): # Update initial progress update_stats.update(processed=processed_items, total=total_items) - async with async_cache.pipeline() as pipe: + 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: json.dumps(v) for title_id, v in data_batch}, + mapping={title_id: encode(v) for title_id, v in data_batch}, ) # A second copy of each entry here costs ~60MB of cache. product_map = { - v["id"]: json.dumps(title_id) + v["id"]: encode(title_id) for title_id, v in data_batch if v.get("id") } diff --git a/backend/tests/handler/metadata/test_launchbox_handler.py b/backend/tests/handler/metadata/test_launchbox_handler.py index ff0fc3c72..56a6b6bc2 100644 --- a/backend/tests/handler/metadata/test_launchbox_handler.py +++ b/backend/tests/handler/metadata/test_launchbox_handler.py @@ -18,6 +18,7 @@ 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.metadata.launchbox_handler.handler import LaunchboxHandler from handler.metadata.launchbox_handler.local_source import LocalSource from handler.metadata.launchbox_handler.media import ( @@ -641,6 +642,26 @@ class TestRemoteSourceGetRom: ) assert result is None + async def test_reads_a_compressed_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 + ) + 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"} diff --git a/backend/tests/handler/test_dump_cache.py b/backend/tests/handler/test_dump_cache.py new file mode 100644 index 000000000..b1b7670f8 --- /dev/null +++ b/backend/tests/handler/test_dump_cache.py @@ -0,0 +1,77 @@ +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" + + +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) + + +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_store_written_before_compression(self): + """An existing store holds plain JSON, so it has to keep answering.""" + legacy = json.dumps(BIG_RECORD).encode() + + assert decode(legacy) == BIG_RECORD + + def test_reads_a_value_handed_over_as_text(self): + """`fakeredis` and a decoding client both hand back `str`.""" + assert decode(json.dumps(BIG_RECORD)) == BIG_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/tasks/test_update_launchbox_metadata.py b/backend/tests/tasks/test_update_launchbox_metadata.py index 219f77392..d3ae2afad 100644 --- a/backend/tests/tasks/test_update_launchbox_metadata.py +++ b/backend/tests/tasks/test_update_launchbox_metadata.py @@ -1,4 +1,3 @@ -import json import os from typing import Any from unittest.mock import AsyncMock, patch @@ -7,6 +6,7 @@ import anyio import pytest from config import TASK_TIMEOUT +from handler.dump_cache import decode from handler.metadata.launchbox_handler.handler import LaunchboxHandler from handler.metadata.launchbox_handler.types import ( LAUNCHBOX_FILES_KEY, @@ -123,7 +123,7 @@ class TestUpdateLaunchboxMetadataTask: ) @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_launchbox_metadata.async_cache.pipeline") + @patch("tasks.scheduled.update_launchbox_metadata.async_binary_cache.pipeline") async def test_xml_parsing( self, mock_async_cache_pipeline, @@ -215,9 +215,7 @@ class TestUpdateLaunchboxMetadataTask: def values(calls) -> list[Any]: return [ - json.loads(value) - for call in calls - for value in call[1]["mapping"].values() + decode(value) for call in calls for value in call[1]["mapping"].values() ] # The title indexes point at the record, rather than repeating it. @@ -246,7 +244,7 @@ class TestUpdateLaunchboxMetadataTask: ] @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_launchbox_metadata.async_cache.pipeline") + @patch("tasks.scheduled.update_launchbox_metadata.async_binary_cache.pipeline") async def test_empty_xml_elements_handling( self, mock_async_cache_pipeline, @@ -285,7 +283,7 @@ class TestUpdateLaunchboxMetadataTask: assert len(platform_calls) == 1 @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_launchbox_metadata.async_cache.pipeline") + @patch("tasks.scheduled.update_launchbox_metadata.async_binary_cache.pipeline") async def test_missing_xml_files_handling( self, mock_async_cache_pipeline, @@ -345,7 +343,7 @@ class TestUpdateLaunchboxMetadataTaskIntegration: return UpdateLaunchboxMetadataTask() @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_launchbox_metadata.async_cache.pipeline") + @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 ): @@ -412,15 +410,17 @@ class TestBatchedCacheWriter: assert pipe.execute.call_count == 0 - async def test_values_are_json_encoded(self): + 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", {"Name": "Super Mario Bros."}) + await writer.hset("key", "field", record) - pipe.hset.assert_called_once_with( - "key", mapping={"field": '{"Name": "Super Mario Bros."}'} - ) + 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.""" @@ -449,7 +449,7 @@ class TestInitialImportFlag: ready to the provider heartbeat.""" @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_launchbox_metadata.async_cache.pipeline") + @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 ): @@ -475,7 +475,7 @@ class TestInitialImportFlag: mock_delete.assert_awaited_once_with(LAUNCHBOX_METADATA_INITIAL_IMPORT_KEY) @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_launchbox_metadata.async_cache.pipeline") + @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 ): diff --git a/backend/tests/tasks/test_update_switch_titledb.py b/backend/tests/tasks/test_update_switch_titledb.py index 987e1eab5..c30937047 100644 --- a/backend/tests/tasks/test_update_switch_titledb.py +++ b/backend/tests/tasks/test_update_switch_titledb.py @@ -3,6 +3,7 @@ from unittest.mock import AsyncMock, patch import pytest +from handler.dump_cache import decode from tasks.scheduled.update_switch_titledb import ( SWITCH_PRODUCT_ID_KEY, SWITCH_TITLEDB_INDEX_KEY, @@ -63,7 +64,7 @@ class TestUpdateSwitchTitleDBTask: ) @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_switch_titledb.async_cache.pipeline") + @patch("tasks.scheduled.update_switch_titledb.async_binary_cache.pipeline") async def test_run_success( self, mock_async_cache_pipeline, @@ -105,7 +106,7 @@ class TestUpdateSwitchTitleDBTask: assert len(product_calls) > 0 @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_switch_titledb.async_cache.pipeline") + @patch("tasks.scheduled.update_switch_titledb.async_binary_cache.pipeline") async def test_run_filters_empty_data( self, mock_async_cache_pipeline, @@ -137,7 +138,7 @@ class TestUpdateSwitchTitleDBTask: assert key is not None and key != "" @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_switch_titledb.async_cache.pipeline") + @patch("tasks.scheduled.update_switch_titledb.async_binary_cache.pipeline") async def test_run_batches_data( self, mock_async_cache_pipeline, @@ -179,7 +180,7 @@ class TestUpdateSwitchTitleDBTask: mock_super_run.assert_called_once_with(True) @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_switch_titledb.async_cache.pipeline") + @patch("tasks.scheduled.update_switch_titledb.async_binary_cache.pipeline") async def test_run_invalid_json( self, mock_async_cache_pipeline, @@ -193,7 +194,7 @@ class TestUpdateSwitchTitleDBTask: await task.run(force=True) @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_switch_titledb.async_cache.pipeline") + @patch("tasks.scheduled.update_switch_titledb.async_binary_cache.pipeline") async def test_run_empty_json( self, mock_async_cache_pipeline, @@ -214,7 +215,7 @@ class TestUpdateSwitchTitleDBTask: assert mock_pipe.execute.called @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_switch_titledb.async_cache.pipeline") + @patch("tasks.scheduled.update_switch_titledb.async_binary_cache.pipeline") async def test_product_id_mapping( self, mock_async_cache_pipeline, @@ -235,7 +236,7 @@ class TestUpdateSwitchTitleDBTask: hset_calls = mock_pipe.hset.call_args_list product_mapping = { - product_id: json.loads(raw) + 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() @@ -248,7 +249,7 @@ class TestUpdateSwitchTitleDBTask: } @patch.object(RemoteFilePullTask, "run") - @patch("tasks.scheduled.update_switch_titledb.async_cache.pipeline") + @patch("tasks.scheduled.update_switch_titledb.async_binary_cache.pipeline") @patch("tasks.scheduled.update_switch_titledb.log") async def test_completion_log( self, diff --git a/backend/tools/measure_dump_cache.py b/backend/tools/measure_dump_cache.py new file mode 100644 index 000000000..625e34fe5 --- /dev/null +++ b/backend/tools/measure_dump_cache.py @@ -0,0 +1,498 @@ +"""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 pathlib import Path +from typing import Any, Final + +import redis +from defusedxml import ElementTree as ET + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from handler.dump_cache import COMPRESS_MIN_BYTES, decode, encode # noqa: E402 + +# Mirrors LAUNCHBOX_METADATA_STORE.keys and SWITCH_TITLEDB_STORE.keys, whose +# modules need the app to import. 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`, whose module needs +# the app to 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`, whose module needs the app.""" + 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 a tool cannot import the task without the app. +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} + 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) -> tuple[int, int]: + """Drop only this tool's stores, returning `used_memory` and RSS 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) + info = client.info("memory") + return int(info["used_memory"]), int(info["used_memory_rss"]) + + +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: + """Total stored bytes at each candidate COMPRESS_MIN_BYTES, on real records.""" + import zstandard + + from handler.dump_cache import COMPRESSION_LEVEL + + compressor = zstandard.ZstdCompressor(level=COMPRESSION_LEVEL) + sample: list[bytes] = [] + for _, _, value in iter_launchbox(metadata_zip): + sample.append(plain(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)) + 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 = 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, serialize in passes: + base_used, _ = clear_stores(client) + start = time.perf_counter() + load(client, records(), serialize) + 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())