From 75e8a9efaee4b236b857770f1ab2d5db4969396e Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi <3247106+gantoine@users.noreply.github.com> Date: Wed, 7 Oct 2026 14:37:36 -0400 Subject: [PATCH] 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) * 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) * 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) * 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) * 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) * 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) * 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) * 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) * 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) * 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) --------- Co-authored-by: Claude Opus 5.5 (1M context) --- .../0149_roms_fs_name_no_ext_index.py | 27 +++ backend/endpoints/auth.py | 5 +- backend/endpoints/saves.py | 6 +- backend/endpoints/sync/retroarch.py | 195 +++++++++++------- backend/handler/auth/hybrid_auth.py | 20 +- backend/handler/database/saves_handler.py | 7 + backend/handler/sync/retroarch/psp.py | 24 ++- .../handler/sync/retroarch/sync_handler.py | 6 +- backend/models/rom.py | 1 + backend/tests/endpoints/test_oauth.py | 33 +++ backend/tests/endpoints/test_saves.py | 26 ++- .../tests/endpoints/test_sync_retroarch.py | 54 +++++ backend/tests/handler/auth/test_auth.py | 34 +++ .../handler/database/test_saves_handler.py | 67 +++++- .../sync/retroarch/test_sync_handler.py | 32 ++- .../GameDetails/SaveDataTab.test.ts | 55 ++++- .../v2/components/GameDetails/SaveDataTab.vue | 19 +- .../GameDetails/UploadAssetDialog.test.ts | 37 +++- .../GameDetails/UploadAssetDialog.vue | 22 +- 19 files changed, 542 insertions(+), 128 deletions(-) create mode 100644 backend/alembic/versions/0149_roms_fs_name_no_ext_index.py diff --git a/backend/alembic/versions/0149_roms_fs_name_no_ext_index.py b/backend/alembic/versions/0149_roms_fs_name_no_ext_index.py new file mode 100644 index 000000000..37a0d0898 --- /dev/null +++ b/backend/alembic/versions/0149_roms_fs_name_no_ext_index.py @@ -0,0 +1,27 @@ +"""Index `roms.fs_name_no_ext` for RetroArch Cloud Sync's ROM lookup + +Revision ID: 0149_roms_fs_name_no_ext_index +Revises: 0148_rom_age_limits +Create Date: 2026-10-06 00:00:00.000000 + +""" + +from alembic import op + +# revision identifiers, used by Alembic. +revision = "0149_roms_fs_name_no_ext_index" +down_revision = "0148_rom_age_limits" +branch_labels = None +depends_on = None + +INDEX_NAME = "idx_roms_fs_name_no_ext" + + +def upgrade() -> None: + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.create_index(INDEX_NAME, ["fs_name_no_ext"], if_not_exists=True) + + +def downgrade() -> None: + with op.batch_alter_table("roms", schema=None) as batch_op: + batch_op.drop_index(INDEX_NAME, if_exists=True) diff --git a/backend/endpoints/auth.py b/backend/endpoints/auth.py index c7b0b75a6..4db1ffd72 100644 --- a/backend/endpoints/auth.py +++ b/backend/endpoints/auth.py @@ -1,3 +1,4 @@ +import asyncio from datetime import datetime, timedelta, timezone from typing import Annotated, Final, Literal, Optional, cast from urllib.parse import urlencode @@ -264,7 +265,9 @@ async def token( detail="Missing username or password", ) - user = auth_handler.authenticate_user(form_data.username, form_data.password) + user = await asyncio.to_thread( + auth_handler.authenticate_user, form_data.username, form_data.password + ) if not user: _record_login_failure(request, form_data.username, "token", "credentials") raise HTTPException( diff --git a/backend/endpoints/saves.py b/backend/endpoints/saves.py index 21beee514..ab40cdf80 100644 --- a/backend/endpoints/saves.py +++ b/backend/endpoints/saves.py @@ -271,7 +271,11 @@ async def add_save( ) db_save = db_save_handler.get_save_by_filename( - user_id=request.user.id, rom_id=rom.id, file_name=actual_filename, slot=slot + user_id=request.user.id, + rom_id=rom.id, + file_name=actual_filename, + emulator=emulator, + slot=slot, ) if device and slot and not overwrite: diff --git a/backend/endpoints/sync/retroarch.py b/backend/endpoints/sync/retroarch.py index 4bf52055e..d19a4378e 100644 --- a/backend/endpoints/sync/retroarch.py +++ b/backend/endpoints/sync/retroarch.py @@ -1,5 +1,6 @@ """WebDAV surface for RetroArch Cloud Sync, plus read-only browsing for generic clients.""" +import asyncio import os import uuid from collections.abc import AsyncIterator, Callable @@ -121,15 +122,24 @@ def _can_read_roms(request: Request) -> bool: def _rom_visibility(request: Request) -> Callable[[Rom], bool]: - return get_permissions(request).can_see_rom + # Permissions are resolved on first use, which every caller makes in a thread. + return lambda rom: get_permissions(request).can_see_rom(rom) -def _resolve_rom(request: Request, kind: AssetKind, file_name: str) -> Rom | None: +async def _resolve_rom(request: Request, kind: AssetKind, file_name: str) -> Rom | None: game_name = sync_handler.game_name_from_file_name(kind, file_name) - return sync_handler.resolve_rom(game_name, _rom_visibility(request)) + return await asyncio.to_thread( + sync_handler.resolve_rom, game_name, _rom_visibility(request) + ) -def _get_asset( +async def _get_asset( + user: User, rom: Rom, parsed: RetroArchSyncPath +) -> Save | State | Screenshot | None: + return await asyncio.to_thread(_find_asset, user, rom, parsed) + + +def _find_asset( user: User, rom: Rom, parsed: RetroArchSyncPath ) -> Save | State | Screenshot | None: if parsed.is_state_screenshot: @@ -155,6 +165,12 @@ def _get_asset( ) +def _find_rom_file( + request: Request, slug: str, file_name: str +) -> browser.RomFile | None: + return browser.find_rom_file(slug, file_name, get_permissions(request)) + + def _serve(handler: FSHandler, path: str, filename: str) -> Response: try: resolved_path = handler.validate_path(path) @@ -228,7 +244,6 @@ async def retroarch_sync_propfind(request: Request, file_path: str) -> Response: return denied depth = 0 if request.headers.get("depth") == "0" else 1 - permissions = get_permissions(request) parts = sync_handler.split_segments(file_path) if parts is None: return _empty(status.HTTP_404_NOT_FOUND) @@ -244,17 +259,8 @@ async def retroarch_sync_propfind(request: Request, file_path: str) -> Response: entries.append(_collection_entry("roms")) if not request.user.is_kiosk_guest: entries += [_collection_entry("saves"), _collection_entry("states")] - elif parts == ["roms"]: - entries = [_collection_entry("roms")] - if depth != 0: - entries += [ - _collection_entry(f"roms/{p.fs_slug}", p.name) - for p in browser.list_platforms(permissions) - ] - elif len(parts) == 2 and parts[0] == "roms": - entries = _platform_listing(parts[1], depth, permissions) - elif len(parts) == 3 and parts[0] == "roms": - entries = _rom_file_entry(parts[1], parts[2], permissions) + elif parts[0] == "roms": + entries = await asyncio.to_thread(_roms_listing, request, parts, depth) elif parts[0] in ("saves", "states"): entries = await _save_state_listing( parts, depth, request.user, _rom_visibility(request) @@ -274,6 +280,25 @@ async def retroarch_sync_propfind(request: Request, file_path: str) -> Response: ) +def _roms_listing( + request: Request, parts: list[str], depth: int +) -> list[browser.PropfindEntry] | None: + permissions = get_permissions(request) + if len(parts) == 1: + entries = [_collection_entry("roms")] + if depth != 0: + entries += [ + _collection_entry(f"roms/{p.fs_slug}", p.name) + for p in browser.list_platforms(permissions) + ] + return entries + if len(parts) == 2: + return _platform_listing(parts[1], depth, permissions) + if len(parts) == 3: + return _rom_file_entry(parts[1], parts[2], permissions) + return None + + def _collection_entry( path: str, display_name: str | None = None ) -> browser.PropfindEntry: @@ -377,7 +402,7 @@ async def retroarch_sync_get(request: Request, file_path: str) -> Response: return denied if file_path.strip("/") == MANIFEST_FILE_NAME: - touch_retroarch_device(request.user) + await asyncio.to_thread(touch_retroarch_device, request.user) manifest = await sync_handler.build_manifest( request.user, _rom_visibility(request) ) @@ -405,8 +430,8 @@ async def retroarch_sync_get(request: Request, file_path: str) -> Response: if not _can_read_roms(request): return _empty(status.HTTP_403_FORBIDDEN) - file = browser.find_rom_file( - rom_parts[1], rom_parts[2], get_permissions(request) + file = await asyncio.to_thread( + _find_rom_file, request, rom_parts[1], rom_parts[2] ) if not file: return _empty(status.HTTP_404_NOT_FOUND) @@ -422,11 +447,11 @@ async def retroarch_sync_get(request: Request, file_path: str) -> Response: if not parsed: return _empty(status.HTTP_404_NOT_FOUND) - rom = _resolve_rom(request, parsed.kind, parsed.file_name) + rom = await _resolve_rom(request, parsed.kind, parsed.file_name) if not rom: return _empty(status.HTTP_404_NOT_FOUND) - asset = _get_asset(request.user, rom, parsed) + asset = await _get_asset(request.user, rom, parsed) if not asset: return _empty(status.HTTP_404_NOT_FOUND) @@ -499,7 +524,7 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response: except ValueError: return _empty(status.HTTP_409_CONFLICT) - rom = _resolve_rom(request, parsed.kind, file_name) + rom = await _resolve_rom(request, parsed.kind, file_name) if not rom: log.warning(f"Cloud sync upload {hl(file_path)} matches no ROM in the library") return _empty(status.HTTP_409_CONFLICT) @@ -509,7 +534,8 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response: if parsed.is_state_screenshot: # Written under the owning state's real name, which may differ from the # canonical one, so an existing screenshot is updated rather than forked. - owning_state = sync_handler.resolve_state_by_slot( + owning_state = await asyncio.to_thread( + sync_handler.resolve_state_by_slot, request.user, rom, parsed.emulator, @@ -538,31 +564,17 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response: rom_id=rom.id, emulator=parsed.emulator, ) - existing_screenshot = next( - ( - shot - for shot in db_screenshot_handler.get_screenshots( - user_id=request.user.id, rom_ids={rom.id} - ) - if shot.file_name == screenshot_file_name - and shot.file_path == screenshot_path - ), - None, + created = await asyncio.to_thread( + _record_screenshot, + request.user, + rom, + scanned_screenshot, + screenshot_file_name, + screenshot_path, + ) + return _empty( + status.HTTP_201_CREATED if created else status.HTTP_204_NO_CONTENT ) - if existing_screenshot: - db_screenshot_handler.update_screenshot( - existing_screenshot.id, - { - "file_size_bytes": scanned_screenshot.file_size_bytes, - "missing_from_fs": False, - }, - ) - return _empty(status.HTTP_204_NO_CONTENT) - - scanned_screenshot.rom_id = rom.id - scanned_screenshot.user_id = request.user.id - db_screenshot_handler.add_screenshot(screenshot=scanned_screenshot) - return _empty(status.HTTP_201_CREATED) asset_path = sync_handler.build_asset_file_path( request.user, rom, parsed.kind, parsed.emulator @@ -570,7 +582,7 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response: # A state resolved by slot may have its own file name; writing to it keeps # the row pointing at the fresh bytes instead of orphaning them. - existing = _get_asset(request.user, rom, parsed) + existing = await _get_asset(request.user, rom, parsed) write_file_name = existing.file_name if existing else file_name replaced_hash = ( await fs_asset_handler.unrecorded_hash(existing) @@ -591,9 +603,57 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response: rom_id=rom.id, emulator=parsed.emulator, ) + await asyncio.to_thread( + _record_asset, request.user, rom, parsed, existing, scanned, replaced_hash + ) + # The row moves with the bytes when it was filed elsewhere, e.g. under the + # ROM's previous platform folder. + if existing and existing.file_path != scanned.file_path: + with suppress(FileNotFoundError): + await fs_asset_handler.remove_file(file_path=existing.full_path) + + # `last_played` is left alone on purpose: a first sync uploads the whole + # backlog at once, which would stamp every game as just-played. + return _empty(status.HTTP_204_NO_CONTENT if existing else status.HTTP_201_CREATED) + + +def _record_screenshot( + user: User, rom: Rom, scanned: Screenshot, file_name: str, file_path: str +) -> bool: + """Upsert a state screenshot's row, returning whether it was created.""" + existing = next( + ( + shot + for shot in db_screenshot_handler.get_screenshots( + user_id=user.id, rom_ids={rom.id} + ) + if shot.file_name == file_name and shot.file_path == file_path + ), + None, + ) + if existing: + db_screenshot_handler.update_screenshot( + existing.id, + {"file_size_bytes": scanned.file_size_bytes, "missing_from_fs": False}, + ) + return False + + scanned.rom_id = rom.id + scanned.user_id = user.id + db_screenshot_handler.add_screenshot(screenshot=scanned) + return True + + +def _record_asset( + user: User, + rom: Rom, + parsed: RetroArchSyncPath, + existing: Save | State | Screenshot | None, + scanned: Save | State, + replaced_hash: str | None, +) -> None: + """Point the existing row at the freshly written bytes, or add a new one.""" if existing: - # The row moves with the bytes when it was filed elsewhere, e.g. under - # the ROM's previous platform folder. fields = { "file_size_bytes": scanned.file_size_bytes, "file_path": scanned.file_path, @@ -607,21 +667,15 @@ async def retroarch_sync_put(request: Request, file_path: str) -> Response: ) else: db_state_handler.update_state(existing.id, fields) - if existing.file_path != scanned.file_path: - with suppress(FileNotFoundError): - await fs_asset_handler.remove_file(file_path=existing.full_path) - else: - scanned.rom_id = rom.id - scanned.user_id = request.user.id - scanned.emulator = parsed.emulator - if isinstance(scanned, Save): - db_save_handler.add_save(save=scanned) - else: - db_state_handler.add_state(state=scanned) + return - # `last_played` is left alone on purpose: a first sync uploads the whole - # backlog at once, which would stamp every game as just-played. - return _empty(status.HTTP_204_NO_CONTENT if existing else status.HTTP_201_CREATED) + scanned.rom_id = rom.id + scanned.user_id = user.id + scanned.emulator = parsed.emulator + if isinstance(scanned, Save): + db_save_handler.add_save(save=scanned) + else: + db_state_handler.add_state(state=scanned) @router.api_route( @@ -656,24 +710,25 @@ async def retroarch_sync_delete(request: Request, file_path: str) -> Response: if not parsed: return _empty(status.HTTP_404_NOT_FOUND) - rom = _resolve_rom(request, parsed.kind, parsed.file_name) + rom = await _resolve_rom(request, parsed.kind, parsed.file_name) if not rom: return _empty(status.HTTP_404_NOT_FOUND) - asset = _get_asset(request.user, rom, parsed) + asset = await _get_asset(request.user, rom, parsed) if not asset: return _empty(status.HTTP_404_NOT_FOUND) log.info(f"Cloud sync delete {hl(asset.file_name)} [{rom.platform_slug}]") if isinstance(asset, Screenshot): - db_screenshot_handler.delete_screenshot(asset.id) + await asyncio.to_thread(db_screenshot_handler.delete_screenshot, asset.id) elif isinstance(asset, Save): - db_save_handler.delete_save( - asset.id, content_hash=await fs_asset_handler.unrecorded_hash(asset) + content_hash = await fs_asset_handler.unrecorded_hash(asset) + await asyncio.to_thread( + db_save_handler.delete_save, asset.id, content_hash=content_hash ) else: - db_state_handler.delete_state(asset.id) + await asyncio.to_thread(db_state_handler.delete_state, asset.id) with suppress(FileNotFoundError): await fs_asset_handler.remove_file(file_path=asset.full_path) diff --git a/backend/handler/auth/hybrid_auth.py b/backend/handler/auth/hybrid_auth.py index c95bdc050..00770bb02 100644 --- a/backend/handler/auth/hybrid_auth.py +++ b/backend/handler/auth/hybrid_auth.py @@ -1,3 +1,4 @@ +import asyncio from datetime import datetime, timezone from typing import NamedTuple @@ -49,6 +50,16 @@ def resolve_client_token(raw_token: str) -> ClientTokenIdentity | None: ) +def _basic_auth_user(username: str, password: str) -> User | None: + """The enabled user these credentials belong to, marked active.""" + user = auth_handler.authenticate_user(username, password) + if user is None or not user.enabled: + return None + + user.set_last_active() + return user + + class HybridAuthBackend(AuthenticationBackend): async def authenticate( self, conn: HTTPConnection @@ -77,13 +88,14 @@ class HybridAuthBackend(AuthenticationBackend): if not credentials: return None - user = auth_handler.authenticate_user( - credentials.username, credentials.password + # bcrypt takes ~250ms, which would stall every request on the + # event loop; WebDAV clients send Basic auth on each request. + user = await asyncio.to_thread( + _basic_auth_user, credentials.username, credentials.password ) - if user is None or not user.enabled: + if user is None: return None - user.set_last_active() return (AuthCredentials(user.oauth_scopes), user) # Check if bearer auth header is valid diff --git a/backend/handler/database/saves_handler.py b/backend/handler/database/saves_handler.py index 913bc9e91..c89cf42f6 100644 --- a/backend/handler/database/saves_handler.py +++ b/backend/handler/database/saves_handler.py @@ -74,12 +74,19 @@ class DBSavesHandler(DBBaseHandler): user_id: int, rom_id: int, file_name: str, + emulator: str | None, slot: str | None = None, session: Session = INJECTED_SESSION, ) -> Save | None: query = select(Save).filter_by( rom_id=rom_id, user_id=user_id, file_name=file_name ) + # Another core's save lives in its own folder, so it is a different save. + # Clients that send no core keep matching any, preferring an unfiled one. + if emulator is not None: + query = query.filter(Save.emulator == emulator) + else: + query = query.order_by(Save.emulator.is_(None).desc()) if slot is not None: query = query.filter(Save.slot == slot) else: diff --git a/backend/handler/sync/retroarch/psp.py b/backend/handler/sync/retroarch/psp.py index 9d80fe3ab..00ad199be 100644 --- a/backend/handler/sync/retroarch/psp.py +++ b/backend/handler/sync/retroarch/psp.py @@ -351,7 +351,7 @@ async def _resolve_folder_rom( else: sfo_title = title if isinstance(title, str) else None - rom = _resolve_rom(info.save_folder, sfo_title, can_see) + rom = await asyncio.to_thread(_resolve_rom, info.save_folder, sfo_title, can_see) if rom: return rom @@ -380,7 +380,8 @@ async def _add_bundle( await fs_asset_handler.write_file( file=zip_bytes, path=bundle_path, filename=bundle_name ) - bundle = db_save_handler.add_save( + bundle = await asyncio.to_thread( + db_save_handler.add_save, Save( rom_id=rom.id, user_id=user.id, @@ -390,7 +391,7 @@ async def _add_bundle( content_hash=content_hash_of_bytes(zip_bytes), emulator=info.emulator, slot=None, - ) + ), ) await _cache_member_md5s(bundle, entries) @@ -408,7 +409,9 @@ async def put_psp_file( # place rather than keeping each partial merge as save history. async with _folder_locks[f"{user.id}:{info.save_folder}"]: pending_dir = f"{user.id}/{info.save_folder}" - existing = _find_bundle_by_folder(user, info.save_folder, can_see) + existing = await asyncio.to_thread( + _find_bundle_by_folder, user, info.save_folder, can_see + ) merged: dict[str, bytes] = {} if existing: @@ -449,7 +452,8 @@ async def _rewrite_bundle(bundle: Save, entries: dict[str, bytes]) -> None: await fs_asset_handler.write_file( file=zip_bytes, path=bundle.file_path, filename=bundle.file_name ) - updated = db_save_handler.update_save( + updated = await asyncio.to_thread( + db_save_handler.update_save, bundle.id, { "file_size_bytes": len(zip_bytes), @@ -482,7 +486,9 @@ async def _read_bundle_names(bundle: Save) -> list[str] | None: async def get_psp_file( user: User, info: PspFilePath, can_see: Callable[[Rom], bool] ) -> bytes | None: - bundle = _find_bundle_by_folder(user, info.save_folder, can_see) + bundle = await asyncio.to_thread( + _find_bundle_by_folder, user, info.save_folder, can_see + ) if not bundle: return None entries = await _read_bundle(bundle, {info.file_name}) @@ -494,7 +500,9 @@ async def delete_psp_file( ) -> None: """Drop one member from its folder's bundle, and the bundle once empty.""" async with _folder_locks[f"{user.id}:{info.save_folder}"]: - bundle = _find_bundle_by_folder(user, info.save_folder, can_see) + bundle = await asyncio.to_thread( + _find_bundle_by_folder, user, info.save_folder, can_see + ) if not bundle: return @@ -509,7 +517,7 @@ async def delete_psp_file( await _rewrite_bundle(bundle, entries) return - db_save_handler.delete_save(bundle.id) + await asyncio.to_thread(db_save_handler.delete_save, bundle.id) with suppress(FileNotFoundError): await fs_asset_handler.remove_file(file_path=bundle.full_path) diff --git a/backend/handler/sync/retroarch/sync_handler.py b/backend/handler/sync/retroarch/sync_handler.py index fbe7ac937..efafba091 100644 --- a/backend/handler/sync/retroarch/sync_handler.py +++ b/backend/handler/sync/retroarch/sync_handler.py @@ -475,7 +475,7 @@ 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) + 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) @@ -485,7 +485,9 @@ async def build_manifest( user: User, can_see: Callable[[Rom], bool] ) -> list[dict[str, str]]: """The server manifest RetroArch diffs against, sorted by path.""" - assets, saves = _manifest_assets(user, can_see) + # 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 diff --git a/backend/models/rom.py b/backend/models/rom.py index 6b792dc65..216aeef74 100644 --- a/backend/models/rom.py +++ b/backend/models/rom.py @@ -787,6 +787,7 @@ class Rom(BaseModel): # The digest is opaque to a range scan, so the scan loop's # (platform_id, fs_name) batch lookup needs an index of its own. Index("idx_roms_platform_id_fs_name", "platform_id", "fs_name"), + Index("idx_roms_fs_name_no_ext", "fs_name_no_ext"), # Covers the group_by_meta_id dedup window, which reads only these # columns, so the index has to carry every one of them: a single # missing column (flashpoint_id or fs_name_no_ext, the window's diff --git a/backend/tests/endpoints/test_oauth.py b/backend/tests/endpoints/test_oauth.py index f093adf72..d6d66e631 100644 --- a/backend/tests/endpoints/test_oauth.py +++ b/backend/tests/endpoints/test_oauth.py @@ -1,7 +1,11 @@ +import asyncio + +import pytest from fastapi import status from fastapi.exceptions import HTTPException from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS +from handler.auth.base_handler import auth_handler from handler.auth.constants import EDIT_SCOPES @@ -105,6 +109,35 @@ def test_auth_via_upass(client, admin_user): assert body["expires"] == OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS +def test_auth_via_upass_checks_password_off_event_loop( + client, admin_user, monkeypatch: pytest.MonkeyPatch +): + on_loop: list[bool] = [] + verify_password = auth_handler.verify_password + + def recording_verify_password(plain: str, hashed: str | None) -> bool: + try: + asyncio.get_running_loop() + on_loop.append(True) + except RuntimeError: + on_loop.append(False) + return verify_password(plain, hashed) + + monkeypatch.setattr(auth_handler, "verify_password", recording_verify_password) + + response = client.post( + "/api/token", + data={ + "grant_type": "password", + "username": "test_admin", + "password": "test_admin_password", + }, + ) + + assert response.status_code == status.HTTP_200_OK + assert on_loop == [False] + + def test_auth_via_upass_with_invalid_credentials(client, admin_user): try: client.post( diff --git a/backend/tests/endpoints/test_saves.py b/backend/tests/endpoints/test_saves.py index 5fa89c2ef..0ae6b5a46 100644 --- a/backend/tests/endpoints/test_saves.py +++ b/backend/tests/endpoints/test_saves.py @@ -420,7 +420,7 @@ class TestSaveUploadWithSync: "endpoints.saves.fs_asset_handler.write_file", new_callable=mock.AsyncMock ) @mock.patch("endpoints.saves.scan_save", new_callable=mock.AsyncMock) - def test_reupload_updates_file_path_and_emulator( + def test_reupload_under_another_emulator_keeps_both_saves( self, mock_scan, _mock_write, @@ -431,9 +431,8 @@ class TestSaveUploadWithSync: platform: Platform, admin_user: User, ): - """Re-uploading the same filename under a different emulator must move - the row's file_path/emulator to where the new bytes landed, so the - stored hash never disagrees with the served content.""" + """A same-named upload for another core is a separate save in that + core's folder, so the first core's save is left untouched.""" existing = make_save( rom, admin_user, @@ -470,17 +469,16 @@ class TestSaveUploadWithSync: ) assert response.status_code == status.HTTP_200_OK + assert response.json()["id"] != existing.id + assert response.json()["emulator"] == "new_emu" + assert response.json()["file_path"] == new_path - updated = db_save_handler.get_save(user_id=admin_user.id, id=existing.id) - assert updated is not None - assert updated.file_path == new_path - assert updated.emulator == "new_emu" - assert updated.content_hash == "f" * 32 - assert updated.file_size_bytes == 200 - # full_path now points at the freshly written bytes, not the stale ones. - assert updated.full_path == f"{new_path}/test.sav" - # The orphaned bytes at the old location are cleaned up. - mock_remove.assert_awaited_once_with(f"{platform.slug}/saves/old_emu/test.sav") + kept = db_save_handler.get_save(user_id=admin_user.id, id=existing.id) + assert kept is not None + assert kept.emulator == "old_emu" + assert kept.file_path == f"{platform.slug}/saves/old_emu" + assert kept.content_hash == "0" * 32 + mock_remove.assert_not_awaited() @mock.patch( "endpoints.saves.fs_asset_handler.write_file", new_callable=mock.AsyncMock diff --git a/backend/tests/endpoints/test_sync_retroarch.py b/backend/tests/endpoints/test_sync_retroarch.py index 4c46c1bad..808700881 100644 --- a/backend/tests/endpoints/test_sync_retroarch.py +++ b/backend/tests/endpoints/test_sync_retroarch.py @@ -1,6 +1,8 @@ +import asyncio import hashlib from collections.abc import Sequence from pathlib import Path +from typing import Any from unittest import mock import pytest @@ -696,6 +698,58 @@ class TestRetroArchSyncUpload: assert saves[0].emulator == "snes9x" assert saves[0].slot is None + @mock.patch( + "endpoints.sync.retroarch.fs_asset_handler.write_file", + new_callable=mock.AsyncMock, + ) + @mock.patch("endpoints.sync.retroarch.scan_save", new_callable=mock.AsyncMock) + def test_queries_and_writes_off_the_event_loop( + self, + mock_scan_save: mock.AsyncMock, + _mock_write_file: mock.AsyncMock, + client, + rom: Rom, + saves_path: str, + monkeypatch: pytest.MonkeyPatch, + ): + mock_scan_save.return_value = Save( + file_name="test_rom.srm", + file_path=saves_path, + file_size_bytes=4, + content_hash="8d777f385d3dfec8815d20f7496026dc", + ) + on_loop: dict[str, bool] = {} + + def spy(owner: object, name: str) -> None: + original = getattr(owner, name) + + def recording(*args: Any, **kwargs: Any) -> Any: + try: + asyncio.get_running_loop() + on_loop[name] = True + except RuntimeError: + on_loop[name] = False + return original(*args, **kwargs) + + monkeypatch.setattr(owner, name, recording) + + spy(sync_handler, "resolve_rom") + spy(db_save_handler, "get_save_by_path") + spy(db_save_handler, "add_save") + + response = client.put( + "/api/sync/retroarch/saves/Snes9x/test_rom.srm", + content=b"data", + auth=ADMIN_AUTH, + ) + + assert response.status_code == status.HTTP_201_CREATED + assert on_loop == { + "resolve_rom": False, + "get_save_by_path": False, + "add_save": False, + } + @mock.patch( "endpoints.sync.retroarch.fs_asset_handler.write_file", new_callable=mock.AsyncMock, diff --git a/backend/tests/handler/auth/test_auth.py b/backend/tests/handler/auth/test_auth.py index 20fc3e7ec..15e0ec3c4 100644 --- a/backend/tests/handler/auth/test_auth.py +++ b/backend/tests/handler/auth/test_auth.py @@ -1,3 +1,4 @@ +import threading from base64 import b64encode from datetime import timedelta from typing import Any @@ -227,6 +228,39 @@ async def test_hybrid_auth_backend_basic_auth_header(editor_user: User): assert set(creds.scopes).issubset(editor_user.oauth_scopes) +async def test_hybrid_auth_backend_basic_auth_runs_db_and_bcrypt_off_event_loop( + editor_user: User, monkeypatch: pytest.MonkeyPatch +): + token = b64encode(b"test_editor:test_editor_password").decode() + loop_thread = threading.get_ident() + check_threads: list[int] = [] + active_threads: list[int] = [] + verify_password = auth_handler.verify_password + set_last_active = User.set_last_active + + def recording_verify_password(*args: Any) -> bool: + check_threads.append(threading.get_ident()) + return verify_password(*args) + + def recording_set_last_active(self: User) -> None: + active_threads.append(threading.get_ident()) + set_last_active(self) + + monkeypatch.setattr(auth_handler, "verify_password", recording_verify_password) + monkeypatch.setattr(User, "set_last_active", recording_set_last_active) + + class MockConnection(HTTPConnection): + def __init__(self) -> None: + self.scope: dict[str, dict[str, Any]] = {"session": {}} + self._headers = Headers({"Authorization": f"Basic {token}"}) + + result = await HybridAuthBackend().authenticate(MockConnection()) + + assert result is not None + assert check_threads and loop_thread not in check_threads + assert active_threads and loop_thread not in active_threads + + async def test_hybrid_auth_backend_basic_auth_header_unencoded(editor_user: User): class MockConnection(HTTPConnection): def __init__(self): diff --git a/backend/tests/handler/database/test_saves_handler.py b/backend/tests/handler/database/test_saves_handler.py index ccee72b37..3fdf438a6 100644 --- a/backend/tests/handler/database/test_saves_handler.py +++ b/backend/tests/handler/database/test_saves_handler.py @@ -119,6 +119,7 @@ class TestDBSavesHandlerPlatformFiltering: user_id=admin_user.id, rom_id=rom.id, file_name=save.file_name, + emulator=save.emulator, slot=save.slot, ) @@ -142,7 +143,11 @@ class TestDBSavesHandlerPlatformFiltering: # No null-slot save exists, so a slot-less lookup should find nothing. assert ( db_save_handler.get_save_by_filename( - user_id=admin_user.id, rom_id=rom.id, file_name="shared.sav", slot=None + user_id=admin_user.id, + rom_id=rom.id, + file_name="shared.sav", + emulator="test_emu", + slot=None, ) is None ) @@ -152,6 +157,7 @@ class TestDBSavesHandlerPlatformFiltering: user_id=admin_user.id, rom_id=rom.id, file_name="shared.sav", + emulator="test_emu", slot="Slot A", ) assert found is not None @@ -175,17 +181,74 @@ class TestDBSavesHandlerPlatformFiltering: user_id=admin_user.id, rom_id=rom.id, file_name="shared.sav", + emulator="test_emu", slot="Slot A", ) is None ) found = db_save_handler.get_save_by_filename( - user_id=admin_user.id, rom_id=rom.id, file_name="shared.sav", slot=None + user_id=admin_user.id, + rom_id=rom.id, + file_name="shared.sav", + emulator="test_emu", + slot=None, ) assert found is not None assert found.id == slotless.id + def test_get_save_by_filename_ignores_another_emulators_save( + self, admin_user: User, rom: Rom + ): + mgba = make_save( + rom, admin_user, "shared.sav", emulator="mgba", file_size_bytes=100 + ) + + assert ( + db_save_handler.get_save_by_filename( + user_id=admin_user.id, + rom_id=rom.id, + file_name="shared.sav", + emulator="snes9x", + ) + is None + ) + + found = db_save_handler.get_save_by_filename( + user_id=admin_user.id, + rom_id=rom.id, + file_name="shared.sav", + emulator="mgba", + ) + assert found is not None + assert found.id == mgba.id + + def test_get_save_by_filename_without_emulator_prefers_unfiled_save( + self, admin_user: User, rom: Rom + ): + mgba = make_save( + rom, admin_user, "shared.sav", emulator="mgba", file_size_bytes=100 + ) + + def lookup() -> Save | None: + return db_save_handler.get_save_by_filename( + user_id=admin_user.id, + rom_id=rom.id, + file_name="shared.sav", + emulator=None, + ) + + found = lookup() + assert found is not None + assert found.id == mgba.id + + unfiled = make_save( + rom, admin_user, "shared.sav", emulator=None, file_size_bytes=100 + ) + found = lookup() + assert found is not None + assert found.id == unfiled.id + def test_platform_filtering_with_different_emulators( self, admin_user: User, platform: Platform, rom: Rom ): diff --git a/backend/tests/handler/sync/retroarch/test_sync_handler.py b/backend/tests/handler/sync/retroarch/test_sync_handler.py index d7be3ebd7..df322e0e9 100644 --- a/backend/tests/handler/sync/retroarch/test_sync_handler.py +++ b/backend/tests/handler/sync/retroarch/test_sync_handler.py @@ -1,17 +1,21 @@ import os +import threading from collections.abc import Iterator from pathlib import Path -from typing import cast +from typing import Any, cast from unittest import mock import pytest +from handler.database import db_save_handler from handler.filesystem import fs_asset_handler from handler.filesystem.retroarch_sync_handler import BlobFile, FSRetroArchSyncHandler from handler.redis_handler import async_cache, sync_cache from handler.sync.retroarch.sync_handler import ( HASH_CACHE_TTL_SECONDS, + build_manifest, cached_hashes, + list_manifest_paths, user_blob_path, ) from models.user import User @@ -57,6 +61,32 @@ class TestCachedMd5s: mget.assert_called_once() +class TestManifestQueriesOffEventLoop: + @pytest.fixture + def query_threads(self) -> Iterator[list[int]]: + threads: list[int] = [] + get_saves = db_save_handler.get_saves + + def recording_get_saves(*args: Any, **kwargs: Any) -> Any: + threads.append(threading.get_ident()) + return get_saves(*args, **kwargs) + + with mock.patch.object(db_save_handler, "get_saves", recording_get_saves): + yield threads + + async def test_build_manifest(self, admin_user: User, query_threads: list[int]): + await build_manifest(admin_user, lambda _rom: True) + + assert query_threads and threading.get_ident() not in query_threads + + async def test_list_manifest_paths( + self, admin_user: User, query_threads: list[int] + ): + await list_manifest_paths(admin_user, lambda _rom: True, "saves") + + assert query_threads and threading.get_ident() not in query_threads + + class TestBlobStorageLocation: def test_blobs_live_in_the_users_assets_folder(self, admin_user: User): # The assets root is a documented volume; anything outside it is lost on container recreate. diff --git a/frontend/src/v2/components/GameDetails/SaveDataTab.test.ts b/frontend/src/v2/components/GameDetails/SaveDataTab.test.ts index 5b3c022a1..c38e48b53 100644 --- a/frontend/src/v2/components/GameDetails/SaveDataTab.test.ts +++ b/frontend/src/v2/components/GameDetails/SaveDataTab.test.ts @@ -1,9 +1,11 @@ import { mount } from "@vue/test-utils"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import type { UserStateSchema } from "@/__generated__"; +import type { UserSaveSchema, UserStateSchema } from "@/__generated__"; import storeAuth from "@/stores/auth"; +import { saveFixture, stateFixture } from "@/utils/assets.fixtures"; import { detailedRomFixture } from "@/utils/rom.fixtures"; import { userFixture } from "@/utils/user.fixtures"; +import { toUserSave, toUserState } from "@/v2/utils/saveStates.fixtures"; import SaveDataTab from "./SaveDataTab.vue"; vi.mock("vue-i18n"); @@ -17,8 +19,13 @@ vi.mock("@/v2/composables/useRomSync", () => ({ useRomSync: () => ({ refetchRom: vi.fn() }), })); vi.mock("@/v2/composables/useSnackbar", () => ({ - useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }), + useSnackbar: () => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn() }), })); +const { uploadSaves } = vi.hoisted(() => ({ uploadSaves: vi.fn() })); +vi.mock("@/services/api/save", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, default: { ...actual.default, uploadSaves } }; +}); const UploadAssetDialog = { props: { cores: { type: Array, default: () => [] } }, @@ -26,22 +33,20 @@ const UploadAssetDialog = { }; function state(id: number, emulator: string): UserStateSchema { - return { - id, - user_id: 1, - file_name: `state_${id}.state`, - updated_at: "2026-09-16T10:00:00Z", - emulator, - } as UserStateSchema; + return toUserState(stateFixture({ id, emulator }), "player"); } -function mountTab(states: UserStateSchema[]) { +function save(id: number, emulator: string): UserSaveSchema { + return toUserSave(saveFixture({ id, emulator }), "player"); +} + +function mountTab(states: UserStateSchema[], saves: UserSaveSchema[] = []) { return mount(SaveDataTab, { props: { rom: detailedRomFixture({ id: 1, platform_slug: "ps2", - all_user_saves: [], + all_user_saves: saves, all_user_states: states, }), }, @@ -70,4 +75,32 @@ describe("SaveDataTab upload cores", () => { "play", ]); }); + + it("offers the cores existing saves carry", () => { + const wrapper = mountTab([state(1, "play")], [save(2, "pcsx2")]); + + expect(wrapper.findComponent(UploadAssetDialog).props("cores")).toEqual([ + "pcsx2", + "play", + ]); + }); + + it("files an uploaded save under the picked core", async () => { + uploadSaves.mockResolvedValue([]); + const wrapper = mountTab([]); + const file = new File(["x"], "a.srm"); + + wrapper.findComponent(UploadAssetDialog).vm.$emit("submit", { + type: "save", + files: [file], + slot: null, + emulator: "mgba", + }); + + await vi.waitFor(() => + expect(uploadSaves).toHaveBeenCalledWith( + expect.objectContaining({ emulator: "mgba", slot: undefined }), + ), + ); + }); }); diff --git a/frontend/src/v2/components/GameDetails/SaveDataTab.vue b/frontend/src/v2/components/GameDetails/SaveDataTab.vue index 0c2314299..b5c259652 100644 --- a/frontend/src/v2/components/GameDetails/SaveDataTab.vue +++ b/frontend/src/v2/components/GameDetails/SaveDataTab.vue @@ -119,8 +119,8 @@ const subtabDefs = computed[]>(() => [ ]); // ---------- Upload / refresh plumbing ---------- -// Every upload goes through the dialog, which asks saves for a slot and -// states for a core; dropped files land in it pre-picked. +// Every upload goes through the dialog, which asks saves for a slot and both +// for a core; dropped files land in it pre-picked. const uploadDialog = ref<{ type: AssetType; files: File[] } | null>(null); function openUpload(type: AssetType, files: File[] = []) { uploadDialog.value = { type, files }; @@ -128,7 +128,7 @@ function openUpload(type: AssetType, files: File[] = []) { function closeUpload() { uploadDialog.value = null; } -// The cores the player offers plus whatever the existing states carry, keyed +// The cores the player offers plus whatever the existing files carry, keyed // case-insensitively as the backend matches them. const uploadCores = computed(() => { const cores = new Map(); @@ -136,7 +136,9 @@ const uploadCores = computed(() => { props.rom.platform_slug, configStore.config.EJS_NETPLAY_ENABLED, ); - const carried = myStates.value.map((state) => state.emulator); + const carried = [...mySaves.value, ...myStates.value].map( + (asset) => asset.emulator, + ); for (const core of [...offered, ...carried]) { if (!core || cores.has(emulatorKey(core))) continue; cores.set(emulatorKey(core), core); @@ -150,7 +152,7 @@ async function onUploadSubmit({ emulator, }: UploadAssetPayload) { uploadDialog.value = null; - if (type === "save") await onSaveUpload(files, slot); + if (type === "save") await onSaveUpload(files, slot, emulator); else await onStateUpload(files, emulator); } const uploadingSaves = ref(false); @@ -174,7 +176,11 @@ async function refreshRom() { await refetchRom(props.rom.id); } -async function onSaveUpload(files: File[], slot: string | null) { +async function onSaveUpload( + files: File[], + slot: string | null, + emulator: string | null, +) { if (files.length === 0 || uploadingSaves.value) return; uploadingSaves.value = true; @@ -184,6 +190,7 @@ async function onSaveUpload(files: File[], slot: string | null) { rom: props.rom, savesToUpload: files.map((saveFile) => ({ saveFile })), slot: slot ?? undefined, + emulator: emulator ?? undefined, overwrite: slot !== null, }); const successful = results.filter((r) => r.status === "fulfilled").length; diff --git a/frontend/src/v2/components/GameDetails/UploadAssetDialog.test.ts b/frontend/src/v2/components/GameDetails/UploadAssetDialog.test.ts index c9e7cdd51..901aa1938 100644 --- a/frontend/src/v2/components/GameDetails/UploadAssetDialog.test.ts +++ b/frontend/src/v2/components/GameDetails/UploadAssetDialog.test.ts @@ -168,9 +168,8 @@ describe("UploadAssetDialog", () => { expect(await submitted(wrapper)).toMatchObject({ slot: null }); }); - it("names a new slot and asks saves for nothing else", async () => { + it("names a new slot", async () => { const wrapper = mountDialog("save", [new File(["x"], "a.srm")]); - expect(wrapper.findAll("select")).toHaveLength(1); await choose(wrapper, 0, 0); await wrapper.get("input.slot-name").setValue(" speedrun "); @@ -180,6 +179,40 @@ describe("UploadAssetDialog", () => { }); }); + it("files a save under the picked core and out of the slots", async () => { + const wrapper = mountDialog("save", [new File(["x"], "a.srm")]); + expect(wrapper.findAll("select")).toHaveLength(2); + await choose(wrapper, 1, 1); + + expect(await submitted(wrapper)).toMatchObject({ + type: "save", + slot: null, + emulator: "mgba", + }); + }); + + it("returns to autosave when the core is cleared", async () => { + const wrapper = mountDialog("save", [new File(["x"], "a.srm")]); + await choose(wrapper, 1, 1); + await choose(wrapper, 1, 0); + + expect(await submitted(wrapper)).toMatchObject({ + slot: "autosave", + emulator: null, + }); + }); + + it("keeps a slot picked before the core", async () => { + const wrapper = mountDialog("save", [new File(["x"], "a.srm")]); + await choose(wrapper, 0, 2); + await choose(wrapper, 1, 1); + + expect(await submitted(wrapper)).toMatchObject({ + slot: "main_quest", + emulator: "mgba", + }); + }); + it("does not submit while the form is invalid", async () => { formValid.value = false; const wrapper = mountDialog("save", [new File(["x"], "a.srm")]); diff --git a/frontend/src/v2/components/GameDetails/UploadAssetDialog.vue b/frontend/src/v2/components/GameDetails/UploadAssetDialog.vue index 835d279e2..4ec503f60 100644 --- a/frontend/src/v2/components/GameDetails/UploadAssetDialog.vue +++ b/frontend/src/v2/components/GameDetails/UploadAssetDialog.vue @@ -1,6 +1,6 @@ @@ -159,7 +170,6 @@ async function submit() { autocomplete="off" />