diff --git a/backend/endpoints/sync/retroarch.py b/backend/endpoints/sync/retroarch.py index ce1183f42..025b9cdca 100644 --- a/backend/endpoints/sync/retroarch.py +++ b/backend/endpoints/sync/retroarch.py @@ -327,7 +327,8 @@ def _rom_file_entry( async def _save_state_listing( parts: list[str], depth: int, user: User, can_see: Callable[[Rom], bool] ) -> list[browser.PropfindEntry] | None: - paths = await sync_handler.list_manifest_paths(user, can_see) + tree: AssetKind = "saves" if parts[0] == "saves" else "states" + paths = await sync_handler.list_manifest_paths(user, can_see, tree) clean = "/".join(parts) if clean in paths: diff --git a/backend/handler/filesystem/retroarch_sync_handler.py b/backend/handler/filesystem/retroarch_sync_handler.py index 1524d321f..3e4c30072 100644 --- a/backend/handler/filesystem/retroarch_sync_handler.py +++ b/backend/handler/filesystem/retroarch_sync_handler.py @@ -2,11 +2,12 @@ thumbnails/ and system/.""" import asyncio -import os +import stat from dataclasses import dataclass from pathlib import Path from config import SYNC_RETROARCH_BASE_PATH +from utils.filesystem import iter_files from .base_handler import FSHandler @@ -23,27 +24,20 @@ class BlobFile: def _walk_files(root: Path) -> list[BlobFile]: """Every file under `root`, without descending into symlinked directories.""" files: list[BlobFile] = [] - pending = [""] - while pending: - relative_dir = pending.pop() + for directory, name in iter_files(str(root), recursive=True): + path = directory / name try: - with os.scandir(root / relative_dir) as entries: - for entry in entries: - relative = ( - f"{relative_dir}/{entry.name}" if relative_dir else entry.name - ) - try: - if entry.is_dir(follow_symlinks=False): - pending.append(relative) - elif entry.is_file(): - stat = entry.stat() - files.append( - BlobFile(relative, stat.st_size, stat.st_mtime) - ) - except OSError: - continue + file_stat = path.stat() except OSError: continue + if stat.S_ISREG(file_stat.st_mode): + files.append( + BlobFile( + path.relative_to(root).as_posix(), + file_stat.st_size, + file_stat.st_mtime, + ) + ) return files diff --git a/backend/handler/sync/retroarch/psp.py b/backend/handler/sync/retroarch/psp.py index 920120797..27baa41d0 100644 --- a/backend/handler/sync/retroarch/psp.py +++ b/backend/handler/sync/retroarch/psp.py @@ -15,6 +15,7 @@ from collections import defaultdict from collections.abc import Callable, Collection, Iterable from contextlib import suppress from dataclasses import dataclass +from functools import partial from io import BytesIO from pathlib import Path from typing import Literal @@ -265,6 +266,18 @@ def _exceeds_bundle_limits(member_sizes: Collection[int]) -> bool: ) +def _checked_bundle_infos(zf: zipfile.ZipFile) -> list[zipfile.ZipInfo]: + """The bundle's members, as declared by its central directory. + + Raises: + zipfile.BadZipFile: The bundle exceeds the bundle limits. + """ + infos = zf.infolist() + if _exceeds_bundle_limits([info.file_size for info in infos]): + raise zipfile.BadZipFile("PSP bundle exceeds the size limits") + return infos + + def _load_bundle_entries( path: Path, names: Collection[str] | None = None ) -> dict[str, bytes]: @@ -275,29 +288,23 @@ def _load_bundle_entries( zipfile.BadZipFile: The bundle is corrupt or exceeds the bundle limits. """ with zipfile.ZipFile(path) as zf: - infos = zf.infolist() - if _exceeds_bundle_limits([info.file_size for info in infos]): - raise zipfile.BadZipFile("PSP bundle exceeds the size limits") - # `read` stops at each member's declared size, so the check above holds. + # `read` stops at each member's declared size, so the limit check holds. return { info.filename: zf.read(info) - for info in infos + for info in _checked_bundle_infos(zf) if names is None or info.filename in names } def _load_bundle_member_names(path: Path) -> list[str]: - """The bundle's member names, read from its central directory without inflating. + """The bundle's member names, without inflating any member. Raises: FileNotFoundError: The bundle file is gone. zipfile.BadZipFile: The bundle is corrupt or exceeds the bundle limits. """ with zipfile.ZipFile(path) as zf: - infos = zf.infolist() - if _exceeds_bundle_limits([info.file_size for info in infos]): - raise zipfile.BadZipFile("PSP bundle exceeds the size limits") - return [info.filename for info in infos] + return [info.filename for info in _checked_bundle_infos(zf)] def _write_bundle(entries: dict[str, bytes]) -> bytes: @@ -373,7 +380,7 @@ async def _add_bundle( await fs_asset_handler.write_file( file=zip_bytes, path=bundle_path, filename=bundle_name ) - added = db_save_handler.add_save( + bundle = db_save_handler.add_save( Save( rom_id=rom.id, user_id=user.id, @@ -385,11 +392,7 @@ async def _add_bundle( slot=None, ) ) - # The merged instance keeps the Python-side `updated_at`, which the - # database may store truncated, so the cache key is built from a re-read. - bundle = db_save_handler.get_save(user_id=user.id, id=added.id) - if bundle: - await _prime_member_md5s(bundle, entries) + await _cache_member_md5s(bundle, entries) async def put_psp_file( @@ -454,7 +457,7 @@ async def _rewrite_bundle(bundle: Save, entries: dict[str, bytes]) -> None: "missing_from_fs": False, }, ) - await _prime_member_md5s(updated, entries) + await _cache_member_md5s(updated, entries) async def _read_bundle( @@ -467,6 +470,15 @@ async def _read_bundle( return None +async def _read_bundle_names(bundle: Save) -> list[str] | None: + try: + path = fs_asset_handler.validate_path(bundle.full_path) + return await asyncio.to_thread(_load_bundle_member_names, path) + except (ValueError, FileNotFoundError, zipfile.BadZipFile) as exc: + log.warning(f"Failed to read PSP bundle {hl(bundle.full_path)}: {exc}") + return None + + async def get_psp_file( user: User, info: PspFilePath, can_see: Callable[[Rom], bool] ) -> bytes | None: @@ -505,7 +517,7 @@ async def delete_psp_file( def _member_md5s_cache_key(bundle: Save) -> str: return ( f"romm:retroarch_sync:psp_member_md5s:{bundle.full_path}" - f":{bundle.content_hash}:{bundle.updated_at.timestamp()}" + f":{bundle.content_hash}" ) @@ -516,13 +528,24 @@ def _member_md5s(members: dict[str, bytes]) -> dict[str, str]: } -async def _prime_member_md5s(bundle: Save, members: dict[str, bytes]) -> None: +async def _member_md5s_json(bundle: Save) -> str | None: + members = await _read_bundle(bundle) + if members is None: + return None + return json.dumps(await asyncio.to_thread(_member_md5s, members)) + + +async def _cache_member_md5s(bundle: Save, members: dict[str, bytes]) -> None: """Cache a just-written bundle's member MD5s, so the next manifest skips inflating it.""" + if not bundle.content_hash: + return + + digests = await asyncio.to_thread(_member_md5s, members) # Best effort: the bundle is already written, and a miss is recomputed later. try: await async_cache.set( _member_md5s_cache_key(bundle), - json.dumps(_member_md5s(members)), + json.dumps(digests), ex=sync_handler.HASH_CACHE_TTL_SECONDS, ) except RedisError as exc: @@ -531,20 +554,6 @@ async def _prime_member_md5s(bundle: Save, members: dict[str, bytes]) -> None: ) -async def _bundle_member_md5s(bundle: Save) -> dict[str, str] | None: - """Each member's MD5, cached so a manifest build doesn't inflate every bundle.""" - cached = await async_cache.get(_member_md5s_cache_key(bundle)) - if cached: - return json.loads(cached) - - members = await _read_bundle(bundle) - if members is None: - return None - - await _prime_member_md5s(bundle, members) - return _member_md5s(members) - - def _member_sync_path(bundle: Save, save_folder: str, member_name: str) -> str: return sync_handler.build_retroarch_sync_path( "saves", bundle.emulator, f"PSP/SAVEDATA/{save_folder}/{member_name}" @@ -559,13 +568,9 @@ async def list_psp_member_paths( for save_folder, save in _latest_bundles_by_folder(saves, can_see).items(): if save.missing_from_fs: continue - try: - path = fs_asset_handler.validate_path(save.full_path) - names = await asyncio.to_thread(_load_bundle_member_names, path) - except (ValueError, FileNotFoundError, zipfile.BadZipFile) as exc: - log.warning(f"Failed to read PSP bundle {hl(save.full_path)}: {exc}") - continue - paths += [_member_sync_path(save, save_folder, name) for name in names] + names = await _read_bundle_names(save) + if names is not None: + paths += [_member_sync_path(save, save_folder, name) for name in names] return paths @@ -574,17 +579,31 @@ async def build_psp_manifest_entries( saves: Iterable[Save], can_see: Callable[[Rom], bool] ) -> list[dict[str, str]]: """One manifest entry per bundle member, since RetroArch diffs per file.""" - entries: list[dict[str, str]] = [] - for save_folder, save in _latest_bundles_by_folder(saves, can_see).items(): - if save.missing_from_fs: - continue - digests = await _bundle_member_md5s(save) - if digests is None: - continue + bundles = [ + (save_folder, save) + for save_folder, save in _latest_bundles_by_folder(saves, can_see).items() + if not save.missing_from_fs + ] + # The key is only stable while the row's content hash tracks the bytes. + cached = [(folder, save) for folder, save in bundles if save.content_hash] + uncached = [(folder, save) for folder, save in bundles if not save.content_hash] + results = await sync_handler.cached_md5s( + [ + (_member_md5s_cache_key(save), partial(_member_md5s_json, save)) + for _, save in cached + ] + ) + results += [await _member_md5s_json(save) for _, save in uncached] + entries: list[dict[str, str]] = [] + for (save_folder, save), digests_json in zip( + cached + uncached, results, strict=True + ): + if digests_json is None: + continue entries += [ {"path": _member_sync_path(save, save_folder, name), "hash": digest} - for name, digest in digests.items() + for name, digest in json.loads(digests_json).items() ] return entries diff --git a/backend/handler/sync/retroarch/sync_handler.py b/backend/handler/sync/retroarch/sync_handler.py index 18270db4c..0bce73dec 100644 --- a/backend/handler/sync/retroarch/sync_handler.py +++ b/backend/handler/sync/retroarch/sync_handler.py @@ -10,7 +10,8 @@ from collections import defaultdict from collections.abc import Awaitable, Callable, Collection, Iterable, Sequence from dataclasses import dataclass from datetime import datetime -from typing import Literal, cast +from functools import partial +from typing import Literal, NamedTuple, cast from handler.database import ( db_rom_handler, @@ -19,7 +20,6 @@ from handler.database import ( db_state_handler, ) from handler.filesystem import fs_asset_handler, fs_retroarch_sync_handler -from handler.filesystem.retroarch_sync_handler import BlobFile from handler.redis_handler import async_cache from handler.sync.retroarch import psp from handler.sync.retroarch.emulator_names import ( @@ -314,35 +314,32 @@ async def cached_md5s( return digests +async def _blob_md5(disk_path: str) -> str | None: + try: + return await fs_retroarch_sync_handler.compute_file_md5(disk_path) + except (ValueError, OSError): + return None + + async def build_blob_manifest_entries(user: User) -> list[dict[str, str]]: - blobs: list[tuple[str, str, BlobFile]] = [] + blob_paths: list[str] = [] + jobs: list[tuple[str, Callable[[], Awaitable[str | None]]]] = [] for category in BLOB_CATEGORIES: prefix = user_blob_path(user, category) for blob in await fs_retroarch_sync_handler.list_blob_files(prefix): blob_path = f"{category}/{blob.relative_path}" - blobs.append((blob_path, f"{prefix}/{blob.relative_path}", blob)) - - def compute(disk_path: str) -> Callable[[], Awaitable[str | None]]: - async def md5() -> str | None: - try: - return await fs_retroarch_sync_handler.compute_file_md5(disk_path) - except (ValueError, OSError): - return None - - return md5 - - digests = await cached_md5s( - [ - ( - f"romm:retroarch_sync:blob_md5:{user.id}:{blob_path}:{blob.size}:{blob.mtime}", - compute(disk_path), + blob_paths.append(blob_path) + jobs.append( + ( + f"romm:retroarch_sync:blob_md5:{user.id}:{blob_path}:{blob.size}:{blob.mtime}", + partial(_blob_md5, f"{prefix}/{blob.relative_path}"), + ) ) - for blob_path, disk_path, blob in blobs - ] - ) + + digests = await cached_md5s(jobs) return [ {"path": blob_path, "hash": digest} - for (blob_path, _, _), digest in zip(blobs, digests, strict=True) + for blob_path, digest in zip(blob_paths, digests, strict=True) if digest ] @@ -378,53 +375,47 @@ def _mark_missing_from_fs(asset: Save | State | Screenshot) -> None: db_screenshot_handler.update_screenshot(asset.id, update) +async def _asset_md5(asset: Save | State | Screenshot) -> str | None: + try: + return await fs_asset_handler.compute_file_md5(asset.full_path) + except FileNotFoundError: + _mark_missing_from_fs(asset) + except OSError as exc: + log.debug(f"Failed to compute MD5 for {asset.full_path}: {exc}") + return None + + async def asset_md5s( assets: Sequence[Save | State | Screenshot], ) -> list[str | None]: """Each asset's MD5, or None when unreadable; a vanished file flags its row.""" - - def compute( - asset: Save | State | Screenshot, - ) -> Callable[[], Awaitable[str | None]]: - async def md5() -> str | None: - try: - return await fs_asset_handler.compute_file_md5(asset.full_path) - except FileNotFoundError: - _mark_missing_from_fs(asset) - except OSError as exc: - log.debug(f"Failed to compute MD5 for {asset.full_path}: {exc}") - return None - - return md5 - return await cached_md5s( [ ( f"romm:retroarch_sync:md5:{asset.full_path}" f":{asset.file_size_bytes}:{asset.updated_at.timestamp()}", - compute(asset), + partial(_asset_md5, asset), ) for asset in assets ] ) -@dataclass(frozen=True) -class ManifestAsset: - """A save, state or state screenshot as the manifest lists it.""" - +class ManifestAsset(NamedTuple): path: str asset: Save | State | Screenshot - # A state screenshot is listed only alongside its state. - parent_path: str | None = None def _manifest_assets( - user: User, can_see: Callable[[Rom], bool] + user: User, can_see: Callable[[Rom], bool], tree: AssetKind | None = None ) -> tuple[list[ManifestAsset], list[Save]]: - """The manifest's saves and states, plus the unslotted saves its PSP bundles come from.""" + """The manifest's saves and states (only `tree`'s when given), plus the unslotted saves its PSP bundles come from.""" # Slotted saves are RomM's timestamped history, which no core would load. - saves = db_save_handler.get_saves(user_id=user.id, slot_is_null=True) + saves = ( + db_save_handler.get_saves(user_id=user.id, slot_is_null=True) + if tree != "states" + else [] + ) listed_saves = [ save for save in saves @@ -432,13 +423,17 @@ def _manifest_assets( and can_see(save.rom) and not psp.is_psp_bundle_file_name(save.file_name) ] - listed_states = [ - (emulator, canonical_state_file_name(state.rom, slot_suffix), state) - for (_rom_id, emulator, slot_suffix), state in group_states_by_slot( - db_state_handler.get_states(user_id=user.id) - ).items() - if not state.missing_from_fs and can_see(state.rom) - ] + listed_states = ( + [ + (emulator, canonical_state_file_name(state.rom, slot_suffix), state) + for (_rom_id, emulator, slot_suffix), state in group_states_by_slot( + db_state_handler.get_states(user_id=user.id) + ).items() + if not state.missing_from_fs and can_see(state.rom) + ] + if tree != "saves" + else [] + ) # A path carries no platform, so only the ROM that GET/PUT/DELETE would # resolve it to may claim it; a same-named ROM elsewhere would shadow it. @@ -472,14 +467,16 @@ def _manifest_assets( screenshot = screenshots.get(state.id) if screenshot and not screenshot.missing_from_fs: - assets.append(ManifestAsset(f"{state_path}.png", screenshot, state_path)) + assets.append(ManifestAsset(f"{state_path}.png", screenshot)) return assets, saves -async def list_manifest_paths(user: User, can_see: Callable[[Rom], bool]) -> list[str]: - """The manifest's save and state paths, sorted, without hashing or listing blobs.""" - assets, saves = _manifest_assets(user, can_see) +async def list_manifest_paths( + user: User, can_see: Callable[[Rom], bool], tree: AssetKind +) -> list[str]: + """`tree`'s manifest paths, sorted, without hashing or listing blobs.""" + assets, saves = _manifest_assets(user, can_see, tree) paths = [entry.path for entry in assets] paths += await psp.list_psp_member_paths(saves, can_see) return sorted(paths) @@ -499,7 +496,9 @@ async def build_manifest( entries = [ {"path": entry.path, "hash": digest} for entry, digest in hashed - if entry.parent_path is None or entry.parent_path in hashed_paths + # A state screenshot is listed only alongside its state. + if not isinstance(entry.asset, Screenshot) + or entry.path.removesuffix(".png") in hashed_paths ] entries += await build_blob_manifest_entries(user) entries += await psp.build_psp_manifest_entries(saves, can_see) diff --git a/backend/tests/endpoints/test_sync_retroarch.py b/backend/tests/endpoints/test_sync_retroarch.py index 21e9ff9e8..48b58d3f1 100644 --- a/backend/tests/endpoints/test_sync_retroarch.py +++ b/backend/tests/endpoints/test_sync_retroarch.py @@ -1052,7 +1052,8 @@ class TestRetroArchSyncPsp: self, uploads: int, client, admin_user: User ): members = {"PARAM.SFO": b"sfo", "SAVE.BIN": b"data"} - for name, data in list(members.items())[:uploads]: + uploaded = list(members.items())[:uploads] + for name, data in uploaded: client.put( f"/api/sync/retroarch/saves/PPSSPP/PSP/SAVEDATA/TEST12345DATA0/{name}", content=data, @@ -1072,10 +1073,33 @@ class TestRetroArchSyncPsp: "path": f"saves/PPSSPP/PSP/SAVEDATA/TEST12345DATA0/{name}", "hash": hashlib.md5(data, usedforsecurity=False).hexdigest(), } - for name, data in list(members.items())[:uploads] + for name, data in uploaded ] load_entries.assert_not_called() + def test_manifest_reads_bundle_hashes_without_per_bundle_gets( + self, client, admin_user: User + ): + client.put( + "/api/sync/retroarch/saves/PPSSPP/PSP/SAVEDATA/TEST12345DATA0/SAVE.BIN", + content=b"data", + auth=ADMIN_AUTH, + ) + + with mock.patch.object(psp.async_cache, "get") as get: + response = client.get( + "/api/sync/retroarch/manifest.server", auth=ADMIN_AUTH + ) + + assert response.status_code == status.HTTP_200_OK + assert response.json() == [ + { + "path": "saves/PPSSPP/PSP/SAVEDATA/TEST12345DATA0/SAVE.BIN", + "hash": hashlib.md5(b"data", usedforsecurity=False).hexdigest(), + } + ] + get.assert_not_called() + def test_upload_succeeds_when_priming_the_cache_fails( self, client, admin_user: User ): @@ -1658,3 +1682,29 @@ class TestRetroArchSyncBrowsing: assert "/api/sync/retroarch/states/Snes9x/test_rom.state.png<" in states.text asset_md5s.assert_not_awaited() list_blob_files.assert_not_awaited() + + def test_propfind_builds_only_the_requested_tree( + self, client, admin_user: User, synced_save: Save, synced_state: State + ): + with ( + mock.patch.object( + sync_handler.db_save_handler, + "get_saves", + wraps=sync_handler.db_save_handler.get_saves, + ) as get_saves, + mock.patch.object( + sync_handler.db_state_handler, + "get_states", + wraps=sync_handler.db_state_handler.get_states, + ) as get_states, + ): + client.request( + "PROPFIND", "/api/sync/retroarch/states/Snes9x/", auth=ADMIN_AUTH + ) + get_saves.assert_not_called() + get_states.reset_mock() + + client.request( + "PROPFIND", "/api/sync/retroarch/saves/Snes9x/", auth=ADMIN_AUTH + ) + get_states.assert_not_called() diff --git a/backend/tests/handler/sync/retroarch/test_sync_handler.py b/backend/tests/handler/sync/retroarch/test_sync_handler.py index 41dc21019..89d910523 100644 --- a/backend/tests/handler/sync/retroarch/test_sync_handler.py +++ b/backend/tests/handler/sync/retroarch/test_sync_handler.py @@ -18,18 +18,9 @@ def _clear_cache() -> Iterator[None]: class TestCachedMd5s: - async def test_hits_skip_compute(self): - await async_cache.set("hit", "cached-md5") - compute = mock.AsyncMock(return_value="fresh-md5") + async def test_misses_are_written_back_with_the_ttl(self): + await cached_md5s([("miss", mock.AsyncMock(return_value="fresh-md5"))]) - assert await cached_md5s([("hit", compute)]) == ["cached-md5"] - compute.assert_not_awaited() - - async def test_misses_are_computed_and_cached(self): - compute = mock.AsyncMock(return_value="fresh-md5") - - assert await cached_md5s([("miss", compute)]) == ["fresh-md5"] - compute.assert_awaited_once() assert await async_cache.get("miss") == b"fresh-md5" ttl = await async_cache.ttl("miss") assert 0 < ttl <= HASH_CACHE_TTL_SECONDS @@ -52,14 +43,10 @@ class TestCachedMd5s: async def test_reads_the_cache_in_one_round_trip(self): jobs = [(f"key{i}", mock.AsyncMock(return_value=f"md5-{i}")) for i in range(5)] - with ( - mock.patch.object(async_cache, "mget", wraps=async_cache.mget) as mget, - mock.patch.object(async_cache, "get", wraps=async_cache.get) as get, - ): + with mock.patch.object(async_cache, "mget", wraps=async_cache.mget) as mget: await cached_md5s(jobs) mget.assert_called_once() - get.assert_not_called() @pytest.fixture