Files
romm/backend/handler/sync/retroarch/sync_handler.py
Georges-Antoine Assi 75e8a9efae fix(sync): keep RetroArch Cloud Sync from stalling the event loop (#5171)
* fix(sync): keep RetroArch Cloud Sync from stalling the event loop

Basic auth ran its bcrypt check (~250ms) on the event loop for every
WebDAV request, and the manifest ran its queries there too, so parallel
RetroArch requests queued behind each other. Both now run in a thread.

Cloud Sync resolves every save and state to a ROM by fs_name_no_ext,
which no index led with; 0149 adds one so unmatched uploads fail fast.

The upload dialog now offers a core for saves as well as states, so a
manually uploaded save lands in the core folder RetroArch reads, and its
slot hint says only unslotted saves reach RetroArch.

Refs #5158

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(sync): cover manifest queries running off the event loop

Addresses Greptile review on #5171: trim the 0149 migration docstring to
its summary, annotate the new MockConnection constructor, and add
regression tests that build_manifest and list_manifest_paths query from a
worker thread.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(auth): mark Basic-auth users active off the event loop

pr-ready step 2 (code-review): run the user lookup, password check and
set_last_active in one worker-thread hop, and test that SaveDataTab offers
save cores and forwards the picked core on upload.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(v2): build SaveDataTab test saves and states from shared fixtures

pr-ready step 3 (simplify): replace the hand-cast UserSaveSchema and
UserStateSchema stubs with saveFixture/stateFixture plus toUserSave/toUserState.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(sync): drop restating index comment and type the test spy

pr-ready step 4 (review-polish): remove the comment that only restated
idx_roms_fs_name_no_ext, and type the manifest test's get_saves spy so mypy
passes across the backend.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(auth): check the password grant's credentials off the event loop

The OAuth password grant ran bcrypt (~250ms) on the event loop, stalling
every other request the worker was serving.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): run RetroArch WebDAV database work off the event loop

GET, PUT, DELETE and PROPFIND resolved ROMs, looked up and wrote save,
state and screenshot rows, and listed whole platforms synchronously inside
async handlers; the PSP bundle helpers did the same. Each now runs that
work in a worker thread.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(saves): keep another core's same-named save on upload

A slot-less upload matched an existing save by file name alone, so
uploading game.srm for a second core rewrote the first core's row to the
new folder and deleted its file. The lookup now only matches a save made
with the requested core. Clients that send no core still match any, so
device conflict detection is unchanged, preferring a save filed under no
core.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* feat(v2): file a save picked with a core out of the slots

RetroArch Cloud Sync only lists unslotted saves, so picking a core in the
upload dialog moves an untouched slot from autosave to "No slot", and
clearing the core moves it back. A slot the user picked is kept.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* revert(i18n): restore the original upload slot hint

Picking a core now files a save out of the slots, so the hint no longer
needs to explain RetroArch Cloud Sync.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 14:37:36 -04:00

509 lines
18 KiB
Python

