Files
romm/backend/handler/streaming/states.py
Georges-Antoine Assi a688676de7 fix: enforce ROM visibility on assets, sync, collections, stats and scan events (#5498)
* fix(sync): cap play sessions on sync completion and require roms.user.write

The completion endpoint fed an unbounded play_sessions list to the same
ingest as POST /api/play-sessions, which allows 100 per batch and requires
roms.user.write. Apply both rules before the session is completed.

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

* fix(config): reject empty platform binding and version values

config.yml exits on load when a platforms or versions value is empty, so
the API must not write one.

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

* fix(collections): require smart collection criteria to be a JSON object

Any other JSON value was stored, then failed the response schema and broke
the smart collection list for every user who could see the collection.

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

* fix(stats): require roms.read on /api/stats

Anonymous callers were served counts over the whole library, including
platforms and ROMs hidden from users. The UI only calls it after login.

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

* fix(permissions): apply ROM visibility to filters, saves, play sessions and collection removal

/api/roms/filters aggregated facet values over the whole library, GET
/api/saves/{id} and GET /api/play-sessions returned the caller's own rows on
hidden ROMs, and removing ROMs from a collection could drop members hidden
from its owner. The facet visibility clauses move onto RomVisibilityFilter so
stats and filters share them.

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

* fix(webhooks): keep non-admin webhooks off the admin's internal metadata origins

The SSRF exception for a self-hosted Playmatch or Hasheous applied to every
request, so a user's webhook could reach any path on that private origin.
Non-admin webhooks now validate and connect with an empty allowlist.

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

* fix(saves): bound total decompressed size when hashing zip archives

Zip content hashing capped each entry but not the archive, so many
entries each under the cap could still decompress and hash far more
than any real save or memory card holds. Budget the decompressed bytes
across the whole archive and cap the entry count; callers keep treating
an over-budget archive as an unknown hash.

The chunked, budgeted entry reader is shared with the memory card
archive check, and the RetroArch store path now hashes off the event
loop like its siblings.

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

* fix(psp): clamp LZ4 literal and match copies to the ZISO block size

The ZISO block decoder appended literals and copied matches for their
full encoded length before checking the output size, and an LZ4 length
can be extended without bound by 0xFF bytes. A small crafted block
could therefore expand far past the block size before being truncated.

Clamp each copy to the room left in the block, stop once it is full,
end the block on a truncated match offset, and copy matches with slices
instead of a per-byte loop (overlapping matches repeat their pattern).
Output for valid blocks is unchanged.

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

* fix(auth): revoke OAuth tokens when a user's credentials change

A password change, admin reset, reset-link reset or rename cleared the
account's web sessions, but its OAuth access tokens kept working until they
expired and its refresh tokens could still be exchanged at /api/token.

Revoking a user's credentials now also records a per-username revocation
time in Redis, kept for the longest token lifetime. Bearer validation and
refresh consumption reject any token whose iat is at or before it. OAuth
tokens now carry a sub-second iat, so a login right after the change still
works; a token without iat counts as older than any revocation.

The revocation is keyed by the token's sub, the same username sessions are
keyed by, so a rename revokes tokens issued under the old name even if
another account later takes it. Client (API) tokens are left alone.

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

* fix(api): reject local file URLs for user-supplied covers and manuals

file:// and launchbox-file:// URLs are meant for covers and manuals that
a scan records from gamelist.xml or LaunchBox metadata. The collection
create/update endpoints and the ROM update endpoint passed a user-supplied
url_cover (and url_manual) straight to the resource handler, which copied
whatever library file it named into the entity's resources. That let any
user with collections.write or roms.write pull files they cannot otherwise
read, including those of hidden platforms and ROMs.

These endpoints now answer 400 for a local file URL, unless it is the value
already stored, which the edit forms echo back on every save.

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

* fix(resources): bound cover downloads and decodes

Remote covers, screenshots, manuals, badges and media files were streamed
to disk with no size limit, and a gzip-encoded body was read whole and
inflated in memory. Downloads now go through one helper that counts bytes
against MAX_ASSET_UPLOAD_SIZE_BYTES, inflates gzip incrementally under the
same cap, and aborts past it, so the partial file is removed and any
earlier copy kept.

Covers are also bounded once on disk: a still image whose header declares
more than MAX_COVER_PIXELS is discarded before it is decoded (and an
uploaded one is refused with a 400), and a DecompressionBombError while
deriving the small cover now discards the download instead of failing the
request and leaving the file behind.

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

* test: fix mypy errors in the new tests

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

* fix: address Greptile review on permission and input hardening

- Date OAuth tokens to before the credential check, so a password change
  that lands during the check revokes the tokens it issues.
- Apply ROM visibility to play sessions in SQL, before the page slice.
- Reject truncated gzip bodies and inflate every gzip member.
- Shorten the zip budget comment; stream real httpx2 responses in tests.

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

* fix: apply code-review findings on permission hardening

Revoke OAuth tokens and sessions on user deletion, apply ROM visibility to
GET /states/{id}, validate update_collection rom_ids, run get_rom_filters off
the event loop, and reuse the shared httpx client factory for webhooks.

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

* refactor: apply simplify pass on permission hardening

Read the OAuth revocation stamp through the async cache, share the
play-session batch-size check, raise a plain OSError for oversized downloads,
and drop a dead slice in the LZ4 decoder.

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

* style: apply review-polish pass on permission hardening

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

* docs: state that ROM visibility is enforced as access control

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

* fix(assets): hide saves, states, screenshots and memory cards on hidden ROMs

Visibility is access control, so per-id save/state/screenshot routes now 404
when the save's ROM is hidden from the caller (hidden ROM, hidden platform or
age limit), and the save/state lists and identifier lists leave those rows
out in SQL. GET /api/saves/summary 404s on a hidden ROM. Memory cards on a
hidden platform 404 on every per-id route, drop out of both lists, and can't
be created against a hidden platform.

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

