Files
romm/backend/handler/streaming/states.py
Terri 8a1e6280b1 feat(saves): add save channels and snapshots (#5198)
* feat(saves): add save channels and snapshots

* feat(saves): close spec gaps in save channels and hash with sigil

* feat(saves): play snapshots in the v2 player, which pushes snapshots

* fix(saves): code review: authorization, retention losses, held-save sync, batched responses

* refactor(saves): simplify pass

* refactor(saves): review-polish pass

* docs(saves): humanizer pass

* feat(saves): run every EmulatorJS page on the v2 player

* feat(saves): per-user snapshot pins

* feat(sigil): store the identity a save restore needs and pin sigil 0f05f25

* fix(saves): meet type-aware lint in the v2 player

* feat(sigil): store N64 header and playlist title ids, pin sigil 0847fda

* feat(saves): convert saves for a core on download and list save layouts

* feat(saves): prune unreachable archival snapshots and empty detached channels on delete

* feat(saves): device sync from the token, held snapshots and shared-card pushes

* feat(saves): arc restores past abandoned snapshots and color channels by age

* fix(saves): code-review and security-audit fixes

* refactor(saves): simplify pass

* chore(saves): review-polish pass

* docs(saves): humanizer pass

* fix(sync): file RetroArch autosave versions as their channel's next snapshot

* fix(saves): address review findings and trim docstrings

* fix(saves): share-lock planned rows by id so PostgreSQL accepts the lock

* test(saves): stub the detached-channels fetch in SaveDataTab stories

* feat(saves): carry the full current snapshot in a 409, pin sigil 2071dff

* chore(sigil): pin 5d4ddb4, which reads .cue and .gdi sheets

* docs(saves): drop v2 wording now that one UI remains

* chore(sigil): pin 0190443, which reads PS2 raw BIN images and cue sheets

* fix(sigil): treat a file too short for its format as routine during scans

* chore(migrations): renumber save channel migrations after upstream's 0154

* fix(snapshots): a hardcore switch on unchanged content makes a new current

* fix(sync): decide a channel's slot from its history and the device's snapshot

* chore(docker): pin sigil at 794d99f for PSP Store release save prefixes

* refactor(db): squash the save channel migrations into 0161

Fold the slot linking (0162) and the rom_files sigil identity columns (0163)
into 0161_save_channels, so the feature ships as one revision.

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

* fix(saves): close visibility and input gaps found in review (pr-ready step 2)

code-review --fix:
- negotiate_sync drops channel slots on ROMs hidden from the caller
- channel PATCH/attach/DELETE answer 404 when the channel's ROM is hidden
- a push copying a save from a hidden ROM answers 404
- _own_device applies require_token_device to bound client tokens
- adopting a legacy save syncs its sharing with the channel it joins

security-audit follow-ups:
- another user's detached public save or state is no longer downloadable
- profile and option values must be a single path segment
- companions are de-duplicated and capped at 8

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

* refactor(saves): share channel and asset lookups, drop duplicates (pr-ready step 3)

simplify:
- readable_channel_or_404 and channels_on_files replace four copies of the
  channel 404 check and two copies of the file-fed channel listing
- readable_rom_asset_or_404 serves both public save and state downloads
- _own_device resolves through require_device; _clone_origin takes the source
- reuse _unprocessable, DESCRIPTOR_EXTENSIONS, SAVE_SLOT_MAX_LENGTH, uniqueBy
  and uuidv7; neutral forms default their required pattern to the allowed one
- RetroArch delete checks held rows in one query, a guarded upload lists the
  slot only without a channel head, and uploads are read off the event loop
- snapshotSession builds push requests once; player comment cleanups

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

* docs(saves): trim two docstrings to two lines (pr-ready step 4)

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

* fix(saves): answer held RetroArch paths with 423, mirror slot labels

- RetroArch Cloud Sync answers 423 Locked for a PUT over a held unslotted save
  and for a DELETE where only held rows sit at the path, instead of 409 and 404
- channelLabelForSlot returns null for blank and state_ slots, as the backend's
  channel_label does, so the player files them under no channel either
- document that sharing a channel lets every user read and push into it

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

* chore(docker): pin sigil at 85f88a8 for Switch .nup containers

* fix(snapshots): a save pushed in another shape or format makes a new current

* refactor(saves): drop the always-true SAVE_SYNC.SNAPSHOTS heartbeat flag

Nothing reads it, and the SAVE_SYNC block's presence already tells a
client the server speaks the snapshot API. Also trim the rom detail
channel field comments to one line each.

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

* refactor(frontend): use uuidv7 for every client-generated id

Drop the randomToken wrapper and the notification inbox's Math.random tab
id, so uuidv7 is the one helper that works outside a secure context.

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

* refactor(saves): trim redundant snapshot API surface, dead code and duplicate logic

API:
- Drop PUT /snapshots/{id}/devices/{device_id}; GET /snapshots/{id}?hold=true holds.
- GET /snapshots is history only (channel_id required); GET /channels serves currents.
- A snapshot carries channel_id instead of an embedded channel.
- POST /saves/{id}/content takes the same query parameters as the GET, plus container_path.

Backend:
- Remove the archival write path, clone.py, DBStatesHandler.get_state, the sigil
  identity-hash path, unused relationships and composite snapshot indexes.
- One held/frozen lookup, one bulk-delete guard, SQLAlchemy dialect upserts, and
  the shared reserve_version_name in the writer.
- The writer takes a visibility filter and checks the channel and parent itself.
- The restore handler picks per-game or merge; fewer wrapper types and tables.

Frontend:
- Channel delete uses the shared typed confirm; DeleteChannelDialog is gone.
- Held offline pushes go through a per-channel SnapshotSession.
- Remove the slot-based pending upload path.
- The timeline shares the fan's badge logic.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* refactor(saves): release archival backups through module functions

The saves and states handlers each built a private DBSnapshotsHandler to
call release_backup and refresh_backup_digests, since they can't import
the shared instance. Both only ever ran inside the caller's session, so
they are now module functions taking it, like channel_for_slot.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* refactor(saves): share one deleted-assets handler instance

The saves handler built its own DBDeletedAssetsHandler because it can't
import the package's instance. The instance is now built in
deleted_assets_handler.py and re-exported by the package, so both use it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 21:59:19 -05:00

874 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_snapshot_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 (
disc_names,
emulator_from_dir_name,
group_states_by_slot,
state_game_name,
)
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, is_public: bool = False
) -> 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"),
is_public=is_public,
)
@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)
)
# A state a channel snapshot holds belongs to that channel's retention.
frozen = db_snapshot_handler.get_frozen_state_ids([s.id for s in states])
states = [s for s in states if s.id not in frozen]
stale = states[limit:]
if stale:
rom_states = db_state_handler.get_states(
user_id=user.id, rom_ids=[rom.id], visibility=UNRESTRICTED
)
discs = disc_names(
(rom, state_game_name(state.file_name)) for state in rom_states
)
served = {
state.id
for state in group_states_by_slot(rom_states, discs).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, is_public=stored.is_public
)
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