"""Maps RetroArch Cloud Sync's ``<root>/<core>/<file>`` namespace onto RomM's
per-ROM asset storage, and back again for the ``manifest.server`` it diffs."""
from __future__ import annotations
import asyncio
import os
import re
from collections import defaultdict
from collections.abc import Awaitable, Callable, Collection, Iterable, Sequence
from dataclasses import dataclass
from datetime import datetime
from functools import partial
from typing import Literal, NamedTuple
from handler.database import (
db_rom_handler,
db_save_handler,
db_screenshot_handler,
db_state_handler,
)
from handler.filesystem import fs_asset_handler, fs_retroarch_sync_handler
from handler.redis_handler import async_cache
from handler.sync.retroarch import psp
from handler.sync.retroarch.emulator_names import (
to_retroarch_dir_name,
to_romm_emulator,
)
from logger.logger import log
from models.assets import EMULATOR_MAX_LENGTH, Save, Screenshot, State
from models.rom import Rom
from models.user import User
AssetKind = Literal["saves", "states"]
MANIFEST_FILE_NAME = "manifest.server"
ASSET_ROOTS: tuple[AssetKind, ...] = ("saves", "states")
# RetroArch's config/thumbnails/system sync categories belong to no ROM, so
# they're kept as opaque per-user blobs.
BLOB_CATEGORIES = ("config", "thumbnails", "system")
# `<game>.state`, `<game>.state3`, `<game>.state.auto`: the auto suffix makes
# this a two-segment extension, which splitext alone gets wrong.
STATE_SUFFIX_PATTERN = re.compile(r"\.state\d*(?:\.auto)?$", re.IGNORECASE)
# Rehashing every asset on each manifest fetch would read gigabytes. Keys carry
# size and mtime, so a changed file misses the cache instead of going stale.
HASH_CACHE_TTL_SECONDS = 60 * 60 * 24
HASH_CONCURRENCY = 8
@dataclass(frozen=True)
class RetroArchSyncPath:
"""A parsed client-side path, e.g. ``saves/Snes9x/Super Mario World.srm``."""
kind: AssetKind
emulator: str | None
file_name: str
@property
def is_state_screenshot(self) -> bool:
return self.kind == "states" and is_state_screenshot_path(self.file_name)
def split_segments(path: str) -> list[str] | None:
"""A client path's non-empty segments, or None if any is `.`, `..` or holds a NUL."""
segments = [segment for segment in path.strip("/").split("/") if segment]
if any(
segment in (os.curdir, os.pardir) or "\x00" in segment for segment in segments
):
return None
return segments
def emulator_from_dir_name(dir_name: str) -> str | None:
"""RomM's `emulator` for a core folder name, or None if too long to store."""
emulator = to_romm_emulator(dir_name)
return emulator if len(emulator) <= EMULATOR_MAX_LENGTH else None
def parse_retroarch_sync_path(path: str) -> RetroArchSyncPath | None:
"""Parse a ``<root>/[<core>/]<file>`` client path, or None if unsupported."""
segments = split_segments(path)
if segments is None or not 2 <= len(segments) <= 3:
return None
if segments[0] not in ASSET_ROOTS:
return None
kind = segments[0]
emulator = None
if len(segments) == 3:
emulator = emulator_from_dir_name(segments[1])
if emulator is None:
return None
return RetroArchSyncPath(kind=kind, emulator=emulator, file_name=segments[-1])
def is_state_screenshot_path(file_name: str) -> bool:
"""Whether a `states/...` file is the `<state file name>.png` RetroArch syncs."""
return file_name.lower().endswith(".png")
def state_name_of_screenshot(file_name: str) -> str:
"""The state file name a `<state file name>.png` screenshot belongs to."""
return file_name[: -len(".png")]
def game_name_from_file_name(kind: AssetKind, file_name: str) -> str:
"""The ROM file name (minus extension) an asset file belongs to."""
if kind == "states":
base = (
state_name_of_screenshot(file_name)
if is_state_screenshot_path(file_name)
else file_name
)
stripped = STATE_SUFFIX_PATTERN.sub("", base)
if stripped != base:
return stripped
return os.path.splitext(base)[0]
return os.path.splitext(file_name)[0]
def state_slot_suffix(file_name: str) -> str:
"""The RetroArch load slot (``state``, ``state1``, ``state.auto``) a state name ends in."""
match = STATE_SUFFIX_PATTERN.search(file_name)
if match:
return match.group(0)[1:].lower()
return os.path.splitext(file_name)[1][1:].lower()
def recency_key(asset: Save | State) -> tuple[datetime, int]:
"""Recency order, with `id` breaking ties on a shared timestamp."""
return (asset.updated_at, asset.id)
def group_states_by_slot(
states: Iterable[State],
) -> dict[tuple[int, str | None, str], State]:
"""The newest state in each (rom, emulator, slot) bucket."""
latest: dict[tuple[int, str | None, str], State] = {}
for state in states:
key = (state.rom_id, state.emulator, state_slot_suffix(state.file_name))
current = latest.get(key)
if current is None or recency_key(state) > recency_key(current):
latest[key] = state
return latest
def canonical_state_file_name(rom: Rom, slot_suffix: str) -> str:
"""The name RetroArch gives this slot, which the manifest advertises."""
return f"{rom.fs_name_no_ext}.{slot_suffix}"
def resolve_state_by_slot(
user: User, rom: Rom, emulator: str | None, requested_file_name: str
) -> State | None:
"""The newest state in the slot a canonical name points at, whatever its name."""
states = db_state_handler.get_states(user_id=user.id, rom_ids=[rom.id])
key = (rom.id, emulator, state_slot_suffix(requested_file_name))
return group_states_by_slot(states).get(key)
def state_screenshot_dir(user: User, rom: Rom, emulator: str | None) -> str:
"""Per core, so same-named states under two cores keep separate screenshots."""
return fs_asset_handler.build_screenshots_file_path(
user=user,
platform_fs_slug=rom.platform.fs_slug,
rom_id=rom.id,
emulator=emulator,
)
def _match_state_screenshot(
user: User, state: State, screenshots: Iterable[Screenshot]
) -> Screenshot | None:
own_dir = state_screenshot_dir(user, state.rom, state.emulator)
rom_dir = state_screenshot_dir(user, state.rom, None)
candidates = [
s
for s in screenshots
if s.file_path == own_dir or not s.file_path.startswith(f"{rom_dir}/")
]
exact_name = f"{state.file_name}.png"
exact = [s for s in candidates if s.file_name == exact_name]
if exact:
return min(exact, key=lambda s: (s.file_path != own_dir, -s.id))
# `State.screenshot` matches on the name stem, which a RetroArch slot name
# (`<rom>.state1`) shares with every other slot's and gallery shot.
if state.file_name_no_ext == state.rom.fs_name_no_ext:
return None
names = {state.file_name, state.file_name_no_ext}
stem_matches = [
s for s in candidates if s.file_name in names or s.file_name_no_ext in names
]
if not stem_matches:
return None
best = min(
stem_matches, key=lambda s: (s.file_name_no_ext != state.file_name, -s.id)
)
return None if best.is_gallery else best
def state_screenshots(user: User, states: Collection[State]) -> dict[int, Screenshot]:
"""The screenshot synced alongside each of these states, by state id."""
if not states:
return {}
by_rom: defaultdict[int, list[Screenshot]] = defaultdict(list)
for screenshot in db_screenshot_handler.get_screenshots(
user_id=user.id, rom_ids={state.rom_id for state in states}
):
by_rom[screenshot.rom_id].append(screenshot)
matches = {
state.id: _match_state_screenshot(user, state, by_rom[state.rom_id])
for state in states
}
return {state_id: shot for state_id, shot in matches.items() if shot}
def resolve_state_screenshot_by_slot(
user: User, rom: Rom, emulator: str | None, requested_file_name: str
) -> Screenshot | None:
"""The screenshot of the state a ``<slot>.png`` name resolves to."""
state = resolve_state_by_slot(
user, rom, emulator, state_name_of_screenshot(requested_file_name)
)
return state_screenshots(user, [state]).get(state.id) if state else None
def build_retroarch_sync_path(
kind: AssetKind, emulator: str | None, file_name: str
) -> str:
if emulator:
return f"{kind}/{to_retroarch_dir_name(emulator)}/{file_name}"
return f"{kind}/{file_name}"
def build_asset_file_path(
user: User, rom: Rom, kind: AssetKind, emulator: str | None
) -> str:
build_path = (
fs_asset_handler.build_saves_file_path
if kind == "saves"
else fs_asset_handler.build_states_file_path
)
return build_path(
user=user,
platform_fs_slug=rom.platform.fs_slug,
rom_id=rom.id,
emulator=emulator,
)
def parse_retroarch_sync_blob_path(path: str) -> str | None:
"""A blob-category client path as ``category/...``, or None if it isn't one."""
segments = split_segments(path)
if segments is None or len(segments) < 2:
return None
if segments[0] not in BLOB_CATEGORIES:
return None
return "/".join(segments)
def user_blob_path(user: User, blob_path: str) -> str:
"""Where a parsed blob path lives under the assets root, namespaced by user."""
return f"{fs_asset_handler.user_folder_path(user)}/retroarch/{blob_path}"
def _decoded(value: str | bytes | None) -> str | None:
if isinstance(value, bytes):
return value.decode()
return value or None
async def cached_hashes(
jobs: Sequence[tuple[str, Callable[[], Awaitable[str | None]]]],
) -> list[str | None]:
"""Each `(cache key, compute)` job's hash, read in one MGET with misses written back in one pipeline."""
if not jobs:
return []
digests = [
_decoded(value) for value in await async_cache.mget([k for k, _ in jobs])
]
misses = [i for i, digest in enumerate(digests) if digest is None]
semaphore = asyncio.Semaphore(HASH_CONCURRENCY)
async def compute(index: int) -> str | None:
async with semaphore:
return await jobs[index][1]()
computed = await asyncio.gather(*(compute(i) for i in misses))
fresh = {i: digest for i, digest in zip(misses, computed, strict=True) if digest}
if fresh:
async with async_cache.pipeline() as pipe:
for i, digest in fresh.items():
await pipe.set(jobs[i][0], digest, ex=HASH_CACHE_TTL_SECONDS)
await pipe.execute()
for i, digest in fresh.items():
digests[i] = digest
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]]:
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}"
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}"),
)
)
digests = await cached_hashes(jobs)
return [
{"path": blob_path, "hash": digest}
for blob_path, digest in zip(blob_paths, digests, strict=True)
if digest
]
def resolve_roms(
game_names: Iterable[str], can_see: Callable[[Rom], bool]
) -> dict[str, Rom]:
"""The ROM each game name belongs to, the first visible one by id when ambiguous."""
names = set(game_names)
exact: dict[str, Rom] = {}
# MariaDB's default collation matches case-insensitively; PostgreSQL doesn't.
folded: dict[str, Rom] = {}
for rom in db_rom_handler.get_roms_by_fs_names_no_ext(names):
if can_see(rom):
exact.setdefault(rom.fs_name_no_ext, rom)
folded.setdefault(rom.fs_name_no_ext.casefold(), rom)
resolved = {name: exact.get(name) or folded.get(name.casefold()) for name in names}
return {name: rom for name, rom in resolved.items() if rom}
def resolve_rom(game_name: str, can_see: Callable[[Rom], bool]) -> Rom | None:
return resolve_roms([game_name], can_see).get(game_name)
def _mark_missing_from_fs(asset: Save | State | Screenshot) -> None:
update = {"missing_from_fs": True}
if isinstance(asset, Save):
db_save_handler.update_save(asset.id, update)
elif isinstance(asset, State):
db_state_handler.update_state(asset.id, update)
else:
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."""
return await cached_hashes(
[
(
f"romm:retroarch_sync:md5:{asset.full_path}"
f":{asset.file_size_bytes}:{asset.updated_at.timestamp()}",
partial(_asset_md5, asset),
)
for asset in assets
]
)
class ManifestAsset(NamedTuple):
path: str
asset: Save | State | Screenshot
def _manifest_assets(
user: User, can_see: Callable[[Rom], bool], tree: AssetKind | None = None
) -> tuple[list[ManifestAsset], Sequence[Save]]:
"""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)
if tree != "states"
else []
)
listed_saves = [
save
for save in saves
if not save.missing_from_fs
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)
]
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.
owners = resolve_roms(
[game_name_from_file_name("saves", save.file_name) for save in listed_saves]
+ [game_name_from_file_name("states", name) for _, name, _ in listed_states],
can_see,
)
def is_addressable(rom: Rom, kind: AssetKind, file_name: str) -> bool:
owner = owners.get(game_name_from_file_name(kind, file_name))
return owner is not None and owner.id == rom.id
assets = [
ManifestAsset(
build_retroarch_sync_path("saves", save.emulator, save.file_name), save
)
for save in listed_saves
if is_addressable(save.rom, "saves", save.file_name)
]
addressable_states = [
(emulator, file_name, state)
for emulator, file_name, state in listed_states
if is_addressable(state.rom, "states", file_name)
]
screenshots = state_screenshots(user, [state for _, _, state in addressable_states])
for emulator, file_name, state in addressable_states:
state_path = build_retroarch_sync_path("states", emulator, file_name)
assets.append(ManifestAsset(state_path, state))
screenshot = screenshots.get(state.id)
if screenshot and not screenshot.missing_from_fs:
assets.append(ManifestAsset(f"{state_path}.png", screenshot))
return assets, saves
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 = await asyncio.to_thread(_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)
async def build_manifest(
user: User, can_see: Callable[[Rom], bool]
) -> list[dict[str, str]]:
"""The server manifest RetroArch diffs against, sorted by path."""
# Off the event loop: on a large library the queries run for seconds and
# would stall every other request the worker is serving.
assets, saves = await asyncio.to_thread(_manifest_assets, user, can_see)
digests = await asset_md5s([entry.asset for entry in assets])
hashed = [
(entry, digest) for entry, digest in zip(assets, digests, strict=True) if digest
]
hashed_paths = {entry.path for entry, _ in hashed}
entries = [
{"path": entry.path, "hash": digest}
for entry, digest in hashed
# 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)
entries.sort(key=lambda entry: entry["path"])
return entries