endpoints/streaming.py had grown to 3778 lines, but only about a third of
that was routes. The rest was a second copy of the layer handler/streaming
already exists to hold: broker verbs, webstation protocol translation,
state and save and memory-card transfer, session teardown.
Split it along those seams rather than by route, and give claim_session
the same treatment: its 406 lines are now four named phases.
Cross-module calls go through the module (states.pull_state_to_library,
commands.stop) instead of imported names, so one definition site is what
tests patch and what every caller reads.
No route path, scope or response model changed, so the OpenAPI schema is
untouched.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A broker's launch, join and desktop replies name the URL the browser loads
in an iframe, and urljoin keeps an absolute (or `javascript:`) URL verbatim,
so a container that answered with one could run script in RomM's origin
instead of its own. The three sites now share one resolver that drops a room
URL leaving the configured host, the stage refuses a source that is not
http(s), and the frame is sandboxed without allow-top-navigation so a
container page cannot steer the tab it sits in.
Also drop the shared secret from the config entry a resolution warning
prints, which named the misconfigured container by dumping it whole.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Session ownership and lifecycle, mostly around who a teardown belongs to:
- file the exit state, save states and state frames under the session's
owner rather than the caller, so an admin driving someone else's session
no longer collects their saves
- beat the heartbeat from the admin desktop view, which the stale sweep was
tearing down three minutes in
- take the claim through release_own_session when a launch aborts, instead
of deleting a key another player may already hold
- require the same claim to stamp a launch, so a late activate cannot revive
a drain marker with a six hour TTL
- pull the in-game save archive on every teardown path, not just the two
that remembered to
- skip draining keys in the admin force-release sweep
Plus: pool members must share a protocol, since the head's capabilities are
what the frontend renders; a claim clears terminations across the whole pool;
multiplayer is only recorded where the broker can actually seat a joiner; and
an unserializable config no longer caches forever on a repr() that repeats.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
- The five new modules each defined `log = logging.getLogger("romm")`, which is
what `logger.logger` already exports; they import it now.
- `ACK_TIMEOUT` had two homes. It is a protocol fact, so `protocol.py` owns it
and the endpoint imports it from there; the unused
`BROKER_LOAD_STATE_TIMEOUT` copy goes.
- Module and function docstrings trimmed to what the code cannot say: the
change history and the justifications belong in the commit messages they came
from.
- `asset_store` takes the union `write_file` accepts rather than `Any`.
- Four hand-rolled `setInterval` pairs (presence beat, session poll, exit
chord, live sessions, activity tick) become `useIntervalFn`, which also
cleared a real gap: the presence composable's timer had no scope teardown.
- The launch pushes are matched on the container the claim's 202 named, not on
the platform: a pool serves one platform from more than one container, so a
second tab could otherwise act on the first's launch.
- Test helpers typed: the push capture and the resume-claim tuple carry real
types, and an unused `_claim_ready` helper goes.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`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>
Every streaming route returned a bare `JSONResponse`, so none of their shapes
reached the OpenAPI schema and `services/api/streaming.ts` hand-maintained a
parallel copy of all eleven of them. A response-shape change was a silent
frontend break with nothing to catch it.
`endpoints/responses/streaming.py` declares the shapes and the routes return
them, so they generate like every other endpoint. The 428 a claim raises when a
container still holds an undecided memory card is declared too, through
`responses=`, rather than staying an undocumented `detail` dict.
The frontend types are regenerated and the hand-written interfaces become
aliases onto them. The typecheck immediately found two places they had already
drifted: the hand-written `PlatformCapabilities` was missing `has_memory_card`,
and `LiveSessionCard` passed a possibly-undefined host username where a
nullable string was expected. The termination notice had drifted on the backend
side too: it records `ended_at`, `rom_id` and `rom_name`, which the first draft
of the schema did not carry.
Releasing a session now hands its teardown to FastAPI's `BackgroundTasks`
rather than attaching it to a hand-built response, which is what lets the route
return a model.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
`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>
`endpoints/states.py` wrote the same write-scan-upsert sequence twice for
screenshots and once for states, and the streaming sync had written its own
third copy of each. The sequence now lives in `handler/asset_store.py`, which
both callers use.
What differs between them stays with the caller: the upload route still owns
its filename validation and last-played bump, and the streaming sync still owns
its byte-identical dedup and its retention limit. `store_state_file` takes a
`fields` map for columns only one caller owns, so the upload path can never
clear the disc the streaming path recorded.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Two shapes of streaming broker were branched on at 19 call sites, and every
consumer re-derived a container's host, key, emulator, capabilities and card
sync from the raw YAML on each call. `_containers_for_platform` re-ran host
parsing and the operator's misconfiguration warnings on every request, and
`_container_label` re-read config.yml once per listed row.
`handler/streaming/`:
- `protocol.py` gives each broker shape a class owning its route prefixes,
timeouts, response dialect, stream-URL assembly and capability flags. A call
site now asks `protocol.supports_disc_swap` or `protocol.save_state_accepted`
instead of re-testing `protocol: webstation`. Instances are interned per
subfolder so identical configs share one object.
- `capabilities.py` holds the per-platform and per-emulator slot tables and the
state transfer limits, keyed purely by platform and emulator.
- `config.py` turns the raw list into frozen `ResolvedContainer` records with
every question already answered, memoized until the config changes, so the
warnings fire once per config rather than once per lookup. A container RomM
cannot dial still resolves, with an empty key: unclaimable, but visible in
the admin fleet view where the operator can see why.
`endpoints/streaming.py` drops ~700 lines and takes records rather than dicts
throughout; `container.emulator` and `container.protocol.session_route(...)`
replace the derivations that used to run per call.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Backend:
- One session-scan iterator (`_iter_session_keys` / `_iter_live_sessions`)
replaces three copies of the Redis scan-and-decode loop, and
`_get_live_session` replaces five independent "a drain marker is nobody's
session" checks.
- `_abort_claim` replaces seven inlined claim-abort cleanups, so a new failure
branch can no longer wedge a container and orphan a blank card.
- `_quiesce_container` and `_collect_exit_state` replace the stop-evacuate-wipe
and guarded state-pull blocks written out in all three teardown paths. The
`_record_termination` calls stay at the call sites: the three order it
differently and each has its own reason.
- `_hold_reservation` / `_drop_reservation` collapse the two
release-after-state-pull helpers into one, and absorb the third copy of that
branch inlined in the released-session teardown.
- `_load_state_broker`'s two protocol branches were byte-identical, so it now
takes its route from `_transfer_route`; `_raise_broker_http_error` and
`_raise_broker_unreachable` replace the error translation copied into
`_call_broker` and `_webstation_activate`.
- `_container_labels` builds the label map once per request rather than
re-reading and re-parsing config.yml for every listed row.
- The joinable listing fetches each ROM once, through `get_rom_simple` rather
than the `@with_details` query, for five columns.
- `store_memory_card_version` hands the hash it computed in memory to the scan,
which was reading the archive back off disk to recompute it.
- `_prune_state_history` takes the history its caller already fetched.
- `playlist_files` in utils/m3u.py is now the one home for "which files are
discs", shared by the download endpoint, the m3u generator and the swapper.
Frontend:
- `useActivityPresence` replaces the presence block copied verbatim from
EmulatorJS.vue into Stream.vue.
- `MemoryCardNameDialog` replaces three copies of the same name-entry dialog.
- The two private axios error extractors give way to the `errorMessage` util,
three hand-rolled spinners to `RSpinner`, six manual listener pairs to
`useEventListener`, and five copy-on-write Set/Map trackers to `reactive`.
- `keepaliveHeaders` moves next to the interceptor that owns the CSRF header.
- The exit chord polls at 10Hz instead of every frame, the stage measures its
offset once instead of per mousemove, `postToStream` reuses the frame list
the attach pass walked, and the admin/home polls skip a hidden tab.
- `containerLabelForPlatform` on the store replaces the two `streamLabel`
definitions that answered differently, and the stream/join action labels move
onto useGameActions so the button and the menu cannot word them differently.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* feat(streaming): forward the rom and interface language to the broker
The webstation activate payload already carries the platform, which is
how RetroArch picks its core; the language travels the same way. Two
values, because they answer different questions. `rom.language` is the
game's own, reduced from rom.languages, which stores names ("French")
from filename parsing and shortcodes ("fr") from metadata providers.
`gui_language` is the player's, from their UI locale, and sits beside
`rom` rather than inside it: it describes the player, so it is sent for
a launch with no rom at all.
A launcher whose games ship several languages in one folder needs both.
ScummVM detects one target per language and the target is what boots, so
without a language a multilingual game starts in whichever variant sorts
first. RomM rarely knows a game's own language and a multilingual folder
is exactly where it usually does not, which is what makes the interface
locale worth sending as the broker's fallback.
A locale keeps its region as a subtag ("pt_BR" becomes "pt-br"): that is
the whole difference between Brazilian and European Portuguese to an
emulator shipping both, and a broker that makes nothing of the region
drops it. Values RomM cannot reduce are omitted so a broker falls back
to its own default rather than failing the launch.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* feat(streaming): add ScummVM to the platform capabilities table
Without an entry the frontend offers no save controls at all for a
ScummVM session. ScummVM's saves are its states, so the broker's single
working slot is both what a save-state writes and what a resume loads,
and there is no memory card. Its own slot 0 autosave rides the save
archive rather than the state routes, which is why this mirrors the
RetroArch shape: no slot grid, one autosave slot.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* style(streaming): satisfy black on the new language tests
Trunk's black wants the signature on one line; it fit all along.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
A streaming session is a play session like any other, so it now appears on
/activity next to the device sessions instead of being visible only through
the admin streaming panel. The container key stands in for the device id and
the entry carries a "streaming" device type.
Entry building and the activity:update / activity:clear broadcasts move onto
ActivityHandler, which the REST endpoint, the socket handlers and streaming
now share; the duplicate builder and the four copies of the emit block are
gone. Every board interaction from streaming is best-effort, so it can never
fail a launch or wedge a teardown.
Teaches the streaming endpoints the webstation activate/exit contract
alongside the existing per-emulator broker mods, lets one container serve
a pool of platforms, and claims the first free container from that pool.
Sessions now sync save states, save archives and whole memory cards back
into the RomM library on release, keep every capture as browsable history,
and record the disc a state was taken on so a resume remounts it. Container
adoptions track a card the container already held so it is never wiped
without asking.
KIOSK_MODE stripped every non-READ grant from all non-admins after group
and override resolution, so a logged-in user with "Saves & States: Write"
still got a 403 from POST /api/states|saves|screenshots. The permission
UI saved grants the server then silently discarded.
The cap now applies only to the synthetic guest KIOSK_MODE hands out
(User.is_kiosk_guest). It has to stay for the guest: with no permission
group of its own it falls back to the server default group ("Viewer
(legacy)" = WRITE_SCOPES), so dropping the cap outright would let
anonymous visitors upload assets and edit collections.
Fixes#4044
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Restrict ROM file deletion to the ROMS/DELETE grant. The new
DELETE /roms/{rom_id}/files/{file_id} route gated on ROMS_WRITE alone and,
unlike its manual/soundtrack/screenshot siblings, carried no category guard,
so a group holding write-but-not-delete could remove game files from disk
while whole-ROM deletion still required ROMS/DELETE.
Gate mutating streaming routes on ROMS_USER_WRITE instead of ROMS_READ,
matching the play-session routes. ROMS_USER_WRITE is always-on for
authenticated users, but absent from READ_SCOPES, which is all KIOSK_MODE
grants an anonymous visitor. Kiosk visitors all share user_id=-1, so session
ownership could not separate them and any visitor could claim sessions and
overwrite another's save states.
Restore the ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES gate on the cleanup
task's cron_string. It was dropped in 06cafd4b1, whose message refers to
update_switch_titledb, leaving the documented opt-out inert and scheduling a
destructive task nightly. That commit also broke two of the task's own tests.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Several endpoints authorized cross-user access by the is_public flag (or
by scope alone for streaming) without re-checking whether the parent ROM
or platform is hidden from the caller. A user blocked from a ROM/platform
could still download a public save/state/screenshot attached to it, or
claim a streaming session for it, by supplying the asset/ROM id directly.
Route all four through the existing assert_rom_visible() 404-masking
helper, right after loading the record and before any file access or
broker launch, matching the ROM detail/content endpoints.
- saves.py / states.py / screenshots.py download_* : public sharing no
longer overrides the hidden-resource boundary.
- streaming.py claim_session : hidden ROM/platform can no longer be
launched via its id; broker is never contacted.
Regression tests cover hidden-ROM and hidden-platform cascade for each
endpoint, plus a positive control that public sharing still works when
the ROM is visible.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Per-platform slot capabilities were duplicated across the frontend store's
hardcoded platformCapabilities() map and the backend's pydantic Field bounds,
independent of the broker's own ceiling. Consolidate the RomM-side knowledge
into one _PLATFORM_CAPABILITIES table in the streaming endpoint:
- /config now ships each container's capabilities, and the frontend selector
reads them instead of keeping its own copy.
- The SaveState/LoadState request bounds derive from the table, and the routes
validate the exact per-platform ceiling before calling the broker (clean 422
instead of a broker 502).
The broker remains the ultimate enforcer; RomM no longer keeps two independent
hardcoded copies of its slot semantics.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Extract the repeated urllib request construction (URL, secret, payload,
headers, urlopen, parsing) shared by the six broker functions into
_broker_request and its best-effort _broker_request_safe variant. The
best-effort wrappers collapse to a few lines each and the nosec B310
annotation now lives in one place.
Slim the tests with a _streaming() context manager plus _auth/_claim_ok
helpers, removing the repeated cm.get_config patch boilerplate.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Address review findings on the streaming framework.
Backend (backend/endpoints/streaming.py):
- Session keys now carry a TTL (6h) so an abandoned session (broker
dead / backend crashed) eventually frees the container instead of
wedging it until an admin force-releases; control calls refresh the
TTL so active sessions never expire.
- _container_for_platform validates each entry has a scheme-bearing
host, skipping malformed ones (mirroring /config) so claim/control
return a clean 404 instead of a 500 KeyError on container["host"].
- _parse_host_url / _derive_broker_host reject schemeless hosts that
would produce the broken "//None:8000/..." broker URL and colliding
session keys; _broker_url raises a clear 502 when no usable host.
- save-and-exit with wait=false drains the session (short-lived key)
instead of deleting it outright, so a concurrent new claim can't
/launch on top of a not-yet-dead emulator and lose the in-flight save.
- New tests cover schemeless/missing-host skips, the claim TTL, and
the wait=false drain window.
Frontend:
- stores/streaming.ts: releaseSession/saveAndExit drop the local
session record only after the backend confirms, so a failed release
no longer leaves the user wedged behind their own still-held session.
- v2/views/Player/Stream.vue: disambiguate the 404 from claimSession
(ROM not found vs container not configured) so the message matches
the real failure; new stream-error-rom-not-found i18n key in all
18 locales.
Generated-By: PostHog Code
Task-Id: e091168f-69fd-4d4a-9f12-d473dd3f17c9
Add /api/streaming endpoints for session claim/release, ROM launch,
save states, volume control, and save-and-exit against per-platform
emulator broker containers. Sessions are stored in Redis with atomic
SET NX claims, owner-bound, and admin force-releasable. Config comes
from config.yml (streaming.enabled + containers list) with a
STREAMING_SAVE_TIMEOUT env override for slow-saving brokers.
Includes 19 endpoint tests covering auth scopes, claim races,
ownership, broker failure paths, and force-release.