feat(streaming): answer the claim before the launch, and push what happens

`POST /streaming/sessions` blocked for up to STREAMING_LAUNCH_TIMEOUT (10
minutes) while a broker unpacked a pkg or archive, and four mechanisms existed
to keep that survivable: a 3s status poll the client ran alongside it purely
for progress, `launch_timeout` shipped through /config so the client could size
its own axios ceiling, and a cancel-then-undo branch that re-released a session
the player had already abandoned, because a blocking POST cannot be cancelled.

The claim now answers 202 as soon as the container is reserved and everything
that can fail synchronously has (404, 409, 428 are all still the claim's own
status). The launch runs detached and pushes to the user room the
force-release notice already used:

- `streaming:launch-ready` carries the room URL and the resume outcome
- `streaming:launch-failed` carries the reason; the claim is already freed
- `streaming:launch-phase` carries the broker's extraction phase

The backend polls the broker for that phase itself, once, however many tabs are
watching, and only pushes changes. `GET /sessions/{platform}/status` stays as
the fallback for a tab that missed a push.

That retires the client's launch poll, the `launch_timeout` plumbing and the
cancel-then-undo branch. Leaving during a launch is now just a release, and the
launch-ready handler hands the container back if the player has already gone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-05 12:04:58 -04:00
parent 1e716b381d
commit 74c77d0bb2
12 changed files with 594 additions and 316 deletions

View File

@@ -37,9 +37,6 @@ class StreamingContainerSchema(BaseModel):
class StreamingConfigSchema(BaseModel):
enabled: bool
containers: list[StreamingContainerSchema]
launch_timeout: int
"""How long a claim may block, so the client sizes its own request ceiling
from this rather than keeping a copy that goes stale."""
class SessionTerminationSchema(BaseModel):
@@ -66,17 +63,45 @@ class SessionStatusSchema(BaseModel):
termination: SessionTerminationSchema | None = None
class ClaimedSessionSchema(BaseModel):
class LaunchingSessionSchema(BaseModel):
"""The 202 a claim answers with: the container is reserved and the game is
on its way up. The room URL follows over the socket, since only the
broker's launch reply carries it."""
platform: str
host: str
container: str
label: str
rom_name: str
claimed_at: str
class LaunchReadyPayload(BaseModel):
"""`streaming:launch-ready`, pushed once the game is up."""
platform: str
container: str
host: str
resume: bool | None = None
"""None when no resume was asked for; False means the state could not be
pushed and the session started fresh."""
class LaunchFailedPayload(BaseModel):
"""`streaming:launch-failed`. The claim is already released."""
platform: str
container: str
detail: str
class LaunchPhasePayload(BaseModel):
"""`streaming:launch-phase`, while a broker unpacks a large title."""
platform: str
container: str
phase: str | None = None
class DesktopSessionSchema(BaseModel):
container: str
platform: str

View File

