diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 7146e551e..13e875b4a 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -13,6 +13,7 @@ import asyncio import json import secrets import time +from dataclasses import dataclass from datetime import datetime, timezone from typing import Annotated, Any, Literal, NamedTuple @@ -505,6 +506,15 @@ async def _reserve_container( ) +@dataclass +class _ClaimUndo: + """What `claim_session` releases if the claim fails before the launch.""" + + session_key: str + session: dict[str, Any] + blank_card_id: int | None = None + + class _ContainerCard(NamedTuple): """What a claim found in the container's own memory-card slot. @@ -518,7 +528,6 @@ class _ContainerCard(NamedTuple): async def _probe_container_card( container: ResolvedContainer, - session: dict[str, Any], card_import: Literal["adopt", "discard"] | None, ) -> _ContainerCard: """Read the card a container still holds, prompting when nobody has said @@ -528,8 +537,8 @@ async def _probe_container_card( on a hunch. Probe once, then the caller records the answer so this never interrupts a claim again. Probed only by the claim winner, so a user who loses the race gets the 409 rather than a prompt describing the card of the - player currently on the container. Every exit from here that is not a - started session releases the claim, so an abandoned dialog leaves no trace. + player currently on the container. The caller releases the claim on any + raise, so an abandoned dialog leaves no trace. """ if ( not container.memory_card_sync @@ -546,7 +555,6 @@ async def _probe_container_card( log.warning("could not read the container memory card, %s", exc) if card_import == "discard": return _ContainerCard(undecided=True) - await lifecycle.abort_claim(container.key, session) if card_import is None: raise HTTPException( status_code=428, @@ -564,12 +572,10 @@ async def _probe_container_card( # The slot is empty now, so the import the user asked for cannot # happen. Abort without recording so the prompt fires again. log.warning("adopt requested but the container slot is empty") - await lifecycle.abort_claim(container.key, session) raise HTTPException( status_code=502, detail=memory_cards.CARD_IMPORT_FAILED_DETAIL ) if content is not None and card_import is None: - await lifecycle.abort_claim(container.key, session) raise HTTPException( status_code=428, detail=MemoryCardImportRequired( @@ -586,27 +592,22 @@ async def _probe_container_card( async def _settle_memory_card( request: Request, container: ResolvedContainer, - session: dict[str, Any], + undo: _ClaimUndo, card: MemoryCard | None, rom: Rom, probe: _ContainerCard, -) -> tuple[MemoryCard | None, int | None]: - """The card this session mounts, plus the id of a blank the claim created. - - Returns (card, blank id). The blank is made only now, so a lost race (409) - never leaves an orphan card behind; if a later step aborts the claim, that - id is what deletes it again. - """ +) -> MemoryCard | None: + """Return the card this session mounts.""" if not container.memory_card_sync: - return card, None + return card - created_blank_card_id: int | None = None if card is None: + # Made only after the claim is won, so a lost race (409) leaves no orphan. card = memory_cards.create_blank_card( request.user.id, container.emulator, rom.platform_id ) - created_blank_card_id = card.id - session["memory_card_id"] = card.id + undo.blank_card_id = card.id + undo.session["memory_card_id"] = card.id # Through mutate_session, not a plain SET: a force-release landing in # this window deletes the key, and writing it back whole would resurrect # a claim on a container whose emulator is already being stopped. @@ -618,7 +619,7 @@ async def _settle_memory_card( ) if not probe.undecided: - return card, created_blank_card_id + return card # Establish version 1 from the container's own card before hydrate runs, so # the hydrate that follows pushes the adopted card back rather than a blank. @@ -634,7 +635,6 @@ async def _settle_memory_card( # Hydrate would wipe the container next, so a failed import must # abort rather than destroy the card it was asked to keep. log.exception("could not adopt the container memory card") - await lifecycle.abort_claim(container.key, session, created_blank_card_id) raise HTTPException( status_code=502, detail=memory_cards.CARD_IMPORT_FAILED_DETAIL ) from exc @@ -647,7 +647,6 @@ async def _settle_memory_card( log.error( "adopted memory card matched an existing version of card %d", card.id ) - await lifecycle.abort_claim(container.key, session, created_blank_card_id) raise HTTPException( status_code=502, detail=memory_cards.CARD_IMPORT_FAILED_DETAIL ) @@ -657,16 +656,14 @@ async def _settle_memory_card( outcome="adopt" if probe.content is not None else "discard", user_id=request.user.id, ) - return card, created_blank_card_id + return card async def _hydrate_saves( request: Request, container: ResolvedContainer, - session: dict[str, Any], rom: Rom, card: MemoryCard | None, - blank_card_id: int | None, save: Save | None = None, save_foreign: bool = False, import_state: State | None = None, @@ -693,7 +690,6 @@ async def _hydrate_saves( log.exception("memory card hydration failed") hydrated = False if not hydrated: - await lifecycle.abort_claim(container.key, session, blank_card_id) raise HTTPException( status_code=502, detail="Could not prepare the memory card" ) @@ -868,7 +864,7 @@ async def claim_session( container = await _win_container(request, candidates, session, platform) session_key = container.key - card_before_claim = session["memory_card_id"] + undo = _ClaimUndo(session_key, session) try: # An archive-resume container's newest archive carries only the newest capture, # so any other state and save pairing needs the state imported. @@ -923,7 +919,6 @@ async def claim_session( elif save_foreign and (spec is None or not spec.accepts("save")): refusal = "This container cannot restore the picked save" if refusal is not None: - await lifecycle.abort_claim(session_key, session) raise HTTPException(status_code=400, detail=refusal) if resume_foreign: resume_slot = import_slot @@ -947,7 +942,7 @@ async def claim_session( # container these steps can outlast the window after which a claim is stale. claim_hold = asyncio.create_task(hold_session_claim(session_key, session)) try: - probe = await _probe_container_card(container, session, req.card_import) + probe = await _probe_container_card(container, req.card_import) # The player is back in a session, so any note about their previous one # being force-released has served its purpose. Cleared across the whole @@ -957,8 +952,8 @@ async def claim_session( for candidate in candidates: await clear_termination(candidate.key, request.user.id) - memory_card, created_blank_card_id = await _settle_memory_card( - request, container, session, memory_card, rom, probe + memory_card = await _settle_memory_card( + request, container, undo, memory_card, rom, probe ) # Push the resume state before launch so its file is in place when the @@ -977,23 +972,16 @@ async def claim_session( archive_path, state_imported = await _hydrate_saves( request, container, - session, rom, memory_card, - created_blank_card_id, picked_save, save_foreign=save_foreign, import_state=resume_state if resume_via_import else None, ) finally: claim_hold.cancel() - except HTTPException: - # Each refusal above already released the claim with its own context. - raise except BaseException: - # `_settle_memory_card` records a blank it created on the session. - blank_card_id = session["memory_card_id"] if card_before_claim is None else None - await lifecycle.abort_claim(session_key, session, blank_card_id) + await lifecycle.abort_claim(undo.session_key, undo.session, undo.blank_card_id) raise resume_import: launch.ResumeImport = "none" if resume_via_import: @@ -1024,7 +1012,7 @@ async def claim_session( resume_import=resume_import, memory_card_synced=memory_card is not None, multiplayer=multiplayer, - blank_card_id=created_blank_card_id, + blank_card_id=undo.blank_card_id, ) return LaunchingSessionSchema( diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 935839cc0..77a6574cf 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -9090,6 +9090,59 @@ def test_claim_aborts_on_an_unexpected_error_keeps_the_players_card( ] +def test_claim_releases_once_on_an_http_error_from_a_step( + client, access_token, admin_user: User, rom: Rom +): + """A step that raises an HTTPException without releasing anything still frees + the container and its blank card, through a single release.""" + with _streaming(_mc_container_for(rom)): + with ( + patch("handler.streaming.commands.launch") as launch, + patch("handler.streaming.memory_cards.fetch_card", return_value=None), + patch( + "handler.streaming.saves.wait_for_save_pull", + new=AsyncMock(side_effect=HTTPException(status_code=503)), + ), + patch( + "handler.streaming.lifecycle.abort_claim", + new=AsyncMock(wraps=lifecycle.abort_claim), + ) as abort_claim, + _spawns_nothing(), + ): + r = _mc_claim(client, access_token, rom.id) + assert r.status_code == 503 + launch.assert_not_called() + abort_claim.assert_awaited_once() + assert ( + asyncio.run(session_store.get_session(_key_of(_mc_container_for(rom)))) is None + ) + assert db_memory_card_handler.get_cards(admin_user.id, "pcsx2") == [] + + +def test_claim_releases_once_when_card_hydration_fails( + client, access_token, admin_user: User, rom: Rom +): + """A helper's own refusal is released by the claim alone, never twice.""" + with _streaming(_mc_container_for(rom)): + with ( + patch("handler.streaming.commands.launch"), + patch("handler.streaming.memory_cards.fetch_card", return_value=None), + patch( + "handler.streaming.memory_cards.hydrate_card_to_broker", + new=AsyncMock(return_value=False), + ), + patch( + "handler.streaming.lifecycle.abort_claim", + new=AsyncMock(wraps=lifecycle.abort_claim), + ) as abort_claim, + _spawns_nothing(), + ): + r = _mc_claim(client, access_token, rom.id) + assert r.status_code == 502 + abort_claim.assert_awaited_once() + assert db_memory_card_handler.get_cards(admin_user.id, "pcsx2") == [] + + def test_claim_aborted_after_adopt_keeps_the_adopted_card( client, access_token, admin_user: User, rom: Rom ):