diff --git a/backend/endpoints/responses/streaming.py b/backend/endpoints/responses/streaming.py index faa5723e9..12e65fc57 100644 --- a/backend/endpoints/responses/streaming.py +++ b/backend/endpoints/responses/streaming.py @@ -30,11 +30,15 @@ class StreamingContainerSchema(BaseModel): emulator: str supports_memory_cards: bool supports_save_picker: bool + supports_live_states: bool class StreamingConfigSchema(BaseModel): enabled: bool containers: list[StreamingContainerSchema] + emulator_labels: dict[str, str] + """Display name per emulator id, so a save or state tagged with one can be + labelled without a second copy of the map on the frontend.""" class SessionTerminationSchema(BaseModel): @@ -50,6 +54,9 @@ class SessionTerminationSchema(BaseModel): platform: str | None = None rom_id: int | None = None rom_name: str | None = None + container: str | None = None + claimed_at: str | None = None + desktop: bool = False class SessionStatusSchema(BaseModel): @@ -58,6 +65,9 @@ class SessionStatusSchema(BaseModel): extraction_phase: str | None = None """Set while a webstation broker unpacks a pkg or archive, which is the part of a launch long enough that the player needs to see something.""" + host: str | None = None + """The room URL of a launched session, for a tab that missed launch-ready, + reported by the status poll only and left None by a heartbeat.""" termination: SessionTerminationSchema | None = None @@ -78,6 +88,8 @@ class LaunchReadyPayload(BaseModel): platform: str container: str + claimed_at: str + """The claim's stamp, since a re-claim of the same container shares its key.""" host: str resume: bool | None = None """None when no resume was asked for; False means the state could not be @@ -89,6 +101,7 @@ class LaunchFailedPayload(BaseModel): platform: str container: str + claimed_at: str detail: str @@ -97,9 +110,28 @@ class LaunchPhasePayload(BaseModel): platform: str container: str + claimed_at: str phase: str | None = None +class ContainerBusyDetail(BaseModel): + """The 409 body when a claim finds its container held.""" + + message: str + draining: bool + """A previous session is still shutting down, rather than anyone holding it.""" + rom_name: str | None + """The game holding it, None when the caller may not see which.""" + claimed_at: str | None + + +SOCKET_PAYLOADS: tuple[type[BaseModel], ...] = ( + LaunchReadyPayload, + LaunchFailedPayload, + LaunchPhasePayload, +) + + class DesktopSessionSchema(BaseModel): container: str platform: str @@ -117,7 +149,7 @@ class JoinedSessionSchema(BaseModel): class SaveAndExitResponse(BaseModel): - status: Literal["ok"] + status: Literal["ok", "not_found"] saved: bool platform: str released: bool @@ -223,6 +255,9 @@ class AdminContainerSchema(BaseModel): configured: bool """False for a container with no usable broker address: it can never be claimed, and saying so beats listing it as idle.""" + draining: bool = False + """The previous session's exit work is still running, so the container is + held by nobody and about to come free.""" session: ContainerSessionSchema | None = None diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 2523d909b..8c6997979 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -25,6 +25,7 @@ from endpoints.responses.streaming import ( AdminContainersResponse, AdminSessionSchema, AdminSessionsResponse, + ContainerBusyDetail, ContainerSessionSchema, DesktopSessionSchema, ForceReleaseResponse, @@ -77,7 +78,8 @@ from handler.streaming.config import ( container_for_session, containers_by_key, containers_for_platform, - resolve_containers, + emulator_labels, + first_claim_targets, streaming_enabled, ) from handler.streaming.protocol import room_url_on @@ -97,8 +99,11 @@ from handler.streaming.session_store import ( record_termination, refresh_session, release_own_session, + same_claim, session_disc_id, + session_is_desktop, session_is_stale, + session_platform_matches, session_redis_key, set_session_disc, stamp_launched, @@ -167,11 +172,21 @@ class LoadStateRequest(BaseModel): slot: Annotated[int, Field(ge=1, le=MAX_SLOT)] = 1 +CONTAINER_KEY_MAX_LENGTH = 300 +CLAIMED_AT_MAX_LENGTH = 64 + +# A claim is named by its container and the stamp it was taken at. +ContainerQuery = Annotated[ + str | None, Query(alias="container", max_length=CONTAINER_KEY_MAX_LENGTH) +] +ClaimedAtQuery = Annotated[str | None, Query(max_length=CLAIMED_AT_MAX_LENGTH)] + + class DesktopStreamingSessionRequest(BaseModel): # The container to open, named by the key GET /streaming/containers # reports. Named rather than pooled: an admin configuring a container # needs that one, not whichever is free. - container: Annotated[str, Field(min_length=1, max_length=300)] + container: Annotated[str, Field(min_length=1, max_length=CONTAINER_KEY_MAX_LENGTH)] def platform_capabilities(platform: str) -> PlatformCapabilities: @@ -202,9 +217,12 @@ async def _session_status( platform: str, request: Request, candidates: list[ResolvedContainer] | None = None, + *, + include_desktop: bool = False, + claimed_at: str | None = None, ) -> dict[str, Any]: - """Whether the caller holds a session among `candidates` (the platform's first - pool by default), and if not, why it ended. Read-only, so it is safe to poll.""" + """Whether the caller holds this platform's session among `candidates` (its + first pool by default) and, if not, why it ended, read-only so safe to poll.""" if candidates is None: candidates = containers_for_platform(platform) if not candidates: @@ -212,10 +230,22 @@ async def _session_status( status_code=404, detail=f"No streaming container configured for platform '{platform}'", ) - found = await access.find_session_for_user(candidates, request.user.id) + found = await access.find_session_for_user( + candidates, + request.user.id, + platform=platform, + include_desktop=include_desktop, + claimed_at=claimed_at, + ) if found is not None: container, _, session = found - status: dict[str, Any] = {"status": "active", "platform": platform} + status: dict[str, Any] = { + "status": "active", + "platform": platform, + # The room the launch answered with, so a tab that missed the + # launch-ready push can enter the stream off a poll. + "host": session.get("host"), + } # An activate that has not returned yet leaves no launched_at behind. # Gating the broker round trip on it keeps this route pure Redis for # the rest of the session, which is the part that gets polled forever. @@ -228,11 +258,14 @@ async def _session_status( ) return status # The tombstone is keyed per container, so with a pool the caller's notice - # can sit under any of them. + # can sit under any of them, and another claim's is not the answer. termination = None for candidate in candidates: - termination = await get_termination(candidate.key, request.user.id) - if termination is not None: + notice = await get_termination(candidate.key, request.user.id) + if notice is not None and access.session_in_scope( + notice, platform, include_desktop, claimed_at + ): + termination = notice break return { "status": "ended", @@ -255,36 +288,41 @@ def _joinable_container_label( @protected_route(router.get, "/config", [Scope.ROMS_READ]) async def get_config(request: Request) -> StreamingConfigSchema: """Return streaming configuration to the frontend""" - # Keyed by platform: a pool is a backend concern, the frontend picks a + # One row per platform: a pool is a backend concern, the frontend picks a # platform and the claim decides which container serves it. - safe_containers: dict[str, StreamingContainerSchema] = {} - for c in resolve_containers(): - if c.platform in safe_containers: - continue + safe_containers: list[StreamingContainerSchema] = [] + for c in first_claim_targets(): # The record carries the platform's label and capabilities, so a # platform hidden from this caller must not be listed here either. if not access.platform_is_visible(request, c.platform): continue - safe_containers[c.platform] = StreamingContainerSchema( - platform=c.platform, - host=c.host, - label=c.label, - # Ship slot capabilities so the frontend selector reads them - # instead of keeping its own hardcoded per-platform copy. - capabilities=SlotCapabilitiesSchema(**c.capabilities), - # State namespace for this container, so the frontend can - # filter the resume picker the same way hydration filters. - emulator=c.emulator, - # Whether this container syncs whole memory cards, so the - # frontend only offers the card picker where it applies. - supports_memory_cards=c.memory_card_sync, - # Whether an older save archive still lands here, so the frontend - # only offers the save picker where a pick means something. - supports_save_picker=c.supports_save_picker, + safe_containers.append( + StreamingContainerSchema( + platform=c.platform, + host=c.host, + label=c.label, + # Ship slot capabilities so the frontend selector reads them + # instead of keeping its own hardcoded per-platform copy. + capabilities=SlotCapabilitiesSchema(**c.capabilities), + # State namespace for this container, so the frontend can + # filter the resume picker the same way hydration filters. + emulator=c.emulator, + # Whether this container syncs whole memory cards, so the + # frontend only offers the card picker where it applies. + supports_memory_cards=c.memory_card_sync, + # Whether an older save archive still lands here, so the frontend + # only offers the save picker where a pick means something. + supports_save_picker=c.supports_save_picker, + # Whether the in-game Save and Load buttons reach a broker that + # honours them, which an exit-state emulator's does not. + supports_live_states=c.supports_live_states, + ) ) return StreamingConfigSchema( - enabled=streaming_enabled(), containers=list(safe_containers.values()) + enabled=streaming_enabled(), + containers=safe_containers, + emulator_labels=emulator_labels(), ) @@ -309,12 +347,12 @@ async def _win_container( if not entered: raise HTTPException( status_code=409, - detail={ - "message": "You already have a session on this platform", - "draining": False, - "rom_name": None, - "claimed_at": None, - }, + detail=ContainerBusyDetail( + message="You already have a session on this platform", + draining=False, + rom_name=None, + claimed_at=None, + ).model_dump(), ) return await _reserve_container(request, candidates, session, platform) @@ -326,24 +364,26 @@ async def _reserve_container( platform: str, ) -> ResolvedContainer: """Walk the platform's containers and claim the first one available.""" - # Status, heartbeat and release all resolve by platform and answer with the - # first match, so a second session for one user is one nothing can reach. - held = await access.find_session_for_user(candidates, request.user.id) + # Status, heartbeat and release reach one session per platform, so a second + # is unreachable. One elsewhere is no bar: its container fails the claim below. + held = await access.find_session_for_user( + candidates, request.user.id, platform=platform + ) if held is not None: - holder, _, mine = held + own_container, _, mine = held if not session_is_stale(mine): raise HTTPException( status_code=409, - detail={ - "message": "You already have a session on this platform", - "draining": False, - "rom_name": access.visible_rom_name(request, mine), - "claimed_at": mine.get("claimed_at"), - }, + detail=ContainerBusyDetail( + message="You already have a session on this platform", + draining=False, + rom_name=access.visible_rom_name(request, mine), + claimed_at=mine.get("claimed_at"), + ).model_dump(), ) # Their own session, abandoned. Take that container back rather than # rolling them onto a free one and stranding this one until its TTL. - candidates = [holder] + candidates = [own_container] async def try_claim(candidate: ResolvedContainer) -> bool: # SET NX is atomic: exactly one concurrent claim wins the key. The TTL @@ -386,40 +426,56 @@ async def _reserve_container( platform, existing.get("user_id"), ) + # A container serves several platforms, so the swept session may be another + # one's, and its state, saves and card belong to that platform's emulator. + record = ( + container_for_session( + containers_by_key(), candidate.key, existing.get("platform") + ) + or candidate + ) if not await lifecycle.await_teardown_within_budget( - candidate, + record, candidate.key, existing, max(0.0, deadline - time.monotonic()), + claimed_by=request.user.id, ): continue if await try_claim(candidate): return candidate - # Report the head of the pool as the holder: with one container that is the - # only holder, and with several the player just needs to know the platform - # is busy. - existing = await get_session(candidates[0].key) or {} - # A drain marker belongs to nobody: the previous session is over and its - # exit state is still coming out of the container, so rom_name and - # claimed_at are both blank and "in use" would name no one. The player who - # just pressed save-and-exit sees this, and needs to be told to wait rather - # than that somebody else took their platform. - draining = bool(existing.get("draining")) + # A drain marker names no holder, so the holder comes from a live session, + # while `draining` still says a container is about to come free. + snapshots = [ + snapshot or {} + for snapshot in await asyncio.gather( + *(get_session(candidate.key) for candidate in candidates) + ) + ] + draining = any(snapshot.get("draining") for snapshot in snapshots) + holder = next( + ( + snapshot + for snapshot in snapshots + if snapshot and not snapshot.get("draining") + ), + {}, + ) if draining: - message = "The previous session is still saving, try again shortly" + message = "The previous session is still shutting down, try again shortly" elif len(candidates) == 1: message = "Session in use" else: message = f"All {len(candidates)} containers for this platform are in use" raise HTTPException( status_code=409, - detail={ - "message": message, - "draining": draining, - "rom_name": access.visible_rom_name(request, existing), - "claimed_at": existing.get("claimed_at"), - }, + detail=ContainerBusyDetail( + message=message, + draining=draining, + rom_name=access.visible_rom_name(request, holder), + claimed_at=holder.get("claimed_at"), + ).model_dump(), ) @@ -638,7 +694,10 @@ async def _hydrate_saves( [Scope.ROMS_USER_WRITE], # The prompt for a card the container still holds is a real body the client # parses, so it is declared rather than left as an undocumented `detail`. - responses={428: {"model": MemoryCardImportRequired}}, + responses={ + 409: {"model": ContainerBusyDetail}, + 428: {"model": MemoryCardImportRequired}, + }, status_code=202, ) async def claim_session( @@ -786,6 +845,9 @@ async def claim_session( if resume_state is not None and not resume_after_launch: resume_pushed = await states.push_resume_state(container, resume_state) + # The last exit's detached save pull may still be filing the archive to hydrate. + await saves.wait_for_save_pull(request.user.id, rom.id) + archive_path = await _hydrate_saves( request, container, @@ -833,16 +895,28 @@ async def claim_session( router.post, "/sessions/{platform}/save-and-exit", [Scope.ROMS_USER_WRITE] ) async def save_and_exit_session( - request: Request, platform: str, req: Annotated[SaveAndExitRequest, Body()] + request: Request, + platform: str, + req: Annotated[SaveAndExitRequest, Body()], + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, ) -> SaveAndExitResponse: + """Save game state then release the session. + + Args: + req: `wait` true (the default) blocks until the broker confirms the save + and kill, false has the broker do both in the background. + container_key: the claimed container, as on release. + claimed_at: the claim's stamp, as on release. """ - Save game state then release the session. - wait=true (default): blocks until broker confirms save+kill complete. - wait=false: broker fires save+kill in background, returns immediately. - """ - container, session_key, session = await access.resolve_owned_session( - platform, request + target = await access.resolve_claim( + platform, request, container_key, claimed_at, game_only=True ) + if target is None: + return SaveAndExitResponse( + status="not_found", saved=False, platform=platform, released=True + ) + container, session_key, session = target if req.slot: _assert_valid_slot(platform, req.slot) @@ -852,7 +926,7 @@ async def save_and_exit_session( # still writing, and the wipe can race its exit flush. card_sync = container.memory_card_sync effective_wait = True if card_sync else req.wait - saved, effective_slot = await asyncio.to_thread( + saved, effective_slot, settled = await asyncio.to_thread( commands.save_and_exit, container, slot=req.slot, wait=effective_wait ) @@ -866,6 +940,8 @@ async def save_and_exit_session( await lifecycle.record_play_session(session) await lifecycle.clear_session_activity(session_key, session) + # Before the key goes, so a claim that wins it next waits for the pull. + await lifecycle.start_exit_save_pull(container, session, settled=settled) # Sync the exit save to the library. With wait=false the broker save may # still be running; the pull blocks on the broker until it finishes. @@ -930,8 +1006,6 @@ async def save_and_exit_session( except StreamingSessionContended: released = False - lifecycle.collect_exit_saves(container, session) - if not released: log.error("save-and-exit could not give up session %s", session_key) log.info("save-and-exit, platform=%s saved=%s", platform, saved) @@ -946,65 +1020,85 @@ async def save_and_exit_session( async def heartbeat_session( request: Request, platform: str, - container_key: str | None = Query(default=None, alias="container", max_length=300), + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, ) -> SessionStatusSchema: - """Refresh the session's liveness stamp and report whether it still exists. + """Refresh the liveness stamp the frontend beats every ~30s, without which the + claim is abandoned after _STREAMING_SESSION_STALE_SECONDS for the next to take. - The frontend calls this every ~30s while a session is active. A session - that stops refreshing counts as abandoned after _STREAMING_SESSION_STALE_SECONDS - and the next claim may take the container over. + Args: + container_key: the claim to beat, needed for any desktop, or for a + container outside the platform's first pool. + claimed_at: the claim's stamp, so a tab that missed its own takeover does + not keep the claim that replaced it alive. - Reports `ended` rather than raising 404 when the caller no longer holds the - session, so a force-released player learns why on the poll they are already - making rather than watching a dead stream. - - `container` names the claim to refresh, needed for a desktop on a container - outside the platform's first pool. + Returns: + `ended` rather than a 404 once the caller no longer holds the session, so + a force-released player learns why on the poll they already make. """ user_id = request.user.id - # A named claim answers for itself: another session the caller holds on the - # platform is not the one this client is beating. + # A named claim answers for itself, and naming the container is the only way + # to reach a desktop, which a game tab must never beat. + named = container_key is not None candidates = ( [access.named_container(platform, container_key)] if container_key is not None else containers_for_platform(platform) ) - found = await access.find_session_for_user(candidates, user_id) - if found is None: - return SessionStatusSchema( - **await _session_status(platform, request, candidates) + found = await access.find_session_for_user( + candidates, + user_id, + platform=platform, + include_desktop=named, + claimed_at=claimed_at, + ) + if found is not None: + _, session_key, held = found + # Merging keeps a swap that landed since the read. Refusing a draining or + # re-claimed session returns None, so the client stops beating a dead claim. + try: + refreshed = await mutate_session( + session_key, + {"last_seen": datetime.now(timezone.utc).isoformat()}, + require=lambda s: same_claim(s, held), + ) + except StreamingSessionContended: + # A key too busy to write is a key that exists, so the session is live + # and the missed stamp is covered by the next beat. + log.warning("heartbeat could not stamp contended session %s", session_key) + return SessionStatusSchema(status="active", platform=platform) + if refreshed is not None: + await lifecycle.refresh_session_activity(session_key, refreshed) + return SessionStatusSchema(status="active", platform=platform) + return SessionStatusSchema( + **await _session_status( + platform, + request, + candidates, + include_desktop=named, + claimed_at=claimed_at, ) - _, session_key, _ = found - - # Merging keeps a swap that landed since the read. Refusing a draining or - # re-claimed session returns None, so the client stops beating a dead claim. - try: - refreshed = await mutate_session( - session_key, - {"last_seen": datetime.now(timezone.utc).isoformat()}, - require=lambda s: not s.get("draining") and s.get("user_id") == user_id, - ) - except StreamingSessionContended: - # A key too busy to write is a key that exists, so the session is live - # and the missed stamp is covered by the next beat. - log.warning("heartbeat could not stamp contended session %s", session_key) - return SessionStatusSchema(status="active", platform=platform) - if refreshed is None: - return SessionStatusSchema( - **await _session_status(platform, request, candidates) - ) - await lifecycle.refresh_session_activity(session_key, refreshed) - return SessionStatusSchema(status="active", platform=platform) + ) @protected_route(router.get, "/sessions/{platform}/status", [Scope.ROMS_READ]) -async def session_status(request: Request, platform: str) -> SessionStatusSchema: +async def session_status( + request: Request, + platform: str, + claimed_at: ClaimedAtQuery = None, +) -> SessionStatusSchema: """Does the caller still hold this platform's session? Unlike the heartbeat this has no side effects, so a client can call it on mount or after a reconnect without extending a claim it may not own. + + Args: + claimed_at: the claim's stamp, so a tab never adopts a claim that + replaced its own. """ - return SessionStatusSchema(**await _session_status(platform, request)) + return SessionStatusSchema( + **await _session_status(platform, request, claimed_at=claimed_at) + ) @protected_route(router.post, "/sessions/{platform}/join", [Scope.ROMS_READ]) @@ -1024,16 +1118,26 @@ async def join_session( candidate, _, session = await access.resolve_named_container( platform, container ) - found = (candidate, session) if session is not None else None + found = ( + (candidate, session) + if session is not None and session_platform_matches(session, platform) + else None + ) else: found = None for candidate in containers_for_platform(platform): session = await get_live_session(candidate.key) if session is None: continue - if session.get("multiplayer"): - found = (candidate, session) - break + if not session_platform_matches(session, platform): + continue + # A member the caller cannot join is not the answer and must not + # mask a later one that is. + joinable, _ = access.joinable_session_rom(request, session) + if not joinable: + continue + found = (candidate, session) + break if found is None: raise HTTPException( @@ -1074,10 +1178,16 @@ async def join_session( @protected_route(router.post, "/sessions/{platform}/volume", [Scope.ROMS_USER_WRITE]) async def set_volume( - request: Request, platform: str, req: Annotated[VolumeRequest, Body()] + request: Request, + platform: str, + req: Annotated[VolumeRequest, Body()], + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, ) -> VolumeResponse: """Set emulator audio volume (0-100).""" - container, session_key, _ = await access.resolve_owned_session(platform, request) + container, session_key, _ = await access.require_claim( + platform, request, container_key, claimed_at + ) ok = await asyncio.to_thread(commands.set_volume, container, req.level) if not ok: @@ -1089,10 +1199,16 @@ async def set_volume( @protected_route(router.post, "/sessions/{platform}/mute", [Scope.ROMS_USER_WRITE]) async def set_mute( - request: Request, platform: str, req: Annotated[MuteRequest, Body()] + request: Request, + platform: str, + req: Annotated[MuteRequest, Body()], + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, ) -> MuteResponse: """Toggle or explicitly set mute state. Omit body to toggle.""" - container, session_key, _ = await access.resolve_owned_session(platform, request) + container, session_key, _ = await access.require_claim( + platform, request, container_key, claimed_at + ) confirmed = await asyncio.to_thread(commands.set_mute, container, req.mute) if confirmed is None: @@ -1106,15 +1222,19 @@ async def set_mute( router.post, "/sessions/{platform}/save-state", [Scope.ROMS_USER_WRITE] ) async def save_state( - request: Request, platform: str, req: Annotated[SaveStateRequest, Body()] + request: Request, + platform: str, + req: Annotated[SaveStateRequest, Body()], + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, ) -> SaveStateResponse: """Save game state to a slot without stopping the emulator. The autosave slot is a valid target: the library keeps every capture, so the player writes through one slot rather than picking one. """ - container, session_key, session = await access.resolve_owned_session( - platform, request + container, session_key, session = await access.require_claim( + platform, request, container_key, claimed_at ) _assert_valid_slot(platform, req.slot) @@ -1145,10 +1265,16 @@ async def save_state( router.post, "/sessions/{platform}/load-state", [Scope.ROMS_USER_WRITE] ) async def load_state( - request: Request, platform: str, req: Annotated[LoadStateRequest, Body()] + request: Request, + platform: str, + req: Annotated[LoadStateRequest, Body()], + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, ) -> LoadStateResponse: """Load game state from a manual slot or the platform's autosave slot.""" - container, session_key, _ = await access.resolve_owned_session(platform, request) + container, session_key, _ = await access.require_claim( + platform, request, container_key, claimed_at + ) _assert_valid_slot(platform, req.slot) ok = await asyncio.to_thread(commands.load_state, container, req.slot) @@ -1161,11 +1287,15 @@ async def load_state( @protected_route(router.post, "/sessions/{platform}/swap-disc", [Scope.ROMS_USER_WRITE]) async def swap_disc( - request: Request, platform: str, req: Annotated[SwapDiscRequest, Body()] + request: Request, + platform: str, + req: Annotated[SwapDiscRequest, Body()], + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, ) -> SwapDiscResponse: """Change the mounted disc without restarting the emulator.""" - container, session_key, session = await access.resolve_owned_session( - platform, request + container, session_key, session = await access.require_claim( + platform, request, container_key, claimed_at ) # Container-scoped, not platform-scoped: only the webstation broker has a # tray route, so a legacy container serving this platform gets the same @@ -1208,38 +1338,27 @@ async def release_session( platform: str, background_tasks: BackgroundTasks, reason: str | None = Query(default=None, max_length=200), - container_key: str | None = Query(default=None, alias="container", max_length=300), + container_key: ContainerQuery = None, + claimed_at: ClaimedAtQuery = None, save: bool = Query(default=True), ) -> ReleaseSessionResponse: """Release a session and tell the broker to stop the emulator. - `reason` is only meaningful when an admin ends someone else's session; it - is surfaced to the displaced player. `container` names which container to - release, needed when a pool serves the platform and the admin is ending a - session they do not own; it is the key `GET /streaming/sessions` reports. - - `save=false` is a player leaving deliberately without saving. It defaults - on because the other way in here is a tab closing, where nobody chose - anything and the last minutes of play would otherwise be gone. + Args: + reason: why an admin ended someone else's session, shown to that player. + container_key: which pool member to release: the holder sends the one it + claimed, an admin the key `GET /streaming/sessions` reports. + claimed_at: the stamp binding this release to one claim; admin panels end + whatever is running and send none. + save: false for a player leaving deliberately without saving; on by + default because a closing tab chose nothing and would lose recent play. """ - if container_key is not None: - container, session_key, session = await access.resolve_named_container( - platform, container_key - ) - if session is None: - return ReleaseSessionResponse(status="not_found", platform=platform) - access.assert_session_owner(session, request) - else: - try: - container, session_key, session = await access.resolve_owned_session( - platform, request - ) - except HTTPException as exc: - # Nothing configured or nothing active: releasing is a no-op rather - # than an error, matching a repeated release from the same tab. - if exc.status_code != 404: - raise - return ReleaseSessionResponse(status="not_found", platform=platform) + target = await access.resolve_claim( + platform, request, container_key, claimed_at, game_only=False + ) + if target is None: + return ReleaseSessionResponse(status="not_found", platform=platform) + container, session_key, session = target # Teardown pulls the whole card off the broker and pushes a blank one back, # several seconds of broker round-trips. The player who quit does not need @@ -1276,7 +1395,11 @@ async def list_containers(request: Request) -> AdminContainersResponse: containers: list[AdminContainerSchema] = [] for container_key, entries in containers_by_key().items(): first = entries[0] - session = await get_live_session(container_key) if container_key else None + held = await get_session(container_key) if container_key else None + # A drain marker holds the key with no owner. Reported as its own state + # rather than as a session, since there is nobody to name or release. + draining = bool(held and held.get("draining")) + session = None if draining else held user_id = session.get("user_id") if session else None user = db_user_handler.get_user(user_id) if isinstance(user_id, int) else None containers.append( @@ -1289,12 +1412,13 @@ async def list_containers(request: Request) -> AdminContainersResponse: # A container whose host has no scheme has an empty key and can # never be claimed, so surface it rather than listing it as idle. configured=bool(container_key), + draining=draining, session=( ContainerSessionSchema( platform=session.get("platform"), rom_id=session.get("rom_id"), rom_name=session.get("rom_name"), - desktop=bool(session.get("desktop")), + desktop=session_is_desktop(session), claimed_at=session.get("claimed_at"), user_id=user_id, username=user.username if user else None, @@ -1307,7 +1431,12 @@ async def list_containers(request: Request) -> AdminContainersResponse: return AdminContainersResponse(enabled=streaming_enabled(), containers=containers) -@protected_route(router.post, "/desktop", [Scope.ROMS_USER_WRITE]) +@protected_route( + router.post, + "/desktop", + [Scope.ROMS_USER_WRITE], + responses={409: {"model": ContainerBusyDetail}}, +) async def claim_desktop_session( request: Request, req: Annotated[DesktopStreamingSessionRequest, Body()] ) -> DesktopSessionSchema: @@ -1360,11 +1489,14 @@ async def claim_desktop_session( existing = await get_session(session_key) or {} raise HTTPException( status_code=409, - detail={ - "message": "Container in use", - "rom_name": access.visible_rom_name(request, existing), - "claimed_at": existing.get("claimed_at"), - }, + detail=ContainerBusyDetail( + message="Container in use", + # A drain marker means the previous session is still shutting + # down, not that anyone holds it. + draining=bool(existing.get("draining")), + rom_name=access.visible_rom_name(request, existing), + claimed_at=existing.get("claimed_at"), + ).model_dump(), ) try: @@ -1384,7 +1516,7 @@ async def claim_desktop_session( room_url = str(launch_result.get("url", "")) if launch_result else "" host = room_url_on(container.host, room_url) - await stamp_launched(session_key, session) + await stamp_launched(session_key, session, host=None) log.info("desktop session claimed, container=%s", session_key) return DesktopSessionSchema( container=session_key, @@ -1409,19 +1541,10 @@ async def list_joinable_sessions( sessions: list[JoinableSessionSchema] = [] async for container_key, s in iter_live_sessions(): - if not s.get("multiplayer"): - continue - if s.get("user_id") == request.user.id: - continue if rom_id is not None and s.get("rom_id") != rom_id: continue - session_rom_id = s.get("rom_id") - rom = ( - db_rom_handler.get_rom_simple(session_rom_id) - if session_rom_id is not None - else None - ) - if not access.rom_is_visible(request, rom): + joinable, rom = access.joinable_session_rom(request, s) + if not joinable: continue user_id = s.get("user_id") @@ -1431,7 +1554,7 @@ async def list_joinable_sessions( container=container_key, label=_joinable_container_label(grouped, container_key), platform=s.get("platform"), - rom_id=session_rom_id, + rom_id=s.get("rom_id"), rom_name=s.get("rom_name"), host_username=host.username if host else None, claimed_at=s.get("claimed_at"), @@ -1471,7 +1594,7 @@ async def list_sessions(request: Request) -> AdminSessionsResponse: platform=s.get("platform"), rom_id=s.get("rom_id"), rom_name=s.get("rom_name"), - desktop=bool(s.get("desktop")), + desktop=session_is_desktop(s), claimed_at=s.get("claimed_at"), user_id=user_id, username=user.username if user else None, @@ -1513,12 +1636,16 @@ async def force_release_all( # emulator anyway rather than leave it running. await asyncio.to_thread(commands.stop, container) else: - state_slot = await lifecycle.quiesce_container(container, session) + stopped = await lifecycle.quiesce_container(container, session) # Credit playtime to the session's owner, not the admin. await lifecycle.record_play_session(session) await lifecycle.clear_session_activity(container_key, session) - await lifecycle.collect_exit_state(container, session, state_slot) - lifecycle.collect_exit_saves(container, session) + await lifecycle.collect_exit_state( + container, session, stopped.state_slot + ) + await lifecycle.start_exit_save_pull( + container, session, settled=stopped.settled + ) # Note who ended it before the key goes, so the player's next poll # can explain the stream vanishing. diff --git a/backend/handler/streaming/access.py b/backend/handler/streaming/access.py index fefb2cbe4..dbc228ebe 100644 --- a/backend/handler/streaming/access.py +++ b/backend/handler/streaming/access.py @@ -12,7 +12,12 @@ from handler.streaming.config import ( containers_for_platform, entry_for_platform, ) -from handler.streaming.session_store import get_live_session +from handler.streaming.session_store import ( + get_live_session, + session_is_desktop, + session_platform_matches, +) +from logger.logger import log from models.rom import Rom from models.user import Role @@ -50,26 +55,40 @@ def rom_is_visible(request: Request, rom: Rom | None) -> bool: return get_permissions(request).can_see_rom(rom.id, rom.platform_id) -def _session_rom_is_visible(request: Request, session: dict[str, Any]) -> bool: - """Can the caller see the ROM a session is running?""" +def session_rom(session: dict[str, Any]) -> Rom | None: + """The ROM a session is running, None for a desktop or a deleted entry.""" rom_id = session.get("rom_id") - if rom_id is None: - return True - return rom_is_visible(request, db_rom_handler.get_rom_simple(rom_id)) + return db_rom_handler.get_rom_simple(rom_id) if rom_id is not None else None + + +def session_rom_is_visible(request: Request, session: dict[str, Any]) -> bool: + """Can the caller see the ROM a session is running?""" + return rom_is_visible(request, session_rom(session)) + + +def joinable_session_rom( + request: Request, session: dict[str, Any] +) -> tuple[bool, Rom | None]: + """Whether a live session is one this caller may ask to join (its host opted + into multiplayer, it is somebody else's, its ROM is not hidden), with that ROM.""" + if not session.get("multiplayer") or session.get("user_id") == request.user.id: + return False, None + rom = session_rom(session) + return rom_is_visible(request, rom), rom def assert_session_rom_visible( request: Request, session: dict[str, Any], *, not_found_detail: str ) -> None: """Raise 404 when the session's ROM is hidden from the caller.""" - if not _session_rom_is_visible(request, session): + if not session_rom_is_visible(request, session): raise HTTPException(status_code=404, detail=not_found_detail) def visible_rom_name(request: Request, session: dict[str, Any]) -> str | None: """The name of the ROM a session is running, blanked when the caller cannot see that ROM. "Busy" is safe to report to anyone; what is running is not.""" - if not session or not _session_rom_is_visible(request, session): + if not session or not session_rom_is_visible(request, session): return None name = session.get("rom_name") return str(name) if name else None @@ -89,19 +108,45 @@ def platform_is_visible(request: Request, platform_slug: str) -> bool: return get_permissions(request).can_see_platform(platform.id) +def session_in_scope( + session: dict[str, Any], + platform: str, + include_desktop: bool, + claimed_at: str | None = None, +) -> bool: + """Whether a stored session, or the notice it left, is the one a route asked + about: same platform, a desktop only if named, the given claim.""" + if not include_desktop and session_is_desktop(session): + return False + if claimed_at is not None and session.get("claimed_at") != claimed_at: + return False + return session_platform_matches(session, platform) + + async def find_session_for_user( - candidates: list[ResolvedContainer], user_id: int + candidates: list[ResolvedContainer], + user_id: int, + *, + platform: str, + include_desktop: bool = False, + claimed_at: str | None = None, ) -> tuple[ResolvedContainer, str, dict[str, Any]] | None: """The candidate holding this user's session, as (container, key, session). - With a pool the platform no longer identifies the container, the session - does. + With a pool the platform no longer identifies the container, the session does. + + Args: + platform: only sessions claimed for it match. + include_desktop: whether a desktop matches, only when its container is named. + claimed_at: only the one claim the caller was given matches. """ for candidate in candidates: session_key = candidate.key session = await get_live_session(session_key) if session is None: continue + if not session_in_scope(session, platform, include_desktop, claimed_at): + continue if session.get("user_id") == user_id: return candidate, session_key, session return None @@ -137,7 +182,7 @@ async def resolve_named_container( async def resolve_owned_session( platform: str, request: Request ) -> tuple[ResolvedContainer, str, dict[str, Any]]: - """Find the caller's session in the platform's first pool. + """Find the caller's session for this platform in its first pool. Returns (container, session_key, session). Raises 404 when the platform has no configured container or nothing is active, 403 when every active session @@ -156,6 +201,9 @@ async def resolve_owned_session( session = await get_live_session(session_key) if session is None: continue + # These routes act on a game; a desktop is reached by naming it. + if not session_in_scope(session, platform, include_desktop=False): + continue if session.get("user_id") == request.user.id: return candidate, session_key, session others.append((candidate, session_key, session)) @@ -182,6 +230,70 @@ async def resolve_owned_session( return others[0] +async def resolve_claim( + platform: str, + request: Request, + container_key: str | None, + claimed_at: str | None, + *, + game_only: bool, +) -> tuple[ResolvedContainer, str, dict[str, Any]] | None: + """The session a route acting on a claim reaches, or None when that claim is gone. + + Args: + container_key: the container the caller named, if any. + claimed_at: the stamp of the one claim the caller was given. + game_only: only a game of this platform matches a named container, while + a release ends whatever it holds. + """ + if container_key is not None: + container, session_key, session = await resolve_named_container( + platform, container_key + ) + if session is None: + return None + if game_only and not session_in_scope(session, platform, include_desktop=False): + return None + else: + try: + container, session_key, session = await resolve_owned_session( + platform, request + ) + except HTTPException as exc: + # Nothing of the caller's is active, so a stamped claim is gone and a + # repeated call from the same tab finds nothing: both are a no-op. + if exc.status_code != 404 and claimed_at is None: + raise + return None + + # A tab whose claim was replaced (a takeover, or Play pressed again elsewhere) + # must not act on the claim that took its place. + if claimed_at is not None and session.get("claimed_at") != claimed_at: + log.info("%s ignored for a replaced claim", request.url.path) + return None + # After the stamp check, so another player's takeover reads as a gone claim. + if container_key is not None: + assert_session_owner(session, request) + return container, session_key, session + + +async def require_claim( + platform: str, + request: Request, + container_key: str | None, + claimed_at: str | None, +) -> tuple[ResolvedContainer, str, dict[str, Any]]: + """The game a control route drives, raising 404 once the caller's claim is gone.""" + target = await resolve_claim( + platform, request, container_key, claimed_at, game_only=True + ) + if target is None: + raise HTTPException( + status_code=404, detail=f"No active session for platform '{platform}'" + ) + return target + + def container_by_key(container_key: str) -> tuple[ResolvedContainer, str]: """A configured container named by its key, plus the platform to file its sessions under. diff --git a/backend/handler/streaming/capabilities.py b/backend/handler/streaming/capabilities.py index b55af2556..d93d3149e 100644 --- a/backend/handler/streaming/capabilities.py +++ b/backend/handler/streaming/capabilities.py @@ -172,6 +172,10 @@ _SAVE_PICKER_EMULATORS = frozenset( {"eden", "retroarch", "rpcs3", "shadps4", "xemu", "xenia"} ) +# Emulators whose webstation broker writes a state only on exit and refuses one +# pushed in, so a resume is the slot on the activate plus the save archive. +_EXIT_STATE_EMULATORS = frozenset({"duckstation", "rpcs3"}) + def slot_capabilities(platform: str, emulator: str = "") -> PlatformCapabilities: """Save-state and disc capabilities for a platform, or a no-slots default. @@ -201,6 +205,12 @@ def emulator_clears_saves(emulator: str) -> bool: return emulator.strip().lower() in _SAVE_PICKER_EMULATORS +def emulator_resumes_from_archive(emulator: str) -> bool: + """Whether this emulator resumes from the state its save archive restores + rather than from a state file pushed into the container.""" + return emulator.strip().lower() in _EXIT_STATE_EMULATORS + + def known_to_lack_memory_card(platform: str) -> bool: """True only for a platform listed above as having no memory card. diff --git a/backend/handler/streaming/commands.py b/backend/handler/streaming/commands.py index 6f8b148a8..018544571 100644 --- a/backend/handler/streaming/commands.py +++ b/backend/handler/streaming/commands.py @@ -5,7 +5,7 @@ for the effect and never for the route that produces it. """ import urllib.error -from typing import Any +from typing import Any, NamedTuple from config import STREAMING_SAVE_TIMEOUT from handler.streaming import broker, webstation @@ -50,14 +50,23 @@ def launch( ) +class SaveAndExitOutcome(NamedTuple): + """What a save-and-exit reports back to the route.""" + + saved: bool + slot: int + # The broker answered once the emulator was done writing its saves. + settled: bool + + def save_and_exit( container: ResolvedContainer, slot: int = 0, wait: bool = True -) -> tuple[bool, int]: +) -> SaveAndExitOutcome: """ POST /save-and-exit to the broker. Best-effort, logs but never raises. With wait=True the call blocks until save+kill completes (use for button press). With wait=False the broker fires save+kill in the background (use for navigation away). - Returns (saved, slot). Brokers resolve slot 0 to their default autosave + Returns (saved, slot, settled). Brokers resolve slot 0 to their default autosave slot and echo the effective slot back, which the state sync needs to pull the right file afterwards. """ @@ -75,7 +84,7 @@ def save_and_exit( if report is not None and isinstance(report.get("state_slot"), int): effective_slot = report["state_slot"] log.info("broker exit, saved=%s slot=%d", saved, effective_slot) - return saved, effective_slot + return SaveAndExitOutcome(saved, effective_slot, settled=report is not None) body = broker.request_safe( container, @@ -91,7 +100,8 @@ def save_and_exit( log.info( "broker save-and-exit, saved=%s slot=%d wait=%s", saved, effective_slot, wait ) - return saved, effective_slot + # Only a confirmed save that blocked on the kill leaves nothing still writing. + return SaveAndExitOutcome(saved, effective_slot, settled=saved and wait) def set_volume(container: ResolvedContainer, level: int) -> bool: @@ -169,10 +179,18 @@ def swap_disc(container: ResolvedContainer, disc_path: str) -> bool: return bool(body and body.get("status") == "ok") -def stop(container: ResolvedContainer, save: bool = True) -> int | None: +class StopOutcome(NamedTuple): + """What a stop leaves for the teardown to collect.""" + + state_slot: int | None = None + # The broker answered once the emulator was done writing its saves. + settled: bool = False + + +def stop(container: ResolvedContainer, save: bool = True) -> StopOutcome: """Tell the broker to stop emulator. Best-effort, don't raise on failure. - Returns the slot a state was captured in, or None when none was. With + The outcome's slot is where a state was captured, if one was. With `save` off no state is written at all, which is what a player leaving without saving asked for; the game's own save data still travels either way, so progress made at an in-game save point survives the stop. @@ -183,11 +201,14 @@ def stop(container: ResolvedContainer, save: bool = True) -> int | None: """ if container.is_webstation: report = webstation.exit_session(container, slot=0, save=save) - if save and report and report.get("state_saved"): - slot = report.get("state_slot") - return slot if isinstance(slot, int) else None - return None + if report is None: + return StopOutcome() + slot = report.get("state_slot") + if save and report.get("state_saved") and isinstance(slot, int): + return StopOutcome(slot, settled=True) + return StopOutcome(settled=True) + # These brokers ack before the emulator has flushed its saves. broker.request_safe( container, "/launch", "stop", method="DELETE", timeout=ACK_TIMEOUT ) - return None + return StopOutcome() diff --git a/backend/handler/streaming/config.py b/backend/handler/streaming/config.py index c636cfabb..abb81e1ff 100644 --- a/backend/handler/streaming/config.py +++ b/backend/handler/streaming/config.py @@ -22,6 +22,7 @@ from handler.streaming.capabilities import ( PlatformCapabilities, StateTransferLimits, emulator_clears_saves, + emulator_resumes_from_archive, known_to_lack_memory_card, slot_capabilities, state_transfer_limits, @@ -52,7 +53,10 @@ _EMULATOR_DISPLAY_NAMES: dict[str, str] = { "eden": "Eden", "flycast": "Flycast", "pcsx2": "PCSX2", + "play": "Play!", "ppsspp": "PPSSPP", + # Platform-less name; emulator_display_label names the core instead. + "retroarch": "RetroArch", "rpcs3": "RPCS3", "shadps4": "shadPS4", "xemu": "xemu", @@ -121,6 +125,12 @@ _RETROARCH_CORE_NAMES: dict[str, str] = { } +def emulator_labels() -> dict[str, str]: + """Display name per emulator id, for surfaces that label an id they were + handed rather than one they resolved (a save's `emulator`, say).""" + return dict(_EMULATOR_DISPLAY_NAMES) + + def emulator_display_label(emulator: str, platform: str) -> str: """Play-button text for an emulator serving a platform, e.g. "PCSX2" or "RA PPSSPP". Unknown emulators fall back to their configured name.""" @@ -173,6 +183,17 @@ class ResolvedContainer: """Whether the launch screen may offer a save other than the newest.""" return self.is_webstation and self.clears_stale_saves + @property + def resumes_from_archive(self) -> bool: + """Whether a resume rides the save archive, with no state file to push.""" + return self.is_webstation and emulator_resumes_from_archive(self.emulator) + + @property + def supports_live_states(self) -> bool: + """Whether the player may save or load a state while the game runs. An + exit-state broker refuses both, though its slot still backs the library.""" + return self.capabilities["has_autosave"] and not self.resumes_from_archive + def interchangeable_with(self, other: ResolvedContainer) -> bool: """Whether two containers serving a platform are one pool: a player landing on either finds the same saves and the same controls.""" @@ -579,6 +600,12 @@ def containers_for_platform(platform: str) -> list[ResolvedContainer]: return pools[0] if pools else [] +def first_claim_targets() -> list[ResolvedContainer]: + """The first container a game claim tries, one per platform, in config + order.""" + return [pools[0][0] for pools in _pools_by_platform(resolve_containers()).values()] + + def containers_by_key() -> dict[str, list[ResolvedContainer]]: """Configured containers grouped by key. A container serving several platforms has one record per platform, all sharing one key.""" @@ -610,9 +637,10 @@ def container_for_session( def configured_emulator(platform: str) -> str: - """The emulator a configured container serves this platform with, if any.""" - entry = entry_for_platform(resolve_containers(), platform) - return entry.emulator if entry else "" + """The emulator a claim's container serves this platform with, empty when none + can be claimed, taken from the pool a claim walks since slot ceilings read it.""" + pool = containers_for_platform(platform) + return pool[0].emulator if pool else "" def streaming_enabled() -> bool: diff --git a/backend/handler/streaming/launch.py b/backend/handler/streaming/launch.py index 07ff95a21..2c60b058f 100644 --- a/backend/handler/streaming/launch.py +++ b/backend/handler/streaming/launch.py @@ -61,6 +61,11 @@ async def run_launch( phase_watch = asyncio.create_task( _watch_launch_phase(container, session_key, session, platform) ) + # An exit-state broker resumes from the state its archive restores, so with + # no archive uploaded there is nothing of this player's to resume. + resume_on_activate = (resume_pushed or resume_after_launch) and not ( + container.resumes_from_archive and archive_path is None + ) try: # Wrapped in asyncio.to_thread because urllib is synchronous. if container.is_webstation: @@ -79,9 +84,7 @@ async def run_launch( }, gui_language=gui_language, archive_path=archive_path, - resume_slot=( - resume_slot if resume_pushed or resume_after_launch else None - ), + resume_slot=resume_slot if resume_on_activate else None, memory_card_synced=memory_card_synced, multiplayer=multiplayer, ) @@ -102,6 +105,7 @@ async def run_launch( LaunchFailedPayload( platform=platform, container=session_key, + claimed_at=session["claimed_at"], detail=_failure_detail(exc), ).model_dump(), ) @@ -111,14 +115,19 @@ async def run_launch( claim_hold.cancel() log.info("session claimed, platform=%s rom=%s", platform, rom_name) - await stamp_launched(session_key, session) + host = container.protocol.stream_url(container.host, launch_result) + await stamp_launched(session_key, session, host=host) await lifecycle.publish_session_activity(session_key, session) # The webstation broker's deferred load waits for its emulator to report # the game running, and holds off further until the state file is there, so # this push lands ahead of it even though it runs after activate. if resume_after_launch and resume_state is not None: - resume_pushed = await states.push_resume_state(container, resume_state) + if container.resumes_from_archive: + # The activate's slot already handed this broker the whole resume. + resume_pushed = resume_on_activate + else: + resume_pushed = await states.push_resume_state(container, resume_state) await push_to_user( session.get("user_id"), @@ -126,7 +135,8 @@ async def run_launch( LaunchReadyPayload( platform=platform, container=session_key, - host=container.protocol.stream_url(container.host, launch_result), + claimed_at=session["claimed_at"], + host=host, resume=resume_pushed if resume_state is not None else None, ).model_dump(), ) @@ -191,6 +201,9 @@ async def _watch_launch_phase( session.get("user_id"), "streaming:launch-phase", LaunchPhasePayload( - platform=platform, container=session_key, phase=phase + platform=platform, + container=session_key, + claimed_at=session["claimed_at"], + phase=phase, ).model_dump(), ) diff --git a/backend/handler/streaming/lifecycle.py b/backend/handler/streaming/lifecycle.py index a9742b2c3..08815b5ff 100644 --- a/backend/handler/streaming/lifecycle.py +++ b/backend/handler/streaming/lifecycle.py @@ -107,30 +107,44 @@ async def release_after_state_pull( async def quiesce_container( container: ResolvedContainer, session: dict[str, Any], *, save: bool = True -) -> int | None: +) -> commands.StopOutcome: """Stop the emulator, then evacuate and wipe its memory card. Every teardown path opens this way, and the order is load-bearing: stopping first is what makes the card quiescent, and the wipe runs only where the - evacuation captured the card. Returns the slot the stop wrote an exit state - to, if any. + evacuation captured the card. Returns what the stop left to collect. """ - state_slot = await asyncio.to_thread(commands.stop, container, save) + stopped = await asyncio.to_thread(commands.stop, container, save) if await memory_cards.evacuate_session_card(session, container): await memory_cards.wipe_session_card(container) - return state_slot + return stopped -def collect_exit_saves(container: ResolvedContainer, session: dict[str, Any]) -> None: - """Start pulling the in-game save archive a stopped session left behind. +async def _pull_exit_saves( + container: ResolvedContainer, + mark: saves.SavePullMark, + broker_session: str | None, + settled: bool, +) -> None: + """The spawned half of `collect_exit_saves`, which lets the next claim + through however the pull ended.""" + try: + await saves.pull_saves_to_library( + mark.user_id, mark.rom_id, container, broker_session, settled=settled + ) + finally: + await saves.clear_save_pull_pending(mark) - Fire and forget: the broker keeps the archive after the emulator dies, so - no teardown has to wait on it. Whole-card sync containers evacuate the card - instead and have no archive, and a session that ran no ROM (the admin - desktop) has nowhere to file one, so neither schedules anything. - One home for the rule: every teardown path files a session's saves the same - way, and under the session's owner rather than whoever ended it. +async def mark_exit_saves_pending( + container: ResolvedContainer, session: dict[str, Any] +) -> saves.SavePullMark | None: + """Hold the owner's next claim on this ROM until the exit pull has filed. + + Returns: + The mark for `collect_exit_saves`, or None when no pull will run: a + whole-card sync container evacuates the card instead, and a desktop ran + no ROM to file one under. """ rom_id = session.get("rom_id") user_id = session.get("user_id") @@ -139,14 +153,40 @@ def collect_exit_saves(container: ResolvedContainer, session: dict[str, Any]) -> or not isinstance(rom_id, int) or not isinstance(user_id, int) ): + return None + return await saves.mark_save_pull_pending(user_id, rom_id) + + +def collect_exit_saves( + container: ResolvedContainer, + session: dict[str, Any], + mark: saves.SavePullMark | None, + *, + settled: bool, +) -> None: + """Pull a stopped session's save archive in the background, since the broker + keeps it after the emulator dies, filing it under the owner whoever ended it. + + Args: + mark: cleared by the pull however it ends. + settled: the broker confirmed the emulator is done writing, so the first + answer is final. + """ + if mark is None: return background.spawn_sync_task( - saves.pull_saves_to_library( - user_id, rom_id, container, broker_session_id(session) - ) + _pull_exit_saves(container, mark, broker_session_id(session), settled) ) +async def start_exit_save_pull( + container: ResolvedContainer, session: dict[str, Any], *, settled: bool +) -> None: + """Mark the exit pull pending, then start it, for a stop that is already done.""" + mark = await mark_exit_saves_pending(container, session) + collect_exit_saves(container, session, mark, settled=settled) + + async def collect_exit_state( container: ResolvedContainer, session: dict[str, Any], state_slot: int | None ) -> None: @@ -332,15 +372,14 @@ async def teardown_released_session( return keepalive = _hold_reservation(session_key, token, session) + pull_mark: saves.SavePullMark | None = None try: - # The marker, or the claim it could not replace, holds the container - # throughout, so no concurrent claim can interleave. - state_slot = await quiesce_container(container, session, save=save) + # Before anything slow: on a pool the player's next claim can land on a + # free sibling while this container drains. + pull_mark = await mark_exit_saves_pending(container, session) - # Leave a note when this is a force-release rather than a player closing - # their own game. A different user is the obvious case; a reason covers - # the rest, since only the admin panel sends one and an admin can be - # logged in as the same account that is playing in another tab. + # A force-release rather than the player quitting: another user, or a reason, + # which only the admin panel sends. Before the quiesce, so a poll finds it. if session.get("user_id") != acting_user_id or reason is not None: await record_termination( session, @@ -357,12 +396,18 @@ async def teardown_released_session( reason or "-", ) + # The marker, or the claim it could not replace, holds the container + # throughout, so no concurrent claim can interleave. + stopped = await quiesce_container(container, session, save=save) + await record_play_session(session) await clear_session_activity(session_key, session) # Awaited, not spawned: the claim is released below. - await collect_exit_state(container, session, state_slot) - collect_exit_saves(container, session) + await collect_exit_state(container, session, stopped.state_slot) + collect_exit_saves(container, session, pull_mark, settled=stopped.settled) + # The pull clears it from here. + pull_mark = None log.info("session released, platform=%s", platform) except Exception: @@ -375,10 +420,17 @@ async def teardown_released_session( # whatever is still on the container; a phantom claim is not. keepalive.cancel() await _drop_reservation(session_key, token, session) + if pull_mark is not None: + # No pull is coming, so a claim has nothing to wait for. + await saves.clear_save_pull_pending(pull_mark) async def _teardown_abandoned_session( - container: ResolvedContainer, session_key: str, session: dict[str, Any] + container: ResolvedContainer, + session_key: str, + session: dict[str, Any], + *, + claimed_by: int, ) -> bool: """Free a container whose owner vanished without releasing (heartbeat went stale). Same order as an owner release: stop the emulator so the card is @@ -411,17 +463,22 @@ async def _teardown_abandoned_session( return False keepalive = asyncio.ensure_future(hold_drain_marker(session_key, token)) + pull_mark: saves.SavePullMark | None = None try: - state_slot = await quiesce_container(container, session) + # Before anything slow, as a release does. + pull_mark = await mark_exit_saves_pending(container, session) + # That tab may still be showing the stream, so leave a force-release's note, + # but not for the owner coming back, whose new tab it would end. + if session.get("user_id") != claimed_by: + await record_termination( + session, session_key, ended_by=None, reason="abandoned" + ) + stopped = await quiesce_container(container, session) await record_play_session(session) await clear_session_activity(session_key, session) - # That tab may still be showing the stream, so leave the same note an - # admin force-release does rather than letting the picture simply stop. - await record_termination( - session, session_key, ended_by=None, reason="abandoned" - ) - await collect_exit_state(container, session, state_slot) - collect_exit_saves(container, session) + await collect_exit_state(container, session, stopped.state_slot) + collect_exit_saves(container, session, pull_mark, settled=stopped.settled) + pull_mark = None except Exception: log.exception("abandoned session teardown failed, key=%s", session_key) finally: @@ -431,6 +488,8 @@ async def _teardown_abandoned_session( # goes, never a claim that replaced it in the meantime. keepalive.cancel() await drop_drain_marker(session_key, token) + if pull_mark is not None: + await saves.clear_save_pull_pending(pull_mark) return True @@ -447,6 +506,8 @@ async def await_teardown_within_budget( session_key: str, session: dict[str, Any], budget: float, + *, + claimed_by: int, ) -> bool: """Tear down an abandoned session, but only wait `budget` seconds for it. @@ -456,7 +517,9 @@ async def await_teardown_within_budget( this leaves behind blocks a claim until the teardown drops it. """ task = background.spawn_sync_task( - _teardown_abandoned_session(container, session_key, session) + _teardown_abandoned_session( + container, session_key, session, claimed_by=claimed_by + ) ) try: return await asyncio.wait_for(asyncio.shield(task), timeout=budget) diff --git a/backend/handler/streaming/saves.py b/backend/handler/streaming/saves.py index a3b00cebb..be91a7b4c 100644 --- a/backend/handler/streaming/saves.py +++ b/backend/handler/streaming/saves.py @@ -7,12 +7,17 @@ a .zip extension so the whole card set travels as a unit. """ import asyncio +import secrets +import time from datetime import datetime, timezone +from typing import NamedTuple from fastapi import HTTPException +from redis.exceptions import WatchError from handler.database import db_rom_handler, db_save_handler, db_user_handler from handler.filesystem import fs_asset_handler +from handler.redis_handler import async_cache from handler.scan_handler import scan_save from handler.streaming import broker, webstation from handler.streaming.config import ResolvedContainer @@ -22,6 +27,78 @@ from models.rom import Rom from models.user import User from utils.filesystem import sanitize_filename +# An exit files its archive in the background, so a claim landing behind it would +# hydrate from the archive before last. The exit leaves a marker a claim waits out. +SAVE_PULL_WAIT_SECONDS = 20.0 +_SAVE_PULL_KEY_PREFIX = "romm:streaming:save-pull:" +# Backstop for a backend that dies mid-pull: a marker nobody clears would cost +# every later claim on that ROM the full wait. +_SAVE_PULL_TTL_SECONDS = 10 * 60 +_SAVE_PULL_POLL_SECONDS = 0.25 + + +def _save_pull_redis_key(user_id: int, rom_id: int) -> str: + return f"{_SAVE_PULL_KEY_PREFIX}{user_id}:{rom_id}" + + +class SavePullMark(NamedTuple): + """One exit's pending pull, whose token lets only that pull clear it.""" + + user_id: int + rom_id: int + token: str + + +async def mark_save_pull_pending(user_id: int, rom_id: int) -> SavePullMark: + """Hold this user's claims on this ROM until the returned mark is cleared, a + later mark taking over so an earlier pull finishing cannot let a claim past it.""" + token = secrets.token_hex(8) + await async_cache.set( + _save_pull_redis_key(user_id, rom_id), token, ex=_SAVE_PULL_TTL_SECONDS + ) + return SavePullMark(user_id, rom_id, token) + + +async def clear_save_pull_pending(mark: SavePullMark) -> None: + """Drop the marker, while it is still the one `mark` set.""" + key = _save_pull_redis_key(mark.user_id, mark.rom_id) + async with async_cache.pipeline() as pipe: + await pipe.watch(key) + current = await pipe.get(key) + if isinstance(current, bytes): + current = current.decode() + if current != mark.token: + await pipe.unwatch() + return + pipe.multi() + await pipe.delete(key) + try: + await pipe.execute() + except WatchError: + # Only a later mark or the TTL moves the key, and neither is ours. + pass + + +async def wait_for_save_pull( + user_id: int, rom_id: int, budget: float = SAVE_PULL_WAIT_SECONDS +) -> bool: + """Wait for a pull of this user's saves for this ROM to finish filing. + + Returns: + Whether nothing is pending any more, False once `budget` runs out, since a + claim is interactive and must not hang on a wedged pull. + """ + key = _save_pull_redis_key(user_id, rom_id) + deadline = time.monotonic() + budget + while await async_cache.exists(key): + if time.monotonic() >= deadline: + log.warning( + "gave up waiting for the previous session's saves, rom_id=%d", rom_id + ) + return False + await asyncio.sleep(_SAVE_PULL_POLL_SECONDS) + return True + def fetch_save_archive( container: ResolvedContainer, broker_session_id: str | None = None @@ -117,11 +194,17 @@ async def pull_saves_to_library( rom_id: int, container: ResolvedContainer, broker_session_id: str | None = None, + *, + settled: bool = False, ) -> bool: """Background task: pull in-game saves from the broker and store them. Best-effort by design, a sync failure must never surface to the player, the save still exists inside the container. + + Args: + settled: the emulator is done writing, so one attempt is final where the + retries would wait out one still writing. """ user = db_user_handler.get_user(user_id) rom = db_rom_handler.get_rom(rom_id) @@ -129,7 +212,7 @@ async def pull_saves_to_library( return False emulator = container.emulator - for attempt in range(broker.PULL_ATTEMPTS): + for attempt in range(1 if settled else broker.PULL_ATTEMPTS): if attempt > 0: await asyncio.sleep(broker.PULL_RETRY_DELAY) content = await asyncio.to_thread( diff --git a/backend/handler/streaming/session_store.py b/backend/handler/streaming/session_store.py index 34a3a3bc0..1903b9cbe 100644 --- a/backend/handler/streaming/session_store.py +++ b/backend/handler/streaming/session_store.py @@ -278,6 +278,20 @@ async def mutate_session( return session if outcome is _CasOutcome.WROTE else None +def session_platform_matches(session: dict[str, Any], platform: str) -> bool: + """Whether a session was claimed for this platform, a record from before the + field existed matching anything so an upgrade cannot strand one.""" + stored = session.get("platform") + if not isinstance(stored, str) or not stored: + return True + return stored.lower() == platform.lower() + + +def session_is_desktop(session: dict[str, Any]) -> bool: + """Whether a session is an admin desktop rather than a game.""" + return bool(session.get("desktop")) + + def same_claim(session: dict[str, Any], claim: dict[str, Any]) -> bool: """Whether a session read back is still the one a route resolved. Identity is the holder plus the moment they took it, so a re-claim by the same user does @@ -413,7 +427,9 @@ async def hold_session_claim(session_key: str, claim: dict[str, Any]) -> None: return -async def stamp_launched(session_key: str, claim: dict[str, Any]) -> None: +async def stamp_launched( + session_key: str, claim: dict[str, Any], host: str | None +) -> None: """Record that the activate returned, so the status poll stops asking the broker for an extraction phase. @@ -424,11 +440,18 @@ async def stamp_launched(session_key: str, claim: dict[str, Any]) -> None: Best-effort: a stamp that never lands only costs a few redundant broker round trips, and failing a session that is already up would be worse. + + Args: + host: a game's room URL, for the status poll to hand a tab that missed + the push; None for a desktop, whose POST is the only reader. """ try: await mutate_session( session_key, - {"launched_at": datetime.now(timezone.utc).isoformat()}, + { + "launched_at": datetime.now(timezone.utc).isoformat(), + **({"host": host} if host else {}), + }, require=lambda current: same_claim(current, claim), ) except StreamingSessionContended: @@ -570,6 +593,12 @@ async def record_termination( "platform": session.get("platform"), "rom_id": session.get("rom_id"), "rom_name": session.get("rom_name"), + # Which claim ended: a user can hold one per container, plus a desktop, + # and only the tab that holds this one should act on the notice. + "container": session_key, + # A re-claim of the container keeps its key, so the stamp names the claim. + "claimed_at": session.get("claimed_at"), + "desktop": session_is_desktop(session), } await async_cache.set( _termination_redis_key(session_key, user_id), diff --git a/backend/handler/streaming/states.py b/backend/handler/streaming/states.py index b78eea2f8..6d5a9106c 100644 --- a/backend/handler/streaming/states.py +++ b/backend/handler/streaming/states.py @@ -57,13 +57,16 @@ _SLOT_PATTERNS = { # RetroArch leaves the number off its default slot: "GAME.state" is slot 0 # and "GAME.state3" is slot 3. "retroarch": re.compile(r"\.state(\d{0,2})$"), + # DuckStation and RPCS3 write one exit state per game with no slot in the + # name, so the empty group reads as the working slot 0. + "duckstation": re.compile(r"()\.sav$"), + "rpcs3": re.compile(r"()\.SAVESTAT(?:\.zst|\.gz)?$"), } -# Lowest slot each emulator's broker will actually address. Everything but -# RetroArch counts from 1, so a "0" in one of their names is a filename that -# happens to look like a state, not a slot they could load. -_MIN_SLOT = {"retroarch": 0} +# Lowest slot each emulator's broker addresses. The rest count from 1, so a "0" +# in one of their names is a filename that looks like a state, not a slot. +_MIN_SLOT = {"duckstation": 0, "retroarch": 0, "rpcs3": 0} def slot_from_state_filename(emulator: str, filename: str) -> int | None: @@ -482,9 +485,10 @@ async def hydrate_states_to_broker( For the same reason, a resume pick already sent at claim time means there is nothing to add here: any push would overwrite it before the broker's - deferred load fires. + deferred load fires. A container that resumes from its save archive takes no + state file at all, and the archive already carries the newest exit state. """ - if resume_pushed: + if resume_pushed or container.resumes_from_archive: return 0 user = db_user_handler.get_user(user_id) diff --git a/backend/main.py b/backend/main.py index b334491b9..0b8fb032e 100644 --- a/backend/main.py +++ b/backend/main.py @@ -52,6 +52,7 @@ from endpoints.permissions import router as permissions_router from endpoints.platform import router as platform_router from endpoints.play_sessions import router as play_sessions_router from endpoints.recommendations import router as recommendations_router +from endpoints.responses.streaming import SOCKET_PAYLOADS as STREAMING_SOCKET_PAYLOADS from endpoints.roms import router as rom_router from endpoints.saves import router as saves_router from endpoints.screenshots import router as screenshots_router @@ -77,6 +78,7 @@ from utils.context import ( set_context_middleware, ) from utils.memory_cards import MEMORY_CARD_MAX_BYTES +from utils.openapi import publish_socket_payloads logging.config.dictConfig(LOGGING_CONFIG) @@ -219,6 +221,8 @@ app.include_router(streaming_router, prefix="/api") app.mount("/ws", socket_handler.socket_app) app.mount("/netplay", netplay_socket_handler.socket_app) +publish_socket_payloads(app, STREAMING_SOCKET_PAYLOADS) + # NOTE: This code is only executed when running the application directly, # not by deployments using gunicorn. diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 43b2cc849..f29dcf1b5 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -55,9 +55,11 @@ from handler.streaming.capabilities import ( from handler.streaming.config import ( ResolvedContainer, _derive_broker_host, + configured_emulator, emulator_display_label, pools_for_platform, reset_cache, + resolve_containers, resolve_entry, ) from handler.streaming.protocol import protocol_for @@ -329,6 +331,18 @@ def test_get_config_ships_platform_capabilities(client, access_token): } +def test_get_config_ships_the_emulator_labels(client, access_token): + """Saves and states are tagged with the emulator that wrote them, so the + display names ride along rather than being copied into the frontend.""" + with _streaming({"platform": "ps2", "host": "http://192.168.1.10:3000"}): + r = client.get("/api/streaming/config", headers=_auth(access_token)) + labels = r.json()["emulator_labels"] + assert labels["pcsx2"] == "PCSX2" + assert labels["play"] == "Play!" + # The id a save carries, with no platform to pick a core from. + assert labels["retroarch"] == "RetroArch" + + def test_get_config_ships_capabilities_for_a_retroarch_platform(client, access_token): """RetroArch serves dozens of platforms, none of them listed by name. Without a fallback they all reported no states and the player offered no save @@ -547,6 +561,59 @@ def test_clears_stale_saves_has_no_picker_to_gate_on_a_legacy_container(caplog): assert "clears_stale_saves" in caplog.text +def test_only_a_webstation_exit_state_emulator_resumes_from_its_archive(): + """Only the webstation broker takes an archive to restore, so on any other + protocol the resume state still has to be pushed as a file.""" + base = { + "platform": "psx", + "host": "http://192.168.1.10:3000", + "broker_host": "http://192.168.1.10:8000", + } + webstation = {**base, "protocol": "webstation"} + assert _resolved({**webstation, "emulator": "duckstation"}).resumes_from_archive + assert _resolved({**webstation, "emulator": "rpcs3"}).resumes_from_archive + assert not _resolved({**webstation, "emulator": "pcsx2"}).resumes_from_archive + assert not _resolved({**base, "emulator": "duckstation"}).resumes_from_archive + + +def test_an_exit_state_emulator_offers_no_live_states(): + """DuckStation and RPCS3 brokers answer a mid-session save or load with a + 400, so the player must not offer one. psx is one platform entry whichever + emulator serves it, so RetroArch on psx keeps its controls.""" + webstation = { + "platform": "psx", + "host": "http://192.168.1.10:3000", + "broker_host": "http://192.168.1.10:8000", + "protocol": "webstation", + } + assert not _resolved({**webstation, "emulator": "duckstation"}).supports_live_states + assert not _resolved( + {**webstation, "platform": "ps3", "emulator": "rpcs3"} + ).supports_live_states + assert _resolved({**webstation, "emulator": "retroarch"}).supports_live_states + # No states at all is no live states either. + assert not _resolved( + {**webstation, "platform": "xbox", "emulator": "xemu"} + ).supports_live_states + + +def test_get_config_ships_whether_a_container_takes_live_states(client, access_token): + """The exit-state library still needs has_autosave, so the Save and Load + buttons read their own flag rather than switching the slot off.""" + container = { + "host": "http://box:3010", + "protocol": "webstation", + "platforms": {"psx": "duckstation", "gba": "retroarch"}, + } + with _streaming(container): + r = client.get("/api/streaming/config", headers=_auth(access_token)) + assert r.status_code == 200 + by_platform = {c["platform"]: c for c in r.json()["containers"]} + assert by_platform["psx"]["supports_live_states"] is False + assert by_platform["psx"]["capabilities"]["has_autosave"] is True + assert by_platform["gba"]["supports_live_states"] is True + + def test_a_container_that_disagrees_on_clearing_saves_is_a_pool_of_its_own(caplog): """The picker is advertised from the head of the pool, so a member that keeps its own newer files would take the pick and silently discard it.""" @@ -692,6 +759,47 @@ def test_get_config_offers_disc_swap_only_on_a_webstation_container( assert ws_caps["supports_disc_swap"] is True +def test_get_config_leaves_out_a_container_no_claim_can_reach(client, access_token): + """A host with no scheme resolves to no key, so every claim on it fails and + listing it would put a Play button on a platform that can never stream.""" + with _streaming({"platform": "ps2", "host": "192.168.1.10:3000"}): + response = client.get("/api/streaming/config", headers=_auth(access_token)) + assert response.status_code == 200 + assert response.json()["containers"] == [] + + +def test_get_config_lists_a_platform_once_whatever_the_case(client, access_token): + """Platforms are matched case-insensitively everywhere else, so two records + naming one platform in different case are one platform to every claim.""" + with _streaming( + {"platform": "PS2", "host": "http://box-a:3000"}, + {"platform": "ps2", "host": "http://box-b:3000"}, + ): + response = client.get("/api/streaming/config", headers=_auth(access_token)) + assert response.status_code == 200 + assert len(response.json()["containers"]) == 1 + + +def test_configured_emulator_names_the_container_a_claim_wins(client): + """Slot ceilings are read off this emulator, so it has to be the one on the + container a claim lands on, not the first record in the file.""" + with _streaming( + {"platform": "ps2", "host": "192.168.1.10:3000", "emulator": "retroarch"}, + { + "platform": "ps2", + "host": "http://box:3000", + "broker_host": "http://box:8000", + "emulator": "pcsx2", + }, + ): + assert configured_emulator("ps2") == "pcsx2" + + +def test_configured_emulator_is_empty_without_a_claimable_container(client): + with _streaming({"platform": "ps2", "host": "192.168.1.10:3000"}): + assert configured_emulator("ps2") == "" + + # ── Nested platform config ──────────────────────────────────────────────────── @@ -945,6 +1053,8 @@ def test_claim_answers_before_the_launch_and_pushes_the_room_url( assert "host" not in body assert [event for event, _ in sent] == ["streaming:launch-ready"] assert _launch_ready(sent)["host"] == "http://192.168.1.10:3000" + # A re-claim of the same container is only told apart by its stamp. + assert _launch_ready(sent)["claimed_at"] == body["claimed_at"] def test_a_failed_launch_pushes_the_reason_and_frees_the_container( @@ -963,6 +1073,7 @@ def test_a_failed_launch_pushes_the_reason_and_frees_the_container( assert event == "streaming:launch-failed" assert payload["detail"] == "broker said no" assert payload["container"] == _key_of(_container_for(rom)) + assert payload["claimed_at"] == r.json()["claimed_at"] assert _session_raw(_container_for(rom)) is None @@ -995,9 +1106,10 @@ def test_launch_phase_is_pushed_while_a_webstation_unpacks( r = _claim(client, access_token, rom.id) assert r.status_code == 202 - pushed = [p["phase"] for event, p in sent if event == "streaming:launch-phase"] + phases_sent = [p for event, p in sent if event == "streaming:launch-phase"] # Only changes are pushed, so a repeated phase is not re-sent. - assert pushed == ["unpacking", "installing"] + assert [p["phase"] for p in phases_sent] == ["unpacking", "installing"] + assert {p["claimed_at"] for p in phases_sent} == {r.json()["claimed_at"]} assert sent[-1][0] == "streaming:launch-ready" @@ -1194,10 +1306,11 @@ def _pool_member(rom: Rom, index: int) -> dict: } -def _volume(client, token, platform: str, level: int = 42): +def _volume(client, token, platform: str, level: int = 42, params=None): return client.post( f"/api/streaming/sessions/{platform}/volume", json={"level": level}, + params=params, headers=_auth(token), ) @@ -1207,6 +1320,16 @@ def _session_raw(container: dict): return asyncio.run(async_cache.get(key)) +def _drain(container: dict) -> None: + session = _load_session(session_store.session_redis_key(_key_of(container))) + token = asyncio.run(session_store.claim_drain_marker(_key_of(container), session)) + assert token is not None + + +def _stub_stop(): + return patch("handler.streaming.commands.stop", return_value=commands.StopOutcome()) + + def test_pool_claim_falls_through_to_a_free_container( client, access_token, viewer_access_token, rom: Rom ): @@ -1234,6 +1357,48 @@ def test_pool_409s_only_once_every_container_is_held( assert "2 containers" in r3.json()["detail"]["message"] +def test_a_busy_pool_names_the_holder_while_a_member_drains( + client, access_token, viewer_access_token, editor_access_token, rom: Rom +): + """A drain marker names nobody, so reading only the head of the pool told + the waiting player the platform was saving while another member played on.""" + head, tail = _pool_member(rom, 0), _pool_member(rom, 1) + with _streaming(head, tail): + _claim_ok(client, access_token, rom.id) + _claim_ok(client, viewer_access_token, rom.id) + holder = json.loads(_session_raw(tail)) + _drain(head) + r = _claim_ok(client, editor_access_token, rom.id) + + assert r.status_code == 409 + detail = r.json()["detail"] + # One member is about to come free, which is what "try again shortly" says. + assert detail["draining"] is True + assert detail["rom_name"] == rom.name + assert detail["claimed_at"] == holder["claimed_at"] + + +def test_a_busy_pool_reports_a_drain_on_any_member( + client, access_token, viewer_access_token, editor_access_token, rom: Rom +): + """The container about to come free is the one the waiting player is told to + wait for, wherever in the pool it sits.""" + head, tail = _pool_member(rom, 0), _pool_member(rom, 1) + with _streaming(head, tail): + _claim_ok(client, access_token, rom.id) + _claim_ok(client, viewer_access_token, rom.id) + holder = json.loads(_session_raw(head)) + _drain(tail) + r = _claim_ok(client, editor_access_token, rom.id) + + assert r.status_code == 409 + detail = r.json()["detail"] + assert detail["draining"] is True + assert "shutting down" in detail["message"] + assert detail["rom_name"] == rom.name + assert detail["claimed_at"] == holder["claimed_at"] + + def test_a_claim_never_lands_in_a_later_pool( client, access_token, viewer_access_token, rom: Rom ): @@ -1265,6 +1430,37 @@ def test_a_pool_does_not_roll_its_own_holder_onto_a_second_container( assert free is None +def test_a_session_on_one_platform_does_not_block_a_claim_on_another( + client, access_token +): + """The caller's ps2 session sits on a key the ngc walk visits too, and only + occupies that container rather than counting as the player's ngc session.""" + ps2_rom = _rom_on("ps2") + ngc_rom = _rom_on("ngc") + second = _nested( + host="http://192.168.1.11:3000", broker_host="http://192.168.1.11:8000" + ) + with _streaming(_nested(), second): + r1 = _claim_ok(client, access_token, ps2_rom.id) + r2 = _claim_ok(client, access_token, ngc_rom.id) + assert [r1.status_code, r2.status_code] == [202, 202] + assert r1.json()["container"] == _key_of(_nested()) + assert r2.json()["container"] == _key_of(second) + + +def test_status_does_not_report_a_session_on_another_platform(client, access_token): + """The ps2 claim shares its key with the container's ngc row, and a poll for + ngc must not read that as a session the caller holds there.""" + ps2_rom = _rom_on("ps2") + with _streaming(_nested()): + assert _claim_ok(client, access_token, ps2_rom.id).status_code == 202 + r = client.get( + "/api/streaming/sessions/ngc/status", headers=_auth(access_token) + ) + assert r.status_code == 200 + assert r.json()["status"] == "ended" + + @contextmanager def _claim_in_flight(platform: str, user_id: int) -> Iterator[None]: """Stand in for a claim from the same player that is inside the reserve and @@ -1306,7 +1502,7 @@ def test_a_pool_hands_the_owner_of_a_stale_session_their_own_container_back( _age_session_on( _pool_member(rom, 0), session_store._STREAMING_SESSION_STALE_SECONDS + 60 ) - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): r2 = _claim_ok(client, access_token, rom.id) free = asyncio.run(session_store.get_session(_key_of(_pool_member(rom, 1)))) assert r2.status_code == 202 @@ -1324,7 +1520,7 @@ def test_pool_never_evicts_a_stale_session_while_a_container_is_free( _age_session_on( _pool_member(rom, 0), session_store._STREAMING_SESSION_STALE_SECONDS + 60 ) - with patch("handler.streaming.commands.stop", return_value=None) as stop_broker: + with _stub_stop() as stop_broker: r2 = _claim_ok(client, viewer_access_token, rom.id) assert r2.status_code == 202 assert r2.json()["container"] == _key_of(_pool_member(rom, 1)) @@ -1341,7 +1537,7 @@ def test_pool_takes_over_a_stale_session_once_every_container_is_held( _age_session_on( _pool_member(rom, 1), session_store._STREAMING_SESSION_STALE_SECONDS + 60 ) - with patch("handler.streaming.commands.stop", return_value=None) as stop_broker: + with _stub_stop() as stop_broker: r3 = _claim_ok(client, viewer_access_token, rom.id) assert r3.status_code == 202 assert r3.json()["container"] == _key_of(_pool_member(rom, 1)) @@ -1400,6 +1596,52 @@ def test_an_admin_cannot_guess_which_of_two_sessions_to_control( assert r.status_code == 409 +def test_an_admin_names_which_of_two_sessions_to_control( + client, access_token, viewer_access_token, editor_access_token, rom: Rom +): + with _streaming(_pool_member(rom, 0), _pool_member(rom, 1)): + _claim_ok(client, viewer_access_token, rom.id) + _claim_ok(client, editor_access_token, rom.id) + with patch( + "handler.streaming.commands.set_volume", return_value=True + ) as volume: + r = _volume( + client, + access_token, + rom.platform_slug, + params={"container": _key_of(_pool_member(rom, 1))}, + ) + assert r.status_code == 200 + assert volume.call_args[0][0].host == "http://192.168.1.11:3000" + + +@pytest.mark.parametrize( + "route, body, command", + [ + ("volume", {"level": 42}, "set_volume"), + ("mute", {"mute": True}, "set_mute"), + ("save-state", {"slot": 1}, "save_state"), + ("load-state", {"slot": 1}, "load_state"), + ("swap-disc", {"file_id": 1}, "swap_disc"), + ], +) +def test_a_control_for_a_replaced_claim_never_reaches_the_broker( + client, access_token, rom: Rom, route, body, command +): + """A tab that missed its takeover must not drive the claim that replaced it.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with patch(f"handler.streaming.commands.{command}") as broker: + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/{route}", + json=body, + params={"claimed_at": "2020-01-01T00:00:00+00:00"}, + headers=_auth(access_token), + ) + assert r.status_code == 404 + broker.assert_not_called() + + def test_admin_release_names_the_container( client, access_token, viewer_access_token, editor_access_token, rom: Rom ): @@ -1408,7 +1650,7 @@ def test_admin_release_names_the_container( with _streaming(_pool_member(rom, 0), _pool_member(rom, 1)): _claim_ok(client, viewer_access_token, rom.id) _claim_ok(client, editor_access_token, rom.id) - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): r = client.delete( f"/api/streaming/sessions/{rom.platform_slug}", params={"container": _key_of(_pool_member(rom, 1))}, @@ -1452,7 +1694,7 @@ def test_admin_release_ends_a_session_on_a_container_in_a_later_pool( key = _key_of(later) assert key not in [c.key for c in streaming.containers_for_platform("ps2")] assert _desktop(client, access_token, key)[0].status_code == 200 - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): r = client.delete( "/api/streaming/sessions/ps2", params={"container": key}, @@ -1494,7 +1736,7 @@ def test_heartbeat_naming_a_released_container_reports_ended(client, access_toke _desktop(client, access_token, _key_of(_webstation()))[0].status_code == 200 ) assert _desktop(client, access_token, key)[0].status_code == 200 - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): released = client.delete( "/api/streaming/sessions/ps2", params={"container": key}, @@ -1537,7 +1779,7 @@ def test_status_finds_the_termination_on_whichever_container_held_it( with _streaming(_pool_member(rom, 0), _pool_member(rom, 1)): _claim_ok(client, access_token, rom.id) _claim_ok(client, viewer_access_token, rom.id) - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): client.delete( "/api/streaming/sessions", params={"reason": "maintenance"}, @@ -1552,6 +1794,76 @@ def test_status_finds_the_termination_on_whichever_container_held_it( assert r.json()["termination"]["reason"] == "maintenance" +def test_status_does_not_report_a_desktop_notice_to_a_game_poll(client, access_token): + """One tombstone per container and one room per user, so the poll has to + scope the notice the same way it scopes the session it looked for.""" + ps2_rom = _rom_on("ps2") + with _streaming(_webstation()): + key = _key_of(_webstation()) + assert _desktop(client, access_token, key)[0].status_code == 200 + with _stub_stop(): + ended = client.delete( + "/api/streaming/sessions/ps2", + params={"container": key, "reason": "patching the host"}, + headers=_auth(access_token), + ) + assert ended.status_code == 200 + r = client.get( + f"/api/streaming/sessions/{ps2_rom.platform_slug}/status", + headers=_auth(access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "ended" + assert r.json()["termination"] is None + + +def test_a_desktop_beat_still_learns_why_its_claim_ended(client, access_token): + """The desktop names its container, which is what puts its own notice in + scope: nothing else would tell that tab it was taken away.""" + with _streaming(_webstation()): + key = _key_of(_webstation()) + assert _desktop(client, access_token, key)[0].status_code == 200 + with _stub_stop(): + client.delete( + "/api/streaming/sessions/ps2", + params={"container": key, "reason": "patching the host"}, + headers=_auth(access_token), + ) + r = client.post( + "/api/streaming/sessions/ps2/heartbeat", + params={"container": key}, + headers=_auth(access_token), + ) + assert r.json()["status"] == "ended" + notice = r.json()["termination"] + assert notice["reason"] == "patching the host" + assert notice["desktop"] is True + assert notice["container"] == key + + +def test_status_does_not_report_a_notice_from_another_platform(client, access_token): + """A container serving two platforms files both notices under one key, so + the ngc session ending is not an answer for the ps2 tab.""" + ngc_rom = _rom_on("ngc") + with _streaming(_nested()): + _claim_ok(client, access_token, ngc_rom.id) + with _stub_stop(): + client.delete( + "/api/streaming/sessions/ngc", + params={"reason": "patching the host"}, + headers=_auth(access_token), + ) + r = client.get( + "/api/streaming/sessions/ps2/status", headers=_auth(access_token) + ) + ngc = client.get( + "/api/streaming/sessions/ngc/status", headers=_auth(access_token) + ) + assert r.json()["status"] == "ended" + assert r.json()["termination"] is None + assert ngc.json()["termination"]["reason"] == "patching the host" + + def test_heartbeat_refreshes_the_session_on_the_container_that_holds_it( client, access_token, viewer_access_token, rom: Rom ): @@ -1661,7 +1973,7 @@ def test_a_proxied_host_disagreeing_with_its_subfolder_cannot_be_claimed(caplog) with _streaming(entry): with caplog.at_level(logging.WARNING, logger="romm"): candidates = streaming.containers_for_platform("ps2") - listed = streaming.resolve_containers() + listed = resolve_containers() finally: romm_logger.removeHandler(caplog.handler) assert candidates == [] @@ -1833,6 +2145,35 @@ def _claim_webstation_ok(client, token, rom_id): return _claim(client, token, rom_id) +def test_containers_reports_a_container_that_is_still_saving( + client, access_token, rom: Rom +): + """A drain marker has no owner, so the row read as idle while the previous + session's state was still coming out of the container.""" + container = _container_for(rom) + with _streaming(container): + _claim_ok(client, access_token, rom.id) + _drain(container) + rows = _containers(client, access_token).json()["containers"] + + assert rows[0]["draining"] is True + assert rows[0]["session"] is None + + +def test_a_desktop_refused_over_a_drain_says_it_is_saving(client, access_token): + """Nobody holds a draining container, so "in use" names no one and the + admin needs to hear that waiting is enough.""" + ps2_rom = _rom_on("ps2") + container = _webstation() + with _streaming(container): + _claim_webstation_ok(client, access_token, ps2_rom.id) + _drain(container) + response, _ = _desktop(client, access_token, _key_of(container)) + + assert response.status_code == 409 + assert response.json()["detail"]["draining"] is True + + def test_containers_lists_one_row_per_container(client, access_token): """A container serves many platforms but hosts one session, so the fleet view counts containers, not the platform rows /config ships.""" @@ -1923,6 +2264,115 @@ def test_desktop_and_a_game_block_each_other(client, access_token): assert _desktop(client, access_token, key)[0].status_code == 409 +def test_an_admins_desktop_does_not_block_their_game_claim(client, access_token): + """A desktop occupies its container, not the platform, so the claim rolls + onto the free pool member.""" + ps2_rom = _rom_on("ps2") + second = _webstation( + host="http://192.168.1.11:3000", broker_host="http://192.168.1.11:8000" + ) + with _streaming(_webstation(), second): + assert ( + _desktop(client, access_token, _key_of(_webstation()))[0].status_code == 200 + ) + r = _claim_webstation_ok(client, access_token, ps2_rom.id) + assert r.status_code == 202 + assert r.json()["container"] == _key_of(second) + + +def test_an_unnamed_heartbeat_skips_the_callers_desktop( + client, access_token, viewer_access_token +): + """An admin playing on one pool member while holding a desktop on another + beats their game session, not the desktop the walk reaches first.""" + ps2_rom = _rom_on("ps2") + second = _webstation( + host="http://192.168.1.11:3000", broker_host="http://192.168.1.11:8000" + ) + with _streaming(_webstation(), second): + # The viewer takes the head of the pool, so the admin's game lands on + # the second member and the desktop gets the head once it is released. + assert ( + _claim_webstation_ok(client, viewer_access_token, ps2_rom.id).status_code + == 202 + ) + assert _claim_webstation_ok(client, access_token, ps2_rom.id).json()[ + "container" + ] == _key_of(second) + with ( + _stub_stop(), + patch("handler.streaming.background.spawn_sync_task"), + ): + client.delete( + "/api/streaming/sessions/ps2", headers=_auth(viewer_access_token) + ) + assert ( + _desktop(client, access_token, _key_of(_webstation()))[0].status_code == 200 + ) + _age_session_on(_webstation(), 120) + _age_session_on(second, 120) + desktop_before = json.loads(_session_raw(_webstation()))["last_seen"] + game_before = json.loads(_session_raw(second))["last_seen"] + r = client.post( + "/api/streaming/sessions/ps2/heartbeat", headers=_auth(access_token) + ) + desktop_after = json.loads(_session_raw(_webstation()))["last_seen"] + game_after = json.loads(_session_raw(second))["last_seen"] + assert r.json()["status"] == "active" + assert game_after > game_before + assert desktop_after == desktop_before + + +def test_an_unnamed_release_leaves_the_callers_desktop_alone(client, access_token): + """Desktop.vue names its container and a game tab never does, so an unnamed + release must not end the desktop the admin has open.""" + with _streaming(_webstation()): + key = _key_of(_webstation()) + assert _desktop(client, access_token, key)[0].status_code == 200 + with _stub_stop(): + r = client.delete( + "/api/streaming/sessions/ps2", headers=_auth(access_token) + ) + session = asyncio.run(session_store.get_session(key)) + assert r.json()["status"] == "not_found" + assert session is not None and session["desktop"] is True + + +def test_an_unnamed_release_leaves_another_platforms_session_alone( + client, access_token +): + """The container's ngc row shares a key with the caller's ps2 session, so an + unnamed ngc release must not end the ps2 game.""" + ps2_rom = _rom_on("ps2") + with _streaming(_nested()): + assert _claim_ok(client, access_token, ps2_rom.id).status_code == 202 + with _stub_stop(): + r = client.delete( + "/api/streaming/sessions/ngc", headers=_auth(access_token) + ) + session = asyncio.run(session_store.get_session(_key_of(_nested()))) + assert r.json()["status"] == "not_found" + assert session is not None and session["platform"] == "ps2" + + +def test_an_unnamed_heartbeat_leaves_another_platforms_session_alone( + client, access_token +): + """An ngc tab beating unnamed must not keep the caller's ps2 session on the + same container alive.""" + ps2_rom = _rom_on("ps2") + with _streaming(_nested()): + assert _claim_ok(client, access_token, ps2_rom.id).status_code == 202 + _age_session_on(_nested(), 120) + before = json.loads(_session_raw(_nested()))["last_seen"] + r = client.post( + "/api/streaming/sessions/ngc/heartbeat", headers=_auth(access_token) + ) + after = json.loads(_session_raw(_nested()))["last_seen"] + assert r.json()["status"] == "ended" + assert after == before + + def test_desktop_is_admin_only(client, viewer_access_token): with _streaming(_webstation()): key = _key_of(_first_container("ps2")) @@ -1970,11 +2420,12 @@ def test_releasing_a_desktop_session_syncs_nothing_to_the_library(client, access container = _first_container("ps2") assert _desktop(client, access_token, _key_of(container))[0].status_code == 200 with ( - patch("handler.streaming.commands.stop", return_value=None) as stop, + _stub_stop() as stop, patch("handler.streaming.background.spawn_sync_task") as spawn, ): response = client.delete( f"/api/streaming/sessions/{container.platform}", + params={"container": _key_of(container)}, headers=_auth(access_token), ) assert response.status_code == 200 @@ -2136,13 +2587,37 @@ def test_stale_session_taken_over_on_claim( with _streaming(_container_for(rom)): r1 = _claim_ok(client, access_token, rom.id) _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) - with patch("handler.streaming.commands.stop", return_value=None) as stop_broker: + with _stub_stop() as stop_broker: r2 = _claim_ok(client, viewer_access_token, rom.id) assert r1.status_code == 202 assert r2.status_code == 202 stop_broker.assert_called_once() +def test_a_swept_session_is_torn_down_with_its_own_platforms_record( + client, access_token, viewer_access_token +): + """An ngc claim sweeping a stale ps2 session on a shared container tears it + down as pcsx2, since the state and card coming out are that emulator's.""" + ps2_rom = _rom_on("ps2") + ngc_rom = _rom_on("ngc") + with _streaming(_nested()): + _claim_ok(client, access_token, ps2_rom.id) + _age_session_on(_nested(), session_store._STREAMING_SESSION_STALE_SECONDS + 60) + with ( + patch( + "handler.streaming.commands.stop", return_value=commands.StopOutcome(3) + ) as stop, + patch( + "handler.streaming.states.pull_state_to_library", new=AsyncMock() + ) as pull_state, + ): + r = _claim_ok(client, viewer_access_token, ngc_rom.id) + assert r.status_code == 202 + assert stop.call_args.args[0].emulator == "pcsx2" + assert pull_state.call_args.args[2].emulator == "pcsx2" + + def test_the_owner_of_a_stale_session_can_claim_it_again( client, access_token, rom: Rom ): @@ -2151,7 +2626,7 @@ def test_the_owner_of_a_stale_session_can_claim_it_again( with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) - with patch("handler.streaming.commands.stop", return_value=None) as stop_broker: + with _stub_stop() as stop_broker: r2 = _claim_ok(client, access_token, rom.id) assert r2.status_code == 202 stop_broker.assert_called_once() @@ -2169,7 +2644,7 @@ def test_takeover_leaves_the_displaced_owner_a_notice( "user_id" ] _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): _claim_ok(client, viewer_access_token, rom.id) notice = asyncio.run(session_store.get_termination(_key_of(container), owner)) @@ -2179,6 +2654,29 @@ def test_takeover_leaves_the_displaced_owner_a_notice( assert notice["rom_id"] == rom.id +def test_taking_over_ones_own_stale_session_pushes_no_notice( + client, access_token, rom: Rom +): + """The notice goes to the user, whose only tab is now the one that just + claimed this container, and it would end that fresh claim.""" + container = _container_for(rom) + sent: list[str] = [] + + async def _capture(user_id: Any, event: str, payload: dict[str, Any]) -> None: + sent.append(event) + + with _streaming(container): + _claim_ok(client, access_token, rom.id) + _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + with ( + _stub_stop(), + patch("handler.streaming.session_store.push_to_user", new=_capture), + ): + _claim_ok(client, access_token, rom.id) + + assert "streaming:session-ended" not in sent + + def test_takeover_aborts_when_the_owner_comes_back_first( client, access_token, viewer_access_token, rom: Rom ): @@ -2206,7 +2704,7 @@ def test_takeover_aborts_when_the_owner_comes_back_first( with ( patch.object(streaming, "session_is_stale", stale_then_fresh), patch.object(lifecycle, "session_is_stale", stale_then_fresh), - patch("handler.streaming.commands.stop", return_value=None) as stop_broker, + _stub_stop() as stop_broker, ): r = _claim_ok(client, viewer_access_token, rom.id) @@ -2221,7 +2719,7 @@ def test_fresh_session_not_taken_over( and the running emulator is never stopped.""" with _streaming(_container_for(rom)): r1 = _claim_ok(client, access_token, rom.id) - with patch("handler.streaming.commands.stop", return_value=None) as stop_broker: + with _stub_stop() as stop_broker: r2 = _claim_ok(client, viewer_access_token, rom.id) assert r1.status_code == 202 assert r2.status_code == 409 @@ -2245,6 +2743,40 @@ def test_heartbeat_refreshes_last_seen(client, access_token, rom: Rom): assert not session_store.session_is_stale(session) +def test_a_heartbeat_for_a_replaced_claim_reports_ended(client, access_token, rom: Rom): + """A tab that missed its takeover must not keep the claim that replaced it + alive: the stamp it was given is what identifies the claim it holds.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + _age_session(rom, 60) + before = json.loads(_session_raw(_container_for(rom)))["last_seen"] + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/heartbeat", + params={"claimed_at": "2020-01-01T00:00:00+00:00"}, + headers=_auth(access_token), + ) + after = json.loads(_session_raw(_container_for(rom)))["last_seen"] + assert r.status_code == 200 + assert r.json()["status"] == "ended" + assert after == before + + +def test_a_heartbeat_naming_its_own_claim_still_refreshes_it( + client, access_token, rom: Rom +): + with _streaming(_container_for(rom)): + claimed_at = _claim_ok(client, access_token, rom.id).json()["claimed_at"] + _age_session(rom, 60) + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/heartbeat", + params={"claimed_at": claimed_at}, + headers=_auth(access_token), + ) + session = json.loads(_session_raw(_container_for(rom))) + assert r.json()["status"] == "active" + assert not session_store.session_is_stale(session) + + def test_heartbeat_racing_a_teardown_reports_ended(client, access_token, rom: Rom): """The refresh finds nothing when the claim was released between the lookup and the write; answering "active" there would leave the client beating a @@ -2270,6 +2802,71 @@ def test_heartbeat_racing_a_teardown_reports_ended(client, access_token, rom: Ro assert r.json()["status"] == "ended" +def test_heartbeat_for_a_session_reassigned_mid_request_reports_ended( + client, access_token, viewer_access_token, viewer_user: User, rom: Rom +): + """The write re-checks the owner the lookup found: a takeover landing in + between must not have the loser's beat keep it alive.""" + container = _container_for(rom) + with _streaming(container): + _claim_ok(client, access_token, rom.id) + _age_session(rom, 60) + before = json.loads(_session_raw(container))["last_seen"] + key = session_store.session_redis_key(_key_of(container)) + + real_find = access.find_session_for_user + + async def find_then_reassign(*args, **kwargs): + found = await real_find(*args, **kwargs) + session = json.loads(await async_cache.get(key)) + session["user_id"] = viewer_user.id + await async_cache.set(key, json.dumps(session)) + return found + + with patch.object(access, "find_session_for_user", find_then_reassign): + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/heartbeat", + headers=_auth(access_token), + ) + after = json.loads(_session_raw(container))["last_seen"] + assert r.status_code == 200 + assert r.json()["status"] == "ended" + assert after == before + + +def test_heartbeat_for_a_claim_restamped_mid_request_reports_ended( + client, access_token, rom: Rom +): + """The same player pressing Play again between the lookup and the write + replaces the claim, which the old tab's beat must not keep alive.""" + container = _container_for(rom) + with _streaming(container): + claimed_at = _claim_ok(client, access_token, rom.id).json()["claimed_at"] + _age_session(rom, 60) + before = json.loads(_session_raw(container))["last_seen"] + key = session_store.session_redis_key(_key_of(container)) + + real_find = access.find_session_for_user + + async def find_then_restamp(*args, **kwargs): + found = await real_find(*args, **kwargs) + session = json.loads(await async_cache.get(key)) + session["claimed_at"] = "2099-01-01T00:00:00+00:00" + await async_cache.set(key, json.dumps(session)) + return found + + with patch.object(access, "find_session_for_user", find_then_restamp): + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/heartbeat", + params={"claimed_at": claimed_at}, + headers=_auth(access_token), + ) + after = json.loads(_session_raw(container))["last_seen"] + assert r.status_code == 200 + assert r.json()["status"] == "ended" + assert after == before + + def test_heartbeat_does_not_revive_a_draining_session(client, access_token, rom: Rom): """A container being torn down must not be made to look live again: the emulator is already stopped and its card evacuated.""" @@ -2359,7 +2956,8 @@ def test_heartbeat_for_unknown_platform_returns_404(client, access_token, rom: R def test_status_reports_active_for_owner(client, access_token, rom: Rom): - with _streaming(_container_for(rom)): + container = _container_for(rom) + with _streaming(container): _claim_ok(client, access_token, rom.id) r = client.get( f"/api/streaming/sessions/{rom.platform_slug}/status", @@ -2371,9 +2969,36 @@ def test_status_reports_active_for_owner(client, access_token, rom: Rom): "platform": rom.platform_slug, "extraction_phase": None, "termination": None, + "host": container["host"], } +def test_status_carries_the_room_the_launch_answered_with(client, access_token): + """launch-ready is pushed once: a tab that was reloading when the game came + up has only the poll to find its way back into the stream.""" + rom = _rom_on("ps2") + container = _webstation() + with _streaming(container): + assert _claim_webstation_ok(client, access_token, rom.id).status_code == 202 + r = client.get( + "/api/streaming/sessions/ps2/status", headers=_auth(access_token) + ) + assert r.status_code == 200 + assert r.json()["host"].endswith("/room/x") + + +def test_a_desktop_launch_is_stamped_without_a_room(client, access_token): + """The desktop POST is the only place its room is read, so the session keeps + just the launch stamp the status fallback gates its broker call on.""" + container = _webstation() + with _streaming(container): + response, _ = _desktop(client, access_token, _key_of(container)) + assert response.status_code == 200 + session = json.loads(_session_raw(container)) + assert session["launched_at"] + assert "host" not in session + + def test_status_does_not_refresh_the_session(client, access_token, rom: Rom): """Status is read-only: polling it must not extend a claim, otherwise a background tab could keep a container hostage without playing.""" @@ -2389,6 +3014,24 @@ def test_status_does_not_refresh_the_session(client, access_token, rom: Rom): assert session_store.session_is_stale(session) +def test_status_for_a_replaced_claim_reports_ended(client, access_token, rom: Rom): + """A loading tab whose claim was re-taken on the same container must not be + handed the new claim's room as its own.""" + with _streaming(_container_for(rom)): + first = _claim_ok(client, access_token, rom.id) + _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + with _stub_stop(): + second = _claim_ok(client, access_token, rom.id) + assert second.json()["container"] == first.json()["container"] + r = client.get( + f"/api/streaming/sessions/{rom.platform_slug}/status", + params={"claimed_at": first.json()["claimed_at"]}, + headers=_auth(access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "ended" + + def test_admin_release_leaves_termination_notice( client, access_token, viewer_access_token, rom: Rom ): @@ -2457,6 +3100,123 @@ def test_heartbeat_carries_termination_notice( assert body["termination"]["reason"] == "patching the host" +def test_a_termination_notice_names_the_container_it_ended( + client, access_token, viewer_access_token, rom: Rom +): + """A player can hold a session on several containers, so the notice has to + say which one ended for the right tab to act on it.""" + with _streaming(_container_for(rom)): + _claim_ok(client, viewer_access_token, rom.id) + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"reason": "maintenance window"}, + headers=_auth(access_token), + ) + r = client.get( + f"/api/streaming/sessions/{rom.platform_slug}/status", + headers=_auth(viewer_access_token), + ) + notice = r.json()["termination"] + assert notice["container"] == _key_of(_container_for(rom)) + assert notice["desktop"] is False + + +def test_a_termination_notice_names_the_claim_it_ended( + client, access_token, viewer_access_token, rom: Rom +): + """A re-claim of the same container keeps its key, so only the stamp tells + the tab that lost its claim from the one holding the next.""" + with _streaming(_container_for(rom)): + claimed_at = _claim_ok(client, viewer_access_token, rom.id).json()["claimed_at"] + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + r = client.get( + f"/api/streaming/sessions/{rom.platform_slug}/status", + headers=_auth(viewer_access_token), + ) + assert r.json()["termination"]["claimed_at"] == claimed_at + + +def test_status_does_not_report_the_notice_of_another_claim( + client, access_token, viewer_access_token, rom: Rom +): + """A poll names the claim it asks about, so a notice filed for another + claim on the container must not tell it who ended its own.""" + with _streaming(_container_for(rom)): + _claim_ok(client, viewer_access_token, rom.id) + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"reason": "maintenance window"}, + headers=_auth(access_token), + ) + r = client.get( + f"/api/streaming/sessions/{rom.platform_slug}/status", + params={"claimed_at": "2026-09-17T10:05:00+00:00"}, + headers=_auth(viewer_access_token), + ) + assert r.json()["status"] == "ended" + assert r.json()["termination"] is None + + +def test_a_termination_notice_lands_before_the_drain( + client, access_token, viewer_access_token, rom: Rom +): + """The session ends when the drain marker is written, so a poll during the + seconds-long drain is told why the stream stopped, not a bare `ended`.""" + container = _container_for(rom) + seen: list[dict[str, Any] | None] = [] + + with _streaming(container): + _claim_ok(client, viewer_access_token, rom.id) + user_id = json.loads(_session_raw(container))["user_id"] + + async def capture(*args, **kwargs): + seen.append( + await session_store.get_termination(_key_of(container), user_id) + ) + return commands.StopOutcome() + + with patch( + "handler.streaming.lifecycle.quiesce_container", + new=AsyncMock(side_effect=capture), + ): + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"reason": "maintenance window"}, + headers=_auth(access_token), + ) + assert seen and seen[0] is not None + assert seen[0]["reason"] == "maintenance window" + + +def test_a_takeover_notice_lands_before_the_drain( + client, access_token, viewer_access_token, rom: Rom +): + """The abandoned owner's tab polls through the takeover's drain like any + other, so the notice has to be there before the quiesce starts.""" + container = _container_for(rom) + seen: list[dict[str, Any] | None] = [] + + with _streaming(container): + _claim_ok(client, access_token, rom.id) + owner = json.loads(_session_raw(container))["user_id"] + _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + + async def capture(*args, **kwargs): + seen.append(await session_store.get_termination(_key_of(container), owner)) + return commands.StopOutcome() + + with patch( + "handler.streaming.lifecycle.quiesce_container", + new=AsyncMock(side_effect=capture), + ): + _claim_ok(client, viewer_access_token, rom.id) + assert seen and seen[0] is not None + assert seen[0]["reason"] == "abandoned" + + def test_force_release_all_leaves_termination_notice( client, access_token, viewer_access_token, rom: Rom ): @@ -2616,12 +3376,8 @@ def test_status_stops_asking_the_broker_once_the_launch_returned(client, access_ r = client.get( "/api/streaming/sessions/ps2/status", headers=_auth(access_token) ) - assert r.json() == { - "status": "active", - "platform": "ps2", - "extraction_phase": None, - "termination": None, - } + assert r.json()["status"] == "active" + assert r.json()["extraction_phase"] is None broker.assert_not_called() @@ -2638,12 +3394,8 @@ def test_status_on_a_legacy_container_never_asks_for_a_phase( f"/api/streaming/sessions/{rom.platform_slug}/status", headers=_auth(access_token), ) - assert r.json() == { - "status": "active", - "platform": rom.platform_slug, - "extraction_phase": None, - "termination": None, - } + assert r.json()["status"] == "active" + assert r.json()["extraction_phase"] is None broker.assert_not_called() @@ -2654,7 +3406,7 @@ def test_release_uses_container_key_not_platform(client, access_token, rom: Rom) """release_session must find the session by broker_host, not platform string.""" with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): r = client.delete( f"/api/streaming/sessions/{rom.platform_slug}", headers=_auth(access_token), @@ -2663,6 +3415,80 @@ def test_release_uses_container_key_not_platform(client, access_token, rom: Rom) assert r.json()["status"] == "released" +def test_a_release_for_a_replaced_claim_leaves_the_session( + client, access_token, rom: Rom +): + """A tab whose claim was taken over still releases on unload, and it must + not end the session that replaced it.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with _stub_stop() as stop: + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"claimed_at": "2020-01-01T00:00:00+00:00"}, + headers=_auth(access_token), + ) + session = asyncio.run(session_store.get_session(_key_of(_container_for(rom)))) + assert r.status_code == 200 + assert r.json()["status"] == "not_found" + stop.assert_not_called() + assert session is not None + + +def test_a_release_naming_its_own_claim_still_ends_the_session( + client, access_token, rom: Rom +): + with _streaming(_container_for(rom)): + claimed_at = _claim_ok(client, access_token, rom.id).json()["claimed_at"] + with _stub_stop() as stop: + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"claimed_at": claimed_at}, + headers=_auth(access_token), + ) + assert r.json()["status"] == "released" + stop.assert_called_once() + + +def test_a_release_for_a_claim_another_player_took_over_is_a_no_op( + client, viewer_access_token, editor_access_token, rom: Rom +): + """The tab lost its claim, so the player now holding the container is none + of its business, not a forbidden target.""" + with _streaming(_container_for(rom)): + _claim_ok(client, editor_access_token, rom.id) + with _stub_stop() as stop: + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={ + "container": _key_of(_container_for(rom)), + "claimed_at": "2020-01-01T00:00:00+00:00", + }, + headers=_auth(viewer_access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "not_found" + stop.assert_not_called() + + +def test_an_unnamed_release_for_a_claim_another_player_took_over_is_a_no_op( + client, viewer_access_token, editor_access_token, rom: Rom +): + """A stamped release that names no container reads a takeover the same way + as a named one.""" + with _streaming(_container_for(rom)): + _claim_ok(client, editor_access_token, rom.id) + with _stub_stop() as stop: + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + params={"claimed_at": "2020-01-01T00:00:00+00:00"}, + headers=_auth(viewer_access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "not_found" + stop.assert_not_called() + + def test_release_by_other_user_is_forbidden( client, access_token, viewer_access_token, rom: Rom ): @@ -2715,11 +3541,12 @@ def test_save_and_exit_releases_session_once_the_state_is_pulled( with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) with ( - patch("handler.streaming.commands.save_and_exit", return_value=(True, 10)), + patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 10, True), + ), patch("handler.streaming.states.pull_state_to_library", new=AsyncMock()), - # Plain MagicMock: the async original would auto-mock to AsyncMock, - # whose call handed to the mocked spawn is a never-awaited coroutine. - patch("handler.streaming.saves.pull_saves_to_library", new=MagicMock()), + patch("handler.streaming.saves.pull_saves_to_library", new=AsyncMock()), patch( "handler.streaming.background.spawn_sync_task", side_effect=spawned.append, @@ -2740,13 +3567,128 @@ def test_save_and_exit_releases_session_once_the_state_is_pulled( assert r2.status_code == 202 +def test_a_save_and_exit_for_a_replaced_claim_leaves_the_session( + client, access_token, rom: Rom +): + """A playing tab that missed its takeover saves and exits on unload, and + must not end the session that replaced it.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(False, 10, False), + ) as save_and_exit: + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + params={ + "container": _key_of(_container_for(rom)), + "claimed_at": "2020-01-01T00:00:00+00:00", + }, + json={"slot": 0, "wait": True}, + headers=_auth(access_token), + ) + session = asyncio.run(session_store.get_session(_key_of(_container_for(rom)))) + assert r.status_code == 200 + assert r.json()["status"] == "not_found" + save_and_exit.assert_not_called() + assert session is not None + + +def test_a_save_and_exit_naming_its_own_claim_still_ends_the_session( + client, access_token, rom: Rom +): + with _streaming(_container_for(rom)): + claimed_at = _claim_ok(client, access_token, rom.id).json()["claimed_at"] + with patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(False, 10, False), + ) as save_and_exit: + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + params={ + "container": _key_of(_container_for(rom)), + "claimed_at": claimed_at, + }, + json={"slot": 0, "wait": True}, + headers=_auth(access_token), + ) + assert r.json()["status"] == "ok" + save_and_exit.assert_called_once() + + +def test_a_named_save_and_exit_leaves_another_platforms_session_alone( + client, access_token +): + """The container's ngc row shares a key with the caller's ps2 session, so a + named ngc save-and-exit must not save and kill the ps2 game.""" + ps2_rom = _rom_on("ps2") + with _streaming(_nested()): + assert _claim_ok(client, access_token, ps2_rom.id).status_code == 202 + with patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 10, True), + ) as save_and_exit: + r = client.post( + "/api/streaming/sessions/ngc/save-and-exit", + params={"container": _key_of(_nested())}, + json={"slot": 0, "wait": True}, + headers=_auth(access_token), + ) + session = asyncio.run(session_store.get_session(_key_of(_nested()))) + assert r.json()["status"] == "not_found" + save_and_exit.assert_not_called() + assert session is not None and session["platform"] == "ps2" + + +def test_a_named_save_and_exit_leaves_a_desktop_alone(client, access_token): + """Save-and-exit acts on a game, so naming a desktop's container reaches + nothing to save.""" + container = _webstation() + key = _key_of(container) + with _streaming(container): + assert _desktop(client, access_token, key)[0].status_code == 200 + with patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 10, True), + ) as save_and_exit: + r = client.post( + "/api/streaming/sessions/ps2/save-and-exit", + params={"container": key}, + json={"slot": 0, "wait": True}, + headers=_auth(access_token), + ) + session = asyncio.run(session_store.get_session(key)) + assert r.json()["status"] == "not_found" + save_and_exit.assert_not_called() + assert session is not None and session["desktop"] is True + + +def test_a_save_and_exit_with_nothing_active_is_a_no_op(client, access_token, rom: Rom): + """A retried unload finds its claim already gone, which ends nothing.""" + with _streaming(_container_for(rom)): + with patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(False, 10, False), + ) as save_and_exit: + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + json={"slot": 0, "wait": True}, + headers=_auth(access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "not_found" + assert r.json()["released"] is True + save_and_exit.assert_not_called() + + def test_save_and_exit_failure_still_releases_session(client, access_token, rom: Rom): """A failed save is reported as saved=False, but the session is still released - the container must not stay claimed by a dead session.""" with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) with patch( - "handler.streaming.commands.save_and_exit", return_value=(False, 10) + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(False, 10, False), ): r = client.post( f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", @@ -2766,7 +3708,8 @@ def test_save_and_exit_rejects_a_slot_the_platform_lacks(client, access_token): with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) with patch( - "handler.streaming.commands.save_and_exit", return_value=(True, 9) + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 9, True), ) as broker: r = client.post( "/api/streaming/sessions/ngc/save-and-exit", @@ -2781,7 +3724,7 @@ def test_force_release_all_stops_brokers(client, access_token, rom: Rom): """Force-release must tell each broker to stop, not just clear Redis.""" with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) - with patch("handler.streaming.commands.stop", return_value=None) as stop_broker: + with _stub_stop() as stop_broker: r = client.delete("/api/streaming/sessions", headers=_auth(access_token)) assert r.status_code == 200 assert stop_broker.call_count == 1 @@ -2931,12 +3874,15 @@ def test_save_and_exit_pulls_broker_effective_slot(client, access_token, rom: Ro with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) with ( - patch("handler.streaming.commands.save_and_exit", return_value=(True, 10)), + patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 10, True), + ), _spawns_nothing() as spawn, patch( "handler.streaming.states.pull_state_to_library", new=MagicMock() ) as pull, - patch("handler.streaming.saves.pull_saves_to_library", new=MagicMock()), + patch("handler.streaming.saves.pull_saves_to_library", new=AsyncMock()), ): r = client.post( f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", @@ -2957,13 +3903,17 @@ def test_save_and_exit_failed_blocking_save_skips_state_pull( with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) with ( - patch("handler.streaming.commands.save_and_exit", return_value=(False, 10)), + patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(False, 10, False), + ), patch("handler.streaming.background.spawn_sync_task") as spawn, patch( "handler.streaming.states.pull_state_to_library", new=MagicMock() ) as state_pull, patch( - "handler.streaming.saves.pull_saves_to_library", new=MagicMock() + "handler.streaming.saves.pull_saves_to_library", + new_callable=AsyncMock, ) as save_pull, ): r = client.post( @@ -2971,10 +3921,11 @@ def test_save_and_exit_failed_blocking_save_skips_state_pull( json={"slot": 0, "wait": True}, headers=_auth(access_token), ) + spawn.assert_called_once() + asyncio.run(spawn.call_args[0][0]) assert r.status_code == 200 state_pull.assert_not_called() - save_pull.assert_called_once() - spawn.assert_called_once() + save_pull.assert_awaited_once() def test_save_and_exit_holds_the_container_until_the_state_is_pulled( @@ -2988,9 +3939,12 @@ def test_save_and_exit_holds_the_container_until_the_state_is_pulled( with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) with ( - patch("handler.streaming.commands.save_and_exit", return_value=(True, 10)), + patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 10, True), + ), patch("handler.streaming.states.pull_state_to_library", new=MagicMock()), - patch("handler.streaming.saves.pull_saves_to_library", new=MagicMock()), + patch("handler.streaming.saves.pull_saves_to_library", new=AsyncMock()), _spawns_nothing(), ): r = client.post( @@ -3038,7 +3992,10 @@ def test_save_and_exit_without_a_rom_drains_only_briefly( ) ) with ( - patch("handler.streaming.commands.save_and_exit", return_value=(True, 10)), + patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 10, True), + ), patch("handler.streaming.background.spawn_sync_task") as spawn, ): r = client.post( @@ -3458,6 +4415,34 @@ def test_hydrate_skipped_when_resume_state_already_pushed(rom: Rom, admin_user: push.assert_not_called() +@pytest.mark.parametrize( + ("emulator", "name"), + [ + ("duckstation", "SLUS-00594_resume.20260918-010000000000.sav"), + ("rpcs3", "BLUS30443_1.20260918-010000000000.SAVESTAT"), + ], +) +def test_hydrate_pushes_nothing_to_an_exit_state_emulator( + rom: Rom, admin_user: User, emulator, name +): + """Their broker refuses a state file, and the save archive already carries + the exit state these library entries were pulled from.""" + db_state_handler.add_state(_state_for(rom, admin_user, name, emulator)) + container = {**_container_for(rom), "protocol": "webstation", "emulator": emulator} + with ( + patch( + "handler.filesystem.fs_asset_handler.read_file", + new=AsyncMock(return_value=b"state-bytes"), + ), + patch("handler.streaming.states.push_state_file", return_value=True) as push, + ): + pushed = asyncio.run( + states.hydrate_states_to_broker(admin_user.id, rom.id, _resolved(container)) + ) + assert pushed == 0 + push.assert_not_called() + + def test_hydrate_pushes_newest_state_under_container_name(rom: Rom, admin_user: User): """Only the newest capture is hydrated, and it lands under the unstamped name the emulator expects on disk.""" @@ -4189,19 +5174,527 @@ def test_release_spawns_saves_pull(client, access_token, rom: Rom): with _streaming(_container_for(rom)): _claim_ok(client, access_token, rom.id) with ( - patch("handler.streaming.commands.stop", return_value=None), + _stub_stop(), patch("handler.streaming.background.spawn_sync_task") as spawn, patch( - "handler.streaming.saves.pull_saves_to_library", new=MagicMock() + "handler.streaming.saves.pull_saves_to_library", + new_callable=AsyncMock, ) as pull, ): r = client.delete( f"/api/streaming/sessions/{rom.platform_slug}", headers=_auth(access_token), ) + spawn.assert_called_once() + asyncio.run(spawn.call_args[0][0]) assert r.status_code == 200 - spawn.assert_called_once() - assert pull.call_args[0][1] == rom.id + pull.assert_awaited_once() + assert pull.await_args_list[0].args[1] == rom.id + + +def test_a_claim_behind_an_exit_waits_for_that_exits_saves( + client, access_token, admin_user: User, rom: Rom +): + """Runs both ends for real: nothing else ties the key an exit marks to the + one the next claim waits on.""" + # Equal ids would let a claim that swaps them find the exit's key anyway. + if rom.id == admin_user.id: + rom = _rom_on("distinct_id") + order: list[str] = [] + real_wait = saves.wait_for_save_pull + + async def slow_pull(*args, **kwargs) -> bool: + await asyncio.sleep(saves._SAVE_PULL_POLL_SECONDS * 2) + order.append("filed") + return True + + async def hydrate(*args, **kwargs) -> bool: + order.append("hydrate") + return True + + async def wait_while_it_files(user_id: int, rom_id: int) -> bool: + filing = asyncio.ensure_future(spawn.call_args[0][0]) + done = await real_wait(user_id, rom_id, budget=5) + order.append("waited" if done else "gave up") + await filing + return done + + with ( + _streaming(_container_for(rom)), + patch("handler.streaming.saves.pull_saves_to_library", new=slow_pull), + ): + _claim_ok(client, access_token, rom.id) + with ( + _stub_stop(), + patch("handler.streaming.background.spawn_sync_task") as spawn, + ): + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + with ( + patch( + "handler.streaming.saves.wait_for_save_pull", new=wait_while_it_files + ), + patch("handler.streaming.saves.hydrate_saves_to_broker", new=hydrate), + ): + r = _claim_ok(client, access_token, rom.id) + assert r.status_code == 202 + assert order == ["filed", "waited", "hydrate"] + + +async def _save_pull_pending(user_id: int, rom_id: int) -> bool: + """Whether a claim would wait on a save pull, read the way the claim reads it.""" + return not await saves.wait_for_save_pull(user_id, rom_id, budget=0) + + +def test_a_release_marks_its_save_pull_before_stopping_the_emulator( + client, access_token, admin_user: User, rom: Rom +): + """On a pool the player's next claim lands on a free sibling while this + container drains, so the pull has to be pending before the slow part.""" + head, tail = _pool_member(rom, 0), _pool_member(rom, 1) + at_stop: list[tuple[bool, bool]] = [] + + async def quiesce(container, session, *, save=True): + sibling_free = await session_store.get_live_session(_key_of(tail)) is None + at_stop.append((sibling_free, await _save_pull_pending(admin_user.id, rom.id))) + return commands.StopOutcome() + + with _streaming(head, tail): + _claim_ok(client, access_token, rom.id) + with ( + patch("handler.streaming.lifecycle.quiesce_container", new=quiesce), + patch("handler.streaming.background.spawn_sync_task") as spawn, + ): + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + spawn.call_args[0][0].close() + assert r.status_code == 200 + assert at_stop == [(True, True)] + + +def test_an_abandoned_teardown_marks_its_save_pull_before_stopping_the_emulator( + client, access_token, admin_user: User, rom: Rom +): + container = _container_for(rom) + at_stop: list[bool] = [] + + async def quiesce(container, session, *, save=True): + at_stop.append(await _save_pull_pending(admin_user.id, rom.id)) + return commands.StopOutcome() + + with _streaming(container): + _claim_ok(client, access_token, rom.id) + _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + session = json.loads(_session_raw(container)) + with ( + patch("handler.streaming.lifecycle.quiesce_container", new=quiesce), + patch("handler.streaming.background.spawn_sync_task") as spawn, + ): + torn = asyncio.run( + lifecycle._teardown_abandoned_session( + _resolved(container), + _key_of(container), + session, + claimed_by=admin_user.id, + ) + ) + spawn.call_args[0][0].close() + assert torn is True + assert at_stop == [True] + + +def test_a_release_that_fails_before_its_pull_leaves_nothing_pending( + client, access_token, admin_user: User, rom: Rom +): + """Only a pull clears the mark, so a teardown that never gets to one has to, + or the player's next claim sits out the whole wait for nothing.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with ( + patch( + "handler.streaming.lifecycle.quiesce_container", + new=AsyncMock(side_effect=RuntimeError("broker gone")), + ), + patch("handler.streaming.background.spawn_sync_task") as spawn, + ): + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + spawn.assert_not_called() + assert asyncio.run(_save_pull_pending(admin_user.id, rom.id)) is False + + +def test_an_abandoned_teardown_that_fails_before_its_pull_leaves_nothing_pending( + client, access_token, admin_user: User, rom: Rom +): + container = _container_for(rom) + with _streaming(container): + _claim_ok(client, access_token, rom.id) + _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + session = json.loads(_session_raw(container)) + with ( + patch( + "handler.streaming.lifecycle.quiesce_container", + new=AsyncMock(side_effect=RuntimeError("broker gone")), + ), + patch("handler.streaming.background.spawn_sync_task") as spawn, + ): + asyncio.run( + lifecycle._teardown_abandoned_session( + _resolved(container), + _key_of(container), + session, + claimed_by=admin_user.id, + ) + ) + spawn.assert_not_called() + assert asyncio.run(_save_pull_pending(admin_user.id, rom.id)) is False + + +def _run_exit_pulls(spawn: MagicMock) -> None: + """Run the save pulls a teardown spawned, and drop whatever else it did.""" + for spawned in (c.args[0] for c in spawn.call_args_list): + if spawned.cr_code.co_name == "_pull_exit_saves": + asyncio.run(spawned) + else: + spawned.close() + + +def test_a_webstation_exit_that_changed_no_saves_lets_the_next_claim_straight_through( + client, access_token, rom: Rom, monkeypatch +): + """A webstation exit answers once the save dump is written, so its first + "nothing new" is final and retrying it only holds the next claim.""" + # Long enough that a single retry outlasts the claim's wait below. + monkeypatch.setattr(broker, "PULL_RETRY_DELAY", 1.0) + waited: list[bool] = [] + real_wait = saves.wait_for_save_pull + + async def wait_while_it_files(user_id: int, rom_id: int) -> bool: + filing = asyncio.ensure_future(pull) + waited.append(await real_wait(user_id, rom_id, budget=0.5)) + filing.cancel() + return waited[-1] + + with ( + _streaming(_webstation_for(rom)), + patch("handler.streaming.saves.fetch_save_archive", return_value=None), + ): + _claim_webstation_ok(client, access_token, rom.id) + with ( + patch( + "handler.streaming.webstation.exit_session", + return_value={"state_saved": False, "state_slot": None}, + ), + patch("handler.streaming.background.spawn_sync_task") as spawn, + ): + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + (pull,) = ( + c.args[0] + for c in spawn.call_args_list + if c.args[0].cr_code.co_name == "_pull_exit_saves" + ) + with patch( + "handler.streaming.saves.wait_for_save_pull", new=wait_while_it_files + ): + r = _claim_webstation_ok(client, access_token, rom.id) + assert r.status_code == 202 + assert waited == [True] + + +def test_a_webstation_exit_that_never_answered_keeps_asking( + client, access_token, rom: Rom +): + """An exit that timed out or failed may still be writing the dump.""" + with _streaming(_webstation_for(rom)): + _claim_webstation_ok(client, access_token, rom.id) + with ( + patch("handler.streaming.webstation.exit_session", return_value=None), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.fetch_save_archive", return_value=None + ) as fetch, + ): + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + _run_exit_pulls(spawn) + assert fetch.call_count == broker.PULL_ATTEMPTS + + +@pytest.mark.parametrize( + ("exit_report", "wait", "attempts"), + [ + (None, True, broker.PULL_ATTEMPTS), + ({"state_saved": True, "state_slot": 10}, False, 1), + ({"state_saved": False, "state_slot": None}, True, 1), + ], +) +def test_a_webstation_save_and_exit_takes_one_answer_only_once_its_exit_answers( + client, + access_token, + rom: Rom, + exit_report: dict | None, + wait: bool, + attempts: int, +): + """This exit always blocks until the dump is written, whatever wait says, + but one that timed out or failed may still be writing it.""" + with _streaming(_webstation_for(rom)): + _claim_webstation_ok(client, access_token, rom.id) + with ( + patch( + "handler.streaming.webstation.exit_session", return_value=exit_report + ), + patch( + "handler.streaming.states.pull_state_to_library", + new=AsyncMock(return_value=True), + ), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.fetch_save_archive", return_value=None + ) as fetch, + ): + client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + json={"slot": 0, "wait": wait}, + headers=_auth(access_token), + ) + _run_exit_pulls(spawn) + assert fetch.call_count == attempts + + +def test_a_release_keeps_asking_while_the_emulator_flushes( + client, access_token, rom: Rom +): + """A per-emulator broker acks the stop before the emulator has flushed its + saves, so an early "nothing new" is not the answer yet.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with ( + _stub_stop(), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.fetch_save_archive", return_value=None + ) as fetch, + ): + client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + _run_exit_pulls(spawn) + assert fetch.call_count == broker.PULL_ATTEMPTS + + +def test_an_abandoned_teardown_keeps_asking_while_the_emulator_flushes( + client, access_token, admin_user: User, rom: Rom +): + container = _container_for(rom) + with _streaming(container): + _claim_ok(client, access_token, rom.id) + _age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60) + session = json.loads(_session_raw(container)) + with ( + _stub_stop(), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.fetch_save_archive", return_value=None + ) as fetch, + ): + asyncio.run( + lifecycle._teardown_abandoned_session( + _resolved(container), + _key_of(container), + session, + claimed_by=admin_user.id, + ) + ) + _run_exit_pulls(spawn) + assert fetch.call_count == broker.PULL_ATTEMPTS + + +def test_a_force_release_keeps_asking_while_the_emulator_flushes( + client, access_token, rom: Rom +): + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with ( + _stub_stop(), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.fetch_save_archive", return_value=None + ) as fetch, + ): + client.delete("/api/streaming/sessions", headers=_auth(access_token)) + _run_exit_pulls(spawn) + assert fetch.call_count == broker.PULL_ATTEMPTS + + +def _broker_saves(body: dict): + """A broker whose save-and-exit answers with `body`, and nothing else.""" + return lambda _container, path, *args, **kwargs: ( + body if path == "/save-and-exit" else None + ) + + +@pytest.mark.parametrize( + ("saved", "attempts"), [(True, 1), (False, broker.PULL_ATTEMPTS)] +) +def test_a_blocking_save_and_exit_takes_one_answer_only_once_the_broker_confirms( + client, access_token, rom: Rom, saved: bool, attempts: int +): + """A save-and-exit that timed out or failed may still be killing the + emulator, so only a confirmed one has finished writing.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with ( + patch( + "handler.streaming.broker.request_safe", + side_effect=_broker_saves({"saved": saved, "slot": 10}), + ), + patch( + "handler.streaming.states.pull_state_to_library", + new=AsyncMock(return_value=True), + ), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.fetch_save_archive", return_value=None + ) as fetch, + ): + client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + json={"slot": 0, "wait": True}, + headers=_auth(access_token), + ) + _run_exit_pulls(spawn) + assert fetch.call_count == attempts + + +def test_a_background_save_and_exit_keeps_asking_while_the_emulator_writes( + client, access_token, rom: Rom +): + """With wait=false the broker is still saving when the pull starts, so an + early "nothing new" is not the answer yet, even from a save it confirmed.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with ( + patch( + "handler.streaming.broker.request_safe", + side_effect=_broker_saves({"saved": True, "slot": 10}), + ), + patch( + "handler.streaming.states.pull_state_to_library", + new=AsyncMock(return_value=True), + ), + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch( + "handler.streaming.saves.fetch_save_archive", return_value=None + ) as fetch, + ): + client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + json={"slot": 0, "wait": False}, + headers=_auth(access_token), + ) + _run_exit_pulls(spawn) + assert fetch.call_count == broker.PULL_ATTEMPTS + + +def test_save_and_exit_marks_the_save_pull_before_giving_up_the_key( + client, access_token, admin_user: User, rom: Rom +): + """With no state to wait on, the key is deleted outright, so a claim can win + it the moment it goes and has to find the pull already pending.""" + key = saves._save_pull_redis_key(admin_user.id, rom.id) + pending_at_release: list[int] = [] + real_release = streaming.release_own_session + + async def release_after_looking(*args, **kwargs): + pending_at_release.append(await async_cache.exists(key)) + return await real_release(*args, **kwargs) + + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with ( + patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(False, 10, False), + ), + patch("handler.streaming.background.spawn_sync_task"), + patch.object(streaming, "release_own_session", release_after_looking), + ): + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + json={"slot": 0, "wait": True}, + headers=_auth(access_token), + ) + asyncio.run(async_cache.delete(key)) + assert r.status_code == 200 + assert pending_at_release == [1] + + +def test_a_claim_waits_for_a_running_save_pull(): + async def scenario() -> bool: + mark = await saves.mark_save_pull_pending(1, 2) + waiter = asyncio.create_task(saves.wait_for_save_pull(1, 2, budget=5)) + await asyncio.sleep(saves._SAVE_PULL_POLL_SECONDS * 2) + assert not waiter.done() + await saves.clear_save_pull_pending(mark) + return await waiter + + assert asyncio.run(scenario()) is True + + +def test_a_wedged_save_pull_does_not_hang_the_claim(): + """A claim is an interactive request: a pull that never finishes costs the + player the previous archive, not a claim that never answers.""" + + async def scenario() -> bool: + mark = await saves.mark_save_pull_pending(1, 2) + try: + return await saves.wait_for_save_pull(1, 2, budget=0.1) + finally: + await saves.clear_save_pull_pending(mark) + + assert asyncio.run(scenario()) is False + + +def test_a_claim_with_nothing_pending_hydrates_straight_away(): + assert asyncio.run(saves.wait_for_save_pull(1, 2, budget=5)) is True + + +def test_an_earlier_pull_finishing_leaves_a_later_exits_mark( + admin_user: User, rom: Rom +): + """A pull can outlast a claim's wait, so the player can play and exit again + while it runs, and its finishing must not let a claim past the later pull.""" + container = _resolved(_container_for(rom)) + session = {"user_id": admin_user.id, "rom_id": rom.id} + + async def scenario() -> tuple[bool, bool]: + with ( + patch("handler.streaming.background.spawn_sync_task") as spawn, + patch("handler.streaming.saves.pull_saves_to_library", new=AsyncMock()), + ): + for _ in range(2): + mark = await lifecycle.mark_exit_saves_pending(container, session) + lifecycle.collect_exit_saves(container, session, mark, settled=False) + first, second = (c.args[0] for c in spawn.call_args_list) + await first + behind_second = await _save_pull_pending(admin_user.id, rom.id) + await second + return behind_second, await _save_pull_pending(admin_user.id, rom.id) + + assert asyncio.run(scenario()) == (True, False) # ── Resume-from-state ───────────────────────────────────────────────────────── @@ -4241,6 +5734,42 @@ def test_stamped_state_filename_round_trips_for_retroarch(): assert states.container_state_filename(stamped) == "Super Mario.state" +def test_exit_state_filenames_resolve_to_the_working_slot(): + """DuckStation and RPCS3 write one state per game, as they exit, with no + slot in its name, so the working slot is the only one a pick can mean.""" + assert states.slot_from_state_filename("duckstation", "SLUS-00594_resume.sav") == 0 + assert states.slot_from_state_filename("duckstation", "SLUS-00594.mcd") is None + assert states.slot_from_state_filename("rpcs3", "BLUS30443_1.SAVESTAT") == 0 + assert states.slot_from_state_filename("rpcs3", "BLUS30443_1.SAVESTAT.zst") == 0 + assert states.slot_from_state_filename("rpcs3", "BLUS30443_1.SAVESTAT.gz") == 0 + assert states.slot_from_state_filename("rpcs3", "PARAM.SFO") is None + + +@pytest.mark.parametrize( + ("emulator", "name", "shape"), + [ + ( + "duckstation", + "SLUS-00594_resume.sav", + r"SLUS-00594_resume\.\d{8}-\d{12}\.sav", + ), + ( + "rpcs3", + "BLUS30443_1.SAVESTAT.zst", + r"BLUS30443_1\.\d{8}-\d{12}\.SAVESTAT\.zst", + ), + ], +) +def test_stamped_exit_state_filename_round_trips(emulator, name, shape): + """Every exit is its own library entry, and the stamped name still resolves + a slot: otherwise the entries the stamp creates could never be picked.""" + when = datetime(2026, 7, 21, 4, 56, 45, 123456, tzinfo=timezone.utc) + stamped = states.stamped_state_filename(emulator, name, when) + assert re.fullmatch(shape, stamped) + assert states.container_state_filename(stamped) == name + assert states.slot_from_state_filename(emulator, stamped) == 0 + + class _ResumeClaim(NamedTuple): response: httpx.Response ready: dict[str, Any] @@ -4467,6 +5996,74 @@ def test_webstation_resume_state_is_pushed_after_activate( assert order.push.call_args[0][1] == "Game.03.p2s" +@pytest.mark.parametrize( + ("emulator", "name"), + [ + ("duckstation", "SLUS-00594_resume.20260918-010000000000.sav"), + ("rpcs3", "BLUS30443_1.20260918-010000000000.SAVESTAT"), + ], +) +def test_an_exit_state_resume_is_the_activate_slot_alone( + client, access_token, rom: Rom, admin_user: User, emulator, name +): + """These brokers refuse a state file mid-session and resume from the exit + state the save archive brings back, so the slot on the activate is the whole + resume. A push would only be refused and report the resume as lost.""" + state = db_state_handler.add_state(_state_for(rom, admin_user, name, emulator)) + activate = MagicMock(return_value={"url": "/room/x"}) + push = MagicMock(return_value=False) + with _streaming({**_webstation_for(rom), "emulator": emulator}): + with ( + patch("handler.streaming.webstation.activate", activate), + patch("handler.streaming.states.push_state_file", push), + patch( + "handler.streaming.saves.hydrate_saves_to_webstation", + new=AsyncMock(return_value="/romm/saves/archive.tar"), + ), + patch( + "handler.filesystem.fs_asset_handler.read_file", + new=AsyncMock(return_value=b"state-bytes"), + ), + patch("handler.streaming.background.spawn_sync_task"), + patch( + "handler.streaming.states.hydrate_states_to_broker", new=MagicMock() + ) as hydrate, + ): + with _pushes() as sent: + r = _claim(client, access_token, rom.id, state_id=state.id) + assert r.status_code == 202 + assert activate.call_args.kwargs["resume_slot"] == 0 + push.assert_not_called() + assert _launch_ready(sent)["resume"] is True + assert hydrate.call_args.kwargs["resume_pushed"] is True + + +def test_an_exit_state_resume_with_no_archive_reports_the_resume_lost( + client, access_token, rom: Rom, admin_user: User +): + """The archive is the whole resume on these brokers, so without one the slot + would load whatever the container last held and the player would not be told.""" + state = db_state_handler.add_state( + _state_for(rom, admin_user, "SLUS-00594_resume.sav", "duckstation") + ) + activate = MagicMock(return_value={"url": "/room/x"}) + with _streaming({**_webstation_for(rom), "emulator": "duckstation"}): + with ( + patch("handler.streaming.webstation.activate", activate), + patch( + "handler.streaming.saves.hydrate_saves_to_webstation", + new=AsyncMock(return_value=None), + ), + patch("handler.streaming.background.spawn_sync_task"), + patch("handler.streaming.states.hydrate_states_to_broker", new=MagicMock()), + ): + with _pushes() as sent: + r = _claim(client, access_token, rom.id, state_id=state.id) + assert r.status_code == 202 + assert activate.call_args.kwargs["resume_slot"] is None + assert _launch_ready(sent)["resume"] is False + + def test_webstation_claim_without_a_state_boots_clean(client, access_token, rom: Rom): """A restored archive puts in-game saves back, nothing more: no picked state means no resume_slot, even though the archive carries the exit @@ -4496,14 +6093,14 @@ def test_stopping_a_webstation_broker_reports_the_state_it_captured(rom: Rom): "handler.streaming.webstation.exit_session", return_value={"state_saved": True, "state_slot": 10}, ): - assert commands.stop(_resolved(container)) == 10 + assert commands.stop(_resolved(container)) == (10, True) with patch( "handler.streaming.webstation.exit_session", return_value={"state_saved": False, "state_slot": 10}, ): - assert commands.stop(_resolved(container)) is None + assert commands.stop(_resolved(container)) == (None, True) with patch("handler.streaming.webstation.exit_session", return_value=None): - assert commands.stop(_resolved(container)) is None + assert commands.stop(_resolved(container)) == (None, False) def test_stopping_without_saving_asks_the_broker_to_write_no_state(rom: Rom): @@ -4514,7 +6111,7 @@ def test_stopping_without_saving_asks_the_broker_to_write_no_state(rom: Rom): "handler.streaming.webstation.exit_session", return_value={"state_saved": False, "state_slot": None}, ) as exit_call: - assert commands.stop(_resolved(container), save=False) is None + assert commands.stop(_resolved(container), save=False).state_slot is None assert exit_call.call_args.kwargs["save"] is False @@ -4533,7 +6130,7 @@ def test_a_webstation_exit_carries_slot_zero_rather_than_dropping_it(rom: Rom): def test_stopping_a_legacy_broker_reports_no_state(rom: Rom): """The per-emulator brokers stop without saving, so nothing is pulled.""" with patch("handler.streaming.broker.request_safe", return_value={}): - assert commands.stop(_resolved(_container_for(rom))) is None + assert commands.stop(_resolved(_container_for(rom))) == (None, False) def test_releasing_a_webstation_session_pulls_the_exit_state( @@ -4579,7 +6176,7 @@ def test_releasing_without_saving_files_no_state(client, access_token, rom: Rom) """The stop button is the deliberate way out without saving, so the exit writes nothing and there is no state to pull into the library.""" pull = AsyncMock(return_value=True) - stop = MagicMock(return_value=None) + stop = MagicMock(return_value=commands.StopOutcome()) with _streaming(_webstation_for(rom)): with ( patch( @@ -4656,7 +6253,7 @@ def test_admin_can_release_other_users_session( """An admin may release a session claimed by someone else.""" with _streaming(_container_for(rom)): _claim_ok(client, viewer_access_token, rom.id) - with patch("handler.streaming.commands.stop", return_value=None) as stop: + with _stub_stop() as stop: r = client.delete( f"/api/streaming/sessions/{rom.platform_slug}", headers=_auth(access_token), @@ -5064,7 +6661,10 @@ def test_save_and_exit_evacuates_card(client, access_token, rom: Rom): ): _mc_claim(client, access_token, rom.id) with ( - patch("handler.streaming.commands.save_and_exit", return_value=(True, 1)), + patch( + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 1, True), + ), patch( "handler.streaming.memory_cards.evacuate_card", new=AsyncMock(return_value=True), @@ -5101,7 +6701,7 @@ def test_release_evacuates_card(client, access_token, rom: Rom): ): _mc_claim(client, access_token, rom.id) with ( - patch("handler.streaming.commands.stop", return_value=None) as stop, + _stub_stop() as stop, patch( "handler.streaming.memory_cards.evacuate_card", new=AsyncMock(return_value=True), @@ -5141,7 +6741,7 @@ def test_release_frees_the_claim_when_teardown_raises(client, access_token, rom: ): _mc_claim(client, access_token, rom.id) with ( - patch("handler.streaming.commands.stop", return_value=None), + _stub_stop(), patch( "handler.streaming.memory_cards.evacuate_session_card", new=AsyncMock(side_effect=OSError("broker went away")), @@ -5174,7 +6774,8 @@ def test_save_and_exit_wait_false_forces_blocking_on_card_sync( _mc_claim(client, access_token, rom.id) with ( patch( - "handler.streaming.commands.save_and_exit", return_value=(True, 1) + "handler.streaming.commands.save_and_exit", + return_value=commands.SaveAndExitOutcome(True, 1, True), ) as save, patch( "handler.streaming.memory_cards.evacuate_card", @@ -5767,7 +7368,7 @@ def test_releasing_a_session_takes_it_off_the_activity_board( container = _container_for(rom) with _streaming(container): _claim_ok(client, access_token, rom.id) - with patch("handler.streaming.commands.stop", return_value=None): + with _stub_stop(): r = client.delete( f"/api/streaming/sessions/{rom.platform_slug}", headers=_auth(access_token), @@ -6107,6 +7708,19 @@ def test_joinable_hides_a_solo_session( assert body["sessions"] == [] +def test_joinable_skips_the_rom_lookup_for_a_session_nobody_may_join( + client, access_token, viewer_access_token, rom: Rom +): + """Home polls this listing, and most live sessions are solo.""" + container = {"host": "http://192.168.1.10:3000", "platform": rom.platform_slug} + with _streaming(container): + _claim_ok(client, access_token, rom.id) + with patch("handler.streaming.access.session_rom") as lookup: + _joinable(client, viewer_access_token) + + lookup.assert_not_called() + + def test_joinable_hides_a_session_nobody_could_join( client, access_token, viewer_access_token, rom: Rom ): @@ -6240,6 +7854,112 @@ def test_joining_a_rom_on_a_hidden_platform_is_404_masked( join_broker.assert_not_called() +def _ws_pool_member(rom: Rom, index: int, **overrides) -> dict: + """One member of a pool of webstation containers, the broker a joiner needs, + on a distinct host so the room URL says which member answered.""" + return _webstation( + **{ + "host": f"http://192.168.1.1{index}:3000", + "broker_host": f"http://192.168.1.1{index}:8000", + "platforms": {rom.platform_slug: "pcsx2"}, + **overrides, + } + ) + + +def _joined_room(url: str = "/webstation/?token=abc"): + return patch("handler.streaming.webstation.join", return_value={"url": url}) + + +def test_joining_walks_past_a_session_whose_rom_is_hidden( + client, + access_token, + editor_access_token, + viewer_access_token, + viewer_user: User, + rom: Rom, + second_rom: Rom, +): + """A hidden ROM earlier in the pool is not the caller's answer, so it must + not mask the joinable session behind it.""" + _hide(PermEntity.ROMS, rom.id, viewer_user.id) + with _streaming(_ws_pool_member(rom, 0), _ws_pool_member(rom, 1)): + _claim_multiplayer(client, access_token, rom.id) + _claim_multiplayer(client, editor_access_token, second_rom.id) + with _joined_room(): + r = _join(client, viewer_access_token, rom.platform_slug) + + assert r.status_code == 200 + assert r.json()["rom_id"] == second_rom.id + + +def test_joining_walks_past_the_callers_own_session( + client, access_token, viewer_access_token, rom: Rom, second_rom: Rom +): + """Joining is for somebody else's game: the caller's own session is the one + they already hold, and the listing leaves it out for the same reason.""" + with _streaming(_ws_pool_member(rom, 0), _ws_pool_member(rom, 1)): + _claim_multiplayer(client, viewer_access_token, rom.id) + _claim_multiplayer(client, access_token, second_rom.id) + with _joined_room(): + r = _join(client, viewer_access_token, rom.platform_slug) + + assert r.status_code == 200 + assert r.json()["rom_id"] == second_rom.id + + +def test_joining_walks_past_a_session_on_another_platform( + client, + access_token, + editor_access_token, + viewer_access_token, + rom: Rom, + second_rom: Rom, +): + """A container serves several platforms and holds one session, so a member + busy with another platform is not this platform's session to join.""" + member = _ws_pool_member( + rom, 0, platforms={rom.platform_slug: "pcsx2", "ngc": "dolphin"} + ) + with _streaming(member, _ws_pool_member(rom, 1)): + _claim_multiplayer(client, access_token, rom.id) + key = session_store.session_redis_key(_key_of(member)) + session = json.loads(asyncio.run(async_cache.get(key))) + session["platform"] = "ngc" + asyncio.run(async_cache.set(key, json.dumps(session))) + _claim_multiplayer(client, editor_access_token, second_rom.id) + with _joined_room(): + r = _join(client, viewer_access_token, rom.platform_slug) + + assert r.status_code == 200 + assert r.json()["rom_id"] == second_rom.id + + +def test_joining_a_named_container_busy_with_another_platform_is_a_404( + client, access_token, viewer_access_token, rom: Rom +): + """Naming the container skips the walk, not its platform check: the game there + now may be another platform's, never the one the caller asked to join.""" + member = _ws_pool_member( + rom, 0, platforms={rom.platform_slug: "pcsx2", "ngc": "dolphin"} + ) + with _streaming(member): + _claim_multiplayer(client, access_token, rom.id) + key = session_store.session_redis_key(_key_of(member)) + session = json.loads(asyncio.run(async_cache.get(key))) + session["platform"] = "ngc" + asyncio.run(async_cache.set(key, json.dumps(session))) + with _joined_room(): + r = _join( + client, + viewer_access_token, + rom.platform_slug, + container=_key_of(member), + ) + + assert r.status_code == 404 + + def test_joining_a_solo_session_finds_nothing_to_join( client, access_token, viewer_access_token, rom: Rom ): @@ -6314,7 +8034,7 @@ def test_joining_requires_auth(client, rom: Rom): def _expand(entry: dict) -> list[ResolvedContainer]: """The records the resolver builds for one raw config entry.""" with _streaming(entry): - return list(streaming.resolve_containers()) + return list(resolve_containers()) def test_expand_platform_block_overrides_container_defaults(): diff --git a/backend/tests/utils/test_openapi.py b/backend/tests/utils/test_openapi.py new file mode 100644 index 000000000..45815a64a --- /dev/null +++ b/backend/tests/utils/test_openapi.py @@ -0,0 +1,51 @@ +from fastapi import FastAPI +from pydantic import BaseModel + +from utils.openapi import publish_socket_payloads + + +class _Inner(BaseModel): + value: int + + +class _Payload(BaseModel): + name: str + inner: _Inner + + +class _Route(BaseModel): + ok: bool + + +def _app() -> FastAPI: + app = FastAPI() + + @app.get("/route") + def route() -> _Route: + return _Route(ok=True) + + publish_socket_payloads(app, [_Payload]) + return app + + +def test_payload_and_its_nested_models_join_route_schemas(): + schemas = _app().openapi()["components"]["schemas"] + + assert "_Route" in schemas + assert schemas["_Payload"]["properties"]["inner"] == { + "$ref": "#/components/schemas/_Inner" + } + assert "_Inner" in schemas + + +def test_schema_is_built_once(): + app = _app() + + assert app.openapi() is app.openapi() + + +def test_app_without_routes_still_gets_the_payloads(): + app = FastAPI() + publish_socket_payloads(app, [_Payload]) + + assert "_Payload" in app.openapi()["components"]["schemas"] diff --git a/backend/utils/openapi.py b/backend/utils/openapi.py new file mode 100644 index 000000000..26aa17d3a --- /dev/null +++ b/backend/utils/openapi.py @@ -0,0 +1,28 @@ +from collections.abc import Sequence +from typing import Any + +from fastapi import FastAPI +from pydantic import BaseModel +from pydantic.json_schema import models_json_schema + + +def publish_socket_payloads(app: FastAPI, models: Sequence[type[BaseModel]]) -> None: + """Add Socket.IO payload models to the app's OpenAPI components. + + No route references them, so FastAPI would leave them out, and the + frontend's generated types would lack the shapes its socket handlers read. + """ + build_schema = app.openapi + + def openapi() -> dict[str, Any]: + if app.openapi_schema is None: + schema = build_schema() + _, definitions = models_json_schema( + [(model, "serialization") for model in models], + ref_template="#/components/schemas/{model}", + ) + components = schema.setdefault("components", {}).setdefault("schemas", {}) + components.update(definitions.get("$defs", {})) + return app.openapi_schema + + app.openapi = openapi # type: ignore[method-assign] diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index 032da6e64..6793cf626 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -72,6 +72,7 @@ export type { ClientTokenSchema } from './models/ClientTokenSchema'; export type { CollectionRomsPayload } from './models/CollectionRomsPayload'; export type { CollectionSchema } from './models/CollectionSchema'; export type { ConfigResponse } from './models/ConfigResponse'; +export type { ContainerBusyDetail } from './models/ContainerBusyDetail'; export type { ContainerSessionSchema } from './models/ContainerSessionSchema'; export type { ConversionStats } from './models/ConversionStats'; export type { ConversionTaskMeta } from './models/ConversionTaskMeta'; @@ -131,7 +132,10 @@ export type { JoinableSessionSchema } from './models/JoinableSessionSchema'; export type { JoinableSessionsResponse } from './models/JoinableSessionsResponse'; export type { JoinedSessionSchema } from './models/JoinedSessionSchema'; export type { LaunchboxImage } from './models/LaunchboxImage'; +export type { LaunchFailedPayload } from './models/LaunchFailedPayload'; export type { LaunchingSessionSchema } from './models/LaunchingSessionSchema'; +export type { LaunchPhasePayload } from './models/LaunchPhasePayload'; +export type { LaunchReadyPayload } from './models/LaunchReadyPayload'; export type { LoadStateRequest } from './models/LoadStateRequest'; export type { LoadStateResponse } from './models/LoadStateResponse'; export type { LogEntrySchema } from './models/LogEntrySchema'; diff --git a/frontend/src/__generated__/models/AdminContainerSchema.ts b/frontend/src/__generated__/models/AdminContainerSchema.ts index 9d9f072ab..a461f546b 100644 --- a/frontend/src/__generated__/models/AdminContainerSchema.ts +++ b/frontend/src/__generated__/models/AdminContainerSchema.ts @@ -10,6 +10,7 @@ export type AdminContainerSchema = { platforms: Array; supports_desktop: boolean; configured: boolean; + draining?: boolean; session?: (ContainerSessionSchema | null); }; diff --git a/frontend/src/__generated__/models/ContainerBusyDetail.ts b/frontend/src/__generated__/models/ContainerBusyDetail.ts new file mode 100644 index 000000000..c6406c415 --- /dev/null +++ b/frontend/src/__generated__/models/ContainerBusyDetail.ts @@ -0,0 +1,14 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +/** + * The 409 body when a claim finds its container held. + */ +export type ContainerBusyDetail = { + message: string; + draining: boolean; + rom_name: (string | null); + claimed_at: (string | null); +}; + diff --git a/frontend/src/__generated__/models/LaunchFailedPayload.ts b/frontend/src/__generated__/models/LaunchFailedPayload.ts new file mode 100644 index 000000000..c458dd803 --- /dev/null +++ b/frontend/src/__generated__/models/LaunchFailedPayload.ts @@ -0,0 +1,14 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +/** + * `streaming:launch-failed`. The claim is already released. + */ +export type LaunchFailedPayload = { + platform: string; + container: string; + claimed_at: string; + detail: string; +}; + diff --git a/frontend/src/__generated__/models/LaunchPhasePayload.ts b/frontend/src/__generated__/models/LaunchPhasePayload.ts new file mode 100644 index 000000000..0419da55e --- /dev/null +++ b/frontend/src/__generated__/models/LaunchPhasePayload.ts @@ -0,0 +1,14 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +/** + * `streaming:launch-phase`, while a broker unpacks a large title. + */ +export type LaunchPhasePayload = { + platform: string; + container: string; + claimed_at: string; + phase?: (string | null); +}; + diff --git a/frontend/src/__generated__/models/LaunchReadyPayload.ts b/frontend/src/__generated__/models/LaunchReadyPayload.ts new file mode 100644 index 000000000..22fda9923 --- /dev/null +++ b/frontend/src/__generated__/models/LaunchReadyPayload.ts @@ -0,0 +1,15 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +/** + * `streaming:launch-ready`, pushed once the game is up. + */ +export type LaunchReadyPayload = { + platform: string; + container: string; + claimed_at: string; + host: string; + resume?: (boolean | null); +}; + diff --git a/frontend/src/__generated__/models/SaveAndExitResponse.ts b/frontend/src/__generated__/models/SaveAndExitResponse.ts index 30be0b567..e94de32ff 100644 --- a/frontend/src/__generated__/models/SaveAndExitResponse.ts +++ b/frontend/src/__generated__/models/SaveAndExitResponse.ts @@ -3,7 +3,7 @@ /* tslint:disable */ /* eslint-disable */ export type SaveAndExitResponse = { - status: string; + status: 'ok' | 'not_found'; saved: boolean; platform: string; released: boolean; diff --git a/frontend/src/__generated__/models/SessionStatusSchema.ts b/frontend/src/__generated__/models/SessionStatusSchema.ts index 89dbda469..5c78470d7 100644 --- a/frontend/src/__generated__/models/SessionStatusSchema.ts +++ b/frontend/src/__generated__/models/SessionStatusSchema.ts @@ -7,6 +7,7 @@ export type SessionStatusSchema = { status: 'active' | 'ended'; platform: string; extraction_phase?: (string | null); + host?: (string | null); termination?: (SessionTerminationSchema | null); }; diff --git a/frontend/src/__generated__/models/SessionTerminationSchema.ts b/frontend/src/__generated__/models/SessionTerminationSchema.ts index b66bc3b59..8d592dc44 100644 --- a/frontend/src/__generated__/models/SessionTerminationSchema.ts +++ b/frontend/src/__generated__/models/SessionTerminationSchema.ts @@ -15,5 +15,8 @@ export type SessionTerminationSchema = { platform?: (string | null); rom_id?: (number | null); rom_name?: (string | null); + container?: (string | null); + claimed_at?: (string | null); + desktop?: boolean; }; diff --git a/frontend/src/__generated__/models/StreamingConfigSchema.ts b/frontend/src/__generated__/models/StreamingConfigSchema.ts index 30daad1bc..eb9b6bb09 100644 --- a/frontend/src/__generated__/models/StreamingConfigSchema.ts +++ b/frontend/src/__generated__/models/StreamingConfigSchema.ts @@ -6,5 +6,6 @@ import type { StreamingContainerSchema } from './StreamingContainerSchema'; export type StreamingConfigSchema = { enabled: boolean; containers: Array; + emulator_labels: Record; }; diff --git a/frontend/src/__generated__/models/StreamingContainerSchema.ts b/frontend/src/__generated__/models/StreamingContainerSchema.ts index 5d46882d5..0121f48bd 100644 --- a/frontend/src/__generated__/models/StreamingContainerSchema.ts +++ b/frontend/src/__generated__/models/StreamingContainerSchema.ts @@ -14,5 +14,6 @@ export type StreamingContainerSchema = { emulator: string; supports_memory_cards: boolean; supports_save_picker: boolean; + supports_live_states: boolean; }; diff --git a/frontend/src/locales/bg_BG/play.json b/frontend/src/locales/bg_BG/play.json index 62391c37c..2084af7d3 100644 --- a/frontend/src/locales/bg_BG/play.json +++ b/frontend/src/locales/bg_BG/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} работи на този контейнер. Първо прекратете тази сесия.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Заглушаване", "stream-occupied-body": "{rom} се играе от {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Предишната сесия все още се затваря. Опитайте отново след малко.", "stream-occupied-fallback": "В момента играе някой друг. Опитайте отново по-късно.", "stream-occupied-title": "Сесията е заета", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/bg_BG/settings.json b/frontend/src/locales/bg_BG/settings.json index 7f762a8fc..91c7b2ecc 100644 --- a/frontend/src/locales/bg_BG/settings.json +++ b/frontend/src/locales/bg_BG/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Предишната сесия се затваря", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/cs_CZ/play.json b/frontend/src/locales/cs_CZ/play.json index 9358454ec..f704da016 100644 --- a/frontend/src/locales/cs_CZ/play.json +++ b/frontend/src/locales/cs_CZ/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "Na tomto kontejneru běží {rom}. Nejprve tuto relaci ukončete.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Ztlumit", "stream-occupied-body": "{rom} se hraje od {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Předchozí relace se stále ukončuje. Zkuste to znovu za chvíli.", "stream-occupied-fallback": "Právě hraje někdo jiný. Zkuste to později.", "stream-occupied-title": "Relace se používá", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/cs_CZ/settings.json b/frontend/src/locales/cs_CZ/settings.json index 9807989e0..ad756ae4a 100644 --- a/frontend/src/locales/cs_CZ/settings.json +++ b/frontend/src/locales/cs_CZ/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Ukončování předchozí relace", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/de_DE/play.json b/frontend/src/locales/de_DE/play.json index e32c2e508..52e0f3fb1 100644 --- a/frontend/src/locales/de_DE/play.json +++ b/frontend/src/locales/de_DE/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "Auf diesem Container läuft {rom}. Beende zuerst diese Sitzung.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Stummschalten", "stream-occupied-body": "{rom} wird seit {time} gespielt.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Die vorherige Sitzung wird noch beendet. Versuche es gleich noch einmal.", "stream-occupied-fallback": "Jemand anderes spielt gerade. Versuchen Sie es später erneut.", "stream-occupied-title": "Sitzung in Benutzung", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/de_DE/settings.json b/frontend/src/locales/de_DE/settings.json index b9bff3853..b65c049c5 100644 --- a/frontend/src/locales/de_DE/settings.json +++ b/frontend/src/locales/de_DE/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Vorherige Sitzung wird beendet", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/en_GB/play.json b/frontend/src/locales/en_GB/play.json index e754dadc2..0f1fc2734 100644 --- a/frontend/src/locales/en_GB/play.json +++ b/frontend/src/locales/en_GB/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} is running on this container. End that session first.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Mute", "stream-occupied-body": "{rom} has been playing since {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "The previous session is still shutting down. Try again in a moment.", "stream-occupied-fallback": "Someone else is currently playing. Try again later.", "stream-occupied-title": "Session in use", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/en_GB/settings.json b/frontend/src/locales/en_GB/settings.json index a8ce4109f..4ab063709 100644 --- a/frontend/src/locales/en_GB/settings.json +++ b/frontend/src/locales/en_GB/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Shutting down the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/en_US/play.json b/frontend/src/locales/en_US/play.json index 135c92888..e67c6d035 100644 --- a/frontend/src/locales/en_US/play.json +++ b/frontend/src/locales/en_US/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} is running on this container. End that session first.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Mute", "stream-occupied-body": "{rom} has been playing since {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "The previous session is still shutting down. Try again in a moment.", "stream-occupied-fallback": "Someone else is currently playing. Try again later.", "stream-occupied-title": "Session in use", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/en_US/settings.json b/frontend/src/locales/en_US/settings.json index 68eeb8cba..f339380d3 100644 --- a/frontend/src/locales/en_US/settings.json +++ b/frontend/src/locales/en_US/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Shutting down the previous session", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/es_ES/play.json b/frontend/src/locales/es_ES/play.json index 86f54d809..c8ec3257d 100644 --- a/frontend/src/locales/es_ES/play.json +++ b/frontend/src/locales/es_ES/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} se está ejecutando en este contenedor. Finaliza esa sesión primero.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Silenciar", "stream-occupied-body": "{rom} se está jugando desde las {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "La sesión anterior aún se está cerrando. Inténtalo de nuevo en un momento.", "stream-occupied-fallback": "Otra persona está jugando en este momento. Inténtalo de nuevo más tarde.", "stream-occupied-title": "Sesión en uso", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/es_ES/settings.json b/frontend/src/locales/es_ES/settings.json index d8f333225..cfd9d2b8b 100644 --- a/frontend/src/locales/es_ES/settings.json +++ b/frontend/src/locales/es_ES/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Cerrando la sesión anterior", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/fr_FR/play.json b/frontend/src/locales/fr_FR/play.json index 284be0cfc..da41ceea4 100644 --- a/frontend/src/locales/fr_FR/play.json +++ b/frontend/src/locales/fr_FR/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} est en cours d'exécution sur ce conteneur. Terminez d'abord cette session.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Couper le son", "stream-occupied-body": "{rom} est en cours de partie depuis {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "La session précédente est encore en cours de fermeture. Réessayez dans un instant.", "stream-occupied-fallback": "Quelqu'un d'autre joue actuellement. Réessayez plus tard.", "stream-occupied-title": "Session en cours d'utilisation", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/fr_FR/settings.json b/frontend/src/locales/fr_FR/settings.json index b221cbb26..9067c4e2e 100644 --- a/frontend/src/locales/fr_FR/settings.json +++ b/frontend/src/locales/fr_FR/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Fermeture de la session précédente", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/hu_HU/play.json b/frontend/src/locales/hu_HU/play.json index d45aef98a..2005490f1 100644 --- a/frontend/src/locales/hu_HU/play.json +++ b/frontend/src/locales/hu_HU/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "Ezen a konténeren fut: {rom}. Előbb fejezd be azt a munkamenetet.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Némítás", "stream-occupied-body": "A(z) {rom} játékban van {time} óta.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Az előző munkamenet még leáll. Próbáld újra egy pillanat múlva.", "stream-occupied-fallback": "Jelenleg valaki más játszik. Próbálja meg később.", "stream-occupied-title": "A munkamenet használatban van", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/hu_HU/settings.json b/frontend/src/locales/hu_HU/settings.json index bd45a1154..98b981f0a 100644 --- a/frontend/src/locales/hu_HU/settings.json +++ b/frontend/src/locales/hu_HU/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Az előző munkamenet leállítása", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/it_IT/play.json b/frontend/src/locales/it_IT/play.json index 0ed68941d..0608a6663 100644 --- a/frontend/src/locales/it_IT/play.json +++ b/frontend/src/locales/it_IT/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} è in esecuzione su questo container. Termina prima quella sessione.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Disattiva audio", "stream-occupied-body": "{rom} è in gioco da {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "La sessione precedente è ancora in chiusura. Riprova tra un momento.", "stream-occupied-fallback": "Qualcun altro sta giocando in questo momento. Riprova più tardi.", "stream-occupied-title": "Sessione in uso", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/it_IT/settings.json b/frontend/src/locales/it_IT/settings.json index 8621d0c73..602ab4a98 100644 --- a/frontend/src/locales/it_IT/settings.json +++ b/frontend/src/locales/it_IT/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Chiusura della sessione precedente", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/ja_JP/play.json b/frontend/src/locales/ja_JP/play.json index 474a92f9e..95bae7b5a 100644 --- a/frontend/src/locales/ja_JP/play.json +++ b/frontend/src/locales/ja_JP/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "このコンテナでは {rom} が実行中です。先にそのセッションを終了してください。", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "ミュート", "stream-occupied-body": "{rom} は {time} からプレイされています。", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "前のセッションはまだ終了処理中です。しばらくしてからもう一度お試しください。", "stream-occupied-fallback": "現在、他の人がプレイ中です。後でもう一度お試しください。", "stream-occupied-title": "セッション使用中", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/ja_JP/settings.json b/frontend/src/locales/ja_JP/settings.json index 3454c575f..6dcc42d6c 100644 --- a/frontend/src/locales/ja_JP/settings.json +++ b/frontend/src/locales/ja_JP/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "前のセッションを終了しています", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/ko_KR/play.json b/frontend/src/locales/ko_KR/play.json index 6a4371ae1..f6c23fe3c 100644 --- a/frontend/src/locales/ko_KR/play.json +++ b/frontend/src/locales/ko_KR/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "이 컨테이너에서 {rom}이(가) 실행 중입니다. 먼저 해당 세션을 종료하세요.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "음소거", "stream-occupied-body": "{rom}을(를) {time}부터 플레이하고 있습니다.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "이전 세션이 아직 종료되는 중입니다. 잠시 후 다시 시도하세요.", "stream-occupied-fallback": "현재 다른 사람이 플레이 중입니다. 나중에 다시 시도하세요.", "stream-occupied-title": "세션 사용 중", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/ko_KR/settings.json b/frontend/src/locales/ko_KR/settings.json index 19b6b46bc..d8781fbce 100644 --- a/frontend/src/locales/ko_KR/settings.json +++ b/frontend/src/locales/ko_KR/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "이전 세션을 종료하는 중", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/pl_PL/play.json b/frontend/src/locales/pl_PL/play.json index 6c2774ab5..f4bf3b6e6 100644 --- a/frontend/src/locales/pl_PL/play.json +++ b/frontend/src/locales/pl_PL/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "Na tym kontenerze działa {rom}. Najpierw zakończ tę sesję.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Wycisz", "stream-occupied-body": "{rom} jest w grze od {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Poprzednia sesja wciąż się zamyka. Spróbuj ponownie za chwilę.", "stream-occupied-fallback": "Ktoś inny obecnie gra. Spróbuj ponownie później.", "stream-occupied-title": "Sesja w użyciu", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/pl_PL/settings.json b/frontend/src/locales/pl_PL/settings.json index 8b360915c..69cc407fa 100644 --- a/frontend/src/locales/pl_PL/settings.json +++ b/frontend/src/locales/pl_PL/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Zamykanie poprzedniej sesji", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/pt_BR/play.json b/frontend/src/locales/pt_BR/play.json index 3fb16e79f..10fd867e8 100644 --- a/frontend/src/locales/pt_BR/play.json +++ b/frontend/src/locales/pt_BR/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} está em execução neste contêiner. Encerre essa sessão primeiro.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Silenciar", "stream-occupied-body": "{rom} está sendo jogado desde {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "A sessão anterior ainda está sendo encerrada. Tente novamente em instantes.", "stream-occupied-fallback": "Outra pessoa está jogando no momento. Tente novamente mais tarde.", "stream-occupied-title": "Sessão em uso", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/pt_BR/settings.json b/frontend/src/locales/pt_BR/settings.json index fe3829f7c..e6312b6c3 100644 --- a/frontend/src/locales/pt_BR/settings.json +++ b/frontend/src/locales/pt_BR/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Encerrando a sessão anterior", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/ro_RO/play.json b/frontend/src/locales/ro_RO/play.json index 8834d5689..3078a278c 100644 --- a/frontend/src/locales/ro_RO/play.json +++ b/frontend/src/locales/ro_RO/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "{rom} rulează pe acest container. Închide mai întâi acea sesiune.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Dezactivează sunetul", "stream-occupied-body": "{rom} este jucat din {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Sesiunea anterioară încă se închide. Încearcă din nou peste câteva momente.", "stream-occupied-fallback": "Altcineva joacă în acest moment. Încercați din nou mai târziu.", "stream-occupied-title": "Sesiune în uz", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/ro_RO/settings.json b/frontend/src/locales/ro_RO/settings.json index e46ef94f4..c3887f577 100644 --- a/frontend/src/locales/ro_RO/settings.json +++ b/frontend/src/locales/ro_RO/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Se închide sesiunea anterioară", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/ru_RU/play.json b/frontend/src/locales/ru_RU/play.json index 6788de43d..088f31ad1 100644 --- a/frontend/src/locales/ru_RU/play.json +++ b/frontend/src/locales/ru_RU/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "На этом контейнере запущено: {rom}. Сначала завершите эту сессию.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Отключить звук", "stream-occupied-body": "В {rom} играют с {time}.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Предыдущая сессия ещё завершается. Попробуйте снова через несколько секунд.", "stream-occupied-fallback": "Сейчас играет кто-то другой. Повторите попытку позже.", "stream-occupied-title": "Сеанс занят", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/ru_RU/settings.json b/frontend/src/locales/ru_RU/settings.json index 0a0385e7f..b72aad941 100644 --- a/frontend/src/locales/ru_RU/settings.json +++ b/frontend/src/locales/ru_RU/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Завершение предыдущей сессии", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/tr_TR/play.json b/frontend/src/locales/tr_TR/play.json index 3e25f7515..63f1978dc 100644 --- a/frontend/src/locales/tr_TR/play.json +++ b/frontend/src/locales/tr_TR/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "Bu konteynerde {rom} çalışıyor. Önce o oturumu sonlandırın.", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "Sessize al", "stream-occupied-body": "{rom} {time} saatinden beri oynanıyor.", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "Önceki oturum hâlâ kapatılıyor. Birazdan tekrar deneyin.", "stream-occupied-fallback": "Şu anda başka biri oynuyor. Daha sonra tekrar deneyin.", "stream-occupied-title": "Oturum kullanımda", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/tr_TR/settings.json b/frontend/src/locales/tr_TR/settings.json index 6d417f8d6..e3677656b 100644 --- a/frontend/src/locales/tr_TR/settings.json +++ b/frontend/src/locales/tr_TR/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "Önceki oturum kapatılıyor", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/locales/zh_CN/play.json b/frontend/src/locales/zh_CN/play.json index e1a214169..00c78dcbd 100644 --- a/frontend/src/locales/zh_CN/play.json +++ b/frontend/src/locales/zh_CN/play.json @@ -29,6 +29,7 @@ "desktop-back": "返回管理后台", "desktop-error-no-container": "未配置该串流容器。", "desktop-error-occupied": "此容器正在使用中。请先结束占用它的会话。", + "desktop-error-occupied-by": "此容器上正在运行 {rom}。请先结束该会话。", "desktop-error-release": "无法释放桌面会话。容器可能仍在使用中。", "desktop-error-server": "无法打开桌面会话。", "desktop-exit": "结束桌面会话", @@ -225,7 +226,7 @@ "stream-load-state-failed": "无法加载该状态。", "stream-mute": "静音", "stream-occupied-body": "{rom} 自 {time} 起一直在游玩。", - "stream-occupied-draining": "上一个会话仍在保存中。请稍后再试。", + "stream-occupied-draining": "上一个会话仍在关闭中。请稍后再试。", "stream-occupied-fallback": "当前有其他人正在游玩。请稍后再试。", "stream-occupied-title": "会话使用中", "stream-release-failed": "无法释放会话。容器可能仍在使用中。", diff --git a/frontend/src/locales/zh_CN/settings.json b/frontend/src/locales/zh_CN/settings.json index 66db3dc49..a37a71f38 100644 --- a/frontend/src/locales/zh_CN/settings.json +++ b/frontend/src/locales/zh_CN/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "桌面会话", "streaming-disabled": "此服务器已禁用模拟器串流。", + "streaming-draining": "正在关闭上一个会话", "streaming-idle": "空闲", "streaming-load-failed": "无法加载串流容器。", "streaming-none": "未配置任何串流容器。", diff --git a/frontend/src/locales/zh_TW/play.json b/frontend/src/locales/zh_TW/play.json index c85dfca2c..322d7c468 100644 --- a/frontend/src/locales/zh_TW/play.json +++ b/frontend/src/locales/zh_TW/play.json @@ -29,6 +29,7 @@ "desktop-back": "Back to administration", "desktop-error-no-container": "That streaming container is not configured.", "desktop-error-occupied": "This container is already in use. End the session holding it first.", + "desktop-error-occupied-by": "此容器上正在執行 {rom}。請先結束該工作階段。", "desktop-error-release": "The desktop session could not be released. The container may still be in use.", "desktop-error-server": "The desktop session could not be opened.", "desktop-exit": "End desktop session", @@ -225,7 +226,7 @@ "stream-load-state-failed": "The state could not be loaded.", "stream-mute": "靜音", "stream-occupied-body": "{rom} 自 {time} 起一直在遊玩。", - "stream-occupied-draining": "The previous session is still saving. Try again in a moment.", + "stream-occupied-draining": "上一個工作階段仍在關閉中。請稍後再試。", "stream-occupied-fallback": "目前有其他人正在遊玩。請稍後再試。", "stream-occupied-title": "工作階段使用中", "stream-release-failed": "The session could not be released. The container may still be in use.", diff --git a/frontend/src/locales/zh_TW/settings.json b/frontend/src/locales/zh_TW/settings.json index 9fa68eed6..3cdacf352 100644 --- a/frontend/src/locales/zh_TW/settings.json +++ b/frontend/src/locales/zh_TW/settings.json @@ -462,6 +462,7 @@ "streaming-by": "({user})", "streaming-desktop-session": "Desktop session", "streaming-disabled": "Emulator streaming is disabled on this server.", + "streaming-draining": "正在關閉上一個工作階段", "streaming-idle": "Idle", "streaming-load-failed": "Could not load the streaming containers.", "streaming-none": "No streaming containers are configured.", diff --git a/frontend/src/services/api/streaming.test.ts b/frontend/src/services/api/streaming.test.ts new file mode 100644 index 000000000..ced0361bd --- /dev/null +++ b/frontend/src/services/api/streaming.test.ts @@ -0,0 +1,99 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import streamingApi from "@/services/api/streaming"; + +const post = vi.hoisted(() => vi.fn()); + +vi.mock("@/services/api", () => ({ + default: { post }, + keepaliveHeaders: () => ({}), +})); + +describe("releaseSessionKeepalive", () => { + const fetchMock = vi.fn().mockResolvedValue(new Response()); + + beforeEach(() => { + vi.stubGlobal("fetch", fetchMock); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + fetchMock.mockClear(); + }); + + it("names the container and the claim where URLSearchParams has no size", async () => { + // Chrome 111-112 and Safari 16.4 are in .browserslistrc and predate it. + vi.spyOn(URLSearchParams.prototype, "size", "get").mockReturnValue( + undefined as unknown as number, + ); + + await streamingApi.releaseSessionKeepalive( + "ps2", + "WEBSTATION-DEV", + "2026-09-17T12:00:00+00:00", + ); + + expect(fetchMock.mock.calls[0][0]).toBe( + "/api/streaming/sessions/ps2?container=WEBSTATION-DEV&claimed_at=2026-09-17T12%3A00%3A00%2B00%3A00", + ); + }); + + it("sends no query when there is nothing to name", async () => { + await streamingApi.releaseSessionKeepalive("ps2"); + + expect(fetchMock.mock.calls[0][0]).toBe("/api/streaming/sessions/ps2"); + }); +}); + +describe("saveAndExitKeepalive", () => { + const fetchMock = vi.fn().mockResolvedValue(new Response()); + + beforeEach(() => { + vi.stubGlobal("fetch", fetchMock); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + fetchMock.mockClear(); + }); + + it("names the container and the claim it saves", async () => { + await streamingApi.saveAndExitKeepalive( + "ps2", + 0, + "WEBSTATION-DEV", + "2026-09-17T12:00:00+00:00", + ); + + expect(fetchMock.mock.calls[0][0]).toBe( + "/api/streaming/sessions/ps2/save-and-exit?container=WEBSTATION-DEV&claimed_at=2026-09-17T12%3A00%3A00%2B00%3A00", + ); + }); +}); + +describe("saveAndExit", () => { + beforeEach(() => { + post.mockReset(); + }); + + it("names the container and the claim it saves", async () => { + await streamingApi.saveAndExit( + "ps2", + 0, + true, + "WEBSTATION-DEV", + "2026-09-17T12:00:00+00:00", + ); + + expect(post).toHaveBeenCalledWith( + "/streaming/sessions/ps2/save-and-exit", + { slot: 0, wait: true }, + { + params: { + container: "WEBSTATION-DEV", + claimed_at: "2026-09-17T12:00:00+00:00", + }, + }, + ); + }); +}); diff --git a/frontend/src/services/api/streaming.ts b/frontend/src/services/api/streaming.ts index 644cd34e4..bbed3767a 100644 --- a/frontend/src/services/api/streaming.ts +++ b/frontend/src/services/api/streaming.ts @@ -1,16 +1,31 @@ import type { AdminContainerSchema, + AdminContainersResponse, AdminSessionSchema, + AdminSessionsResponse, + ClaimStreamingSessionRequest, + ContainerBusyDetail, LaunchingSessionSchema, DesktopSessionSchema, JoinableSessionSchema, + JoinableSessionsResponse, JoinedSessionSchema, + LaunchFailedPayload, + LaunchPhasePayload, + LaunchReadyPayload, + LoadStateResponse, MemoryCardImportRequired, + MuteResponse, + ReleaseSessionResponse, + SaveAndExitResponse, + SaveStateResponse, SessionStatusSchema, SessionTerminationSchema, SlotCapabilitiesSchema, StreamingConfigSchema, StreamingContainerSchema, + SwapDiscResponse, + VolumeResponse, } from "@/__generated__"; import api, { keepaliveHeaders } from "@/services/api"; @@ -26,34 +41,12 @@ export type StreamingContainer = StreamingContainerSchema; export type StreamingConfig = StreamingConfigSchema; export type LaunchingSession = LaunchingSessionSchema; -// The launch's own result arrives on the socket, and socket payloads reach no -// route so they are not in the OpenAPI schema (constitution SS X.10, backend -// debt). The backend builds each of these from a model of the same name in -// endpoints/responses/streaming.py, so the shapes stay tied. +// Socket payloads reach no route, so the backend publishes them into the +// schema by hand (utils/openapi.py). +export type LaunchReady = LaunchReadyPayload; +export type LaunchFailed = LaunchFailedPayload; +export type LaunchPhase = LaunchPhasePayload; -/** `streaming:launch-ready`: the game is up, and `host` is the iframe URL. */ -export interface LaunchReady { - platform: string; - container: string; - host: string; - /** null when no resume was asked for; false means the state could not be - * pushed and the session started fresh. */ - resume: boolean | null; -} - -/** `streaming:launch-failed`. The claim is already released. */ -export interface LaunchFailed { - platform: string; - container: string; - detail: string; -} - -/** `streaming:launch-phase`, while a broker unpacks a large title. */ -export interface LaunchPhase { - platform: string; - container: string; - phase: string | null; -} export type AdminStreamingSession = AdminSessionSchema; export type AdminStreamingContainer = AdminContainerSchema; export type DesktopSession = DesktopSessionSchema; @@ -68,7 +61,9 @@ export type MemoryCardImportDetail = MemoryCardImportRequired; /** The answer to that prompt, replayed on the retried claim. "discard" erases * the card currently on the container. */ -export type MemoryCardImport = "adopt" | "discard"; +export type MemoryCardImport = NonNullable< + ClaimStreamingSessionRequest["card_import"] +>; export function isMemoryCardImportDetail( value: unknown, @@ -80,6 +75,20 @@ export function isMemoryCardImportDetail( ); } +/** Body of the 409 a claim returns when the container is taken. */ +export type { ContainerBusyDetail }; + +/** The query naming a claim by its container and the stamp it was taken at. */ +function claimParams( + container?: string | null, + claimedAt?: string | null, +): { container?: string; claimed_at?: string } { + return { + ...(container != null ? { container } : {}), + ...(claimedAt != null ? { claimed_at: claimedAt } : {}), + }; +} + // ── Requests ────────────────────────────────────────────────────────────────── async function fetchConfig() { @@ -112,17 +121,18 @@ async function claimSession( async function releaseSession( platform: string, reason?: string, - container?: string, + container?: string | null, save?: boolean, + claimedAt?: string | null, ) { - return api.delete(`/streaming/sessions/${platform}`, { + return api.delete(`/streaming/sessions/${platform}`, { params: { + // The holder names its container and stamp so a taken-over tab cannot end + // the claim that replaced it. An admin names its pick and no stamp. + ...claimParams(container, claimedAt), // Sent whenever the caller supplied one, empty string included: the // backend treats the param's presence as "this is an admin force-release". ...(reason !== undefined ? { reason } : {}), - // Names which container to release, needed when a pool serves the - // platform and the admin is ending a session they do not own. - ...(container !== undefined ? { container } : {}), // Only the player who deliberately stopped without saving sends this. // Everything else leaves it off so the backend still autosaves. ...(save === false ? { save: false } : {}), @@ -131,9 +141,7 @@ async function releaseSession( } async function listJoinableSessions() { - return api.get<{ sessions: JoinableSession[] }>( - "/streaming/sessions/joinable", - ); + return api.get("/streaming/sessions/joinable"); } async function joinSession(platform: string, container?: string) { @@ -144,61 +152,111 @@ async function joinSession(platform: string, container?: string) { ); } -async function saveAndExit(platform: string, slot = 0, wait = true) { - return api.post(`/streaming/sessions/${platform}/save-and-exit`, { - slot, - wait, - }); +async function saveAndExit( + platform: string, + slot = 0, + wait = true, + container?: string | null, + claimedAt?: string | null, +) { + return api.post( + `/streaming/sessions/${platform}/save-and-exit`, + { slot, wait }, + { params: claimParams(container, claimedAt) }, + ); } -async function heartbeatSession(platform: string, container?: string) { +async function heartbeatSession( + platform: string, + container?: string | null, + claimedAt?: string | null, +) { return api.post( `/streaming/sessions/${platform}/heartbeat`, undefined, - { params: { container } }, + { params: claimParams(container, claimedAt) }, ); } -async function sessionStatus(platform: string) { - return api.get(`/streaming/sessions/${platform}/status`); -} - -async function setVolume(platform: string, level: number) { - return api.post(`/streaming/sessions/${platform}/volume`, { - level: Math.round(level), +async function sessionStatus(platform: string, claimedAt?: string | null) { + return api.get(`/streaming/sessions/${platform}/status`, { + params: { claimed_at: claimedAt }, }); } -async function setMute(platform: string, mute?: boolean) { - return api.post( +async function setVolume( + platform: string, + level: number, + container?: string | null, + claimedAt?: string | null, +) { + return api.post( + `/streaming/sessions/${platform}/volume`, + { level: Math.round(level) }, + { params: claimParams(container, claimedAt) }, + ); +} + +async function setMute( + platform: string, + mute?: boolean, + container?: string | null, + claimedAt?: string | null, +) { + return api.post( `/streaming/sessions/${platform}/mute`, mute !== undefined ? { mute } : {}, + { params: claimParams(container, claimedAt) }, ); } -async function saveState(platform: string, slot = 1) { - return api.post(`/streaming/sessions/${platform}/save-state`, { slot }); +async function saveState( + platform: string, + slot = 1, + container?: string | null, + claimedAt?: string | null, +) { + return api.post( + `/streaming/sessions/${platform}/save-state`, + { slot }, + { params: claimParams(container, claimedAt) }, + ); } -async function loadState(platform: string, slot = 1) { - return api.post(`/streaming/sessions/${platform}/load-state`, { slot }); +async function loadState( + platform: string, + slot = 1, + container?: string | null, + claimedAt?: string | null, +) { + return api.post( + `/streaming/sessions/${platform}/load-state`, + { slot }, + { params: claimParams(container, claimedAt) }, + ); } -async function swapDisc(platform: string, fileId: number) { - return api.post(`/streaming/sessions/${platform}/swap-disc`, { - file_id: fileId, - }); +async function swapDisc( + platform: string, + fileId: number, + container?: string | null, + claimedAt?: string | null, +) { + return api.post( + `/streaming/sessions/${platform}/swap-disc`, + { file_id: fileId }, + { params: claimParams(container, claimedAt) }, + ); } async function adminListSessions() { - return api.get<{ sessions: AdminStreamingSession[] }>("/streaming/sessions"); + return api.get("/streaming/sessions"); } async function adminListContainers() { - return api.get<{ enabled: boolean; containers: AdminStreamingContainer[] }>( - "/streaming/containers", - { headers: { "Cache-Control": "no-cache" } }, - ); + return api.get("/streaming/containers", { + headers: { "Cache-Control": "no-cache" }, + }); } async function claimDesktop(container: string) { @@ -211,8 +269,28 @@ async function claimDesktop(container: string) { // sendBeacon cannot carry the CSRF header, so the cookie-sourced header is // set by hand (mirrors the axios interceptor). -function saveAndExitKeepalive(platform: string, slot = 0): Promise { - return fetch(`/api/streaming/sessions/${platform}/save-and-exit`, { +// Names which container and which claim, so an unload cannot end the claim +// that replaced it. +function claimQuery( + container?: string | null, + claimedAt?: string | null, +): string { + const search = new URLSearchParams( + Object.entries(claimParams(container, claimedAt)).filter( + ([, value]) => value, + ), + ).toString(); + return search ? `?${search}` : ""; +} + +function saveAndExitKeepalive( + platform: string, + slot = 0, + container?: string | null, + claimedAt?: string | null, +): Promise { + const query = claimQuery(container, claimedAt); + return fetch(`/api/streaming/sessions/${platform}/save-and-exit${query}`, { method: "POST", keepalive: true, credentials: "same-origin", @@ -223,10 +301,10 @@ function saveAndExitKeepalive(platform: string, slot = 0): Promise { function releaseSessionKeepalive( platform: string, - container?: string, + container?: string | null, + claimedAt?: string | null, ): Promise { - // Names which container to release, for the platforms a pool serves. - const query = container ? `?container=${encodeURIComponent(container)}` : ""; + const query = claimQuery(container, claimedAt); return fetch(`/api/streaming/sessions/${platform}${query}`, { method: "DELETE", keepalive: true, diff --git a/frontend/src/stores/streaming.test.ts b/frontend/src/stores/streaming.test.ts index 521593193..604aeae14 100644 --- a/frontend/src/stores/streaming.test.ts +++ b/frontend/src/stores/streaming.test.ts @@ -4,7 +4,11 @@ import streamingApi, { type JoinableSession } from "@/services/api/streaming"; import { useStreamingStore } from "@/stores/streaming"; vi.mock("@/services/api/streaming", () => ({ - default: { listJoinableSessions: vi.fn() }, + default: { + listJoinableSessions: vi.fn(), + saveAndExit: vi.fn(), + saveAndExitKeepalive: vi.fn(), + }, })); describe("platformCapabilities disc flags", () => { @@ -14,6 +18,7 @@ describe("platformCapabilities disc flags", () => { const store = useStreamingStore(); store.config = { enabled: true, + emulator_labels: {}, containers: [ { platform: "dc", @@ -22,6 +27,7 @@ describe("platformCapabilities disc flags", () => { emulator: "retroarch", supports_memory_cards: false, supports_save_picker: false, + supports_live_states: true, capabilities: { max_slots: 0, has_autosave: true, @@ -43,6 +49,41 @@ describe("platformCapabilities disc flags", () => { }); }); +describe("emulator labels", () => { + beforeEach(() => setActivePinia(createPinia())); + + it("names an emulator by the label the backend ships", () => { + const store = useStreamingStore(); + store.config = { + enabled: true, + containers: [], + emulator_labels: { play: "Play!" }, + }; + expect(store.emulatorLabel("play")).toBe("Play!"); + }); + + it("names an emulator configured in another case", () => { + const store = useStreamingStore(); + store.config = { + enabled: true, + containers: [], + emulator_labels: { play: "Play!" }, + }; + expect(store.emulatorLabel("Play")).toBe("Play!"); + }); + + it("falls back to the id for an emulator it was told nothing about", () => { + const store = useStreamingStore(); + expect(store.emulatorLabel("snes9x")).toBe("snes9x"); + }); + + it("falls back to the id for one named like an object's own members", () => { + const store = useStreamingStore(); + expect(store.emulatorLabel("constructor")).toBe("constructor"); + expect(store.emulatorLabel("__proto__")).toBe("__proto__"); + }); +}); + describe("joinable sessions", () => { const listJoinableSessions = streamingApi.listJoinableSessions as unknown as Mock; @@ -116,3 +157,53 @@ describe("joinable sessions", () => { expect(store.joinableForRom(7)?.host_username).toBe("ana"); }); }); + +describe("save-and-exit", () => { + const saveAndExit = streamingApi.saveAndExit as unknown as Mock; + const saveAndExitKeepalive = + streamingApi.saveAndExitKeepalive as unknown as Mock; + + beforeEach(() => { + setActivePinia(createPinia()); + saveAndExit.mockReset(); + saveAndExitKeepalive.mockReset(); + }); + + it("names the claim it saves", async () => { + saveAndExit.mockResolvedValue({ data: { released: true, saved: true } }); + + await useStreamingStore().saveAndExit( + "ps2", + 0, + false, + "ps2-1", + "2026-01-01T00:00:00Z", + ); + + expect(saveAndExit).toHaveBeenCalledWith( + "ps2", + 0, + false, + "ps2-1", + "2026-01-01T00:00:00Z", + ); + }); + + it("names the claim it saves on unload", () => { + saveAndExitKeepalive.mockResolvedValue(new Response()); + + useStreamingStore().saveAndExitKeepalive( + "ps2", + 0, + "ps2-1", + "2026-01-01T00:00:00Z", + ); + + expect(saveAndExitKeepalive).toHaveBeenCalledWith( + "ps2", + 0, + "ps2-1", + "2026-01-01T00:00:00Z", + ); + }); +}); diff --git a/frontend/src/stores/streaming.ts b/frontend/src/stores/streaming.ts index 4ad1cdf7f..bceafd032 100644 --- a/frontend/src/stores/streaming.ts +++ b/frontend/src/stores/streaming.ts @@ -10,6 +10,7 @@ import type { StreamingConfig, StreamingContainer, } from "@/services/api/streaming"; +import { emulatorLabelFrom } from "@/v2/utils/assets"; export type { LaunchingSession, @@ -39,6 +40,7 @@ export const useStreamingStore = defineStore("streaming", () => { const config = ref({ enabled: false, containers: [], + emulator_labels: {}, }); const launchingSession = ref(null); const loading = ref(false); @@ -79,6 +81,11 @@ export const useStreamingStore = defineStore("streaming", () => { return container.label || container.emulator || null; } + /** The backend's display name for an emulator id, else the id as it stands. */ + function emulatorLabel(emulator: string | null | undefined): string { + return emulatorLabelFrom(config.value.emulator_labels, emulator); + } + /** * Returns per-platform save-state capabilities for the streaming player UI, * sourced from the container config the backend ships in /config (the single @@ -121,6 +128,7 @@ export const useStreamingStore = defineStore("streaming", () => { config.value = { enabled: data.enabled ?? false, containers: data.containers ?? [], + emulator_labels: data.emulator_labels ?? {}, }; } catch (err) { error.value = String(err); @@ -252,10 +260,18 @@ export const useStreamingStore = defineStore("streaming", () => { async function releaseSession( platform: string, save = true, + container?: string | null, + claimedAt?: string | null, ): Promise { if (!platform) return false; try { - await streamingApi.releaseSession(platform, undefined, undefined, save); + await streamingApi.releaseSession( + platform, + undefined, + container, + save, + claimedAt, + ); launchingSession.value = null; return true; } catch (err) { @@ -278,10 +294,18 @@ export const useStreamingStore = defineStore("streaming", () => { platform: string, slot = 0, wait = true, + container?: string | null, + claimedAt?: string | null, ): Promise<{ released: boolean; saved: boolean }> { if (!platform) return { released: false, saved: false }; try { - const { data } = await streamingApi.saveAndExit(platform, slot, wait); + const { data } = await streamingApi.saveAndExit( + platform, + slot, + wait, + container, + claimedAt, + ); const released = data.released ?? true; if (released) launchingSession.value = null; return { released, saved: data.saved ?? false }; @@ -302,11 +326,16 @@ export const useStreamingStore = defineStore("streaming", () => { */ async function heartbeatSession( platform: string, - container?: string, + container?: string | null, + claimedAt?: string | null, ): Promise { if (!platform) return null; try { - const { data } = await streamingApi.heartbeatSession(platform, container); + const { data } = await streamingApi.heartbeatSession( + platform, + container, + claimedAt, + ); return data; } catch (err) { console.warn("[streaming] Could not heartbeat session:", err); @@ -321,10 +350,11 @@ export const useStreamingStore = defineStore("streaming", () => { */ async function fetchSessionStatus( platform: string, + claimedAt?: string, ): Promise { if (!platform) return null; try { - const { data } = await streamingApi.sessionStatus(platform); + const { data } = await streamingApi.sessionStatus(platform, claimedAt); return data; } catch (err) { console.warn("[streaming] Could not fetch session status:", err); @@ -338,26 +368,39 @@ export const useStreamingStore = defineStore("streaming", () => { * is gone (wait=false; the backend forces a blocking save for card-sync * containers anyway). Best-effort, never throws. */ - function saveAndExitKeepalive(platform: string, slot = 0): void { + function saveAndExitKeepalive( + platform: string, + slot = 0, + container?: string | null, + claimedAt?: string | null, + ): void { if (!platform) return; launchingSession.value = null; // The caller is unloading and cannot await, so the rejection is caught on // the promise itself; try/catch here would only see a synchronous throw. - streamingApi.saveAndExitKeepalive(platform, slot).catch((err) => { - console.warn("[streaming] Could not save-and-exit (keepalive):", err); - }); + streamingApi + .saveAndExitKeepalive(platform, slot, container, claimedAt) + .catch((err) => { + console.warn("[streaming] Could not save-and-exit (keepalive):", err); + }); } /** * releaseSession for the pagehide path. Fire-and-forget via fetch * keepalive. Best-effort, never throws. */ - function releaseSessionKeepalive(platform: string): void { + function releaseSessionKeepalive( + platform: string, + container?: string | null, + claimedAt?: string | null, + ): void { if (!platform) return; launchingSession.value = null; - streamingApi.releaseSessionKeepalive(platform).catch((err) => { - console.warn("[streaming] Could not release session (keepalive):", err); - }); + streamingApi + .releaseSessionKeepalive(platform, container, claimedAt) + .catch((err) => { + console.warn("[streaming] Could not release session (keepalive):", err); + }); } return { @@ -369,6 +412,7 @@ export const useStreamingStore = defineStore("streaming", () => { isEnabled, containerForPlatform, containerLabelForPlatform, + emulatorLabel, platformCapabilities, fetchConfig, claimSession, diff --git a/frontend/src/test-utils/serverError.ts b/frontend/src/test-utils/serverError.ts index 00bef7986..f7c09812e 100644 --- a/frontend/src/test-utils/serverError.ts +++ b/frontend/src/test-utils/serverError.ts @@ -1,7 +1,7 @@ import { AxiosError } from "axios"; /** A refused request as axios rejects it, carrying FastAPI's `detail`. */ -export function serverError(detail: string, status = 503): AxiosError { +export function serverError(detail: unknown, status = 503): AxiosError { return Object.assign(new AxiosError(`HTTP ${status}`), { response: { status, data: { detail } }, }); diff --git a/frontend/src/test-utils/streamingStore.ts b/frontend/src/test-utils/streamingStore.ts new file mode 100644 index 000000000..222bee905 --- /dev/null +++ b/frontend/src/test-utils/streamingStore.ts @@ -0,0 +1,14 @@ +import { emulatorLabelFrom } from "@/v2/utils/assets"; + +// Stands in for `@/stores/streaming` via `vi.mock(path, () => import(...))`. +const EMULATOR_LABELS: Record = { + play: "Play!", + retroarch: "RetroArch", +}; + +export function useStreamingStore() { + return { + emulatorLabel: (id: string | null | undefined) => + emulatorLabelFrom(EMULATOR_LABELS, id), + }; +} diff --git a/frontend/src/v2/components/GameDetails/SaveDataTab.test.ts b/frontend/src/v2/components/GameDetails/SaveDataTab.test.ts new file mode 100644 index 000000000..f5318761d --- /dev/null +++ b/frontend/src/v2/components/GameDetails/SaveDataTab.test.ts @@ -0,0 +1,76 @@ +import { mount } from "@vue/test-utils"; +import { createPinia, setActivePinia } from "pinia"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { DetailedRomSchema, UserStateSchema } from "@/__generated__"; +import storeAuth from "@/stores/auth"; +import type { User } from "@/stores/users"; +import SaveDataTab from "./SaveDataTab.vue"; + +vi.mock("vue-i18n", () => ({ + useI18n: () => ({ t: (key: string) => key }), +})); +vi.mock("vue-router", async (importOriginal) => ({ + ...(await importOriginal()), + useRoute: () => ({ query: {}, path: "/rom/1", params: {} }), + useRouter: () => ({ replace: vi.fn(), push: vi.fn() }), +})); +vi.mock("@/v2/composables/useConfirm", () => ({ useConfirm: () => vi.fn() })); +vi.mock("@/v2/composables/useRomSync", () => ({ + useRomSync: () => ({ refetchRom: vi.fn() }), +})); +vi.mock("@/v2/composables/useSnackbar", () => ({ + useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }), +})); + +const UploadAssetDialog = { + props: { cores: { type: Array, default: () => [] } }, + template: `
`, +}; + +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; +} + +function mountTab(states: UserStateSchema[]) { + return mount(SaveDataTab, { + props: { + rom: { + id: 1, + platform_slug: "ps2", + all_user_saves: [], + all_user_states: states, + } as unknown as DetailedRomSchema, + }, + global: { + stubs: { + UploadAssetDialog, + SubtabNav: true, + AssetStrip: true, + AssetList: true, + RDropzone: true, + RBtn: true, + }, + }, + }); +} + +describe("SaveDataTab upload cores", () => { + beforeEach(() => { + setActivePinia(createPinia()); + storeAuth().setCurrentUser({ id: 1 } as User); + }); + + it("offers an emulator configured in another case once", () => { + const wrapper = mountTab([state(1, "play"), state(2, "Play")]); + + expect(wrapper.findComponent(UploadAssetDialog).props("cores")).toEqual([ + "play", + ]); + }); +}); diff --git a/frontend/src/v2/components/GameDetails/SaveDataTab.vue b/frontend/src/v2/components/GameDetails/SaveDataTab.vue index 602b171f7..ef14e4e71 100644 --- a/frontend/src/v2/components/GameDetails/SaveDataTab.vue +++ b/frontend/src/v2/components/GameDetails/SaveDataTab.vue @@ -48,7 +48,7 @@ import { useIdSelection } from "@/v2/composables/useIdSelection"; import { useRomSync } from "@/v2/composables/useRomSync"; import { useSnackbar } from "@/v2/composables/useSnackbar"; import { useSubtabQuery } from "@/v2/composables/useSubtabQuery"; -import type { AssetType } from "@/v2/utils/assets"; +import { emulatorKey, type AssetType } from "@/v2/utils/assets"; import { errorMessage } from "@/v2/utils/errorMessage"; // Slot payload from AssetList/AssetStrip is the full save|state union; these @@ -128,18 +128,20 @@ function openUpload(type: AssetType, files: File[] = []) { function closeUpload() { uploadDialog.value = null; } -// The cores the player offers plus whatever the existing states carry. +// The cores the player offers plus whatever the existing states carry, keyed +// case-insensitively as the backend matches them. const uploadCores = computed(() => { - const cores = new Set( - getSupportedEJSCores( - props.rom.platform_slug, - configStore.config.EJS_NETPLAY_ENABLED, - ), + const cores = new Map(); + const offered = getSupportedEJSCores( + props.rom.platform_slug, + configStore.config.EJS_NETPLAY_ENABLED, ); - for (const state of myStates.value) { - if (state.emulator) cores.add(state.emulator); + const carried = myStates.value.map((state) => state.emulator); + for (const core of [...offered, ...carried]) { + if (!core || cores.has(emulatorKey(core))) continue; + cores.set(emulatorKey(core), core); } - return [...cores]; + return [...cores.values()]; }); async function onUploadSubmit({ type, diff --git a/frontend/src/v2/components/GameDetails/UploadAssetDialog.test.ts b/frontend/src/v2/components/GameDetails/UploadAssetDialog.test.ts index d3fbd3838..9900ee048 100644 --- a/frontend/src/v2/components/GameDetails/UploadAssetDialog.test.ts +++ b/frontend/src/v2/components/GameDetails/UploadAssetDialog.test.ts @@ -11,6 +11,7 @@ vi.mock("vue-i18n", () => ({ vi.mock("@/locales", () => ({ default: { global: { t: (key: string) => key } }, })); +vi.mock("@/stores/streaming", () => import("@/test-utils/streamingStore")); const formValid = { value: true }; @@ -206,6 +207,18 @@ describe("UploadAssetDialog", () => { }); }); + it("names a streamed state's core by its emulator label", async () => { + const wrapper = mountDialog("state", [new File(["x"], "a.state")]); + await wrapper.setProps({ cores: ["play"] }); + + expect(wrapper.findAll("option").map((o) => o.text())).toEqual([ + "play.any-core", + "Play!", + ]); + await choose(wrapper, 0, 1); + expect(await submitted(wrapper)).toMatchObject({ emulator: "play" }); + }); + it("starts from the dropped files every time it opens", async () => { const wrapper = mountDialog("save", [], false); await wrapper.setProps({ diff --git a/frontend/src/v2/components/GameDetails/UploadAssetDialog.vue b/frontend/src/v2/components/GameDetails/UploadAssetDialog.vue index 7788cae2a..835d279e2 100644 --- a/frontend/src/v2/components/GameDetails/UploadAssetDialog.vue +++ b/frontend/src/v2/components/GameDetails/UploadAssetDialog.vue @@ -6,6 +6,7 @@ import { computed, ref, watch } from "vue"; import { useI18n } from "vue-i18n"; import type { SaveSchema } from "@/__generated__"; import { AUTOSAVE_SLOT, SAVE_SLOT_MAX_LENGTH } from "@/services/api/save"; +import { useStreamingStore } from "@/stores/streaming"; import PendingFilesDropzone from "@/v2/components/shared/PendingFilesDropzone.vue"; import type { AssetType } from "@/v2/utils/assets"; import { @@ -48,6 +49,7 @@ const emit = defineEmits<{ }>(); const { t } = useI18n(); +const { emulatorLabel } = useStreamingStore(); const slot = ref(existingSlot(AUTOSAVE_SLOT)); const newSlotName = ref(""); @@ -78,7 +80,7 @@ function onSlot(value: unknown) { const coreItems = computed(() => [ { value: "", title: t("play.any-core") }, - ...props.cores.map((value) => ({ value, title: value })), + ...props.cores.map((value) => ({ value, title: emulatorLabel(value) })), ]); watch( diff --git a/frontend/src/v2/components/Home/LiveSessionCard.vue b/frontend/src/v2/components/Home/LiveSessionCard.vue index 17bd288f7..1aeb14197 100644 --- a/frontend/src/v2/components/Home/LiveSessionCard.vue +++ b/frontend/src/v2/components/Home/LiveSessionCard.vue @@ -57,6 +57,7 @@ async function join(): Promise { romId, romName: title.value, hostUsername: props.session.host_username ?? null, + container: props.session.container, }); } diff --git a/frontend/src/v2/components/Player/AssetPreview.test.ts b/frontend/src/v2/components/Player/AssetPreview.test.ts new file mode 100644 index 000000000..fce753e35 --- /dev/null +++ b/frontend/src/v2/components/Player/AssetPreview.test.ts @@ -0,0 +1,32 @@ +import { mount } from "@vue/test-utils"; +import { describe, expect, it, vi } from "vitest"; +import { stateFixture } from "@/utils/assets.fixtures"; +import AssetPreview from "./AssetPreview.vue"; + +vi.mock("vue-i18n", () => ({ + useI18n: () => ({ t: (key: string) => key }), +})); +vi.mock("@/stores/streaming", () => import("@/test-utils/streamingStore")); + +const RTag = { + props: { text: { type: String, default: "" } }, + template: `{{ text }}`, +}; + +const state = stateFixture({ + file_name: "slot1.state", + file_size_bytes: 2048, + emulator: "play", + updated_at: "2026-05-10T18:45:00Z", +}); + +describe("AssetPreview", () => { + it("names the emulator the way the backend labels it", () => { + const wrapper = mount(AssetPreview, { + props: { asset: state, type: "state" }, + global: { stubs: { RTag, RIcon: true, RTooltip: true } }, + }); + + expect(wrapper.findAll(".tag").map((el) => el.text())).toContain("Play!"); + }); +}); diff --git a/frontend/src/v2/components/Player/AssetPreview.vue b/frontend/src/v2/components/Player/AssetPreview.vue index efc257147..e2a32d3f2 100644 --- a/frontend/src/v2/components/Player/AssetPreview.vue +++ b/frontend/src/v2/components/Player/AssetPreview.vue @@ -6,6 +6,7 @@ import { RIcon, RTag } from "@v2/lib"; import { computed } from "vue"; import { useI18n } from "vue-i18n"; import type { SaveSchema, StateSchema } from "@/__generated__"; +import { useStreamingStore } from "@/stores/streaming"; import { formatBytes } from "@/utils"; import AssetFavoriteMark from "@/v2/components/shared/AssetFavoriteMark.vue"; import AssetLabels from "@/v2/components/shared/AssetLabels.vue"; @@ -44,6 +45,7 @@ defineEmits<{ }>(); const { t } = useI18n(); +const { emulatorLabel } = useStreamingStore(); const screenshotUrl = computed(() => { if (!props.asset) return null; @@ -177,7 +179,7 @@ const emptyText = computed(() => v-if="type === 'state' && asset.emulator" tone="warning" size="x-small" - :text="asset.emulator" + :text="emulatorLabel(asset.emulator)" /> {{ formatBytes(asset.file_size_bytes) }} diff --git a/frontend/src/v2/components/Player/LoadSaveStateDialog.test.ts b/frontend/src/v2/components/Player/LoadSaveStateDialog.test.ts index 3533fdb90..0a40c030b 100644 --- a/frontend/src/v2/components/Player/LoadSaveStateDialog.test.ts +++ b/frontend/src/v2/components/Player/LoadSaveStateDialog.test.ts @@ -14,6 +14,7 @@ const { confirm } = vi.hoisted(() => ({ vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }), })); +vi.mock("@/stores/streaming", () => import("@/test-utils/streamingStore")); vi.mock("@/v2/composables/useConfirm", () => ({ useConfirm: () => confirm, })); diff --git a/frontend/src/v2/components/Player/SaveDataPanel.test.ts b/frontend/src/v2/components/Player/SaveDataPanel.test.ts index 4594fe475..04d08ff28 100644 --- a/frontend/src/v2/components/Player/SaveDataPanel.test.ts +++ b/frontend/src/v2/components/Player/SaveDataPanel.test.ts @@ -7,6 +7,7 @@ import SaveDataPanel from "./SaveDataPanel.vue"; vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key, locale: "en_US" }), })); +vi.mock("@/stores/streaming", () => import("@/test-utils/streamingStore")); function mountPanel(props: { save: SaveSchema | null }) { return mount(SaveDataPanel, { diff --git a/frontend/src/v2/components/Player/SessionEndedReason.test.ts b/frontend/src/v2/components/Player/SessionEndedReason.test.ts new file mode 100644 index 000000000..ee74aaab1 --- /dev/null +++ b/frontend/src/v2/components/Player/SessionEndedReason.test.ts @@ -0,0 +1,18 @@ +import { mount } from "@vue/test-utils"; +import { describe, expect, it, vi } from "vitest"; +import SessionEndedReason from "./SessionEndedReason.vue"; + +vi.mock("vue-i18n", () => ({ + useI18n: () => ({ t: (key: string) => key }), +})); + +describe("SessionEndedReason", () => { + it("shows the reason under its label", () => { + const wrapper = mount(SessionEndedReason, { + props: { reason: "Maintenance" }, + }); + + expect(wrapper.text()).toContain("play.session-ended-reason-label"); + expect(wrapper.text()).toContain("Maintenance"); + }); +}); diff --git a/frontend/src/v2/components/Player/SessionEndedReason.vue b/frontend/src/v2/components/Player/SessionEndedReason.vue new file mode 100644 index 000000000..94cca08d6 --- /dev/null +++ b/frontend/src/v2/components/Player/SessionEndedReason.vue @@ -0,0 +1,33 @@ + + + + + diff --git a/frontend/src/v2/components/Settings/StreamingSection.test.ts b/frontend/src/v2/components/Settings/StreamingSection.test.ts new file mode 100644 index 000000000..1bdff121d --- /dev/null +++ b/frontend/src/v2/components/Settings/StreamingSection.test.ts @@ -0,0 +1,113 @@ +import { flushPromises, mount } from "@vue/test-utils"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import StreamingSection from "./StreamingSection.vue"; + +const { adminListContainers, releaseSession, confirm } = vi.hoisted(() => ({ + adminListContainers: vi.fn(), + releaseSession: vi.fn(), + confirm: vi.fn(), +})); + +vi.mock("@/services/api/streaming", () => ({ + default: { adminListContainers, releaseSession }, +})); + +vi.mock("vue-i18n", () => ({ + useI18n: () => ({ + t: (key: string, params?: Record) => + params ? `${key}::${JSON.stringify(params)}` : key, + locale: { value: "en_US" }, + }), +})); + +vi.mock("vue-router", () => ({ useRouter: () => ({ push: vi.fn() }) })); +vi.mock("@/plugins/router", () => ({ + ROUTES: { STREAM_DESKTOP: "stream-desktop" }, +})); + +vi.mock("@/v2/composables/useConfirm", () => ({ useConfirm: () => confirm })); +vi.mock("@/v2/composables/useSnackbar", () => ({ + useSnackbar: () => ({ success: vi.fn(), error: vi.fn() }), +})); + +const RBtnStub = { + name: "RBtn", + props: ["disabled", "prependIcon"], + template: "", +}; + +function container(overrides: Record = {}) { + return { + container: "WEBSTATION-DEV", + label: "Webstation", + host: "https://webstation:8080", + platforms: ["ps2"], + supports_desktop: true, + configured: true, + draining: false, + session: null, + ...overrides, + }; +} + +async function mountSection() { + const wrapper = mount(StreamingSection, { + global: { + stubs: { + RBtn: RBtnStub, + RIcon: true, + RSpinner: true, + }, + }, + }); + await flushPromises(); + return wrapper; +} + +function desktopButton(wrapper: Awaited>) { + return wrapper + .findAllComponents(RBtnStub) + .find((btn) => btn.props("prependIcon") === "mdi-desktop-classic"); +} + +describe("StreamingSection draining containers", () => { + beforeEach(() => { + confirm.mockReset(); + releaseSession.mockReset(); + adminListContainers.mockReset(); + adminListContainers.mockResolvedValue({ + data: { enabled: true, containers: [container()] }, + }); + }); + + it("calls a free container idle", async () => { + const wrapper = await mountSection(); + + expect(wrapper.find(".r-v2-streaming__state").text()).toBe( + "settings.streaming-idle", + ); + expect(desktopButton(wrapper)?.props("disabled")).toBe(false); + }); + + it("says a draining container is still shutting down its last session", async () => { + adminListContainers.mockResolvedValue({ + data: { enabled: true, containers: [container({ draining: true })] }, + }); + + const wrapper = await mountSection(); + + expect(wrapper.find(".r-v2-streaming__state").text()).toBe( + "settings.streaming-draining", + ); + }); + + it("holds the desktop shut until the drain finishes", async () => { + adminListContainers.mockResolvedValue({ + data: { enabled: true, containers: [container({ draining: true })] }, + }); + + const wrapper = await mountSection(); + + expect(desktopButton(wrapper)?.props("disabled")).toBe(true); + }); +}); diff --git a/frontend/src/v2/components/Settings/StreamingSection.vue b/frontend/src/v2/components/Settings/StreamingSection.vue index ef7fda42f..74ea3a47c 100644 --- a/frontend/src/v2/components/Settings/StreamingSection.vue +++ b/frontend/src/v2/components/Settings/StreamingSection.vue @@ -111,6 +111,9 @@ async function release(container: AdminStreamingContainer): Promise { function sessionState(container: AdminStreamingContainer): string { const session = container.session; + // A drain marker holds the container with nobody behind it, so there is no + // session to describe and calling it idle invites a claim that still fails. + if (container.draining) return t("settings.streaming-draining"); if (!session) return t("settings.streaming-idle"); return [ session.desktop @@ -192,7 +195,11 @@ onMounted(load); variant="outlined" density="compact" prepend-icon="mdi-desktop-classic" - :disabled="!container.configured || !!container.session" + :disabled=" + !container.configured || + !!container.session || + !!container.draining + " @click="openDesktop(container)" > {{ t("settings.streaming-open-desktop") }} diff --git a/frontend/src/v2/components/shared/AssetChips.test.ts b/frontend/src/v2/components/shared/AssetChips.test.ts index d341ba1dd..8ef32e142 100644 --- a/frontend/src/v2/components/shared/AssetChips.test.ts +++ b/frontend/src/v2/components/shared/AssetChips.test.ts @@ -1,11 +1,13 @@ import { mount } from "@vue/test-utils"; import { describe, expect, it, vi } from "vitest"; +import type { SaveSchema } from "@/__generated__"; import { saveFixture } from "@/utils/assets.fixtures"; import AssetChips from "./AssetChips.vue"; vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }), })); +vi.mock("@/stores/streaming", () => import("@/test-utils/streamingStore")); const RTag = { props: { text: { type: String, default: "" } }, @@ -14,7 +16,9 @@ const RTag = { const save = saveFixture({ file_size_bytes: 2048, emulator: "snes9x" }); -function chips(props: { latest?: boolean; showEmulator?: boolean } = {}) { +function chips( + props: { latest?: boolean; showEmulator?: boolean; asset?: SaveSchema } = {}, +) { return mount(AssetChips, { props: { asset: save, ...props }, global: { stubs: { RTag, RIcon: true } }, @@ -29,6 +33,12 @@ describe("AssetChips", () => { expect(wrapper.get(".r-asset-chips__size").text()).toContain("2 KB"); }); + it("names the emulator the way the backend labels it", () => { + const wrapper = chips({ asset: { ...save, emulator: "play" } }); + + expect(wrapper.findAll(".tag").map((el) => el.text())).toEqual(["Play!"]); + }); + it("tags the latest version and can hide the emulator", () => { const wrapper = chips({ latest: true, showEmulator: false }); diff --git a/frontend/src/v2/components/shared/AssetChips.vue b/frontend/src/v2/components/shared/AssetChips.vue index e7907bf60..a9fdfca56 100644 --- a/frontend/src/v2/components/shared/AssetChips.vue +++ b/frontend/src/v2/components/shared/AssetChips.vue @@ -4,6 +4,7 @@ // . import { RTag } from "@v2/lib"; import { useI18n } from "vue-i18n"; +import { useStreamingStore } from "@/stores/streaming"; import { formatBytes } from "@/utils"; import type { Asset } from "@/v2/utils/assets"; @@ -22,6 +23,7 @@ withDefaults( ); const { t } = useI18n(); +const { emulatorLabel } = useStreamingStore();