refactor(streaming): move the session store and broker transport into handlers

`endpoints/streaming.py` held a general-purpose Redis session store and an HTTP
client alongside its routes, so both were reachable only through the ASGI test
client and neither could serve a second caller. They now sit in
`handler/streaming/` next to the container and protocol modules, matching how
`handler/netplay_handler.py` already owns its Redis room state.

- `session_store.py`: the keys, TTLs, compare-and-set helpers, drain markers,
  staleness rule and termination notices. Its names are public now, because the
  module boundary is the privacy boundary.
- `broker.py`: the urllib transport, its bounded reads and byte caps, and the
  translation of a transport failure into the 502/503 the frontend parses.

The endpoint module drops from 5157 lines to 3616 and keeps the routes, the
claim and teardown flows, and the asset sync.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-09-05 10:55:45 -04:00
parent 1da0212b7f
commit f6b842fe62
4 changed files with 1098 additions and 1001 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,306 @@
"""The HTTP transport to a container's broker.
urllib rather than an async client because every call here runs inside
`asyncio.to_thread`: the broker verbs block for as long as an emulator takes to
answer, and a save can legitimately hold one open for half a minute.
The bounded reads matter. urllib's `timeout` bounds a single socket operation,
not the transfer, so a broker feeding one byte per timeout window could hold a
read open indefinitely; reading in chunks against a wall clock is what ends it,
and the byte caps are what keep a misbehaving broker from filling memory.
"""
import json
import logging
import time
import urllib.error
import urllib.request
from email.message import Message
from typing import Any, NoReturn
from fastapi import HTTPException
from handler.streaming.config import ResolvedContainer
log = logging.getLogger("romm")
# Broker HTTP deadlines, grouped by what the call actually waits on:
# ACK - the broker only acknowledges; the work runs async on its side
# LAUNCH - process spawn + config patch + window setup
# LOAD_STATE - worst case 9 slot cycles x ~5s xdotool timeout
# TRANSFER - save archive and memory card transfers; state transfers use
# their own per-emulator deadline, see _STATE_TRANSFER_LIMITS
# CARD_HYDRATE / CARD_TEARDOWN - whole-card push at claim / pull at exit;
# hydration may wait on a slow first-run card format, teardown must not
# hold a closing session hostage for two minutes
ACK_TIMEOUT = 5
LAUNCH_TIMEOUT = 10
LOAD_STATE_TIMEOUT = 60
TRANSFER_TIMEOUT = 60
# The broker waits for the core to report a running game before touching the
# tray, then sits out the tray settle, so this has to outlast that wait.
SWAP_DISC_TIMEOUT = 120
CARD_HYDRATE_TIMEOUT = 120
CARD_TEARDOWN_TIMEOUT = 30
def broker_url(container: ResolvedContainer, path: str) -> str:
"""
Build the URL for the ROM broker API.
The broker runs inside the emulator container on BROKER_PORT (default 8000).
`broker_host` in config.yml is the host:port of the broker endpoint -
separate from `host` which is the browser-facing stream URL.
If broker_host is not set, we assume it is on the same host and swap the port.
Example:
host: http://192.168.1.51:3000 (Selkies web UI, browser-facing)
broker_host: http://192.168.1.51:8000 (broker API, server-to-server)
"""
broker_host = container.broker_host
if not broker_host:
# No usable broker host, raise a 502 with a clear cause so the
# operator sees the misconfiguration instead of an opaque KeyError.
raise HTTPException(
status_code=502,
detail=(
"Streaming container has no usable broker_host/host. "
"Set broker_host (or host with a scheme, e.g. http://...) "
"in the streaming.containers config."
),
)
return f"{broker_host}{path}"
def broker_headers(container: ResolvedContainer) -> dict[str, str]:
"""Auth headers for a broker call, empty when no secret is configured.
Returns a fresh dict so callers can add their own headers to it."""
secret = container.broker_secret
return {"X-Broker-Secret": secret} if secret else {}
# urllib's timeout bounds a single socket operation, not the transfer, so a
# broker feeding one byte per timeout window can hold a read open for as long
# as it likes. Reading in chunks against a wall clock is what ends it.
_BROKER_READ_CHUNK = 1024 * 1024
# Control responses are small; a JSON body past this is a broker fault.
_BROKER_JSON_MAX_BYTES = 4 * 1024 * 1024
# An error body only ever reaches a log line and a 502 detail.
_BROKER_ERROR_MAX_BYTES = 8 * 1024
def broker_error_body(exc: urllib.error.HTTPError) -> str:
"""The text a failed broker call answered with.
HTTPError is itself the response, so it holds a connection until something
closes it, and its body is as long as the broker cares to make it.
"""
try:
return exc.read(_BROKER_ERROR_MAX_BYTES).decode(errors="replace")
except OSError as read_exc:
log.warning("could not read broker error body, %s", read_exc)
return ""
finally:
exc.close()
def _read_bounded(resp: Any, max_bytes: int, deadline: float) -> bytes:
"""Read up to `max_bytes` from an open response, giving up at `deadline`.
Reads one byte past the cap so the caller can tell a body that fits from
one that was truncated.
"""
chunks: list[bytes] = []
size = 0
while size <= max_bytes:
if time.monotonic() > deadline:
raise TimeoutError("broker response exceeded its time budget")
chunk = resp.read(min(_BROKER_READ_CHUNK, max_bytes + 1 - size))
if not chunk:
break
chunks.append(chunk)
size += len(chunk)
return b"".join(chunks)
def request(
container: ResolvedContainer,
path: str,
*,
method: str = "POST",
body: dict[str, Any] | None = None,
timeout: float,
) -> Any:
"""
Send a signed request to the broker and return its parsed JSON body (an
empty dict when the broker replies with no content). Uses only Python
stdlib urllib, no extra dependencies. Raises the underlying urllib/OS
error; callers decide whether to surface or swallow it.
"""
url = broker_url(container, path)
headers = broker_headers(container)
data = None
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
headers["Content-Length"] = str(len(data))
req = urllib.request.Request(url, data=data, method=method, headers=headers)
deadline = time.monotonic() + timeout
with urllib.request.urlopen(req, timeout=timeout) as resp: # nosec B310
raw = _read_bounded(resp, _BROKER_JSON_MAX_BYTES, deadline)
if len(raw) > _BROKER_JSON_MAX_BYTES:
raise ValueError("broker response exceeds size limit")
return json.loads(raw) if raw else {}
def request_safe(
container: ResolvedContainer,
path: str,
label: str,
*,
method: str = "POST",
body: dict[str, Any] | None = None,
timeout: float,
) -> Any | None:
"""
Best-effort variant of request: returns the parsed body, or None if
the broker is unreachable or errors. Never raises, control ops must not 500
on a broker hiccup.
"""
try:
return request(container, path, method=method, body=body, timeout=timeout)
except Exception as exc:
log.warning("broker %s failed, %s", label, exc)
# An HTTPError is an open response, and these routes are called often.
if isinstance(exc, urllib.error.HTTPError):
exc.close()
return None
def get_binary(
container: ResolvedContainer,
path: str,
*,
max_bytes: int,
timeout: float,
) -> tuple[Message, bytes]:
"""
GET a binary body from the broker, returning (response headers, content).
Headers come back because some routes carry metadata there. Raises the
underlying urllib/OS error, or ValueError for an empty or oversized body.
"""
req = urllib.request.Request(
broker_url(container, path),
method="GET",
headers=broker_headers(container),
)
deadline = time.monotonic() + timeout
with urllib.request.urlopen(req, timeout=timeout) as resp: # nosec B310
headers = resp.headers
content = _read_bounded(resp, max_bytes, deadline)
if not content:
raise ValueError("broker returned an empty body")
if len(content) > max_bytes:
raise ValueError("broker response exceeds size limit")
return headers, content
def get_binary_safe(
container: ResolvedContainer,
path: str,
label: str,
*,
max_bytes: int,
timeout: float,
) -> tuple[Message, bytes] | None:
"""
Best-effort variant of get_binary: returns None instead of raising.
A 404 is a normal answer on these routes (no state in the slot, no new
saves, no captured frame), so it is not logged.
"""
try:
return get_binary(container, path, max_bytes=max_bytes, timeout=timeout)
except urllib.error.HTTPError as exc:
# The error is a response too, and these routes are polled.
exc.close()
if exc.code != 404:
log.warning("broker %s failed, HTTP %d", label, exc.code)
return None
except Exception as exc:
log.warning("broker %s failed, %s", label, exc)
return None
def put_binary_json(
container: ResolvedContainer,
path: str,
content: bytes,
label: str,
*,
content_type: str,
timeout: float,
) -> dict[str, Any] | None:
"""
PUT a binary body to the broker and return its parsed JSON reply, or None
on failure. Best-effort, logs but never raises.
"""
req = urllib.request.Request(
broker_url(container, path),
data=content,
method="PUT",
headers={
"Content-Type": content_type,
"Content-Length": str(len(content)),
**broker_headers(container),
},
)
deadline = time.monotonic() + timeout
try:
with urllib.request.urlopen(req, timeout=timeout) as resp: # nosec B310
body = json.loads(_read_bounded(resp, _BROKER_JSON_MAX_BYTES, deadline))
return body if isinstance(body, dict) else {}
except Exception as exc:
log.warning("broker %s failed, %s", label, exc)
if isinstance(exc, urllib.error.HTTPError):
exc.close()
return None
def put_binary(
container: ResolvedContainer,
path: str,
content: bytes,
label: str,
*,
content_type: str,
timeout: float,
) -> bool:
"""PUT a binary body to the broker, reporting whether it acked with ok."""
body = put_binary_json(
container, path, content, label, content_type=content_type, timeout=timeout
)
return bool(body and body.get("status") == "ok")
def raise_http_error(exc: urllib.error.HTTPError) -> NoReturn:
"""Translate a broker error response into the 502 the frontend parses."""
error_body = broker_error_body(exc)
log.error("broker HTTP error %d: %s", exc.code, error_body)
try:
detail = json.loads(error_body)
except Exception:
detail = error_body
raise HTTPException(
status_code=502, detail=f"Broker returned {exc.code}: {detail}"
) from exc
def raise_unreachable(
exc: BaseException, subject: str, url: str, hint: str
) -> NoReturn:
"""Translate a transport failure into a 503 naming what to check."""
log.error("broker unreachable at %s: %s", url, exc)
raise HTTPException(
status_code=503, detail=f"Could not reach {subject} at {url}. {hint}"
) from exc