@@ -28,11 +28,14 @@ from decorators.auth import protected_route
from endpoints.responses.streaming import (
AdminContainersResponse,
AdminSessionsResponse,
ClaimedSessionSchema,
DesktopSessionSchema,
ForceReleaseResponse,
JoinableSessionsResponse,
JoinedSessionSchema,
LaunchFailedPayload,
LaunchingSessionSchema,
LaunchPhasePayload,
LaunchReadyPayload,
LoadStateResponse,
MemoryCardImportRequired,
MemoryCardSummarySchema,
@@ -98,6 +101,7 @@ from handler.streaming.session_store import (
iter_live_sessions,
iter_session_keys,
mutate_session,
push_to_user,
record_termination,
refresh_session,
release_own_session,
@@ -2295,12 +2299,184 @@ async def get_config(request: Request) -> StreamingConfigSchema:
}
return StreamingConfigSchema(
enabled=streaming_enabled(),
containers=list(safe_containers.values()),
launch_timeout=STREAMING_LAUNCH_TIMEOUT,
enabled=streaming_enabled(), containers=list(safe_containers.values())
)
async def _run_launch(
*,
container: ResolvedContainer,
session_key: str,
session: dict[str, Any],
user: User,
rom: Rom,
platform: str,
rom_name: str,
rom_path: str,
rom_language: str | None,
gui_language: str | None,
archive_path: str | None,
resume_state: State | None,
resume_slot: int | None,
resume_pushed: bool,
resume_after_launch: bool,
memory_card_synced: bool,
multiplayer: bool,
blank_card_id: int | None,
) -> None:
"""Start the game, then tell the player's tabs where to find it.
Runs detached from the claim request: a webstation activate blocks through
pkg and archive extraction, minutes on a large title, and a request held
open that long cannot be cancelled by a player who changes their mind. The
claim is already won when this starts, so the container is reserved
throughout; a failure here frees it exactly as a failed synchronous launch
used to.
"""
# Nothing beats for the player until the stream is up, so without this the
# next claimant reads the record as abandoned and tears the container down
# mid-extraction.
claim_hold = asyncio.create_task(hold_session_claim(session_key, session))
phase_watch = asyncio.create_task(
_watch_launch_phase(container, session_key, session, platform)
)
try:
# Wrapped in asyncio.to_thread because urllib is synchronous.
if container.is_webstation:
launch_result = await asyncio.to_thread(
_webstation_activate,
container,
session_id=str(session["broker_session_id"]),
user=user,
emulator=container.emulator,
rom={
"id": rom.id,
"name": rom_name,
"platform": platform,
"language": rom_language,
"path": rom_path,
},
gui_language=gui_language,
archive_path=archive_path,
resume_slot=(
resume_slot if resume_pushed or resume_after_launch else None
),
memory_card_synced=memory_card_synced,
multiplayer=multiplayer,
)
else:
launch_result = await asyncio.to_thread(
_call_broker,
container,
rom_path,
rom_name,
resume_slot if resume_pushed else None,
)
except Exception as exc:
log.exception("launch failed, platform=%s", platform)
await _abort_claim(session_key, blank_card_id)
await push_to_user(
session.get("user_id"),
"streaming:launch-failed",
LaunchFailedPayload(
platform=platform,
container=session_key,
detail=_launch_failure_detail(exc),
).model_dump(),
)
return
finally:
phase_watch.cancel()
claim_hold.cancel()
log.info("session claimed, platform=%s rom=%s", platform, rom_name)
await stamp_launched(session_key)
await _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 _push_resume_state(container, resume_state)
await push_to_user(
session.get("user_id"),
"streaming:launch-ready",
LaunchReadyPayload(
platform=platform,
container=session_key,
host=container.protocol.stream_url(container.host, launch_result),
resume=resume_pushed if resume_state is not None else None,
).model_dump(),
)
# Hydrate the container with the user's newest stored state in the
# background, the stream should not wait on file transfers.
_spawn_sync_task(
_hydrate_states_to_broker(
user.id, rom.id, container, resume_pushed=resume_pushed
)
)
# A resumed state remembers which disc it was captured on. The launch
# always starts on the playlist's first disc, so put the right one back.
resume_disc_id = (
resume_state.disc_file_id if resume_pushed and resume_state else None
)
if isinstance(resume_disc_id, int):
_spawn_sync_task(
_restore_session_disc(
rom.id,
container,
session_key,
file_id=resume_disc_id,
broker_session_id=session["broker_session_id"],
)
)
def _launch_failure_detail(exc: BaseException) -> str:
"""What to tell the player about a launch that never came up."""
if isinstance(exc, HTTPException):
return str(exc.detail)
return "The container could not start the game"
# How often the backend asks a launching broker how far it has got. The player
# sees nothing until the stream is up, so this is the only progress there is.
_LAUNCH_PHASE_POLL_SECONDS = 3.0
async def _watch_launch_phase(
container: ResolvedContainer,
session_key: str,
session: dict[str, Any],
platform: str,
) -> None:
"""Push the broker's extraction phase while a launch is still running.
The client used to poll for this itself, on a route that had to reach the
broker to answer. Asking once here and pushing the answer costs one round
trip however many tabs are watching.
"""
if not container.protocol.reports_launch_phase:
return
last: str | None = None
while True:
await asyncio.sleep(_LAUNCH_PHASE_POLL_SECONDS)
phase = await asyncio.to_thread(_webstation_launch_phase, container)
if phase == last:
continue
last = phase
await push_to_user(
session.get("user_id"),
"streaming:launch-phase",
LaunchPhasePayload(
platform=platform, container=session_key, phase=phase
).model_dump(),
)
@protected_route(
router.post,
"/sessions",
@@ -2308,19 +2484,28 @@ async def get_config(request: Request) -> StreamingConfigSchema:
# 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}},
status_code=202,
)
async def claim_session(
request: Request, req: Annotated[ClaimStreamingSessionRequest, Body()]
) -> ClaimedSessionSchema:
request: Request,
req: Annotated[ClaimStreamingSessionRequest, Body()],
background_tasks: BackgroundTasks,
) -> LaunchingSessionSchema:
"""
Claim a streaming session and tell the broker to load the ROM.
Reserve a container for a ROM and start loading it.
Answers 202 as soon as the container is reserved and everything that can
fail synchronously has: the launch itself runs detached, and the room URL
arrives over the socket as `streaming:launch-ready` (or
`streaming:launch-failed`, with `streaming:launch-phase` while a broker
unpacks a large title). `GET /sessions/{platform}/status` is the fallback
for a tab that missed the push.
The ROM's filesystem path is derived server-side from its database row -
the client only supplies a ROM id, never a path.
Returns 404 if the ROM doesn't exist or no container serves its platform.
Returns 409 if every container serving the platform is occupied.
Returns 428 if the container's pre-existing memory card needs a decision.
Returns 502/503 if the broker rejects the launch or is unreachable.
"""
rom = db_rom_handler.get_rom(req.rom_id)
if rom is None:
@@ -2664,97 +2849,39 @@ async def claim_session(
except Exception:
log.exception("save hydration failed, continuing launch")
# A webstation activate blocks through pkg/archive extraction, which runs
# well past _STREAMING_SESSION_STALE_SECONDS. Nothing beats for the player until the
# stream is up, so without this refresh the next claimant reads the record
# as abandoned and tears the container down mid-extraction.
claim_hold = asyncio.create_task(hold_session_claim(session_key, session))
try:
# Tell the broker to load the ROM, raises HTTPException on failure.
# Wrapped in asyncio.to_thread because urllib is synchronous.
if container.is_webstation:
launch_result = await asyncio.to_thread(
_webstation_activate,
container,
session_id=str(session["broker_session_id"]),
user=request.user,
emulator=container.emulator,
rom={
"id": rom.id,
"name": rom_name,
"platform": platform,
"language": rom_language,
"path": rom_path,
},
gui_language=gui_language,
archive_path=archive_path,
resume_slot=(
resume_slot if resume_pushed or resume_after_launch else None
),
memory_card_synced=memory_card is not None,
multiplayer=req.multiplayer,
)
else:
launch_result = await asyncio.to_thread(
_call_broker,
container,
rom_path,
rom_name,
resume_slot if resume_pushed else None,
)
except Exception:
# Launch failed, free the claim so the container isn't wedged.
await _abort_claim(session_key, created_blank_card_id)
raise
finally:
claim_hold.cancel()
log.info("session claimed, platform=%s rom=%s", platform, rom_name)
await stamp_launched(session_key)
await _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 _push_resume_state(container, resume_state)
# Hydrate the container with the user's newest stored state in the
# background, the stream should not wait on file transfers.
_spawn_sync_task(
_hydrate_states_to_broker(
request.user.id,
rom.id,
container,
resume_pushed=resume_pushed,
)
)
# A resumed state remembers which disc it was captured on. The launch
# always starts on the playlist's first disc, so put the right one back.
resume_disc_id = (
resume_state.disc_file_id if resume_pushed and resume_state else None
)
if isinstance(resume_disc_id, int):
_spawn_sync_task(
_restore_session_disc(
rom.id,
container,
session_key,
file_id=resume_disc_id,
broker_session_id=session["broker_session_id"],
)
)
host = container.protocol.stream_url(container.host, launch_result)
return ClaimedSessionSchema(
# The launch runs detached: a webstation activate blocks through pkg and
# archive extraction, minutes on a large title, and a request held open
# that long cannot be cancelled by a player who changes their mind. The
# claim is already won, so the container is reserved either way, and the
# room URL reaches the player over the socket when the game is up.
background_tasks.add_task(
_run_launch,
container=container,
session_key=session_key,
session=session,
user=request.user,
rom=rom,
platform=platform,
host=host,
rom_name=rom_name,
rom_path=rom_path,
rom_language=rom_language,
gui_language=gui_language,
archive_path=archive_path,
resume_state=resume_state,
resume_slot=resume_slot,
resume_pushed=resume_pushed,
resume_after_launch=resume_after_launch,
memory_card_synced=memory_card is not None,
multiplayer=req.multiplayer,
blank_card_id=created_blank_card_id,
)
return LaunchingSessionSchema(
platform=platform,
container=session_key,
label=container.label,
rom_name=rom_name,
claimed_at=now,
resume=resume_pushed if req.state_id is not None else None,
)

View File

@@ -536,14 +536,21 @@ async def record_termination(
json.dumps(notice),
ex=_TERMINATION_TTL_SECONDS,
)
# Best-effort: the poll is the source of truth and covers a missed or
# dropped push, so a socket error here must not fail the release itself.
await push_to_user(user_id, "streaming:session-ended", notice)
async def push_to_user(user_id: Any, event: str, payload: dict[str, Any]) -> None:
"""Tell one user's open tabs something happened to their session.
Best-effort by design: every event pushed here also has a poll behind it,
so a dropped socket costs latency rather than correctness.
"""
if not isinstance(user_id, int):
return
try:
await socket_handler.socket_server.emit(
"streaming:session-ended", notice, room=f"user:{user_id}"
)
await socket_handler.socket_server.emit(event, payload, room=f"user:{user_id}")
except Exception: # noqa: BLE001
log.warning("Failed to push session-ended notice", exc_info=True)
log.warning("Failed to push %s", event, exc_info=True)
async def get_termination(session_key: str, user_id: int) -> dict[str, Any] | None:

View File

@@ -7,6 +7,7 @@ import time
import zipfile
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from typing import Any, NamedTuple
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
@@ -201,12 +202,43 @@ def _claim(client, token, rom_id, state_id=None):
return client.post("/api/streaming/sessions", json=body, headers=_auth(token))
@contextmanager
def _pushes():
"""Collect what the backend pushed to the claiming user's tabs.
The claim answers 202 and the room URL follows over the socket, so the
launch's own result is read here rather than off the response.
"""
sent: list[tuple[str, dict]] = []
async def _capture(user_id, event, payload):
sent.append((event, payload))
with patch("endpoints.streaming.push_to_user", new=_capture):
yield sent
def _launch_ready(sent) -> dict:
"""The `streaming:launch-ready` payload, or {} if the launch never got there."""
return next(
(p for event, p in sent if event == "streaming:launch-ready"),
{},
)
def _claim_ok(client, token, rom_id):
"""Claim with the broker launch stubbed, the common happy-path setup."""
with patch("endpoints.streaming._call_broker"):
return _claim(client, token, rom_id)
def _claim_ready(client, token, rom_id):
"""Claim and return (response, launch-ready payload)."""
with _pushes() as sent:
response = _claim_ok(client, token, rom_id)
return response, _launch_ready(sent)
# ── /config ───────────────────────────────────────────────────────────────────
@@ -250,15 +282,6 @@ def test_get_config_ships_platform_capabilities(client, access_token):
}
def test_get_config_ships_the_launch_timeout(client, access_token):
"""The claim blocks for as long as an extraction takes, and the client sets
its own request ceiling from this rather than keeping a second copy that an
operator raising the limit would silently invalidate."""
with _streaming({"platform": "ps2", "host": "http://192.168.1.10:3000"}):
r = client.get("/api/streaming/config", headers=_auth(access_token))
assert r.json()["launch_timeout"] == streaming.STREAMING_LAUNCH_TIMEOUT
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
@@ -520,7 +543,7 @@ def test_nested_platforms_reject_a_second_claim_across_platforms(
with _streaming(_nested()):
first = _claim_ok(client, access_token, ps2_rom.id)
second = _claim_ok(client, access_token, ngc_rom.id)
assert first.status_code == 200
assert first.status_code == 202
assert second.status_code == 409
@@ -635,7 +658,7 @@ def test_claim_derives_rom_path_server_side(client, access_token, rom: Rom):
with _streaming(_container_for(rom)):
with patch("endpoints.streaming._call_broker") as call_broker:
r = _claim(client, access_token, rom.id)
assert r.status_code == 200
assert r.status_code == 202
assert r.json()["rom_name"] == rom.name
_, rom_path, _, _ = call_broker.call_args[0]
assert rom_path == f"{LIBRARY_BASE_PATH}/{rom.full_path}"
@@ -648,7 +671,7 @@ def test_claim_honors_container_library_path(client, access_token, rom: Rom):
with _streaming(container):
with patch("endpoints.streaming._call_broker") as call_broker:
r = _claim(client, access_token, rom.id)
assert r.status_code == 200
assert r.status_code == 202
_, rom_path, _, _ = call_broker.call_args[0]
assert rom_path == f"/mnt/games/{rom.full_path}"
@@ -664,9 +687,13 @@ def test_claim_appends_stream_token_to_host(client, access_token, rom: Rom):
"status": "launching",
"stream_token": "tok-abc",
}
r = _claim(client, access_token, rom.id)
assert r.status_code == 200
assert r.json()["host"] == "https://stream.example:3001?stream_token=tok-abc"
with _pushes() as sent:
r = _claim(client, access_token, rom.id)
assert r.status_code == 202
assert (
_launch_ready(sent)["host"]
== "https://stream.example:3001?stream_token=tok-abc"
)
def test_claim_appends_stream_token_with_ampersand_when_host_has_query(
@@ -682,10 +709,12 @@ def test_claim_appends_stream_token_with_ampersand_when_host_has_query(
"status": "launching",
"stream_token": "tok-abc",
}
r = _claim(client, access_token, rom.id)
assert r.status_code == 200
with _pushes() as sent:
r = _claim(client, access_token, rom.id)
assert r.status_code == 202
assert (
r.json()["host"] == "https://stream.example:3001/?path=abc&stream_token=tok-abc"
_launch_ready(sent)["host"]
== "https://stream.example:3001/?path=abc&stream_token=tok-abc"
)
@@ -698,9 +727,84 @@ def test_claim_leaves_host_unchanged_when_broker_returns_no_token(
with _streaming(container):
with patch("endpoints.streaming._call_broker") as call_broker:
call_broker.return_value = {"status": "launching"}
r = _claim(client, access_token, rom.id)
assert r.status_code == 200
assert r.json()["host"] == "https://stream.example:3001"
with _pushes() as sent:
r = _claim(client, access_token, rom.id)
assert r.status_code == 202
assert _launch_ready(sent)["host"] == "https://stream.example:3001"
def test_claim_answers_before_the_launch_and_pushes_the_room_url(
client, access_token, rom: Rom
):
"""The claim reserves the container and returns; the URL follows.
A launch blocks through pkg and archive extraction, so a request held open
for it could not be cancelled by a player who changed their mind.
"""
with _streaming(_container_for(rom)):
with _pushes() as sent:
r = _claim_ok(client, access_token, rom.id)
assert r.status_code == 202
body = r.json()
assert body["container"] == _key_of(_container_for(rom))
assert body["platform"] == rom.platform_slug
# The room URL is the launch's answer, so it is not in the claim's.
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"
def test_a_failed_launch_pushes_the_reason_and_frees_the_container(
client, access_token, rom: Rom
):
with _streaming(_container_for(rom)):
with patch(
"endpoints.streaming._call_broker",
side_effect=HTTPException(status_code=502, detail="broker said no"),
):
with _pushes() as sent:
r = _claim(client, access_token, rom.id)
assert r.status_code == 202
event, payload = sent[0]
assert event == "streaming:launch-failed"
assert payload["detail"] == "broker said no"
assert payload["container"] == _key_of(_container_for(rom))
assert _session_raw(_container_for(rom)) is None
def test_launch_phase_is_pushed_while_a_webstation_unpacks(
client, access_token, rom: Rom
):
"""The client used to poll a route that had to reach the broker to answer.
Asking once here costs one round trip however many tabs are watching."""
phases = ["unpacking", "unpacking", "installing"]
def _activate(*args, **kwargs):
# Long enough for the phase watcher to tick twice.
time.sleep(0.25)
return {"url": "/room/x"}
with _streaming(_webstation_for(rom)):
with (
patch("endpoints.streaming._LAUNCH_PHASE_POLL_SECONDS", 0.05),
patch(
"endpoints.streaming._webstation_launch_phase",
side_effect=phases + ["installing"] * 20,
),
patch("endpoints.streaming._webstation_activate", _activate),
patch("endpoints.streaming._spawn_sync_task"),
patch("endpoints.streaming._hydrate_saves_to_webstation", new=AsyncMock()),
):
with _pushes() as sent:
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"]
# Only changes are pushed, so a repeated phase is not re-sent.
assert pushed == ["unpacking", "installing"]
assert sent[-1][0] == "streaming:launch-ready"
def test_claim_unknown_rom_returns_404(client, access_token):
@@ -792,7 +896,7 @@ async def test_claim_sets_session_ttl(access_token, rom: Rom):
json={"rom_id": rom.id},
headers=_auth(access_token),
)
assert r.status_code == 200
assert r.status_code == 202
key = session_store.session_redis_key(_key_of(_container_for(rom)))
ttl = await async_cache.ttl(key)
assert ttl > 0
@@ -804,7 +908,7 @@ def test_second_claim_on_same_container_rejected(client, access_token, rom: Rom)
with _streaming(_container_for(rom)):
r1 = _claim_ok(client, access_token, rom.id)
r2 = _claim_ok(client, access_token, rom.id)
assert r1.status_code == 200
assert r1.status_code == 202
assert r2.status_code == 409
assert r2.json()["detail"]["rom_name"] == rom.name
@@ -835,21 +939,27 @@ def test_claim_session_same_container_two_platforms_rejected(
):
r1 = _claim_ok(client, access_token, rom.id)
r2 = _claim_ok(client, access_token, rom2.id)
assert r1.status_code == 200
assert r1.status_code == 202
assert r2.status_code == 409
def test_failed_broker_launch_frees_the_claim(client, access_token, rom: Rom):
"""If the broker rejects the launch, the container must not stay claimed."""
"""If the broker rejects the launch, the container must not stay claimed.
The claim itself is already answered by then, so the failure reaches the
player as a push rather than as the claim's own status."""
with _streaming(_container_for(rom)):
with patch(
"endpoints.streaming._call_broker",
side_effect=HTTPException(status_code=503, detail="unreachable"),
):
r1 = _claim(client, access_token, rom.id)
with _pushes() as sent:
r1 = _claim(client, access_token, rom.id)
r2 = _claim_ok(client, access_token, rom.id)
assert r1.status_code == 503
assert r2.status_code == 200
assert r1.status_code == 202
assert [event for event, _ in sent] == ["streaming:launch-failed"]
assert sent[0][1]["detail"] == "unreachable"
assert r2.status_code == 202
@pytest.mark.asyncio
@@ -873,7 +983,7 @@ async def test_concurrent_claim_only_one_succeeds(access_token, rom: Rom):
headers=headers,
),
)
assert sorted([r1.status_code, r2.status_code]) == [200, 409]
assert sorted([r1.status_code, r2.status_code]) == [202, 409]
# ── Container pool ────────────────────────────────────────────────────────────
@@ -908,10 +1018,10 @@ def test_pool_claim_falls_through_to_a_free_container(client, access_token, rom:
with _streaming(_pool_member(rom, 0), _pool_member(rom, 1)):
r1 = _claim_ok(client, access_token, rom.id)
r2 = _claim_ok(client, access_token, rom.id)
assert [r1.status_code, r2.status_code] == [200, 200]
assert [r1.status_code, r2.status_code] == [202, 202]
# Config order, so the head of the pool stays warm.
assert r1.json()["host"] == "http://192.168.1.10:3000"
assert r2.json()["host"] == "http://192.168.1.11:3000"
assert r1.json()["container"] == _key_of(_pool_member(rom, 0))
assert r2.json()["container"] == _key_of(_pool_member(rom, 1))
def test_pool_409s_only_once_every_container_is_held(client, access_token, rom: Rom):
@@ -937,8 +1047,8 @@ def test_pool_never_evicts_a_stale_session_while_a_container_is_free(
"endpoints.streaming._stop_broker", return_value=None
) as stop_broker:
r2 = _claim_ok(client, viewer_access_token, rom.id)
assert r2.status_code == 200
assert r2.json()["host"] == "http://192.168.1.11:3000"
assert r2.status_code == 202
assert r2.json()["container"] == _key_of(_pool_member(rom, 1))
stop_broker.assert_not_called()
assert _session_raw(_pool_member(rom, 0)) is not None
@@ -956,8 +1066,8 @@ def test_pool_takes_over_a_stale_session_once_every_container_is_held(
"endpoints.streaming._stop_broker", return_value=None
) as stop_broker:
r3 = _claim_ok(client, viewer_access_token, rom.id)
assert r3.status_code == 200
assert r3.json()["host"] == "http://192.168.1.11:3000"
assert r3.status_code == 202
assert r3.json()["container"] == _key_of(_pool_member(rom, 1))
stop_broker.assert_called_once()
@@ -1194,7 +1304,7 @@ def test_containers_reports_a_container_that_can_never_be_claimed(client, access
def test_containers_shows_what_is_running(client, access_token):
ps2_rom = _rom_on("ps2")
with _streaming(_nested()):
assert _claim_ok(client, access_token, ps2_rom.id).status_code == 200
assert _claim_ok(client, access_token, ps2_rom.id).status_code == 202
response = _containers(client, access_token)
session = response.json()["containers"][0]["session"]
assert session["rom_name"] == ps2_rom.name
@@ -1236,7 +1346,7 @@ def test_desktop_and_a_game_block_each_other(client, access_token):
with _streaming(_webstation()):
key = _key_of(_first_container("ps2"))
assert _claim_webstation_ok(client, access_token, ps2_rom.id).status_code == 200
assert _claim_webstation_ok(client, access_token, ps2_rom.id).status_code == 202
assert _desktop(client, access_token, key)[0].status_code == 409
@@ -1467,8 +1577,8 @@ def test_stale_session_taken_over_on_claim(
"endpoints.streaming._stop_broker", return_value=None
) as stop_broker:
r2 = _claim_ok(client, viewer_access_token, rom.id)
assert r1.status_code == 200
assert r2.status_code == 200
assert r1.status_code == 202
assert r2.status_code == 202
stop_broker.assert_called_once()
@@ -1539,7 +1649,7 @@ def test_fresh_session_not_taken_over(
"endpoints.streaming._stop_broker", return_value=None
) as stop_broker:
r2 = _claim_ok(client, viewer_access_token, rom.id)
assert r1.status_code == 200
assert r1.status_code == 202
assert r2.status_code == 409
stop_broker.assert_not_called()
@@ -1956,7 +2066,7 @@ def test_a_slow_launch_keeps_its_own_claim_fresh(client, access_token):
patch.object(session_store, "_STREAMING_SESSION_STALE_SECONDS", 0.2),
patch("endpoints.streaming._webstation_activate", slow_activate),
):
assert _claim(client, access_token, ps2_rom.id).status_code == 200
assert _claim(client, access_token, ps2_rom.id).status_code == 202
key = session_store.session_redis_key(_key_of(_first_container("ps2")))
session = json.loads(asyncio.run(async_cache.get(key)))
# Read under the shrunk window: outside it every stamp looks fresh.
@@ -1990,7 +2100,7 @@ def test_release_by_other_user_is_forbidden(
f"/api/streaming/sessions/{rom.platform_slug}",
headers=_auth(viewer_access_token),
)
assert r_claim.status_code == 200
assert r_claim.status_code == 202
assert r.status_code == 403
@@ -2042,7 +2152,7 @@ def test_save_and_exit_releases_session_once_the_state_is_pulled(
assert r.status_code == 200
assert r.json()["saved"] is True
assert held.status_code == 409
assert r2.status_code == 200
assert r2.status_code == 202
def test_save_and_exit_failure_still_releases_session(client, access_token, rom: Rom):
@@ -2061,7 +2171,7 @@ def test_save_and_exit_failure_still_releases_session(client, access_token, rom:
r2 = _claim_ok(client, access_token, rom.id)
assert r.status_code == 200
assert r.json()["saved"] is False
assert r2.status_code == 200
assert r2.status_code == 202
def test_save_and_exit_rejects_a_slot_the_platform_lacks(client, access_token):
@@ -2181,7 +2291,7 @@ def test_claim_spawns_state_hydration(client, access_token, rom: Rom):
) as hydrate,
):
r = _claim(client, access_token, rom.id)
assert r.status_code == 200
assert r.status_code == 202
spawn.assert_called_once()
assert hydrate.call_args[0][1] == rom.id
@@ -3251,7 +3361,7 @@ def test_claim_hydrates_saves_before_launch(client, access_token, rom: Rom):
patch("endpoints.streaming._hydrate_states_to_broker", new=MagicMock()),
):
r = _claim(client, access_token, rom.id)
assert r.status_code == 200
assert r.status_code == 202
hydrate_saves.assert_awaited_once()
assert call_order == ["saves", "launch"]
@@ -3315,9 +3425,20 @@ def test_stamped_state_filename_round_trips_for_retroarch():
assert streaming._container_state_filename(stamped) == "Super Mario.state"
def _resume_claim(client, token, rom, state_id, push_ok=True):
"""Claim with a resume state and full launch-path mocks. Returns
(response, push mock, call_broker mock, hydrate mock)."""
class _ResumeClaim(NamedTuple):
response: Any
ready: dict
push: Any
call_broker: Any
hydrate: Any
def _resume_claim(client, token, rom, state_id, push_ok=True) -> _ResumeClaim:
"""Claim with a resume state and full launch-path mocks.
`ready` is the launch-ready push, which is where the resume outcome lands
now that the claim answers before the launch runs.
"""
container = {**_container_for(rom), "label": "PCSX2"}
with _streaming(container):
with (
@@ -3332,8 +3453,9 @@ def _resume_claim(client, token, rom, state_id, push_ok=True):
"endpoints.streaming._hydrate_states_to_broker", new=MagicMock()
) as hydrate,
):
r = _claim(client, token, rom.id, state_id=state_id)
return r, push, call_broker, hydrate
with _pushes() as sent:
r = _claim(client, token, rom.id, state_id=state_id)
return _ResumeClaim(r, _launch_ready(sent), push, call_broker, hydrate)
def test_claim_with_own_state_pushes_file_and_slot(
@@ -3344,9 +3466,11 @@ def test_claim_with_own_state_pushes_file_and_slot(
state = db_state_handler.add_state(
_state_for(rom, admin_user, "Game.03.p2s", "pcsx2")
)
r, push, call_broker, hydrate = _resume_claim(client, access_token, rom, state.id)
assert r.status_code == 200
assert r.json()["resume"] is True
r, ready, push, call_broker, hydrate = _resume_claim(
client, access_token, rom, state.id
)
assert r.status_code == 202
assert ready["resume"] is True
push.assert_called_once()
assert push.call_args[0][1] == "Game.03.p2s"
assert push.call_args[0][2] == b"state-bytes"
@@ -3361,9 +3485,9 @@ def test_claim_with_other_users_public_state_allowed(
shared = _state_for(rom, viewer_user, "Game.02.p2s", "pcsx2")
shared.is_public = True
state = db_state_handler.add_state(shared)
r, push, call_broker, _ = _resume_claim(client, access_token, rom, state.id)
assert r.status_code == 200
assert r.json()["resume"] is True
r, ready, push, call_broker, _ = _resume_claim(client, access_token, rom, state.id)
assert r.status_code == 202
assert ready["resume"] is True
assert call_broker.call_args[0][3] == 2
@@ -3374,11 +3498,11 @@ def test_claim_with_other_users_private_state_404(
state = db_state_handler.add_state(
_state_for(rom, viewer_user, "Game.02.p2s", "pcsx2")
)
r, _, _, _ = _resume_claim(client, access_token, rom, state.id)
r = _resume_claim(client, access_token, rom, state.id).response
assert r.status_code == 404
# The rejected pick must not have claimed the container.
with _streaming(_container_for(rom)):
assert _claim_ok(client, access_token, rom.id).status_code == 200
assert _claim_ok(client, access_token, rom.id).status_code == 202
def test_claim_with_wrong_emulator_state_400(
@@ -3387,7 +3511,7 @@ def test_claim_with_wrong_emulator_state_400(
state = db_state_handler.add_state(
_state_for(rom, admin_user, "Game.state", "retroarch")
)
r, _, _, _ = _resume_claim(client, access_token, rom, state.id)
r = _resume_claim(client, access_token, rom, state.id).response
assert r.status_code == 400
@@ -3395,7 +3519,7 @@ def test_claim_with_unparseable_slot_400(
client, access_token, rom: Rom, admin_user: User
):
state = db_state_handler.add_state(_state_for(rom, admin_user, "Game.p2s", "pcsx2"))
r, _, _, _ = _resume_claim(client, access_token, rom, state.id)
r = _resume_claim(client, access_token, rom, state.id).response
assert r.status_code == 400
@@ -3407,20 +3531,21 @@ def test_claim_failed_push_launches_fresh(
state = db_state_handler.add_state(
_state_for(rom, admin_user, "Game.03.p2s", "pcsx2")
)
r, _, call_broker, hydrate = _resume_claim(
r, ready, _, call_broker, hydrate = _resume_claim(
client, access_token, rom, state.id, push_ok=False
)
assert r.status_code == 200
assert r.json()["resume"] is False
assert r.status_code == 202
assert ready["resume"] is False
assert call_broker.call_args[0][3] is None
assert hydrate.call_args.kwargs["resume_pushed"] is False
def test_claim_without_state_reports_no_resume(client, access_token, rom: Rom):
with _streaming(_container_for(rom)):
r = _claim_ok(client, access_token, rom.id)
assert r.status_code == 200
assert r.json()["resume"] is None
with _pushes() as sent:
r = _claim_ok(client, access_token, rom.id)
assert r.status_code == 202
assert _launch_ready(sent)["resume"] is None
# ── Webstation state sync ─────────────────────────────────────────────────────
@@ -3514,9 +3639,10 @@ def test_webstation_resume_state_is_pushed_after_activate(
patch("endpoints.streaming._spawn_sync_task"),
patch("endpoints.streaming._hydrate_states_to_broker", new=MagicMock()),
):
r = _claim(client, access_token, rom.id, state_id=state.id)
assert r.status_code == 200
assert r.json()["resume"] is True
with _pushes() as sent:
r = _claim(client, access_token, rom.id, state_id=state.id)
assert r.status_code == 202
assert _launch_ready(sent)["resume"] is True
assert [c[0] for c in order.mock_calls if c[0] in ("activate", "push")] == [
"activate",
"push",
@@ -3541,7 +3667,7 @@ def test_webstation_claim_without_a_state_boots_clean(client, access_token, rom:
patch("endpoints.streaming._hydrate_states_to_broker", new=MagicMock()),
):
r = _claim(client, access_token, rom.id)
assert r.status_code == 200
assert r.status_code == 202
assert activate.call_args.kwargs["archive_path"] == "/romm/saves/archive.tar"
assert activate.call_args.kwargs["resume_slot"] is None
@@ -4084,7 +4210,7 @@ def test_claim_hydrates_memory_card_before_launch(client, access_token, rom: Rom
patch("endpoints.streaming._spawn_sync_task"),
):
r = _mc_claim(client, access_token, rom.id)
assert r.status_code == 200
assert r.status_code == 202
hydrate_card.assert_awaited_once()
legacy.assert_not_awaited()
assert call_order == ["card", "launch"]
@@ -4270,7 +4396,7 @@ def test_lost_claim_race_does_not_create_blank_card(
),
patch("endpoints.streaming._spawn_sync_task"),
):
assert _mc_claim(client, access_token, rom.id).status_code == 200
assert _mc_claim(client, access_token, rom.id).status_code == 202
assert db_memory_card_handler.get_cards(viewer_user.id, "pcsx2") == []
r = _mc_claim(client, viewer_access_token, rom.id)
assert r.status_code == 409
@@ -4374,7 +4500,7 @@ def test_absent_card_claims_without_prompting(client, access_token, rom: Rom):
patch("endpoints.streaming._spawn_sync_task"),
):
r = _mc_claim(client, access_token, rom.id)
assert r.status_code == 200
assert r.status_code == 202
# The absent answer is recorded too, so the probe never runs again here.
adoption = db_container_adoption_handler.get_adoption(_key_of(container))
assert adoption is not None and adoption.outcome == "discard"
@@ -4398,7 +4524,7 @@ def test_decided_container_does_not_probe_again(
patch("endpoints.streaming._spawn_sync_task"),
):
r = _mc_claim(client, access_token, rom.id)
assert r.status_code == 200
assert r.status_code == 202
fetch.assert_not_called()
@@ -4412,7 +4538,7 @@ def test_sync_disabled_container_does_not_probe(client, access_token, rom: Rom):
patch("endpoints.streaming._spawn_sync_task"),
):
r = _mc_claim(client, access_token, rom.id)
assert r.status_code == 200
assert r.status_code == 202
fetch.assert_not_called()
@@ -4431,7 +4557,7 @@ def test_adopt_stores_the_container_card_as_version_one(
patch("endpoints.streaming._spawn_sync_task"),
):
r = _mc_claim(client, access_token, rom.id, card_import="adopt")
assert r.status_code == 200
assert r.status_code == 202
# The card pushed back down is the adopted one, not a blank.
assert push.call_args[0][1] == card_bytes
assert push.call_args[0][1] != streaming._EMPTY_MEMORY_CARD
@@ -4453,7 +4579,7 @@ def test_discard_wipes_and_records_the_decision(client, access_token, rom: Rom):
patch("endpoints.streaming._spawn_sync_task"),
):
r = _mc_claim(client, access_token, rom.id, card_import="discard")
assert r.status_code == 200
assert r.status_code == 202
assert push.call_args[0][1] == streaming._EMPTY_MEMORY_CARD
adoption = db_container_adoption_handler.get_adoption(_key_of(container))
assert adoption is not None and adoption.outcome == "discard"
@@ -4473,7 +4599,7 @@ def test_unreadable_card_with_override_starts_fresh(client, access_token, rom: R
patch("endpoints.streaming._spawn_sync_task"),
):
r = _mc_claim(client, access_token, rom.id, card_import="discard")
assert r.status_code == 200
assert r.status_code == 202
assert push.call_args[0][1] == streaming._EMPTY_MEMORY_CARD
adoption = db_container_adoption_handler.get_adoption(_key_of(container))
assert adoption is not None and adoption.outcome == "discard"
@@ -4532,7 +4658,7 @@ def test_adopt_retry_recovers_when_the_version_was_already_stored(
patch("endpoints.streaming._spawn_sync_task"),
):
r = _mc_claim(client, access_token, rom.id, card_import="adopt")
assert r.status_code == 200
assert r.status_code == 202
adoption = db_container_adoption_handler.get_adoption(_key_of(container))
assert adoption is not None and adoption.outcome == "adopt"
# Dedup still holds: the retry adds no second copy of the same content.
@@ -4705,7 +4831,7 @@ def test_webstation_claim_hydrates_the_card_and_the_states(
patch("endpoints.streaming._spawn_sync_task"),
):
r = _mc_claim(client, access_token, rom.id)
assert r.status_code == 200
assert r.status_code == 202
card.assert_awaited_once()
# The state hydrate is spawned rather than awaited inline, so the claim can
# return while the push is still in flight.
@@ -4732,7 +4858,7 @@ def test_webstation_claim_tells_the_broker_the_card_is_synced(
patch("endpoints.streaming._spawn_sync_task"),
):
r = _mc_claim(client, access_token, rom.id)
assert r.status_code == 200
assert r.status_code == 202
assert activate.call_args.kwargs["memory_card_synced"] is True
@@ -4843,7 +4969,7 @@ def test_a_broken_activity_board_does_not_fail_the_launch(
activity_handler, "publish_active", side_effect=RuntimeError("redis gone")
):
r = _claim_ok(client, access_token, rom.id)
assert r.status_code == 200
assert r.status_code == 202
assert _session_raw(container) is not None
assert _activity_entry(container, admin_user) is None
@@ -5651,7 +5777,7 @@ def test_resuming_a_state_puts_its_disc_back(client, access_token, admin_user: U
r, restore = _retroarch_resume(client, access_token, rom, state.id)
assert r.status_code == 200
assert r.status_code == 202
assert restore.call_args.kwargs["file_id"] == disc.id
@@ -5665,7 +5791,7 @@ def test_resuming_a_state_with_no_disc_swaps_nothing(
r, restore = _retroarch_resume(client, access_token, rom, state.id)
assert r.status_code == 200
assert r.status_code == 202
restore.assert_not_called()

View File

@@ -46,7 +46,6 @@ export type { Body_update_state_api_states__id__put } from './models/Body_update
export type { Body_update_state_visibility_api_states__id__visibility_put } from './models/Body_update_state_visibility_api_states__id__visibility_put';
export type { Body_upload_memory_card_version_api_memory_cards__id__versions_post } from './models/Body_upload_memory_card_version_api_memory_cards__id__versions_post';
export type { BulkOperationResponse } from './models/BulkOperationResponse';
export type { ClaimedSessionSchema } from './models/ClaimedSessionSchema';
export type { ClaimStreamingSessionRequest } from './models/ClaimStreamingSessionRequest';
export type { CleanupTaskMeta } from './models/CleanupTaskMeta';
export type { CleanupTaskStatusResponse } from './models/CleanupTaskStatusResponse';
@@ -115,6 +114,7 @@ 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 { LaunchingSessionSchema } from './models/LaunchingSessionSchema';
export type { LoadStateRequest } from './models/LoadStateRequest';
export type { LoadStateResponse } from './models/LoadStateResponse';
export type { LogEntrySchema } from './models/LogEntrySchema';

View File

@@ -1,13 +0,0 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type ClaimedSessionSchema = {
platform: string;
host: string;
label: string;
rom_name: string;
claimed_at: string;
resume?: (boolean | null);
};

View File

@@ -0,0 +1,17 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
/**
* The 202 a claim answers with: the container is reserved and the game is
* on its way up. The room URL follows over the socket, since only the
* broker's launch reply carries it.
*/
export type LaunchingSessionSchema = {
platform: string;
container: string;
label: string;
rom_name: string;
claimed_at: string;
};

View File

@@ -6,6 +6,5 @@ import type { StreamingContainerSchema } from './StreamingContainerSchema';
export type StreamingConfigSchema = {
enabled: boolean;
containers: Array<StreamingContainerSchema>;
launch_timeout: number;
};

View File

@@ -1,7 +1,7 @@
import type {
AdminContainerSchema,
AdminSessionSchema,
ClaimedSessionSchema,
LaunchingSessionSchema,
DesktopSessionSchema,
JoinableSessionSchema,
JoinedSessionSchema,
@@ -24,7 +24,36 @@ import api, { keepaliveHeaders } from "@/services/api";
export type PlatformCapabilities = SlotCapabilitiesSchema;
export type StreamingContainer = StreamingContainerSchema;
export type StreamingConfig = StreamingConfigSchema;
export type ActiveSession = ClaimedSessionSchema;
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.
/** `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;
@@ -59,34 +88,23 @@ async function fetchConfig() {
});
}
/** Grace added to the backend's launch timeout, so a claim that runs the full
* server-side budget still returns the server's own error rather than dying
* on a bare client timeout first. */
const CLAIM_TIMEOUT_GRACE_MS = 60_000;
/** The claim blocks until the container has the game up, and a webstation
* broker unpacks pkg and archive ROMs before it can start the emulator. That
* runs far past the client default, so this one call carries its own ceiling,
* built from the launch_timeout /config ships. */
/** Answers 202 as soon as the container is reserved. The room URL arrives on
* the socket as `streaming:launch-ready`, so this needs no ceiling of its own
* beyond the client default. */
async function claimSession(
romId: number,
launchTimeoutSeconds: number,
stateId?: number,
memoryCardId?: number,
cardImport?: MemoryCardImport,
multiplayer?: boolean,
) {
return api.post<ActiveSession>(
"/streaming/sessions",
{
rom_id: romId,
...(stateId !== undefined ? { state_id: stateId } : {}),
...(memoryCardId !== undefined ? { memory_card_id: memoryCardId } : {}),
...(cardImport !== undefined ? { card_import: cardImport } : {}),
...(multiplayer !== undefined ? { multiplayer } : {}),
},
{ timeout: launchTimeoutSeconds * 1_000 + CLAIM_TIMEOUT_GRACE_MS },
);
return api.post<LaunchingSession>("/streaming/sessions", {
rom_id: romId,
...(stateId !== undefined ? { state_id: stateId } : {}),
...(memoryCardId !== undefined ? { memory_card_id: memoryCardId } : {}),
...(cardImport !== undefined ? { card_import: cardImport } : {}),
...(multiplayer !== undefined ? { multiplayer } : {}),
});
}
async function releaseSession(

View File

@@ -14,7 +14,6 @@ describe("platformCapabilities disc flags", () => {
const store = useStreamingStore();
store.config = {
enabled: true,
launch_timeout: 600,
containers: [
{
platform: "dc",

View File

@@ -2,7 +2,7 @@ import { defineStore } from "pinia";
import { ref, computed } from "vue";
import streamingApi from "@/services/api/streaming";
import type {
ActiveSession,
LaunchingSession,
JoinableSession,
JoinedSession,
MemoryCardImport,
@@ -12,7 +12,7 @@ import type {
} from "@/services/api/streaming";
export type {
ActiveSession,
LaunchingSession,
AdminStreamingSession,
JoinableSession,
JoinedSession,
@@ -36,16 +36,11 @@ const NO_CAPABILITIES = {
// ── Store ─────────────────────────────────────────────────────────────────────
export const useStreamingStore = defineStore("streaming", () => {
// The launch timeout stands in until /config answers, and covers a backend
// too old to ship one. It matches that route's own default.
const DEFAULT_LAUNCH_TIMEOUT_SECONDS = 600;
const config = ref<StreamingConfig>({
enabled: false,
containers: [],
launch_timeout: DEFAULT_LAUNCH_TIMEOUT_SECONDS,
});
const activeSession = ref<ActiveSession | null>(null);
const launchingSession = ref<LaunchingSession | null>(null);
const loading = ref(false);
// `loading` is false both before and after the fetch, so consumers that must
// not act on an unresolved config need this instead.
@@ -126,7 +121,6 @@ export const useStreamingStore = defineStore("streaming", () => {
config.value = {
enabled: data.enabled ?? false,
containers: data.containers ?? [],
launch_timeout: data.launch_timeout ?? DEFAULT_LAUNCH_TIMEOUT_SECONDS,
};
} catch (err) {
error.value = String(err);
@@ -161,16 +155,15 @@ export const useStreamingStore = defineStore("streaming", () => {
memoryCardId?: number,
cardImport?: MemoryCardImport,
multiplayer?: boolean,
): Promise<ActiveSession> {
): Promise<LaunchingSession> {
const { data } = await streamingApi.claimSession(
romId,
config.value.launch_timeout,
stateId,
memoryCardId,
cardImport,
multiplayer,
);
activeSession.value = data;
launchingSession.value = data;
return data;
}
@@ -259,7 +252,7 @@ export const useStreamingStore = defineStore("streaming", () => {
if (!platform) return false;
try {
await streamingApi.releaseSession(platform, undefined, undefined, save);
activeSession.value = null;
launchingSession.value = null;
return true;
} catch (err) {
console.warn("[streaming] Could not release session:", err);
@@ -286,7 +279,7 @@ export const useStreamingStore = defineStore("streaming", () => {
try {
const { data } = await streamingApi.saveAndExit(platform, slot, wait);
const released = data.released ?? true;
if (released) activeSession.value = null;
if (released) launchingSession.value = null;
return { released, saved: data.saved ?? false };
} catch (err) {
console.warn("[streaming] Could not save-and-exit:", err);
@@ -342,7 +335,7 @@ export const useStreamingStore = defineStore("streaming", () => {
*/
function saveAndExitKeepalive(platform: string, slot = 0): void {
if (!platform) return;
activeSession.value = null;
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) => {
@@ -356,7 +349,7 @@ export const useStreamingStore = defineStore("streaming", () => {
*/
function releaseSessionKeepalive(platform: string): void {
if (!platform) return;
activeSession.value = null;
launchingSession.value = null;
streamingApi.releaseSessionKeepalive(platform).catch((err) => {
console.warn("[streaming] Could not release session (keepalive):", err);
});
@@ -364,7 +357,7 @@ export const useStreamingStore = defineStore("streaming", () => {
return {
config,
activeSession,
launchingSession,
loading,
configLoaded,
error,

View File

@@ -44,6 +44,9 @@ import { ROUTES } from "@/plugins/router";
import romApi from "@/services/api/rom";
import streamingApi, {
isMemoryCardImportDetail,
type LaunchFailed,
type LaunchPhase,
type LaunchReady,
type MemoryCardImport,
type MemoryCardImportDetail,
} from "@/services/api/streaming";
@@ -151,14 +154,6 @@ watch(sessionActive, (active) => {
// claimed session is worth a confirmation prompt too.
useUnloadGuard(sessionActive);
watch(
() => playerState.value === "loading",
(launching) => {
if (launching) startLaunchPoll();
else stopLaunchPoll();
},
);
// What the play button says while the claim is in flight. The phase only
// arrives once the broker has started unpacking, so the generic line covers
// both the wait before that and every launch with no extraction step.
@@ -563,38 +558,51 @@ function stopSessionPoll() {
}
}
// The claim request blocks until the game is up, and a webstation broker
// unpacks pkg and archive ROMs before it can start the emulator. Minutes can
// pass with nothing to show, so the phase comes from a second request running
// alongside the claim.
const LAUNCH_POLL_MS = 3_000;
let launchPollTimer: ReturnType<typeof setInterval> | null = null;
async function pollLaunchPhase(): Promise<void> {
if (!rom.value) return;
const status = await streamingStore.fetchSessionStatus(
rom.value.platform_slug,
);
// Only the phase is read here. The claim is not recorded until the request
// this runs beside has reached the backend, so an early poll reports the
// session as ended, and acting on that would tear down a live launch.
if (playerState.value !== "loading") return;
launchPhase.value = status?.extraction_phase ?? null;
// ── Launch ─────────────────────────────────────────────────────────
// The claim only reserves the container; the backend runs the launch detached
// and pushes what happened. A launch can take minutes on a title the broker
// has to unpack, and these are the only progress the player sees.
//
// Every push is scoped to this platform: the room is per-user, so a second tab
// streaming something else receives them too.
function isOurLaunch(payload: { platform?: string }): boolean {
return payload.platform === rom.value?.platform_slug;
}
function startLaunchPoll() {
// A joiner does not own the claim, so the status route only gives it 403s.
if (launchPollTimer || isJoining) return;
launchPollTimer = setInterval(() => void pollLaunchPhase(), LAUNCH_POLL_MS);
}
useSocketEvent<LaunchPhase>("streaming:launch-phase", (payload) => {
if (!isOurLaunch(payload) || playerState.value !== "loading") return;
launchPhase.value = payload.phase;
});
function stopLaunchPoll() {
if (launchPollTimer) {
clearInterval(launchPollTimer);
launchPollTimer = null;
}
useSocketEvent<LaunchReady>("streaming:launch-ready", async (payload) => {
if (!isOurLaunch(payload)) return;
launchPhase.value = null;
}
// The player left while the game was coming up. The claim is theirs and
// still held, so hand the container back rather than entering the stream.
if ((playerState.value as PlayerState) === "exited") {
void streamingStore.releaseSession(payload.platform, false);
return;
}
if (payload.resume === false) snackbar.warning(t("play.resume-failed"));
containerHost.value = payload.host;
playerState.value = "playing";
if (fullscreenOnPlay.value) {
await nextTick();
await stage.value?.enterFullscreen();
}
});
useSocketEvent<LaunchFailed>("streaming:launch-failed", (payload) => {
if (!isOurLaunch(payload)) return;
// The backend already released the claim, so there is nothing to hand back.
holdsClaim.value = false;
launchPhase.value = null;
if ((playerState.value as PlayerState) === "exited") return;
errorType.value = "server";
errorMessage.value = t("play.stream-error-generic");
errorHint.value = payload.detail;
playerState.value = "error";
});
// A background tab's timers are throttled, so the poll may not have run for
// minutes. Re-check on the way back rather than leaving a dead stream on
@@ -729,9 +737,9 @@ async function onPlay(cardImport?: MemoryCardImport): Promise<void> {
}
} else {
// The backend derives the ROM's filesystem path and platform from the id.
// A selected state rides along: its file is pushed to the broker and the
// emulator loads it once the game is up.
const session = await streamingStore.claimSession(
// It answers as soon as the container is reserved; the room URL follows
// on the socket, so the state stays "loading" until launch-ready lands.
await streamingStore.claimSession(
rom.value.id,
selectedState.value?.id,
container.value?.supports_memory_cards
@@ -740,35 +748,8 @@ async function onPlay(cardImport?: MemoryCardImport): Promise<void> {
cardImport,
multiplayerOnPlay.value,
);
if (session.resume === false) {
snackbar.warning(t("play.resume-failed"));
}
await flourish;
// Widen past TS's "loading" narrowing: the exit dialog can flip the
// state to "exited" while the claim is awaited.
const stateAfterClaim = playerState.value as PlayerState;
if (stateAfterClaim === "exited") {
// The launch was cancelled from the exit dialog while the claim was
// in flight; the claim that just resolved re-acquired the session,
// so release it again instead of entering the playing state. Nobody
// played anything, so there is nothing worth saving over their pick.
const released = await streamingStore.releaseSession(
rom.value.platform_slug,
false,
);
if (!released) {
snackbar.error(t("play.stream-release-failed"), { timeout: 6000 });
}
return;
}
holdsClaim.value = true;
containerHost.value = session.host;
playerState.value = "playing";
if (fullscreenOnPlay.value) {
await nextTick();
await stage.value?.enterFullscreen();
}
await flourish;
}
} catch (err: unknown) {
// Same race the success path guards: the user can leave via the exit
@@ -1244,7 +1225,6 @@ onBeforeUnmount(() => {
stopExitChordPoll();
presence.stopHeartbeat();
stopSessionPoll();
stopLaunchPoll();
presence.emitStop();
// The claim, not the player state, says whether anything is still held:
// an exit whose release failed leaves it standing, and this is its retry.