* fix(saves): answer a hidden ROM's save summary like a missing one

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

* fix(permissions): enforce ROM visibility in sync, installs and feeds

Hidden ROMs/platforms and age-limited ROMs are access control, so the
paths that skipped the caller's visibility now apply it:

- sync negotiate: saves on hidden ROMs are neither offered, paired nor
  reported as conflicts; a client save on one negotiates like an unknown ROM
- push-pull SSH sync: resolves the device owner's visibility and skips
  saves on hidden ROMs in both directions
- device installs: list and claim leave out requests whose ROM became
  hidden (they stay pending), and outcome notifications don't name it
- recommendations: a hidden seed ROM is no longer named
- music playlists: track_count counts only tracks on visible ROMs
- audit events: firmware targets on hidden platforms are filtered
- setup library: supported platforms honour the caller's visibility
- feeds: a hidden platform found by slug reads as missing

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

* fix(visibility): hide ROMs from virtual collections, stats and scan events

Virtual collections apply the caller's visibility in SQL: a collection with
no visible member is left out (404 by id), member ids and covers skip hidden
ROMs, and the limit counts only visible collections.

Stats save, state and screenshot totals skip assets of hidden ROMs.

Scan events no longer broadcast to every socket. Progress and end events go
to a scan room that sockets of users holding platforms.write or tasks.run
join on connect. scanning_rom and scanning_platform go to the user rooms of
those followers who can see that ROM or platform, resolved once per scan
and grouped by visibility. get_rom_audience now builds on a shared
get_user_visibilities.

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

* fix: apply code-review findings on ROM visibility enforcement

Match virtual collection members by ROM id, build the cover visibility clauses
once, filter feed platforms by visibility in SQL, resolve every id before a
batch save or state delete, filter push-pull saves in the query, and narrow the
hides query to the requested users.

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

* refactor: apply simplify pass on ROM visibility enforcement

Require an explicit visibility filter on the saves, states and memory card
queries, share one roms_facets visibility join and one owned-asset helper,
filter virtual collection members by hidden ids, batch the scan audience's
scope lookup, and move the empty-room emit guard into socket_handler.

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

* test: start the scan audience before emitting from scan_rom

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

* docs: apply humanizer pass on the visibility rule

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

* fix(streaming): don't mount a memory card on a hidden platform

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

* fix: address Greptile review on ROM visibility enforcement

Refresh a running scan's audience after a permission change, fix the precedence
of the scan-room join assertion, and narrow mock await_args before reading them.

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

* revert: drop per-visibility scan event audience

Scan events go back to every socket. Removes handler/scan/audience.py,
the scan room join on connect, the permissions generation bump and the
batched OAuth scope resolution that only the audience used.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 14:33:11 -05:00

863 lines
32 KiB
Python