View File

@@ -0,0 +1,561 @@
"""The Redis-backed record of which container is serving whom.
A session outlives the request that made it and is shared across uvicorn
workers, so it lives in Redis rather than in process memory: the emulator
container keeps running across a backend restart either way, and a claim that
did not survive would strand it. Claiming uses SET NX, which is atomic, so two
concurrent claims for one container cannot both win with no in-process locking.
Everything that mutates a session goes through the compare-and-set helpers
here. A blind write would resurrect a claim a concurrent release had just
deleted, which is the difference between a container that frees itself and one
wedged until its TTL lapses.
"""
import asyncio
import json
import logging
import secrets
import time
from collections.abc import AsyncIterator, Callable
from datetime import datetime, timezone
from enum import Enum, auto
from typing import Any, NamedTuple
from redis.exceptions import WatchError
from handler.redis_handler import async_cache
from handler.socket_handler import socket_handler
log = logging.getLogger("romm")
# Sessions are stored in Redis so they are shared across uvicorn workers and
# survive backend restarts (the emulator container keeps running either way).
# Claiming uses SET NX, which is atomic in Redis. Two concurrent claims for
# the same container cannot both succeed, with no in-process locking needed.
SESSION_KEY_PREFIX = "romm:streaming:session:"
# An active session is long-lived (a game can run for hours), but the key
# must not live forever: if the broker container dies or the backend
# crashes mid-session, the TTL ensures the container is eventually
# reclaimable instead of wedged until an admin force-releases. Control
# calls (save-state / volume / mute / save-and-exit) and the heartbeat
# refresh the TTL so a session in active use never expires.
STREAMING_SESSION_TTL_SECONDS = 6 * 60 * 60
# When save-and-exit runs with wait=false the broker is still killing the
# emulator in the background when the route returns. A short drain TTL
# keeps the key briefly so a concurrent new claim can't /launch on top of
# a not-yet-dead emulator (which would lose the in-flight save). The key
# expires on its own; no explicit DELETE.
STREAMING_SESSION_DRAIN_SECONDS = 5
# Save-and-exit holds the container past the drain window when an exit state is
# still coming back out of it. The marker is short and refreshed for as long as
# the pull runs (see hold_drain_marker) rather than sized to the slowest
# possible transfer, so a backend that dies mid-pull frees the container in a
# minute instead of parking it for the length of a transfer nobody is doing.
DRAIN_MARKER_TTL = 60
_DRAIN_MARKER_REFRESH = 20
# A live player refreshes `last_seen` roughly every 30s (frontend heartbeat,
# piggybacked on the activity interval). A session whose stamp is older than
# this is abandoned (tab closed, browser crashed, network gone) and the next
# claim may tear it down and take the container over. Generous enough to ride
# out background-tab timer throttling (browsers wake timers at least once a
# minute).
_STREAMING_SESSION_STALE_SECONDS = 180
# How often backend-side work running under a claim restamps it. Well inside the
# stale window, so a single missed refresh cannot hand the container away.
_CLAIM_REFRESH_SECONDS = _STREAMING_SESSION_STALE_SECONDS // 3
# How long a marker or a claim may be kept alive by the work behind it. Past
# this the refresh stops and the container ages back out on its own: every step
# under a keepalive carries its own timeout, so overrunning this means something
# is wedged, and a wedged step must not reserve a container indefinitely.
_HOLD_CEILING_SECONDS = 15 * 60
def session_redis_key(session_key: str) -> str:
return f"{SESSION_KEY_PREFIX}{session_key}"
async def get_session(session_key: str) -> dict[str, Any] | None:
raw = await async_cache.get(session_redis_key(session_key))
if raw is None:
return None
try:
return json.loads(raw)
except (TypeError, json.JSONDecodeError):
# Corrupt entry, drop it rather than wedging the container forever.
await async_cache.delete(session_redis_key(session_key))
return None
async def get_live_session(session_key: str) -> dict[str, Any] | None:
"""The session occupying a container, or None when nobody holds it.
A drain marker holds the key while a teardown finishes: it has no owner and
nothing to release, so every reader that asks "who is on this container"
wants it treated as absent.
"""
session = await get_session(session_key)
if session is None or session.get("draining"):
return None
return session
async def iter_session_keys() -> AsyncIterator[str]:
"""Every container key with a session row in the cache."""
async for key in async_cache.scan_iter(match=f"{SESSION_KEY_PREFIX}*"):
# scan_iter yields bytes unless the client decodes responses.
key_str = key.decode() if isinstance(key, bytes) else key
yield key_str.removeprefix(SESSION_KEY_PREFIX)
async def iter_live_sessions() -> AsyncIterator[tuple[str, dict[str, Any]]]:
"""Every occupied container, as (container key, session). Unreadable rows
and drain markers are skipped, so listing routes never re-decide either."""
async for container_key in iter_session_keys():
session = await get_live_session(container_key)
if session is not None:
yield container_key, session
async def refresh_session(session_key: str) -> None:
"""Reset the session TTL back to the full window. Called after every
successful control op so a session in active use never expires; only an
abandoned one (broker dead / backend crashed) ages out."""
await async_cache.expire(
session_redis_key(session_key), STREAMING_SESSION_TTL_SECONDS
)
# A contended session key is rewritten by at most a heartbeat, a swap and a
# release, so a handful of retries is far more than the contention warrants.
_STREAMING_SESSION_CAS_ATTEMPTS = 5
class StreamingSessionContended(Exception):
"""The session key stayed contended for the whole CAS budget.
Kept apart from the None that means "gone": a key nobody could write is
still a key that exists, and callers that treat it as a vanished claim
report a live session as ended.
"""
class _CasOutcome(Enum):
"""How one compare-and-set against a session key ended."""
WROTE = auto()
MISSING = auto() # nothing at the key
CORRUPT = auto() # the key held something that is not a session
REJECTED = auto() # the plan declined to write against what it read
VANISHED = auto() # the write found no key left to overwrite
class _SessionWrite(NamedTuple):
"""What a plan wants left at the key: JSON with a TTL, or a delete."""
value: str | None
ttl: int | None = None
async def cas_session(
session_key: str,
plan: Callable[[dict[str, Any]], _SessionWrite | None],
) -> tuple[_CasOutcome, dict[str, Any] | None]:
"""Run `plan` against the session at `session_key` and apply what it asks
for, atomically.
The whole session is one JSON blob, so a plain read-modify-write silently
drops whichever concurrent update landed in between: a heartbeat racing a
disc swap would write back a copy with no `disc_file_id`. WATCH aborts the
write when the key moved under us and the retry re-reads.
`plan` sees the freshly read session inside the same watch, so a caller can
act on a condition without it going stale between the check and the write,
and returns the write to make or None to abandon this attempt. Returns the
outcome and the session `plan` was given, which callers map to their own
conventions since "gone", "refused" and "the write found nothing" mean
different things to each of them. Raises `StreamingSessionContended` once
the retry budget is spent.
"""
key = session_redis_key(session_key)
for _ in range(_STREAMING_SESSION_CAS_ATTEMPTS):
async with async_cache.pipeline() as pipe:
await pipe.watch(key)
raw = await pipe.get(key)
if raw is None:
await pipe.unwatch()
return _CasOutcome.MISSING, None
try:
session = json.loads(raw)
except (TypeError, json.JSONDecodeError):
session = None
if not isinstance(session, dict):
await pipe.unwatch()
# Drop it rather than wedging the container until the TTL.
await async_cache.delete(key)
return _CasOutcome.CORRUPT, None
write = plan(session)
if write is None:
await pipe.unwatch()
return _CasOutcome.REJECTED, session
pipe.multi()
if write.value is None:
await pipe.delete(key)
else:
# xx so a release landing between the watch and the exec cannot
# be undone by resurrecting the key.
await pipe.set(key, write.value, xx=True, ex=write.ttl)
try:
results = await pipe.execute()
except WatchError:
continue
# An expiry between the watch and the exec does not abort the
# transaction, so an xx write can succeed having set nothing.
if write.value is not None and not (results and results[0]):
return _CasOutcome.VANISHED, session
return _CasOutcome.WROTE, session
raise StreamingSessionContended(session_key)
async def mutate_session(
session_key: str,
changes: dict[str, Any],
*,
require: Callable[[dict[str, Any]], bool] | None = None,
) -> dict[str, Any] | None:
"""Merge `changes` into a live session, atomically.
Returns the stored session, or None when the key is gone, corrupt, or
`require` rejected it. Raises `StreamingSessionContended` when the write
never landed, which is not the same as the key being gone.
"""
def plan(session: dict[str, Any]) -> _SessionWrite | None:
if require is not None and not require(session):
return None
session.update(changes)
return _SessionWrite(json.dumps(session), STREAMING_SESSION_TTL_SECONDS)
outcome, session = await cas_session(session_key, plan)
return session if outcome is _CasOutcome.WROTE else None
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
not pass for the claim it replaced."""
return (
not session.get("draining")
and session.get("user_id") == claim.get("user_id")
and session.get("claimed_at") == claim.get("claimed_at")
)
async def replace_session_if(
session_key: str,
require: Callable[[dict[str, Any]], bool],
value: str | None,
ttl: int | None = None,
) -> bool:
"""Overwrite or delete a session key, while `require` accepts what is there.
Returns True when the intended state is what the key now holds, False when
`require` rejected it. A delete finding the key already gone counts as done;
a write that did not land does not, so it raises
`StreamingSessionContended` along with running out of retries. The caller
still holds what it tried to give up in that case, and must not report
otherwise.
"""
outcome, _ = await cas_session(
session_key,
lambda current: _SessionWrite(value, ttl) if require(current) else None,
)
if outcome is _CasOutcome.MISSING:
return value is None
if outcome is _CasOutcome.VANISHED:
raise StreamingSessionContended(session_key)
return outcome is _CasOutcome.WROTE
def drain_marker(token: str) -> str:
return json.dumps({"draining": True, "drain_token": token})
async def claim_drain_marker(
session_key: str, claim: dict[str, Any], ttl: int = DRAIN_MARKER_TTL
) -> str | None:
"""Replace a session with a drain marker, while the key still holds the claim
that is exiting.
Deliberately not a session record: the session is over, and joinable and the
admin views must not keep advertising it. Deliberately not an unconditional
write either, since an admin force-release and a fresh claim both fit inside
the blocking save+kill that runs before this, and the marker would bury a
session somebody is playing.
Returns the token the marker carries, or None when the key had moved on.
Raises `StreamingSessionContended` when the marker never landed, which leaves the
container held by a claim the caller has already stopped.
"""
token = secrets.token_hex(8)
landed = await replace_session_if(
session_key,
lambda current: same_claim(current, claim),
drain_marker(token),
ttl,
)
return token if landed else None
async def hold_drain_marker(session_key: str, token: str) -> None:
"""Keep a drain marker alive for as long as the work behind it runs.
The marker is short-lived and refreshed rather than sized to the slowest
imaginable pull: a backend that dies mid-pull then frees the container in a
minute instead of parking it for the length of a transfer nobody is doing.
"""
marker = drain_marker(token)
deadline = time.monotonic() + _HOLD_CEILING_SECONDS
while True:
await asyncio.sleep(_DRAIN_MARKER_REFRESH)
try:
held = await replace_session_if(
session_key,
lambda current: current.get("drain_token") == token,
marker,
DRAIN_MARKER_TTL,
)
except StreamingSessionContended:
# Contention is not a takeover: the marker is still ours, the write
# just did not land. Stopping here would leave the work behind the
# marker running against a key nothing refreshes.
continue
if not held:
log.warning("drain marker on %s is no longer ours", session_key)
return
if time.monotonic() >= deadline:
log.warning(
"stopped refreshing the drain marker on %s, the work behind it "
"has run for over %ss",
session_key,
_HOLD_CEILING_SECONDS,
)
return
async def hold_session_claim(session_key: str, claim: dict[str, Any]) -> None:
"""Keep a claim's liveness stamp current for as long as work runs under it.
For the paths where a drain marker could not be written and the claim itself
is what reserves the container. The stamp is the player's, and the player is
gone, so without this the record ages past `_STREAMING_SESSION_STALE_SECONDS` and the
next claimant tears the container down mid-work.
"""
deadline = time.monotonic() + _HOLD_CEILING_SECONDS
while True:
await asyncio.sleep(_CLAIM_REFRESH_SECONDS)
try:
held = await mutate_session(
session_key,
{"last_seen": datetime.now(timezone.utc).isoformat()},
require=lambda current: same_claim(current, claim),
)
except StreamingSessionContended:
continue
if held is None:
log.warning("claim on %s is no longer ours", session_key)
return
if time.monotonic() >= deadline:
log.warning(
"stopped refreshing the claim on %s, the work behind it has run "
"for over %ss",
session_key,
_HOLD_CEILING_SECONDS,
)
return
async def stamp_launched(session_key: str) -> None:
"""Record that the activate returned, so the status poll stops asking the
broker for an extraction phase.
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.
"""
try:
await mutate_session(
session_key, {"launched_at": datetime.now(timezone.utc).isoformat()}
)
except StreamingSessionContended:
log.warning("could not stamp the launch on session %s", session_key)
async def drop_drain_marker(session_key: str, token: str) -> None:
"""Delete a drain marker, while it is still the one `token` wrote.
A marker that expired, or that a later exit replaced, belongs to whoever
holds the container now, and deleting it would free a container mid-play.
"""
try:
await replace_session_if(
session_key,
lambda current: current.get("drain_token") == token,
None,
)
except StreamingSessionContended:
log.warning("could not drop the drain marker on %s", session_key)
async def release_own_session(session_key: str, claim: dict[str, Any]) -> bool:
"""Free a container, while the key still holds the claim being released.
Save-and-exit blocks on the broker for as long as the emulator takes to
write and die, and an admin force-release plus a new claim both fit in that
window. The unguarded delete would then end a session that had just begun.
False means the container is still held, either by somebody else's claim or
because the delete never landed.
"""
try:
return await replace_session_if(
session_key, lambda current: same_claim(current, claim), None
)
except StreamingSessionContended:
log.warning("could not release session %s", session_key)
return False
async def set_session_disc(
session_key: str, file_id: int, broker_session_id: str | None = None
) -> None:
"""Record the disc a session is now running.
The write only lands on the claim it was made for. A swap can outlive that
claim: the broker holds it until the game is up, by which time the key can
be the short drain marker save-and-exit leaves behind, or a fresh claim by
someone else. Writing either would stamp the wrong disc, and the drain
marker would come back with a six-hour TTL that no release path owns.
Best-effort: the disc is already in the tray by the time this runs, so a
key that could not be written costs the next state capture its disc, not
the swap the player asked for.
"""
def _still_the_same_claim(session: dict[str, Any]) -> bool:
if session.get("draining"):
return False
return (
broker_session_id is None
or session.get("broker_session_id") == broker_session_id
)
try:
written = await mutate_session(
session_key, {"disc_file_id": file_id}, require=_still_the_same_claim
)
except StreamingSessionContended:
written = None
if written is None:
log.warning("could not record disc %s on session %s", file_id, session_key)
def broker_session_id(session: dict[str, Any]) -> str | None:
"""The id activate gave the broker, absent on sessions claimed before it."""
value = session.get("broker_session_id")
return str(value) if value else None
def session_disc_id(session: dict[str, Any]) -> int | None:
"""The disc a swap put this session on, if any."""
value = session.get("disc_file_id")
return value if isinstance(value, int) else None
def session_is_stale(session: dict[str, Any]) -> bool:
"""True when the owner's heartbeat stopped long enough ago that the session
counts as abandoned. Sessions written before heartbeats existed carry no
`last_seen`; their `claimed_at` stands in. An unparseable stamp counts as
stale so a corrupt record cannot wedge the container."""
stamp = session.get("last_seen") or session.get("claimed_at")
if not isinstance(stamp, str):
return True
try:
seen = datetime.fromisoformat(stamp)
except ValueError:
return True
if seen.tzinfo is None:
seen = seen.replace(tzinfo=timezone.utc)
age = (datetime.now(timezone.utc) - seen).total_seconds()
return age > _STREAMING_SESSION_STALE_SECONDS
# ── Termination notices ───────────────────────────────────────────────────────
# An admin force-release deletes the session key, but the displaced player's
# browser is still showing a stream that no longer exists. A tombstone keyed by
# container and displaced user lets their next poll say who ended it and why,
# instead of the picture simply stopping. Cleared when that user claims again;
# the TTL covers the case where they never come back.
_TERMINATION_KEY_PREFIX = "romm:streaming:terminated:"
_TERMINATION_TTL_SECONDS = 15 * 60
def _termination_redis_key(session_key: str, user_id: int) -> str:
return f"{_TERMINATION_KEY_PREFIX}{session_key}:{user_id}"
async def record_termination(
session: dict[str, Any],
session_key: str,
*,
ended_by: str | None,
reason: str | None,
) -> None:
"""Leave a note for the player whose session was taken away, and push it
over the socket so the poll isn't the only way that tab finds out. No-op
when the session records no owner, since there is nobody to notify."""
user_id = session.get("user_id")
if not isinstance(user_id, int):
return
notice = {
"ended_by": ended_by,
"reason": reason or None,
"ended_at": datetime.now(timezone.utc).isoformat(),
"platform": session.get("platform"),
"rom_id": session.get("rom_id"),
"rom_name": session.get("rom_name"),
}
await async_cache.set(
_termination_redis_key(session_key, user_id),
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.
try:
await socket_handler.socket_server.emit(
"streaming:session-ended", notice, room=f"user:{user_id}"
)
except Exception: # noqa: BLE001
log.warning("Failed to push session-ended notice", exc_info=True)
async def get_termination(session_key: str, user_id: int) -> dict[str, Any] | None:
raw = await async_cache.get(_termination_redis_key(session_key, user_id))
if raw is None:
return None
try:
return json.loads(raw)
except (TypeError, json.JSONDecodeError):
await async_cache.delete(_termination_redis_key(session_key, user_id))
return None
async def clear_termination(session_key: str, user_id: int) -> None:
await async_cache.delete(_termination_redis_key(session_key, user_id))

View File

@@ -32,6 +32,7 @@ from handler.database import (
)
from handler.database.base_handler import sync_session
from handler.redis_handler import async_cache
from handler.streaming import session_store
from handler.streaming.capabilities import (
DEFAULT_STATE_TRANSFER,
NO_CAPABILITIES,
@@ -792,7 +793,7 @@ async def test_claim_sets_session_ttl(access_token, rom: Rom):
headers=_auth(access_token),
)
assert r.status_code == 200
key = streaming._session_redis_key(_key_of(_container_for(rom)))
key = session_store.session_redis_key(_key_of(_container_for(rom)))
ttl = await async_cache.ttl(key)
assert ttl > 0
assert ttl <= streaming.STREAMING_SESSION_TTL_SECONDS
@@ -898,7 +899,7 @@ def _volume(client, token, platform: str, level: int = 42):
def _session_raw(container: dict):
key = streaming._session_redis_key(_key_of(container))
key = session_store.session_redis_key(_key_of(container))
return asyncio.run(async_cache.get(key))
@@ -930,7 +931,7 @@ def test_pool_never_evicts_a_stale_session_while_a_container_is_free(
with _streaming(_pool_member(rom, 0), _pool_member(rom, 1)):
_claim_ok(client, access_token, rom.id)
_age_session_on(
_pool_member(rom, 0), streaming._STREAMING_SESSION_STALE_SECONDS + 60
_pool_member(rom, 0), session_store._STREAMING_SESSION_STALE_SECONDS + 60
)
with patch(
"endpoints.streaming._stop_broker", return_value=None
@@ -949,7 +950,7 @@ def test_pool_takes_over_a_stale_session_once_every_container_is_held(
_claim_ok(client, access_token, rom.id)
_claim_ok(client, access_token, rom.id)
_age_session_on(
_pool_member(rom, 1), streaming._STREAMING_SESSION_STALE_SECONDS + 60
_pool_member(rom, 1), session_store._STREAMING_SESSION_STALE_SECONDS + 60
)
with patch(
"endpoints.streaming._stop_broker", return_value=None
@@ -1428,7 +1429,7 @@ def test_swap_disc_broker_has_nothing_to_call_on_a_legacy_container():
def _age_session_on(container: dict, seconds: int) -> None:
"""Rewrite one container's stored session last_seen to `seconds` ago."""
key = streaming._session_redis_key(_key_of(container))
key = session_store.session_redis_key(_key_of(container))
raw = asyncio.run(async_cache.get(key))
session = json.loads(raw)
session["last_seen"] = (
@@ -1443,15 +1444,15 @@ def _age_session(rom: Rom, seconds: int) -> None:
def test_session_is_stale_handles_bad_stamps():
"""Missing or corrupt stamps must count as stale, not wedge the container."""
assert streaming._session_is_stale({}) is True
assert streaming._session_is_stale({"last_seen": "not-a-date"}) is True
assert session_store.session_is_stale({}) is True
assert session_store.session_is_stale({"last_seen": "not-a-date"}) is True
fresh = datetime.now(timezone.utc).isoformat()
assert streaming._session_is_stale({"last_seen": fresh}) is False
assert session_store.session_is_stale({"last_seen": fresh}) is False
old = (
datetime.now(timezone.utc)
- timedelta(seconds=streaming._STREAMING_SESSION_STALE_SECONDS + 1)
- timedelta(seconds=session_store._STREAMING_SESSION_STALE_SECONDS + 1)
).isoformat()
assert streaming._session_is_stale({"last_seen": old}) is True
assert session_store.session_is_stale({"last_seen": old}) is True
def test_stale_session_taken_over_on_claim(
@@ -1461,7 +1462,7 @@ def test_stale_session_taken_over_on_claim(
session down (broker stop included) and win the container."""
with _streaming(_container_for(rom)):
r1 = _claim_ok(client, access_token, rom.id)
_age_session(rom, streaming._STREAMING_SESSION_STALE_SECONDS + 60)
_age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60)
with patch(
"endpoints.streaming._stop_broker", return_value=None
) as stop_broker:
@@ -1481,14 +1482,14 @@ def test_takeover_leaves_the_displaced_owner_a_notice(
_claim_ok(client, access_token, rom.id)
owner = json.loads(
asyncio.run(
async_cache.get(streaming._session_redis_key(_key_of(container)))
async_cache.get(session_store.session_redis_key(_key_of(container)))
)
)["user_id"]
_age_session(rom, streaming._STREAMING_SESSION_STALE_SECONDS + 60)
_age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60)
with patch("endpoints.streaming._stop_broker", return_value=None):
_claim_ok(client, viewer_access_token, rom.id)
notice = asyncio.run(streaming._get_termination(_key_of(container), owner))
notice = asyncio.run(session_store.get_termination(_key_of(container), owner))
assert notice is not None
assert notice["reason"] == "abandoned"
@@ -1503,9 +1504,9 @@ def test_takeover_aborts_when_the_owner_comes_back_first(
container = _container_for(rom)
with _streaming(container):
_claim_ok(client, access_token, rom.id)
_age_session(rom, streaming._STREAMING_SESSION_STALE_SECONDS + 60)
_age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60)
real_stale = streaming._session_is_stale
real_stale = session_store.session_is_stale
checked = False
def stale_then_fresh(session):
@@ -1517,7 +1518,7 @@ def test_takeover_aborts_when_the_owner_comes_back_first(
checked = True
return real_stale(session)
with patch.object(streaming, "_session_is_stale", stale_then_fresh):
with patch.object(streaming, "session_is_stale", stale_then_fresh):
with patch(
"endpoints.streaming._stop_broker", return_value=None
) as stop_broker:
@@ -1548,16 +1549,16 @@ def test_heartbeat_refreshes_last_seen(client, access_token, rom: Rom):
rival claim no longer takes it over."""
with _streaming(_container_for(rom)):
_claim_ok(client, access_token, rom.id)
_age_session(rom, streaming._STREAMING_SESSION_STALE_SECONDS + 60)
_age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60)
r = client.post(
f"/api/streaming/sessions/{rom.platform_slug}/heartbeat",
headers=_auth(access_token),
)
assert r.status_code == 200
assert r.json()["status"] == "active"
key = streaming._session_redis_key(_key_of(_container_for(rom)))
key = session_store.session_redis_key(_key_of(_container_for(rom)))
session = json.loads(asyncio.run(async_cache.get(key)))
assert not streaming._session_is_stale(session)
assert not session_store.session_is_stale(session)
def test_heartbeat_racing_a_teardown_reports_ended(client, access_token, rom: Rom):
@@ -1567,7 +1568,7 @@ def test_heartbeat_racing_a_teardown_reports_ended(client, access_token, rom: Ro
container = _container_for(rom)
with _streaming(container):
_claim_ok(client, access_token, rom.id)
key = streaming._session_redis_key(_key_of(container))
key = session_store.session_redis_key(_key_of(container))
real_find = streaming._find_session_for_user
@@ -1591,7 +1592,7 @@ def test_heartbeat_does_not_revive_a_draining_session(client, access_token, rom:
container = _container_for(rom)
with _streaming(container):
_claim_ok(client, access_token, rom.id)
key = streaming._session_redis_key(_key_of(container))
key = session_store.session_redis_key(_key_of(container))
session = json.loads(asyncio.run(async_cache.get(key)))
session["draining"] = True
asyncio.run(async_cache.set(key, json.dumps(session)))
@@ -1611,14 +1612,14 @@ def test_heartbeat_keeps_a_disc_swap_that_landed_first(client, access_token, rom
with _streaming(container):
_claim_ok(client, access_token, rom.id)
session_key = _key_of(container)
key = streaming._session_redis_key(session_key)
key = session_store.session_redis_key(session_key)
real_find = streaming._find_session_for_user
async def find_then_swap(*args, **kwargs):
# The swap lands after the heartbeat read its copy of the session.
found = await real_find(*args, **kwargs)
await streaming._set_session_disc(session_key, 4242)
await session_store.set_session_disc(session_key, 4242)
return found
with patch.object(streaming, "_find_session_for_user", find_then_swap):
@@ -1630,7 +1631,7 @@ def test_heartbeat_keeps_a_disc_swap_that_landed_first(client, access_token, rom
assert r.json()["status"] == "active"
assert session["disc_file_id"] == 4242
assert not streaming._session_is_stale(session)
assert not session_store.session_is_stale(session)
def test_heartbeat_without_session_reports_ended(client, access_token, rom: Rom):
@@ -1689,14 +1690,14 @@ def test_status_does_not_refresh_the_session(client, access_token, rom: Rom):
background tab could keep a container hostage without playing."""
with _streaming(_container_for(rom)):
_claim_ok(client, access_token, rom.id)
_age_session(rom, streaming._STREAMING_SESSION_STALE_SECONDS + 60)
_age_session(rom, session_store._STREAMING_SESSION_STALE_SECONDS + 60)
client.get(
f"/api/streaming/sessions/{rom.platform_slug}/status",
headers=_auth(access_token),
)
key = streaming._session_redis_key(_key_of(_container_for(rom)))
key = session_store.session_redis_key(_key_of(_container_for(rom)))
session = json.loads(asyncio.run(async_cache.get(key)))
assert streaming._session_is_stale(session)
assert session_store.session_is_stale(session)
def test_admin_release_leaves_termination_notice(
@@ -1850,7 +1851,7 @@ def test_reclaim_clears_termination_notice(
def _unstamp_launch(container: dict) -> None:
"""Drop the launched_at stamp, leaving the record in the state a claim
holds while its activate is still running."""
key = streaming._session_redis_key(_key_of(container))
key = session_store.session_redis_key(_key_of(container))
session = json.loads(asyncio.run(async_cache.get(key)))
session.pop("launched_at", None)
asyncio.run(async_cache.set(key, json.dumps(session)))
@@ -1864,7 +1865,7 @@ def test_status_reports_the_extraction_phase_during_a_launch(client, access_toke
_claim_webstation_ok(client, access_token, ps2_rom.id)
_unstamp_launch(_first_container("ps2"))
with patch(
"endpoints.streaming._broker_request_safe",
"handler.streaming.broker.request_safe",
return_value={"extraction_phase": "extracting_pkg"},
):
r = client.get(
@@ -1884,7 +1885,7 @@ def test_status_reports_no_phase_before_the_broker_starts_unpacking(
_claim_webstation_ok(client, access_token, ps2_rom.id)
_unstamp_launch(_first_container("ps2"))
with patch(
"endpoints.streaming._broker_request_safe", return_value={"active": True}
"handler.streaming.broker.request_safe", return_value={"active": True}
):
r = client.get(
"/api/streaming/sessions/ps2/status", headers=_auth(access_token)
@@ -1898,7 +1899,7 @@ def test_status_stops_asking_the_broker_once_the_launch_returned(client, access_
ps2_rom = _rom_on("ps2")
with _streaming(_webstation()):
_claim_webstation_ok(client, access_token, ps2_rom.id)
with patch("endpoints.streaming._broker_request_safe") as broker:
with patch("handler.streaming.broker.request_safe") as broker:
r = client.get(
"/api/streaming/sessions/ps2/status", headers=_auth(access_token)
)
@@ -1914,7 +1915,7 @@ def test_status_on_a_legacy_container_never_asks_for_a_phase(
with _streaming(_container_for(rom)):
_claim_ok(client, access_token, rom.id)
_unstamp_launch(_container_for(rom))
with patch("endpoints.streaming._broker_request_safe") as broker:
with patch("handler.streaming.broker.request_safe") as broker:
r = client.get(
f"/api/streaming/sessions/{rom.platform_slug}/status",
headers=_auth(access_token),
@@ -1936,15 +1937,15 @@ def test_a_slow_launch_keeps_its_own_claim_fresh(client, access_token):
with (
_streaming(_webstation()),
patch.object(streaming, "_CLAIM_REFRESH_SECONDS", 0.05),
patch.object(streaming, "_STREAMING_SESSION_STALE_SECONDS", 0.2),
patch.object(session_store, "_CLAIM_REFRESH_SECONDS", 0.05),
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
key = streaming._session_redis_key(_key_of(_first_container("ps2")))
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.
assert streaming._session_is_stale(session) is False
assert session_store.session_is_stale(session) is False
# ── Release / ownership ───────────────────────────────────────────────────────
@@ -2279,14 +2280,16 @@ def test_save_and_exit_holds_the_container_until_the_state_is_pulled(
# holder it does not have.
assert r2.json()["detail"]["draining"] is True
container = _container_for(rom)
key = streaming._session_redis_key(_key_of(container))
key = session_store.session_redis_key(_key_of(container))
ttl = asyncio.run(async_cache.ttl(key))
# Long enough that a refresh has room to land, short enough that a backend
# dying mid-pull does not park the container for the length of a transfer
# nobody is doing.
assert streaming._DRAIN_MARKER_TTL > 2 * streaming._DRAIN_MARKER_REFRESH
assert session_store.DRAIN_MARKER_TTL > 2 * session_store._DRAIN_MARKER_REFRESH
assert (
streaming.STREAMING_SESSION_DRAIN_SECONDS < ttl <= streaming._DRAIN_MARKER_TTL
streaming.STREAMING_SESSION_DRAIN_SECONDS
< ttl
<= session_store.DRAIN_MARKER_TTL
)
@@ -2297,7 +2300,7 @@ def test_save_and_exit_without_a_rom_drains_only_briefly(
wait=false leaves the short marker that keeps a new launch off a not-yet-dead
emulator, not the long one that guards a pull."""
container = _container_for(rom)
key = streaming._session_redis_key(_key_of(container))
key = session_store.session_redis_key(_key_of(container))
with _streaming(container):
_claim_ok(client, access_token, rom.id)
session = json.loads(asyncio.run(async_cache.get(key)))
@@ -2337,11 +2340,13 @@ def test_drain_marker_is_not_claimed_over_a_takeover():
"""Save-and-exit blocks on the broker for as long as the emulator takes to
die, and a force-release plus a fresh claim fit in that window. The marker
would bury a session somebody is playing."""
key = streaming._session_redis_key("cas-takeover")
key = session_store.session_redis_key("cas-takeover")
claim = _session_at(key)
_session_at(key, claimed_at="2026-01-01T00:05:00+00:00")
try:
assert asyncio.run(streaming._claim_drain_marker("cas-takeover", claim)) is None
assert (
asyncio.run(session_store.claim_drain_marker("cas-takeover", claim)) is None
)
# The claim that took over is still there, untouched.
current = json.loads(asyncio.run(async_cache.get(key)))
assert current["claimed_at"] == "2026-01-01T00:05:00+00:00"
@@ -2353,25 +2358,25 @@ def test_drain_marker_is_not_claimed_over_a_takeover():
def test_a_stale_drain_token_frees_nobody():
"""A pull that outlived its own marker must not release whoever holds the
container now."""
key = streaming._session_redis_key("cas-stale-token")
key = session_store.session_redis_key("cas-stale-token")
token = asyncio.run(
streaming._claim_drain_marker("cas-stale-token", _session_at(key))
session_store.claim_drain_marker("cas-stale-token", _session_at(key))
)
assert token is not None
try:
# The marker expired and a new claim took the container.
_session_at(key, claimed_at="2026-01-01T00:05:00+00:00")
asyncio.run(streaming._drop_drain_marker("cas-stale-token", token))
asyncio.run(session_store.drop_drain_marker("cas-stale-token", token))
assert asyncio.run(async_cache.get(key)) is not None
# The drain that owns the marker still clears it.
retaken = asyncio.run(
streaming._claim_drain_marker(
session_store.claim_drain_marker(
"cas-stale-token",
{"user_id": 1, "claimed_at": "2026-01-01T00:05:00+00:00"},
)
)
assert retaken is not None
asyncio.run(streaming._drop_drain_marker("cas-stale-token", retaken))
asyncio.run(session_store.drop_drain_marker("cas-stale-token", retaken))
assert asyncio.run(async_cache.get(key)) is None
finally:
asyncio.run(async_cache.delete(key))
@@ -2380,12 +2385,13 @@ def test_a_stale_drain_token_frees_nobody():
def test_releasing_a_session_somebody_else_holds_reports_failure():
"""The container is not this claim's to give back, and a release that says
otherwise ends a session that had just begun."""
key = streaming._session_redis_key("cas-release")
key = session_store.session_redis_key("cas-release")
claim = _session_at(key)
_session_at(key, claimed_at="2026-01-01T00:05:00+00:00")
try:
assert (
asyncio.run(streaming._release_own_session("cas-release", claim)) is False
asyncio.run(session_store.release_own_session("cas-release", claim))
is False
)
assert asyncio.run(async_cache.get(key)) is not None
finally:
@@ -2424,7 +2430,7 @@ def test_a_write_that_lands_on_nothing_is_contention_not_success():
with patch.object(async_cache, "pipeline", lambda: _NoOpPipe()):
with pytest.raises(streaming.StreamingSessionContended):
asyncio.run(
streaming._claim_drain_marker(
session_store.claim_drain_marker(
"cas-noop", {"user_id": 1, "claimed_at": "x"}
)
)
@@ -2434,16 +2440,18 @@ def test_a_corrupt_session_key_is_dropped_rather_than_wedging_the_container():
"""A key holding something that is not a session can never be reconciled,
and leaving it parks the container until the TTL runs out. Both CAS paths
drop it and report no session."""
key = streaming._session_redis_key("cas-corrupt")
key = session_store.session_redis_key("cas-corrupt")
try:
asyncio.run(async_cache.set(key, "not a session"))
assert asyncio.run(streaming._mutate_session("cas-corrupt", {"a": 1})) is None
assert (
asyncio.run(session_store.mutate_session("cas-corrupt", {"a": 1})) is None
)
assert asyncio.run(async_cache.get(key)) is None
asyncio.run(async_cache.set(key, "not a session"))
assert (
asyncio.run(
streaming._replace_session_if("cas-corrupt", lambda _: True, None)
session_store.replace_session_if("cas-corrupt", lambda _: True, None)
)
is False
)
@@ -2457,20 +2465,20 @@ def test_work_running_under_a_claim_keeps_it_off_the_stale_list():
itself, and the player whose heartbeat kept it fresh is gone: an unrefreshed
claim reads as abandoned and the next claimant tears the container down. The
refresh stops at the ceiling, so a wedged step cannot hold it forever."""
key = streaming._session_redis_key("cas-hold-claim")
key = session_store.session_redis_key("cas-hold-claim")
claim = _session_at(key, last_seen="2026-01-01T00:00:00+00:00")
try:
# A zero ceiling ends the loop on the first pass, so exactly one refresh
# runs and the test never waits on a clock.
with (
patch.object(streaming, "_CLAIM_REFRESH_SECONDS", 0),
patch.object(streaming, "_HOLD_CEILING_SECONDS", 0),
patch.object(session_store, "_CLAIM_REFRESH_SECONDS", 0),
patch.object(session_store, "_HOLD_CEILING_SECONDS", 0),
):
asyncio.run(streaming._hold_session_claim("cas-hold-claim", claim))
asyncio.run(session_store.hold_session_claim("cas-hold-claim", claim))
current = json.loads(asyncio.run(async_cache.get(key)))
assert current["last_seen"] != "2026-01-01T00:00:00+00:00"
assert not streaming._session_is_stale(current)
assert not session_store.session_is_stale(current)
finally:
asyncio.run(async_cache.delete(key))
@@ -2478,15 +2486,15 @@ def test_work_running_under_a_claim_keeps_it_off_the_stale_list():
def test_holding_a_claim_stops_once_it_is_somebody_else_s():
"""Refreshing past a takeover would keep another player's session alive on
a stamp nobody is producing."""
key = streaming._session_redis_key("cas-hold-lost")
key = session_store.session_redis_key("cas-hold-lost")
claim = _session_at(key)
_session_at(key, claimed_at="2026-01-01T00:05:00+00:00")
try:
with patch.object(streaming, "_CLAIM_REFRESH_SECONDS", 0):
with patch.object(session_store, "_CLAIM_REFRESH_SECONDS", 0):
# Returns rather than looping forever against a claim it lost.
asyncio.run(
asyncio.wait_for(
streaming._hold_session_claim("cas-hold-lost", claim), 5
session_store.hold_session_claim("cas-hold-lost", claim), 5
)
)
current = json.loads(asyncio.run(async_cache.get(key)))
@@ -3557,7 +3565,7 @@ def test_a_webstation_exit_carries_slot_zero_rather_than_dropping_it(rom: Rom):
"""Slot 0 is this broker's working slot, so it has to reach the request:
omitting it would silently fall back to the broker's own default."""
container = _webstation_for(rom)
with patch("endpoints.streaming._broker_request_safe", return_value={}) as req:
with patch("handler.streaming.broker.request_safe", return_value={}) as req:
streaming._webstation_exit(_resolved(container), slot=0)
assert "slot=0" in req.call_args[0][1]
assert "save=0" not in req.call_args[0][1]
@@ -3567,7 +3575,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("endpoints.streaming._broker_request_safe", return_value={}):
with patch("handler.streaming.broker.request_safe", return_value={}):
assert streaming._stop_broker(_resolved(_container_for(rom))) is None
@@ -4088,7 +4096,9 @@ def test_claim_aborts_when_card_hydration_fails(
assert r.status_code == 502
launch.assert_not_called()
# The claim must be released so the container is not wedged.
assert asyncio.run(streaming._get_session(_key_of(_mc_container_for(rom)))) is None
assert (
asyncio.run(session_store.get_session(_key_of(_mc_container_for(rom)))) is None
)
# No orphan blank card survives the aborted claim.
assert db_memory_card_handler.get_cards(admin_user.id, "pcsx2") == []
@@ -4190,7 +4200,7 @@ def test_release_frees_the_claim_when_teardown_raises(client, access_token, rom:
headers=_auth(access_token),
)
assert r.status_code == 200
assert asyncio.run(streaming._get_session(_key_of(container))) is None
assert asyncio.run(session_store.get_session(_key_of(container))) is None
def test_save_and_exit_wait_false_forces_blocking_on_card_sync(
@@ -4308,7 +4318,9 @@ def test_first_claim_with_existing_card_asks_before_wiping(
push.assert_not_called()
launch.assert_not_called()
# The prompt is not a session: an abandoned dialog must leave no claim.
assert asyncio.run(streaming._get_session(_key_of(_mc_container_for(rom)))) is None
assert (
asyncio.run(session_store.get_session(_key_of(_mc_container_for(rom)))) is None
)
def test_unreadable_card_blocks_the_claim(client, access_token, rom: Rom):
@@ -4331,7 +4343,9 @@ def test_unreadable_card_blocks_the_claim(client, access_token, rom: Rom):
assert "broker exploded" not in detail["reason"]
assert detail["reason"] == streaming._CARD_UNREADABLE_REASON
push.assert_not_called()
assert asyncio.run(streaming._get_session(_key_of(_mc_container_for(rom)))) is None
assert (
asyncio.run(session_store.get_session(_key_of(_mc_container_for(rom)))) is None
)
def test_absent_card_claims_without_prompting(client, access_token, rom: Rom):
@@ -4473,7 +4487,7 @@ def test_failed_adopt_aborts_the_claim_without_wiping(
# Nothing is recorded, so the next claim asks again instead of wiping.
assert db_container_adoption_handler.get_adoption(_key_of(container)) is None
assert db_memory_card_handler.get_cards(admin_user.id, "pcsx2") == []
assert asyncio.run(streaming._get_session(_key_of(container))) is None
assert asyncio.run(session_store.get_session(_key_of(container))) is None
def test_adopt_retry_recovers_when_the_version_was_already_stored(
@@ -4543,7 +4557,7 @@ def test_adopt_aborts_when_dedup_matches_an_older_version(
push.assert_not_called()
launch.assert_not_called()
assert db_container_adoption_handler.get_adoption(_key_of(container)) is None
assert asyncio.run(streaming._get_session(_key_of(container))) is None
assert asyncio.run(session_store.get_session(_key_of(container))) is None
def test_adopt_with_unreadable_card_aborts_without_recording(
@@ -4569,7 +4583,7 @@ def test_adopt_with_unreadable_card_aborts_without_recording(
# No decision recorded, so the next claim asks again instead of wiping.
assert db_container_adoption_handler.get_adoption(_key_of(container)) is None
assert db_memory_card_handler.get_cards(admin_user.id, "pcsx2") == []
assert asyncio.run(streaming._get_session(_key_of(container))) is None
assert asyncio.run(session_store.get_session(_key_of(container))) is None
def test_adopt_with_absent_card_aborts_without_recording(
@@ -4591,7 +4605,7 @@ def test_adopt_with_absent_card_aborts_without_recording(
launch.assert_not_called()
assert db_container_adoption_handler.get_adoption(_key_of(container)) is None
assert db_memory_card_handler.get_cards(admin_user.id, "pcsx2") == []
assert asyncio.run(streaming._get_session(_key_of(container))) is None
assert asyncio.run(session_store.get_session(_key_of(container))) is None
def test_occupied_undecided_container_returns_409_not_428(
@@ -4600,7 +4614,7 @@ def test_occupied_undecided_container_returns_409_not_428(
"""The probe belongs to the claim winner: a second player must not be shown
a prompt describing the card of whoever is playing right now."""
container = _mc_container_for(rom)
key = streaming._session_redis_key(_key_of(container))
key = session_store.session_redis_key(_key_of(container))
asyncio.run(
async_cache.set(
key,
@@ -4900,7 +4914,7 @@ def test_the_activate_body_carries_the_multiplayer_flag(client, access_token, ro
rather than the activate helper: the body itself is what matters."""
with _streaming(_ws_for(rom)):
with patch(
"endpoints.streaming._broker_request", return_value={"url": "/room/x"}
"handler.streaming.broker.request", return_value={"url": "/room/x"}
) as request:
client.post(
"/api/streaming/sessions",
@@ -4915,7 +4929,7 @@ def _activate_body(client, token, rom: Rom) -> dict:
"""Claim through the webstation protocol and return the activate body."""
with _streaming(_ws_for(rom)):
with patch(
"endpoints.streaming._broker_request", return_value={"url": "/room/x"}
"handler.streaming.broker.request", return_value={"url": "/room/x"}
) as request:
client.post(
"/api/streaming/sessions",
@@ -5649,7 +5663,7 @@ def _session_for(container: dict, rom: Rom, user: User) -> str:
session_key = _key_of(container)
asyncio.run(
async_cache.set(
streaming._session_redis_key(session_key),
session_store.session_redis_key(session_key),
json.dumps(
{
"rom_id": rom.id,