refactor(streaming): type the session record as a StreamingSession TypedDict (#5395)

* refactor(streaming): type the session record as a StreamingSession TypedDict

The streaming session lived in the cache as a JSON object and moved
through the code as dict[str, Any], so its 18 keys were implied by the
two claim literals and a handful of mutate_session calls spread across
session_store, lifecycle, access, launch, memory_cards and the
endpoint. A misspelt key read as None without a warning.

StreamingSession (total=False, since drain markers and records from
older releases carry only some fields) now names every key and its type,
and every session and claim parameter, return and literal uses it. mypy
checks each .get() and write against it. The scope helpers that also
read a termination notice take a Mapping[str, object] instead.

No behaviour changes: the record's JSON is the same. Tests that built
sessions by hand now build StreamingSessions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(streaming): one-sentence StreamingSession docstring

Addresses Greptile's review on the comment rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-10-29 14:40:02 -04:00
committed by GitHub
parent 04c0277533
commit b5acfa4c44
8 changed files with 150 additions and 93 deletions

View File

@@ -99,6 +99,7 @@ from handler.streaming.protocol import room_url_on
from handler.streaming.session_store import (
STREAMING_SESSION_DRAIN_SECONDS,
STREAMING_SESSION_TTL_SECONDS,
StreamingSession,
StreamingSessionContended,
claim_drain_marker,
claim_gate,
@@ -438,7 +439,7 @@ async def get_state_picks(request: Request, rom_id: int) -> StreamStatePicksSche
async def _win_container(
request: Request,
candidates: list[ResolvedContainer],
session: dict[str, Any],
session: StreamingSession,
platform: str,
) -> ResolvedContainer:
"""Reserve one of the platform's containers for this claim.
@@ -469,7 +470,7 @@ async def _win_container(
async def _reserve_container(
request: Request,
candidates: list[ResolvedContainer],
session: dict[str, Any],
session: StreamingSession,
platform: str,
) -> ResolvedContainer:
"""Walk the platform's containers and claim the first one available."""
@@ -552,20 +553,21 @@ async def _reserve_container(
# A drain marker names no holder, so the holder comes from a live session,
# while `draining` still says a container is about to come free.
snapshots = [
snapshots: list[StreamingSession] = [
snapshot or {}
for snapshot in await asyncio.gather(
*(get_session(candidate.key) for candidate in candidates)
)
]
draining = any(snapshot.get("draining") for snapshot in snapshots)
no_holder: StreamingSession = {}
holder = next(
(
snapshot
for snapshot in snapshots
if snapshot and not snapshot.get("draining")
),
{},
no_holder,
)
if draining:
message = "The previous session is still shutting down, try again shortly"
@@ -589,7 +591,7 @@ class _ClaimUndo:
"""What `claim_session` releases if the claim fails before the launch."""
session_key: str
session: dict[str, Any]
session: StreamingSession
blank_card_id: int | None = None
@@ -914,7 +916,7 @@ async def claim_session(
gui_language = languages.gui_language(request.user)
now = datetime.now(timezone.utc).isoformat()
session = {
session: StreamingSession = {
# Unique per claim, and safe to put in a filename. The webstation
# broker names its exit archive after it, so the pull can tell this
# session's saves from one an earlier pull failed to collect.
@@ -1679,7 +1681,7 @@ async def claim_desktop_session(
session_key = container.key
now = datetime.now(timezone.utc).isoformat()
session = {
session: StreamingSession = {
"user_id": request.user.id,
"broker_session_id": secrets.token_hex(8),
# No ROM and no card. Teardown reads both and skips the save pull, the

View File

@@ -1,6 +1,6 @@
"""Who may see and drive a streaming session, and which container holds it."""
from typing import Any
from collections.abc import Mapping
from fastapi import HTTPException, Request
@@ -21,6 +21,7 @@ from handler.streaming.config import (
key_for_name,
)
from handler.streaming.session_store import (
StreamingSession,
get_live_session,
session_is_desktop,
session_platform_matches,
@@ -30,7 +31,7 @@ from models.permission import PermAction, PermEntity
from models.rom import Rom
def session_owner_id(session: dict[str, Any], request: Request) -> int:
def session_owner_id(session: StreamingSession, request: Request) -> int:
"""Whose library a session's states and saves belong to.
An admin may drive a session they do not own, and what it writes is still
@@ -41,7 +42,7 @@ def session_owner_id(session: dict[str, Any], request: Request) -> int:
return user_id if isinstance(user_id, int) else request.user.id
def assert_session_owner(session: dict[str, Any], request: Request) -> None:
def assert_session_owner(session: StreamingSession, request: Request) -> None:
"""Only the user who claimed a session (or an admin) may control it."""
if session.get("user_id") == request.user.id:
return
@@ -86,19 +87,19 @@ def rom_is_visible(request: Request, rom: Rom | None) -> bool:
return rom is None or get_rom_visibility_filter(request).allows(rom)
def session_rom(session: dict[str, Any]) -> Rom | None:
def session_rom(session: StreamingSession) -> Rom | None:
"""The ROM a session is running, None for a desktop or a deleted entry."""
rom_id = session.get("rom_id")
return db_rom_handler.get_rom_simple(rom_id) if rom_id is not None else None
def session_rom_is_visible(request: Request, session: dict[str, Any]) -> bool:
def session_rom_is_visible(request: Request, session: StreamingSession) -> bool:
"""Can the caller see the ROM a session is running?"""
return rom_is_visible(request, session_rom(session))
def joinable_session_rom(
request: Request, session: dict[str, Any]
request: Request, session: StreamingSession
) -> tuple[bool, Rom | None]:
"""Whether a live session is one this caller may ask to join (its host opted
into multiplayer, it is somebody else's, its ROM is not hidden), with that ROM."""
@@ -109,14 +110,14 @@ def joinable_session_rom(
def assert_session_rom_visible(
request: Request, session: dict[str, Any], *, not_found_detail: str
request: Request, session: StreamingSession, *, not_found_detail: str
) -> None:
"""Raise 404 when the session's ROM is hidden from the caller."""
if not session_rom_is_visible(request, session):
raise HTTPException(status_code=404, detail=not_found_detail)
def visible_rom_name(request: Request, session: dict[str, Any]) -> str | None:
def visible_rom_name(request: Request, session: StreamingSession) -> str | None:
"""The name of the ROM a session is running, blanked when the caller cannot
see that ROM. "Busy" is safe to report to anyone; what is running is not."""
if not session or not session_rom_is_visible(request, session):
@@ -140,7 +141,7 @@ def platform_is_visible(request: Request, platform_slug: str) -> bool:
def session_in_scope(
session: dict[str, Any],
session: Mapping[str, object],
platform: str,
include_desktop: bool,
claimed_at: str | None = None,
@@ -161,7 +162,7 @@ async def find_session_for_user(
platform: str,
include_desktop: bool = False,
claimed_at: str | None = None,
) -> tuple[ResolvedContainer, str, dict[str, Any]] | None:
) -> tuple[ResolvedContainer, str, StreamingSession] | None:
"""The candidate holding this user's session, as (container, key, session).
With a pool the platform no longer identifies the container, the session does.
@@ -197,7 +198,7 @@ def named_container(platform: str, container_key: str) -> ResolvedContainer:
async def resolve_named_container(
platform: str, container_key: str
) -> tuple[ResolvedContainer, str, dict[str, Any] | None]:
) -> tuple[ResolvedContainer, str, StreamingSession | None]:
"""A named container plus whatever session it holds.
Returns (container, session_key, session), the session being None when the
@@ -212,7 +213,7 @@ async def resolve_named_container(
async def resolve_owned_session(
platform: str, request: Request
) -> tuple[ResolvedContainer, str, dict[str, Any]]:
) -> tuple[ResolvedContainer, str, StreamingSession]:
"""Find the caller's session for this platform in its first pool.
Returns (container, session_key, session). Raises 404 when the platform has
@@ -226,7 +227,7 @@ async def resolve_owned_session(
detail=f"No streaming container configured for platform '{platform}'",
)
others: list[tuple[ResolvedContainer, str, dict[str, Any]]] = []
others: list[tuple[ResolvedContainer, str, StreamingSession]] = []
for candidate in candidates:
session_key = candidate.key
session = await get_live_session(session_key)
@@ -268,7 +269,7 @@ async def resolve_claim(
claimed_at: str | None,
*,
game_only: bool,
) -> tuple[ResolvedContainer, str, dict[str, Any]] | None:
) -> tuple[ResolvedContainer, str, StreamingSession] | None:
"""The session a route acting on a claim reaches, or None when that claim is gone.
Args:
@@ -313,7 +314,7 @@ async def require_claim(
request: Request,
container_key: str | None,
claimed_at: str | None,
) -> tuple[ResolvedContainer, str, dict[str, Any]]:
) -> tuple[ResolvedContainer, str, StreamingSession]:
"""The game a control route drives, raising 404 once the caller's claim is gone."""
target = await resolve_claim(
platform, request, container_key, claimed_at, game_only=True

View File

@@ -26,6 +26,7 @@ from handler.streaming import (
)
from handler.streaming.config import ResolvedContainer
from handler.streaming.session_store import (
StreamingSession,
hold_session_claim,
push_to_user,
stamp_launched,
@@ -43,7 +44,7 @@ async def run_launch(
*,
container: ResolvedContainer,
session_key: str,
session: dict[str, Any],
session: StreamingSession,
user: User,
rom: Rom,
platform: str,
@@ -256,7 +257,7 @@ PHASE_POLL_SECONDS = 3.0
async def _watch_launch_phase(
container: ResolvedContainer,
session_key: str,
session: dict[str, Any],
session: StreamingSession,
platform: str,
) -> None:
"""Push the broker's extraction phase while a launch is still running.

View File

@@ -25,6 +25,7 @@ from handler.streaming.config import (
from handler.streaming.session_store import (
DRAIN_MARKER_TTL,
DiscSwap,
StreamingSession,
StreamingSessionContended,
broker_session_id,
claim_drain_marker,
@@ -46,7 +47,7 @@ from logger.logger import log
async def abort_claim(
session_key: str,
claim: dict[str, Any],
claim: StreamingSession,
blank_card_id: int | None = None,
) -> None:
"""Undo a claim that will not become a session.
@@ -66,7 +67,7 @@ async def abort_claim(
def _hold_reservation(
session_key: str, token: str | None, claim: dict[str, Any]
session_key: str, token: str | None, claim: StreamingSession
) -> asyncio.Future[None]:
"""Keep a container reserved while a teardown runs.
@@ -83,7 +84,7 @@ def _hold_reservation(
async def _drop_reservation(
session_key: str, token: str | None, claim: dict[str, Any]
session_key: str, token: str | None, claim: StreamingSession
) -> None:
"""Free whatever `_hold_reservation` was holding. `token` keeps the release
aimed at this drain, so an overrun that outlived its own marker cannot free
@@ -98,7 +99,7 @@ async def release_after_state_pull(
session_key: str,
pull: Coroutine[Any, Any, Any],
token: str | None,
claim: dict[str, Any],
claim: StreamingSession,
) -> None:
"""Run the exit state pull, then free the container it was holding.
@@ -114,7 +115,7 @@ async def release_after_state_pull(
async def quiesce_container(
container: ResolvedContainer, session: dict[str, Any], *, save: bool = True
container: ResolvedContainer, session: StreamingSession, *, save: bool = True
) -> commands.StopOutcome:
"""Stop the emulator, then evacuate and wipe its memory card.
@@ -161,7 +162,7 @@ async def pull_exit_saves(
async def mark_exit_saves_pending(
container: ResolvedContainer, session: dict[str, Any]
container: ResolvedContainer, session: StreamingSession
) -> saves.SavePullMark | None:
"""Hold the owner's next claim on this ROM until the exit pull has filed.
@@ -183,7 +184,7 @@ async def mark_exit_saves_pending(
async def collect_exit_saves(
container: ResolvedContainer,
session: dict[str, Any],
session: StreamingSession,
mark: saves.SavePullMark | None,
*,
settled: bool,
@@ -223,7 +224,7 @@ async def collect_exit_saves(
async def start_exit_save_pull(
container: ResolvedContainer, session: dict[str, Any], *, settled: bool
container: ResolvedContainer, session: StreamingSession, *, settled: bool
) -> None:
"""Mark the exit pull pending, then start it, for a stop that is already done."""
mark = await mark_exit_saves_pending(container, session)
@@ -231,7 +232,7 @@ async def start_exit_save_pull(
async def collect_exit_state(
container: ResolvedContainer, session: dict[str, Any], state_slot: int | None
container: ResolvedContainer, session: StreamingSession, state_slot: int | None
) -> None:
"""File the state the stop wrote, while the claim still guards the container.
@@ -266,7 +267,7 @@ _MIN_PLAY_SESSION_MS = 5_000
_DEVICE_TYPE = "streaming"
async def publish_session_activity(session_key: str, session: dict[str, Any]) -> None:
async def publish_session_activity(session_key: str, session: StreamingSession) -> None:
"""Put a live streaming session on the activity board.
Best-effort: the board is a view, never a reason to fail a launch.
@@ -289,7 +290,7 @@ async def publish_session_activity(session_key: str, session: dict[str, Any]) ->
log.exception("failed to publish streaming session activity")
async def refresh_session_activity(session_key: str, session: dict[str, Any]) -> None:
async def refresh_session_activity(session_key: str, session: StreamingSession) -> None:
"""Keep the activity entry alive on the player's heartbeat.
Re-stores what is already there instead of rebuilding it: nothing on the
@@ -314,7 +315,7 @@ async def refresh_session_activity(session_key: str, session: dict[str, Any]) ->
log.exception("failed to refresh streaming session activity")
async def clear_session_activity(session_key: str, session: dict[str, Any]) -> None:
async def clear_session_activity(session_key: str, session: StreamingSession) -> None:
"""Take a finished streaming session off the activity board.
Every teardown path calls this: the board is socket-driven, so an entry left
@@ -329,7 +330,7 @@ async def clear_session_activity(session_key: str, session: dict[str, Any]) -> N
log.exception("failed to clear streaming session activity")
async def record_play_session(session: dict[str, Any]) -> None:
async def record_play_session(session: StreamingSession) -> None:
"""Record a finished streaming session as RomM playtime.
Reuses the same ingest path as device sync (dedup on user+rom+start_time,
@@ -382,7 +383,7 @@ async def record_play_session(session: dict[str, Any]) -> None:
async def teardown_released_session(
container: ResolvedContainer,
session: dict[str, Any],
session: StreamingSession,
session_key: str,
platform: str,
*,
@@ -471,7 +472,7 @@ async def teardown_released_session(
async def teardown_abandoned_session(
container: ResolvedContainer,
session_key: str,
session: dict[str, Any],
session: StreamingSession,
*,
claimed_by: int | None,
) -> bool:
@@ -554,7 +555,7 @@ ABANDONED_TEARDOWN_WAIT = 30.0
async def await_teardown_within_budget(
container: ResolvedContainer,
session_key: str,
session: dict[str, Any],
session: StreamingSession,
budget: float,
*,
claimed_by: int,

View File

@@ -12,7 +12,7 @@ import io
import urllib.error
import zipfile
from pathlib import PurePosixPath
from typing import Any, TypedDict
from typing import TypedDict
from fastapi import HTTPException
@@ -20,6 +20,7 @@ from handler.database import db_memory_card_handler, db_user_handler
from handler.filesystem import fs_asset_handler
from handler.streaming import broker
from handler.streaming.config import ResolvedContainer
from handler.streaming.session_store import StreamingSession
from logger.logger import log
from models.assets import MemoryCard
from utils.memory_cards import MEMORY_CARD_MAX_BYTES, content_hash_of_bytes
@@ -301,7 +302,7 @@ async def evacuate_card(
async def evacuate_session_card(
session: dict[str, Any], container: ResolvedContainer
session: StreamingSession, container: ResolvedContainer
) -> bool:
"""Evacuate a whole-card-sync session's card before its container is freed.

View File

@@ -16,11 +16,11 @@ import asyncio
import json
import secrets
import time
from collections.abc import AsyncIterator, Callable
from collections.abc import AsyncIterator, Callable, Mapping
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from enum import Enum, auto
from typing import Any, NamedTuple, cast
from typing import Any, NamedTuple, TypedDict, cast
from redis.exceptions import WatchError
@@ -77,6 +77,35 @@ def session_redis_key(session_key: str) -> str:
return f"{SESSION_KEY_PREFIX}{session_key}"
class StoredDiscSwap(TypedDict):
file_id: int
at: str
class StreamingSession(TypedDict, total=False):
"""A container's session record, of which a drain marker holds only
`draining` and `drain_token` and an older release's record any subset."""
user_id: int
broker_session_id: str
rom_id: int | None
rom_name: str | None
platform: str
claimed_at: str
last_seen: str
launched_at: str
multiplayer: bool
memory_card_id: int | None
desktop: bool
host: str
core: str | None
core_tier: str | None
disc_file_id: int | None
disc_swaps: list[StoredDiscSwap]
draining: bool
drain_token: str
# A claim reads whether the player already holds a session on the platform and
# only then reserves a container, two round trips a second claim from the same
# player can slip between. The gate below makes the pair atomic per player and
@@ -108,19 +137,19 @@ async def claim_gate(platform: str, user_id: int) -> AsyncIterator[bool]:
await async_cache.delete(key)
async def get_session(session_key: str) -> dict[str, Any] | None:
async def get_session(session_key: str) -> StreamingSession | None:
raw = await async_cache.get(session_redis_key(session_key))
if raw is None:
return None
try:
return cast(dict[str, Any] | None, json.loads(raw))
return cast(StreamingSession | None, 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:
async def get_live_session(session_key: str) -> StreamingSession | 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
@@ -139,7 +168,7 @@ async def iter_session_keys() -> AsyncIterator[str]:
yield as_text(key).removeprefix(SESSION_KEY_PREFIX)
async def iter_live_sessions() -> AsyncIterator[tuple[str, dict[str, Any]]]:
async def iter_live_sessions() -> AsyncIterator[tuple[str, StreamingSession]]:
"""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():
@@ -190,8 +219,8 @@ class _SessionWrite(NamedTuple):
async def cas_session(
session_key: str,
plan: Callable[[dict[str, Any]], _SessionWrite | None],
) -> tuple[_CasOutcome, dict[str, Any] | None]:
plan: Callable[[StreamingSession], _SessionWrite | None],
) -> tuple[_CasOutcome, StreamingSession | None]:
"""Run `plan` against the session at `session_key` and apply what it asks
for, atomically.
@@ -217,14 +246,15 @@ async def cas_session(
await pipe.unwatch()
return _CasOutcome.MISSING, None
try:
session = json.loads(raw)
decoded = json.loads(raw)
except TypeError, json.JSONDecodeError:
session = None
if not isinstance(session, dict):
decoded = None
if not isinstance(decoded, dict):
await pipe.unwatch()
# Drop it rather than wedging the container until the TTL.
await async_cache.delete(key)
return _CasOutcome.CORRUPT, None
session = cast(StreamingSession, decoded)
write = plan(session)
if write is None:
await pipe.unwatch()
@@ -250,10 +280,10 @@ async def cas_session(
async def mutate_session(
session_key: str,
changes: dict[str, Any] | Callable[[dict[str, Any]], dict[str, Any]],
changes: StreamingSession | Callable[[StreamingSession], StreamingSession],
*,
require: Callable[[dict[str, Any]], bool] | None = None,
) -> dict[str, Any] | None:
require: Callable[[StreamingSession], bool] | None = None,
) -> StreamingSession | None:
"""Merge `changes` into a live session, atomically. A callable builds them
from the session as it stands, so they can extend what is stored.
@@ -262,7 +292,7 @@ async def mutate_session(
never landed, which is not the same as the key being gone.
"""
def plan(session: dict[str, Any]) -> _SessionWrite | None:
def plan(session: StreamingSession) -> _SessionWrite | None:
if require is not None and not require(session):
return None
session.update(changes(session) if callable(changes) else changes)
@@ -272,7 +302,7 @@ async def mutate_session(
return session if outcome is _CasOutcome.WROTE else None
def session_platform_matches(session: dict[str, Any], platform: str) -> bool:
def session_platform_matches(session: Mapping[str, object], platform: str) -> bool:
"""Whether a session was claimed for this platform, a record from before the
field existed matching anything so an upgrade cannot strand one."""
stored = session.get("platform")
@@ -281,12 +311,12 @@ def session_platform_matches(session: dict[str, Any], platform: str) -> bool:
return stored.lower() == platform.lower()
def session_is_desktop(session: dict[str, Any]) -> bool:
def session_is_desktop(session: Mapping[str, object]) -> bool:
"""Whether a session is an admin desktop rather than a game."""
return bool(session.get("desktop"))
def same_claim(session: dict[str, Any], claim: dict[str, Any]) -> bool:
def same_claim(session: StreamingSession, claim: StreamingSession) -> 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."""
@@ -299,7 +329,7 @@ def same_claim(session: dict[str, Any], claim: dict[str, Any]) -> bool:
async def replace_session_if(
session_key: str,
require: Callable[[dict[str, Any]], bool],
require: Callable[[StreamingSession], bool],
value: str | None,
ttl: int | None = None,
) -> bool:
@@ -327,13 +357,13 @@ def drain_marker(token: str) -> str:
return json.dumps({"draining": True, "drain_token": token})
def _holds_marker(token: str) -> Callable[[dict[str, Any]], bool]:
def _holds_marker(token: str) -> Callable[[StreamingSession], bool]:
"""Whether a session key still holds the drain marker `token` wrote."""
return lambda current: current.get("drain_token") == token
async def claim_drain_marker(
session_key: str, claim: dict[str, Any], ttl: int = DRAIN_MARKER_TTL
session_key: str, claim: StreamingSession, ttl: int = DRAIN_MARKER_TTL
) -> str | None:
"""Replace a session with a drain marker, while the key still holds the claim
that is exiting.
@@ -394,7 +424,7 @@ async def hold_drain_marker(session_key: str, token: str) -> None:
return
async def hold_session_claim(session_key: str, claim: dict[str, Any]) -> None:
async def hold_session_claim(session_key: str, claim: StreamingSession) -> 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
@@ -428,7 +458,7 @@ async def hold_session_claim(session_key: str, claim: dict[str, Any]) -> None:
async def stamp_launched(
session_key: str,
claim: dict[str, Any],
claim: StreamingSession,
host: str | None,
core: str | None = None,
core_tier: str | None = None,
@@ -481,7 +511,7 @@ async def drop_drain_marker(session_key: str, token: str) -> None:
async def restore_drained_session(
session_key: str, token: str, session: dict[str, Any]
session_key: str, token: str, session: StreamingSession
) -> None:
"""Put `session` back in place of the drain marker `token` wrote, while it is still there."""
try:
@@ -495,7 +525,7 @@ async def restore_drained_session(
log.warning("could not restore the session on %s", session_key)
async def release_own_session(session_key: str, claim: dict[str, Any]) -> bool:
async def release_own_session(session_key: str, claim: StreamingSession) -> 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
@@ -530,7 +560,7 @@ async def set_session_disc(
the swap the player asked for.
"""
def _still_the_same_claim(session: dict[str, Any]) -> bool:
def _still_the_same_claim(session: StreamingSession) -> bool:
if session.get("draining"):
return False
return (
@@ -540,7 +570,7 @@ async def set_session_disc(
at = datetime.now(timezone.utc).isoformat()
def _swapped(session: dict[str, Any]) -> dict[str, Any]:
def _swapped(session: StreamingSession) -> StreamingSession:
swaps = session.get("disc_swaps")
history = swaps if isinstance(swaps, list) else []
return {
@@ -558,13 +588,13 @@ async def set_session_disc(
log.warning("could not record disc %s on session %s", file_id, session_key)
def broker_session_id(session: dict[str, Any]) -> str | None:
def broker_session_id(session: StreamingSession) -> 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:
def session_disc_id(session: StreamingSession) -> 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
@@ -575,7 +605,7 @@ class DiscSwap(NamedTuple):
at: datetime
def session_disc_swaps(session: dict[str, Any]) -> list[DiscSwap]:
def session_disc_swaps(session: StreamingSession) -> list[DiscSwap]:
"""The discs this session's swaps put in the tray, oldest first."""
swaps = session.get("disc_swaps")
history: list[DiscSwap] = []
@@ -589,7 +619,7 @@ def session_disc_swaps(session: dict[str, Any]) -> list[DiscSwap]:
return history
def session_is_stale(session: dict[str, Any]) -> bool:
def session_is_stale(session: StreamingSession) -> 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
@@ -620,7 +650,7 @@ async def in_restart_grace() -> bool:
return bool(await async_cache.exists(_RESTART_GRACE_KEY))
async def get_abandoned_session(session_key: str) -> dict[str, Any] | None:
async def get_abandoned_session(session_key: str) -> StreamingSession | None:
"""The claim on `session_key` when its heartbeat went stale, never a drain marker."""
session = await get_live_session(session_key)
if session is None or not session_is_stale(session):
@@ -644,7 +674,7 @@ def _termination_redis_key(session_key: str, user_id: int) -> str:
async def record_termination(
session: dict[str, Any],
session: StreamingSession,
session_key: str,
*,
ended_by: str | None,

View File

@@ -89,6 +89,7 @@ from handler.streaming.protocol import protocol_for
from handler.streaming.session_store import (
STREAMING_SESSION_DRAIN_SECONDS,
STREAMING_SESSION_TTL_SECONDS,
StreamingSession,
StreamingSessionContended,
release_own_session,
)
@@ -276,11 +277,11 @@ def _auth(token):
return {"Authorization": f"Bearer {token}"}
def _load_session(key: str) -> dict[str, Any]:
def _load_session(key: str) -> StreamingSession:
"""The session stored at `key`, failing the test if nothing is there."""
raw = asyncio.run(async_cache.get(key))
assert raw is not None, f"no session stored at {key}"
return cast(dict[str, Any], json.loads(raw))
return cast(StreamingSession, json.loads(raw))
def _claim(client, token, rom_id, state_id=None, save_id=None):
@@ -4856,9 +4857,12 @@ def test_save_and_exit_without_a_rom_drains_only_briefly(
assert 0 < ttl <= STREAMING_SESSION_DRAIN_SECONDS
def _session_at(key: str, **fields) -> dict[str, Any]:
def _session_at(key: str, **fields) -> StreamingSession:
"""Put a session on the key and hand back the claim a route would hold."""
session = {"user_id": 1, "claimed_at": "2026-01-01T00:00:00+00:00", **fields}
session = cast(
StreamingSession,
{"user_id": 1, "claimed_at": "2026-01-01T00:00:00+00:00", **fields},
)
asyncio.run(
async_cache.set(key, json.dumps(session), ex=STREAMING_SESSION_TTL_SECONDS)
)
@@ -4973,7 +4977,8 @@ def test_a_corrupt_session_key_is_dropped_rather_than_wedging_the_container():
try:
asyncio.run(async_cache.set(key, "not a session"))
assert (
asyncio.run(session_store.mutate_session("cas-corrupt", {"a": 1})) is None
asyncio.run(session_store.mutate_session("cas-corrupt", {"user_id": 1}))
is None
)
assert asyncio.run(async_cache.get(key)) is None
@@ -8649,7 +8654,11 @@ def test_run_launch_sends_rom_identity_fields(rom: Rom, admin_user: User):
rom.save_target = "SLUS-12345"
rom.save_target_layout = SaveTargetLayout.FOLDER_EXACT
activate = MagicMock(return_value={"url": "/room/x"})
session = {"broker_session_id": "s1", "claimed_at": "t1", "user_id": admin_user.id}
session: StreamingSession = {
"broker_session_id": "s1",
"claimed_at": "t1",
"user_id": admin_user.id,
}
with (
patch("handler.streaming.launch.webstation.activate", activate),
patch("handler.streaming.launch.lifecycle.hold_session_claim", new=AsyncMock()),
@@ -8707,7 +8716,11 @@ def test_run_launch_pushes_refusals_when_the_broker_refuses_an_import(
docs=None,
)
activate = MagicMock(side_effect=broker.ImportRefusedError([refusal], 2))
session = {"broker_session_id": "s1", "claimed_at": "t1", "user_id": admin_user.id}
session: StreamingSession = {
"broker_session_id": "s1",
"claimed_at": "t1",
"user_id": admin_user.id,
}
pushed = AsyncMock()
with (
patch("handler.streaming.launch.webstation.activate", activate),
@@ -8805,7 +8818,11 @@ def test_run_launch_skips_the_state_push_when_resuming_via_import(
pushed through the ordinary state-file PUT."""
state = _add_state(rom, admin_user, "Game.00.dolphin", "dolphin")
activate = MagicMock(return_value={"url": "/room/x"})
session = {"broker_session_id": "s1", "claimed_at": "t1", "user_id": admin_user.id}
session: StreamingSession = {
"broker_session_id": "s1",
"claimed_at": "t1",
"user_id": admin_user.id,
}
push_resume = AsyncMock()
with (
patch("handler.streaming.launch.webstation.activate", activate),
@@ -8855,7 +8872,11 @@ def test_run_launch_sends_no_resume_slot_when_the_import_was_lost(
broker load that slot anyway, from whatever the archive does carry."""
state = _add_state(rom, admin_user, "Game.00.dolphin", "dolphin")
activate = MagicMock(return_value={"url": "/room/x"})
session = {"broker_session_id": "s1", "claimed_at": "t1", "user_id": admin_user.id}
session: StreamingSession = {
"broker_session_id": "s1",
"claimed_at": "t1",
"user_id": admin_user.id,
}
push_resume = AsyncMock()
with (
patch("handler.streaming.launch.webstation.activate", activate),
@@ -9410,7 +9431,7 @@ def test_an_earlier_pull_finishing_leaves_a_later_exits_mark(
while it runs, and its finishing must not let a claim past the later pull."""
entry = _container_for(rom)
container = _resolved(entry)
session = {"user_id": admin_user.id, "rom_id": rom.id}
session: StreamingSession = {"user_id": admin_user.id, "rom_id": rom.id}
async def scenario() -> tuple[bool, bool]:
with (
@@ -9437,7 +9458,7 @@ def test_an_exit_save_pull_runs_on_the_streaming_worker(
):
"""A web restart would otherwise cut a pull short and park the next claim."""
container = _resolved(_container_for(rom))
session = {
session: StreamingSession = {
"user_id": admin_user.id,
"rom_id": rom.id,
"broker_session_id": "b1",
@@ -9473,7 +9494,7 @@ def test_an_exit_save_pull_runs_on_the_streaming_worker(
def test_a_queued_exit_save_pull_hands_on_the_disc(admin_user: User, rom: Rom):
session = {"user_id": admin_user.id, "rom_id": rom.id}
session: StreamingSession = {"user_id": admin_user.id, "rom_id": rom.id}
async def scenario() -> AsyncMock:
container = _resolved(_container_for(rom))
@@ -9508,7 +9529,7 @@ def test_a_pull_that_cannot_be_queued_lets_the_next_claim_through(
admin_user: User, rom: Rom, exit_pull_queue: MagicMock
):
container = _resolved(_container_for(rom))
session = {"user_id": admin_user.id, "rom_id": rom.id}
session: StreamingSession = {"user_id": admin_user.id, "rom_id": rom.id}
exit_pull_queue.enqueue.side_effect = ConnectionError("redis went away")
async def scenario() -> bool:
@@ -9522,7 +9543,7 @@ def test_a_pull_that_cannot_be_queued_lets_the_next_claim_through(
def test_a_queued_pull_for_a_container_no_longer_configured_clears_its_mark(
admin_user: User, rom: Rom
):
session = {"user_id": admin_user.id, "rom_id": rom.id}
session: StreamingSession = {"user_id": admin_user.id, "rom_id": rom.id}
async def scenario() -> tuple[bool, AsyncMock]:
container = _resolved(_container_for(rom))
@@ -12261,7 +12282,7 @@ def test_record_play_session_stores_duration(admin_user: User, rom: Rom):
"""A finished streaming session is recorded as playtime and updates the
ROM's last_played, keyed off the stored claim timestamp."""
start = datetime.now(timezone.utc) - timedelta(minutes=10)
session = {
session: StreamingSession = {
"user_id": admin_user.id,
"rom_id": rom.id,
"claimed_at": start.isoformat(),
@@ -12277,7 +12298,7 @@ def test_record_play_session_stores_duration(admin_user: User, rom: Rom):
def test_record_play_session_skips_accidental_short_session(admin_user: User, rom: Rom):
"""A claim released almost immediately is noise, not playtime."""
session = {
session: StreamingSession = {
"user_id": admin_user.id,
"rom_id": rom.id,
"claimed_at": datetime.now(timezone.utc).isoformat(),

View File

@@ -95,7 +95,7 @@ def _stub_teardown(teardown: Any = None) -> Any:
)
async def _stored(entry: dict[str, Any]) -> dict[str, Any] | None:
async def _stored(entry: dict[str, Any]) -> session_store.StreamingSession | None:
return await session_store.get_session(_resolved(entry).key)
@@ -306,7 +306,7 @@ async def test_overlapping_runs_tear_a_session_down_once():
# Both runs read the stale session before either marks it.
both_read = asyncio.Barrier(2)
async def read_together(key: str) -> dict[str, Any] | None:
async def read_together(key: str) -> session_store.StreamingSession | None:
session = await session_store.get_abandoned_session(key)
await both_read.wait()
return session