"""Save-state sync.
Emulator save states are centralized through RomM's states asset store so
they survive container rebuilds and roam across containers. The backend is
the only file mover: after a save it pulls the state file from the broker
and stores it under the session user's assets; on claim it pushes the user's
stored states back down so the container slots always reflect the central
copy (last write wins, central copy is the source of truth).
Broker file API (secret-protected, stdlib on the broker side):
GET /state-file?slot=N - newest state file for slot N. Blocks while a
save is in flight, so no clock coupling between
hosts. Returns raw bytes + X-State-Filename.
PUT /state-file?filename=NAME - write NAME into the emulator's state dir.
GET /state-screenshot?slot=N - the container's own capture of the stream at
the moment of that save, used as the thumbnail.
404 when it captured nothing.
"""
import asyncio
import io
import os
import re
import zipfile
import zlib
from collections.abc import Iterable
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any, NamedTuple
from urllib.parse import quote
from fastapi import HTTPException
from config import STREAMING_STATE_HISTORY_LIMIT
from handler.asset_store import release_thumbnail, store_screenshot, store_state_file
from handler.auth.rom_visibility import UNRESTRICTED
from handler.database import (
db_rom_handler,
db_state_handler,
db_user_handler,
)
from handler.filesystem import fs_asset_handler
from handler.streaming import broker, commands, webstation
from handler.streaming.config import ResolvedContainer
from handler.streaming.session_store import set_session_disc
from handler.sync.retroarch.emulator_names import retroarch_aliases
from handler.sync.retroarch.sync_handler import (
emulator_from_dir_name,
group_states_by_slot,
)
from logger.logger import log
from models.assets import EMULATOR_MAX_LENGTH, State
from models.rom import Rom
from models.user import User
from utils.filesystem import check_filename_length, sanitize_filename
from utils.memory_cards import content_hash_of_bytes
from utils.uploads import is_emulator_folder_name
# Slot number encoded in each emulator's state filename, e.g. PCSX2 writes
# "SERIAL (CRC).03.p2s" for slot 3 and Dolphin writes "GAMEID.s03". Resuming
# from a picked state needs the slot to tell the broker what to load, and the
# match is also where the capture stamp is inserted, so an emulator missing
# from here gets no history either.
_SLOT_PATTERNS = {
"pcsx2": re.compile(r"\.(\d{1,2})\.p2s$"),
"dolphin": re.compile(r"\.s(\d{2})$"),
"xemu": re.compile(r"\.x(\d{2})$"),
# RetroArch leaves the number off its default slot: "GAME.state" is slot 0
# and "GAME.state3" is slot 3. The broker files any pushed state into its
# working slot, so the auto state "GAME.state.auto" resumes from 0 too.
"retroarch": re.compile(r"\.state(?:(\d{1,2})|\.auto)?$"),
# DuckStation and RPCS3 write one exit state per game with no slot in the
# name, so the empty group reads as the working slot 0.
"duckstation": re.compile(r"()\.sav$"),
"rpcs3": re.compile(r"()\.SAVESTAT(?:\.zst|\.gz)?$"),
}
# Lowest slot each emulator's broker addresses. The rest count from 1, so a "0"
# in one of their names is a filename that looks like a state, not a slot.
_MIN_SLOT = {"duckstation": 0, "retroarch": 0, "rpcs3": 0}
def slot_from_state_filename(emulator: str, filename: str) -> int | None:
pattern = _SLOT_PATTERNS.get(emulator)
if pattern is None:
return None
match = pattern.search(filename)
if match is None:
return None
slot = int(match.group(1) or 0)
return slot if slot >= _MIN_SLOT.get(emulator, 1) else None
# Every capture is kept, so the library needs one file per save, not one per
# slot. The stamp goes immediately before the slot token so the patterns above
# still match at the end of the name: states written before this keep
# resolving, and the container-side name is recovered by dropping the stamp.
_STAMP_FORMAT = "%Y%m%d-%H%M%S%f"
_STAMP_PATTERN = re.compile(r"\.\d{8}-\d{12}(?=\.)")
def stamped_state_filename(emulator: str, filename: str, when: datetime) -> str:
"""Return ``filename`` with a capture stamp inserted before its slot token.
An emulator with no known slot convention keeps the original name, since
there is nowhere unambiguous to put the stamp. That emulator gets no
history: each capture lands on the same name and updates its row in place,
the pre-history behavior. No streaming emulator is in that position now.
"""
pattern = _SLOT_PATTERNS.get(emulator)
if pattern is None:
return filename
match = pattern.search(filename)
if match is None:
return filename
stamp = when.strftime(_STAMP_FORMAT)
return f"{filename[: match.start()]}.{stamp}{filename[match.start() :]}"
def container_state_filename(filename: str) -> str:
"""Strip any capture stamp, giving the name the emulator expects on disk."""
return _STAMP_PATTERN.sub("", filename, count=1)
def resolve_resume_state(
user_id: int, rom: Rom, container: ResolvedContainer, state_id: int
) -> tuple[State, int, bool]:
"""Validate a resume-from-state pick and return (state, slot, is_foreign).
Visibility follows the same rule as the state list the picker was built
from: the claiming user's own states plus other users' public ones.
Raises 404 for anything invisible, 400 for a foreign state the broker
will not import, and 503 when the broker couldn't be asked.
"""
state = next(
(
s
for s in db_state_handler.get_rom_shared_states(
rom_id=rom.id, user_id=user_id
)
if s.id == state_id
),
None,
)
if state is None:
raise HTTPException(status_code=404, detail="State not found")
emulator = container.emulator
core = state_core_for(container)
# Another core's file would land where this one's quick-load reads it.
by_stream = _filed_by_stream(state, emulator)
if by_stream and core is not None and not core.matches(state.core):
raise HTTPException(
status_code=400,
detail="State was made by a different RetroArch core",
)
native = is_native_state(state, emulator, core)
if native:
slot = slot_from_state_filename(emulator, state.file_name)
if slot is not None:
return state, slot, False
spec = webstation.require_import_spec(container, emulator, container.platform)
import_slot = spec.resume_slot() if spec is not None else None
if import_slot is not None:
return state, import_slot, True
if not native:
raise HTTPException(
status_code=400,
detail="State was made by a different emulator",
)
raise HTTPException(
status_code=400,
detail="State filename carries no recognizable slot number",
)
class PulledState(NamedTuple):
"""A state file as the broker handed it over."""
filename: str
content: bytes
# The libretro core that wrote it; None from a broker too old to say.
core: str | None = None
# RetroArch's folder name for that core, its library name.
library_name: str | None = None
def fetch_state_file(container: ResolvedContainer, slot: int) -> PulledState | None:
"""GET /state-file from the broker, or None when there is none.
The broker blocks while a save is in flight, so a generous timeout stands
in for save-completion polling. 404 means no state exists for the slot.
"""
limits = container.state_transfer
result = broker.get_binary_safe(
container,
container.protocol.transfer_route(f"/state-file?slot={slot}"),
"state-file GET",
max_bytes=limits["max_bytes"],
timeout=limits["timeout"],
)
if result is None:
return None
headers, content = result
filename = headers.get("X-State-Filename", "")
if not filename:
log.warning("broker state-file response missing a filename")
return None
return PulledState(
filename,
content,
headers.get("X-State-Core") or None,
headers.get("X-State-Library") or None,
)
def push_state_file(
container: ResolvedContainer,
filename: str,
content: bytes,
core: str | None = None,
) -> bool:
"""PUT /state-file to the broker. Best-effort, logs but never raises.
`core` names the libretro core that wrote the state, so a broker running
another one refuses it rather than file it where quick-load reads.
"""
return broker.put_binary(
container,
container.protocol.transfer_route(
f"/state-file?filename={quote(filename, safe='')}"
),
content,
"state-file PUT",
content_type="application/octet-stream",
timeout=container.state_transfer["timeout"],
extra_headers={"X-State-Core": core} if core else None,
)
# PCSX2 embeds a PNG of the moment of save inside every .p2s savestate zip
# under this entry name (pcsx2/SaveState.cpp: EntryFilename_Screenshot).
_SCREENSHOT_ZIP_ENTRY = "Screenshot.png"
SCREENSHOT_MAX_BYTES = 16 * 1024 * 1024
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
def _is_png(data: bytes | None) -> bool:
return data is not None and data.startswith(PNG_MAGIC)
def extract_state_screenshot(emulator: str, state_content: bytes) -> bytes | None:
"""Pull the embedded frame PNG out of a savestate archive, or None when the
format carries no embedded screenshot. Only PCSX2 (.p2s zip) embeds one."""
if emulator != "pcsx2":
return None
try:
with zipfile.ZipFile(io.BytesIO(state_content)) as zf:
with zf.open(_SCREENSHOT_ZIP_ENTRY) as entry:
data = entry.read(SCREENSHOT_MAX_BYTES + 1)
except (KeyError, zipfile.BadZipFile, zlib.error, EOFError, OSError) as exc:
# Never fatal: the state still syncs, it just has no thumbnail.
log.warning("could not extract state screenshot, %s", exc)
return None
if not data or len(data) > SCREENSHOT_MAX_BYTES:
return None
return data
def fetch_state_screenshot(container: ResolvedContainer, slot: int) -> bytes | None:
"""GET /state-screenshot from the broker, the container's own capture of the
stream as the state was saved. A 404 means no frame, so it is not logged."""
result = broker.get_binary_safe(
container,
container.protocol.transfer_route(f"/state-screenshot?slot={slot}"),
"state-screenshot GET",
max_bytes=SCREENSHOT_MAX_BYTES,
timeout=broker.STATE_SCREENSHOT_TIMEOUT,
)
if result is None:
return None
# This source shadows the frame a state embeds for itself, so a body that is
# not a PNG has to read as no frame rather than as an unusable one.
if not _is_png(result[1]):
log.warning("broker state screenshot for slot %d is not a PNG", slot)
return None
return result[1]
async def store_state_screenshot(
user: User, rom: Rom, state_filename: str, image: bytes
) -> None:
"""Bind a thumbnail to a state so the resume picker shows the right frame.
`State.screenshot` matches by filename stem, so the image reuses the state's
stem with a .png extension. is_gallery stays False (the default) so it never
shows in the user's screenshot gallery.
"""
# The zip entry only claims to be a PNG. The broker's body is checked where
# it is chosen, since there the answer decides whether this one is tried.
if not _is_png(image):
log.warning("state screenshot for %s is not a PNG, skipping", state_filename)
return
await store_screenshot(
user,
rom,
image,
sanitize_filename(f"{os.path.splitext(state_filename)[0]}.png"),
)
@dataclass(frozen=True)
class StateCore:
"""Which stored states a RetroArch container's core can load."""
expected: str
# Whether `expected` is the platform's default core, which wrote every
# state stored before cores were recorded.
default_matches: bool
# The emulator other clients file the core's states under, from its
# RetroArch folder; None when the broker can't name it.
folder: str | None = None
@property
def filed_as(self) -> str:
return self.folder or self.expected
@property
def folders(self) -> list[str]:
"""The emulators, lowercased, whose states Cloud Sync slots with this core's."""
return sorted({a.lower() for a in retroarch_aliases(self.filed_as) if a})
def matches(self, core: str | None) -> bool:
return core == self.expected or (core is None and self.default_matches)
def state_core_for(
container: ResolvedContainer, launched: dict[str, Any] | None = None
) -> StateCore | None:
"""The core filter for this container's states, None to filter nothing.
`launched` is the activate reply, which names the running core once the
game is up. Before that the broker is asked for its default, so this
blocks and belongs off the event loop.
"""
if not container.is_webstation or container.emulator.lower() != "retroarch":
return None
reply = launched if isinstance(launched, dict) else {}
booted = reply.get("core")
if isinstance(booted, str) and booted:
return StateCore(
booted,
reply.get("core_tier") == "default",
library_folder(reply.get("library_name")),
)
default = webstation.default_core(container)
expected = container.core or default
if expected is None:
return None
return StateCore(
expected,
default is not None and expected == default,
# From the cores reply default_core just cached, so no second request.
library_folder(webstation.core_library_name(container, expected)),
)
def folder_name(name: Any) -> str | None:
"""`name` when it can be an emulator column and one folder, else None."""
if (
isinstance(name, str)
and name
and len(name) <= EMULATOR_MAX_LENGTH
and is_emulator_folder_name(name)
):
return name
return None
def library_folder(library_name: Any) -> str | None:
"""The emulator Cloud Sync files a RetroArch core's folder under, named
after its library name, or None when there's no usable name."""
if not isinstance(library_name, str) or not library_name:
return None
return folder_name(emulator_from_dir_name(library_name))
def filed_emulator(
emulator: str, core: str | None, library_name: str | None = None
) -> str:
"""The emulator a stream files a state or save under: RetroArch's folder for
the core, where every other client files it, else the core id."""
# Without a recorded core, nothing would tell a state in the core's folder
# from another client's.
if emulator != "retroarch" or core is None:
return emulator
return library_folder(library_name) or folder_name(core) or emulator
def _filed_by_stream(state: State, emulator: str) -> bool:
"""Whether a stream on `emulator` filed this state: under the emulator, or
a RetroArch one with its core recorded, which only a stream records."""
if (state.emulator or "").lower() == emulator:
return True
return emulator == "retroarch" and state.is_stream_capture
def _loads_in(state: State, emulator: str, core: StateCore) -> bool:
"""Whether the running RetroArch core loads this state: one a stream wrote
with this core, or another client's in the core's folder."""
if _filed_by_stream(state, emulator):
return core.matches(state.core)
# By folder, as Cloud Sync slots it, so an alias of the core's name counts.
return (state.emulator or "").lower() in core.folders
def is_native_state(state: State, emulator: str, core: StateCore | None) -> bool:
"""Whether a stream on `emulator` loads this state as its own, no import."""
if core is None:
return _filed_by_stream(state, emulator)
return _loads_in(state, emulator, core)
class StatePicks(NamedTuple):
"""The state ids the resume picker offers, in the order given."""
native: list[int]
pickable: list[int]
def state_picks(
candidates: Iterable[State],
emulator: str,
core: StateCore | None,
imports_states: bool,
) -> StatePicks:
"""Split the states the resume claim takes: native ones with a slot resume as
they are; with `imports_states` the rest import, except another core's capture."""
native: list[int] = []
pickable: list[int] = []
for state in candidates:
loads = is_native_state(state, emulator, core)
if loads and slot_from_state_filename(emulator, state.file_name) is not None:
native.append(state.id)
pickable.append(state.id)
elif imports_states and (loads or not _filed_by_stream(state, emulator)):
pickable.append(state.id)
return StatePicks(native, pickable)
def user_states_for_emulator(
user_id: int, rom_id: int, emulator: str, core: StateCore | None = None
) -> list[State]:
"""The user's states for this ROM and emulator, newest first.
Args:
core: every state that RetroArch core loads, whoever filed it; without
it, the stream's own history, which prune and dedup work on.
"""
states = [
s
for s in db_state_handler.get_states(
user_id=user_id, rom_ids=[rom_id], visibility=UNRESTRICTED
)
if is_native_state(s, emulator, core)
]
# Ties on id, because updated_at only has second resolution: two captures
# in the same second would otherwise order arbitrarily, and only the first
# of them is ever hydrated.
states.sort(key=lambda s: (s.updated_at, s.id), reverse=True)
return states
async def _is_duplicate_of_latest(
latest: State | None, content: bytes, content_hash: str | None = None
) -> bool:
"""Whether ``content`` matches the most recent stored state.
Saving twice without playing in between is common (the exit autosave right
after a manual save), and those captures are identical. Only the newest is
compared: an older match is a genuine revisit of the same point.
"""
if latest is None or latest.file_size_bytes != len(content):
return False
if latest.content_hash is not None:
if content_hash is None:
content_hash = await asyncio.to_thread(content_hash_of_bytes, content)
# A row whose file is gone holds nothing to skip the capture for.
return latest.content_hash == content_hash and (
await fs_asset_handler.file_exists(latest.full_path)
)
try:
existing = await fs_asset_handler.read_file(
f"{latest.file_path}/{latest.file_name}"
)
except FileNotFoundError:
return False
await _backfill_hash(latest, existing)
return existing == content
async def _backfill_hash(state: State, content: bytes) -> None:
"""Store a legacy state's hash so later checks skip the read. Best effort."""
try:
content_hash = await asyncio.to_thread(content_hash_of_bytes, content)
if content_hash is not None:
await asyncio.to_thread(
db_state_handler.backfill_content_hash, state.id, content_hash
)
except Exception as exc:
log.warning("could not record the hash of state %s: %s", state.id, exc)
async def stored_copy(
user_id: int, rom_id: int, emulator: str, content: bytes
) -> State | None:
"""The stored state of this emulator's that holds exactly ``content``, if any."""
content_hash = await asyncio.to_thread(content_hash_of_bytes, content)
for state in user_states_for_emulator(user_id, rom_id, emulator):
if await _is_duplicate_of_latest(state, content, content_hash):
return state
return None
async def _remove_pruned_file(path: str) -> None:
"""Drop a pruned asset's file. A file that will not go leaves the prune
running: the rows are already gone, and stopping here would leave the rest
of the history over the limit as well."""
try:
await fs_asset_handler.remove_file(file_path=path)
except FileNotFoundError:
log.warning("pruned file already gone, %s", path)
except OSError as exc:
log.error("could not remove pruned file %s, leaving it orphaned: %s", path, exc)
async def prune_state_history(
user: User, rom: Rom, emulator: str, history: list[State] | None = None
) -> int:
"""Delete the oldest states past the retention limit, sparing a capture a
Cloud Sync slot serves; a missing file still loses its row.
Args:
history: the newest-first list a caller already holds, saving a refetch.
Returns:
How many went.
"""
limit = STREAMING_STATE_HISTORY_LIMIT
if limit <= 0:
return 0
states = (
history
if history is not None
else user_states_for_emulator(user.id, rom.id, emulator)
)
stale = states[limit:]
if stale:
served = {
state.id
for state in group_states_by_slot(
db_state_handler.get_states(
user_id=user.id, rom_ids=[rom.id], visibility=UNRESTRICTED
)
).values()
if not state.missing_from_fs
}
stale = [state for state in stale if state.id not in served]
for state in stale:
screenshot = state.screenshot
db_state_handler.delete_state(state.id)
await _remove_pruned_file(f"{state.file_path}/{state.file_name}")
try:
await release_thumbnail(screenshot)
except OSError as exc:
log.error(
"could not remove the pruned screenshot of %s, leaving it orphaned: %s",
state.file_name,
exc,
)
if stale:
log.info(
"pruned %d state(s) past the %d limit, rom=%s",
len(stale),
limit,
rom.name,
)
return len(stale)
async def store_state_asset(
user: User,
rom: Rom,
emulator: str,
filename: str,
content: bytes,
screenshot: bytes | None = None,
disc_file_id: int | None = None,
core: str | None = None,
captured_at: datetime | None = None,
library_name: str | None = None,
) -> None:
"""Store a pulled state file as a new entry in the ROM's state history.
Each capture is kept rather than overwriting the slot it came from, so the
player can resume from any earlier point. An unchanged capture is dropped
and the oldest entries are pruned once the retention limit is reached.
Args:
captured_at: when the state was written, for one filed after a newer
capture; defaults to now.
library_name: RetroArch's folder name for `core`, which the state is
filed under.
"""
history = user_states_for_emulator(user.id, rom.id, emulator)
if await _is_duplicate_of_latest(history[0] if history else None, content):
log.info("state identical to the last capture, skipping, rom=%s", rom.name)
return
stamped = stamped_state_filename(
emulator, filename, captured_at or datetime.now(timezone.utc)
)
existing_names = {state.file_name for state in history}
fields: dict[str, Any] = {"disc_file_id": disc_file_id, "core": core}
if captured_at is not None:
fields |= {"created_at": captured_at, "updated_at": captured_at}
stored = await store_state_file(
user,
rom,
filed_emulator(emulator, core, library_name),
content,
stamped,
fields=fields,
)
if captured_at is not None:
# Filed under newer captures, so the prune reads the history afresh.
history = user_states_for_emulator(user.id, rom.id, emulator)
elif stamped not in existing_names:
# The capture is the newest, so it heads the list the prune below reads.
history.insert(0, stored)
# Bind a thumbnail to the state so the resume picker shows the right frame.
# Best-effort: a missing or unreadable screenshot must not fail the sync.
if screenshot is not None:
try:
await store_state_screenshot(user, rom, stamped, screenshot)
except Exception:
log.exception("failed to store state screenshot for %s", stamped)
await prune_state_history(user, rom, emulator, history=history)
async def pull_state_to_library(
user_id: int,
rom_id: int,
container: ResolvedContainer,
slot: int,
disc_file_id: int | None = None,
) -> bool:
"""Background task: pull a freshly saved state from the broker and store it.
Best-effort by design, a sync failure must never surface to the player,
the state still exists inside the container.
"""
user = db_user_handler.get_user(user_id)
rom = db_rom_handler.get_rom(rom_id)
if user is None or rom is None:
return False
emulator = container.emulator
for attempt in range(broker.PULL_ATTEMPTS):
if attempt > 0:
await asyncio.sleep(broker.PULL_RETRY_DELAY)
result = await asyncio.to_thread(fetch_state_file, container, slot)
if result is None:
continue
filename, content, core, library_name = result
try:
filename = sanitize_filename(filename)
# The library stores the name with a capture stamp, so that must fit.
check_filename_length(
stamped_state_filename(emulator, filename, datetime.now(timezone.utc))
)
except ValueError:
log.warning("broker returned a state filename the library cannot store")
return False
# The container's capture is the frame the player saw, and it is the
# same route for every emulator; an embedded frame only fills a 404.
screenshot = await asyncio.to_thread(fetch_state_screenshot, container, slot)
if screenshot is None:
# Off the loop as well: reading the zip copies the whole state body.
screenshot = await asyncio.to_thread(
extract_state_screenshot, emulator, content
)
try:
await store_state_asset(
user,
rom,
emulator,
filename,
content,
screenshot,
disc_file_id,
core=core,
library_name=library_name,
)
except Exception:
log.exception("failed to store pulled state %s", filename)
return False
log.info(
"state synced to library, rom=%s slot=%d file=%s",
rom.name,
slot,
filename,
)
return True
log.warning("no state file to pull after save, rom_id=%d slot=%d", rom_id, slot)
return False
async def push_resume_state(
container: ResolvedContainer,
resume_state: State,
state_core: StateCore | None = None,
) -> bool:
"""Send the state a player picked to resume from down to the container.
Best-effort: a failure means the session just starts fresh, which the claim
response reports through `resume`.
"""
if state_core is not None and not _loads_in(
resume_state, container.emulator.lower(), state_core
):
log.warning(
"resume state is %s's, core %s booted, launching fresh",
resume_state.core,
state_core.expected,
)
return False
try:
content = await fs_asset_handler.read_file(
f"{resume_state.file_path}/{resume_state.file_name}"
)
except Exception:
log.exception("could not read resume state %s", resume_state.file_name)
return False
pushed = await asyncio.to_thread(
push_state_file,
container,
container_state_filename(resume_state.file_name),
content,
# So the broker refuses it too when RomM could not tell which core runs.
resume_state.core or (state_core.expected if state_core is not None else None),
)
if not pushed:
log.warning("resume state not pushed, launching fresh")
return pushed
async def hydrate_states_to_broker(
user_id: int,
rom_id: int,
container: ResolvedContainer,
resume_pushed: bool = False,
state_core: StateCore | None = None,
) -> int:
"""Background task: push the newest stored state for this ROM down to the
freshly claimed container. Emulators read state files lazily, so pushing
right after launch is safe.
Only the newest is sent: every history entry collapses to the same
container-side name, and that name is what the in-emulator quick-load lands
on. Older captures are reached through the resume picker instead.
For the same reason, a resume pick already sent at claim time means there is
nothing to add here: any push would overwrite it before the broker's
deferred load fires. A container that resumes from its save archive takes no
state file at all, and the archive already carries the newest exit state.
"""
if resume_pushed or container.resumes_from_archive:
return 0
# A configured core with no filter means the launch never named what runs.
if container.core is not None and state_core is None:
log.info("not hydrating states into core %s, it is unconfirmed", container.core)
return 0
user = db_user_handler.get_user(user_id)
rom = db_rom_handler.get_rom(rom_id)
if user is None or rom is None:
return 0
emulator = container.emulator
# A row whose file vanished can't be pushed, so the next one down goes.
newest = next(
(
s
for s in user_states_for_emulator(user_id, rom_id, emulator, state_core)
if not s.missing_from_fs
),
None,
)
if newest is None:
return 0
# A broker that can't name its core doesn't refuse another core's state.
if state_core is None and newest.core is not None:
log.info("not hydrating a %s state into an unnamed core", newest.core)
return 0
try:
content = await fs_asset_handler.read_file(
f"{newest.file_path}/{newest.file_name}"
)
except FileNotFoundError:
log.warning("stored state missing on disk, %s", newest.file_name)
return 0
ok = await asyncio.to_thread(
push_state_file,
container,
container_state_filename(newest.file_name),
content,
state_core.expected if state_core is not None else None,
)
if ok:
log.info("hydrated newest state to container, rom=%s", rom.name)
return 1 if ok else 0
async def restore_session_disc(
rom_id: int,
container: ResolvedContainer,
session_key: str,
file_id: int,
broker_session_id: str | None = None,
) -> bool:
"""Background task: switch to the disc a resumed state or the player names.
The launch always mounts the ROM folder so the emulator loads the playlist
and starts on the first disc; anything else would boot a bare image the
tray commands cannot step through. So the disc is restored afterwards, and
the broker holds the swap until the core reports a running game.
Best-effort: a failure leaves the session on disc one, which the player can
fix with the swap control.
"""
rom_file = db_rom_handler.get_rom_file_by_id(file_id)
if rom_file is None or rom_file.rom_id != rom_id:
log.warning(
"resume: could not restore disc, file %s is not in the library", file_id
)
return False
library_base = container.library_path
disc_path = f"{library_base}/{rom_file.full_path}"
if not await asyncio.to_thread(commands.swap_disc, container, disc_path):
log.warning("resume: could not restore disc %s", rom_file.file_name)
return False
await set_session_disc(session_key, file_id, broker_session_id)
log.info("resume: restored disc %s", rom_file.file_name)
return True