mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 02:22:44 +01:00
* fix(streaming): keep foreign saves offered when the import-spec check fails A broker that misses the 5 s import-spec deadline used to read as "imports nothing": the Saves tab vanished and foreign picks were refused with "Save is not a restorable archive". Keep the last good answer in Redis so every worker can fall back on it, cache 404s for five minutes instead of forever, answer a pick that can't be checked with a retryable 503, and refetch the streaming config whenever the Stream page mounts. * fix(streaming): code-review fixes for the import-spec fallback Hold a fallback answer for 10 s so one claim's checks don't each wait out the broker timeout, read the stored answer back through the broker response parser, and warn about a pre-import broker once per worker instead of at every cache expiry. * refactor(streaming): simplify pass on the import-spec fallback Make ImportSpecUnavailable the 503 itself so the save and state pickers no longer convert it by hand, and store the broker's own response body as the last answer instead of rebuilding its shape. * chore(streaming): review-polish on the import-spec fallback Trim the cache comments and the exception docstring, fit the 503 detail within the line limit, and annotate the fresh-worker test dict for mypy. * docs(streaming): humanizer pass on import-spec comments and test docstrings * fix(streaming): tell lasting import-spec failures from passing ones Only timeouts, connection errors, 5xx and 429 fall back to the broker's last answer. A refused request (401, other 4xx) or a reply RomM can't read caches no imports for 30 s and logs an error, so a pick gets a refusal instead of an endless retry. A 404 from a broker that answered before uses that answer, since it is likelier a restart behind a proxy than a downgrade. * fix(streaming): ask for a retry when a picked state can't be checked An older save with the newest state resumes the pick only through an import, so an unanswered import-spec check now returns the 503 instead of launching from the older archive's own state. * fix(streaming): share an in-flight config request App load and the Stream page both fetch the config; two requests could land out of order and leave the older answer in place. (Stability item 5.) * fix(streaming): hold the resume picker until the fresh config lands What the broker imports decides which saves and states are on offer, and the app-load config can predate its answer. The panel shows a spinner until the Stream page's own refetch settles, so a pick can't vanish under the player. (Stability item 4.) * fix(streaming): ask every platform's broker at once on /config The checks ran on the default thread pool (cpu+4 threads), so a broker serving more platforms than that cost one timeout per wave: 10.7 s for 14 platforms on a 6-CPU dev box with a silent broker. The Stream page's picker now waits on /config, so the checks get a pool of their own. * fix(streaming): address Greptile review on the import-spec fallback - Play waits on the fresh config with the resume picker, so it can't send a preselected state the player can't see yet. - The streaming store gets a reset() for logout, and a config reply asked for as the previous account is dropped instead of landing in the next one. - The configFresh write after the refetch checks useIsAlive(). - Trimmed the require_import_spec docstring, the configFresh comment and the /config pool comment to the house length. - Declined: a worker-wide pool for the /config checks. Each request's threads end within the broker timeout, and a shared bounded pool would bring back timeout waves under concurrent loads. * fix(streaming): share /config broker checks across requests Addresses Greptile's re-raised finding on #5174 that each /config request opened its own pool of up to 64 threads, so overlapping page loads during a silent broker multiplied the worker's threads. - The checks run in one worker-wide pool, and a check already in flight for the same container and platform is joined rather than asked again, so concurrent page loads hold no more threads than one does, with no queued-timeout waves. - Callers await the shared run through asyncio.shield, so a request that disconnects doesn't cancel the check others are waiting on. * fix(streaming): file a RetroArch exit's save raw and boot the newest save A RetroArch exit holding one .srm and its states is no longer stored as a .saves.zip: the .srm is filed bare under the core's emulator name with a timestamped name, and each state goes through the state store. Exits with more than one save, a memory card, or unlabelled members still keep the zip. A launch with no pick now boots the newest save, raw or zip. A newer bare .srm goes through the broker's save import when the broker accepts one, and the launch screen defaults to the same save. * fix(streaming): keep the exit zip when a raw save can't be filed safely pr-ready step 2 (code review). - Keep the zip for a core that isn't one plain folder name, a malformed manifest kind, a member that fails to unpack, or a broker that doesn't import saves. - Fall back to the newest archive when the default raw save fails to import. - File exit states oldest first; one unreadable stored state no longer drops the rest. - Rename locals that shadowed the archive module; fix a test return type and a stale comment. * refactor(streaming): simplify the default save comparison pr-ready step 3 (simplify): default_save reuses _newest's ordering, and newestSave takes the first match in the newest-first list. * docs(streaming): trim the raw-save docstrings pr-ready step 4 (review-polish). * fix(streaming): rank saves by their last write and read .ZIP as an archive The web player writes into its existing save row, which only moves updated_at, so ranking by created_at let a stream with no pick boot an older streaming zip over newer web-player progress. The backend default and the launch screen now rank by updated_at, and the picker dates rows by it. Upper-case .ZIP saves are now read as archives on both sides, to match the web player's case-insensitive guard. * feat(states): hash states so duplicate checks skip reading files Adds states.content_hash (migration 0149), filled on every state write: streaming capture, the states upload and update endpoints, the scan and the RetroArch sync push. The streaming duplicate check compares hashes and falls back to reading the file for rows stored before this, which are not backfilled. * fix(streaming): leave an untouched default off the claim and skip missing saves Review items 1 and 2: a default sent as a pick bypassed the zip fallback, and a save marked missing could become the newest. * fix(streaming): code-review fixes for raw exit filing and state hashing pr-ready step 2: keep the zip when a state can't be filed, don't treat a missing state file as a duplicate, fall back to the native archive when a defaulted save fails, hash off the event loop, count filed states as new. * docs(streaming): review-polish, trim the newest-save comment * fix(streaming): bind the background exit pull's states to the swapped disc Decision 1: the exit save job filed states without the session's disc id, so on a multi-disc game its copy could lose the disc binding. The second copy is still dropped by the hash dedupe. * fix(streaming): keep the exit zip when one of its states fails to store Decision 2: a state that threw on store was logged and lost, since the zip holding it was dropped. The zip holds the same .srm, so booting it as the default loses nothing. * fix(sync): keep updated_at when RetroArch sync flags a vanished save or state * fix(streaming): record a legacy state's hash when dedupe reads its bytes * fix(streaming): file a RetroArch exit's auto state raw instead of keeping the zip The auto state now goes into the state history under its own capture stamp, so an exit carrying one files its .srm raw like any other. It is never hydrated, and a resume pick of it is refused, since the broker would file it into its numbered working slot. * fix(streaming): hydrate the newest state still on disk A newer row sync flagged as gone from disk made hydrate push nothing. It now skips such rows the way the save picks already do. * docs(streaming): note the auto-state refusal in resolve_resume_state * fix(streaming): resume a RetroArch auto state like any other state The broker files any pushed state into its working slot, so .state.auto reads as slot 0 like a bare .state. Hydrate and the resume pick now push it instead of skipping or refusing it. * fix(streaming): address Greptile review on raw RetroArch exits - A default .srm the broker refuses at activate now boots the newest native archive instead of failing the launch. Only a default save that rode the import alone falls back; a hand pick still fails. - Exit states the history hasn't seen are filed just under the next state it already holds, so an older slot no longer heads the history over the exit capture teardown filed first. - A raw exit save is skipped only when it matches the newest usable save, so returning to an older save records the play, and a match on a row whose file is gone no longer deletes the new copy. - Stream.test.ts clicks the rendered play button instead of casting the view model to call onPlay. - Trim the raw-exit docstrings to one sentence. * fix(streaming): reserve a free version name for a raw RetroArch exit save Addresses Greptile: the exit's .srm took a second-resolution tag without checking whether another save held that name, so it could overwrite one. Also compares updated_at naively in the mark-missing test, which failed on PostgreSQL's UTC-aware column. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(streaming): file each RetroArch exit state on the disc it was saved on Addresses Greptile: every state in the exit archive took the session's final disc, so a hotkey slot saved before a swap resumed on the wrong one. The session now keeps each swap with its time, and a session that ran more than one disc files each state by its archive timestamp. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
709 lines
27 KiB
Python
709 lines
27 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 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.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 logger.logger import log
|
|
from models.assets import 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
|
|
|
|
# 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
|
|
native = (state.emulator or "").lower() == emulator
|
|
if native:
|
|
# Another core's file would land where this one's quick-load reads it.
|
|
core = state_core_for(container)
|
|
if core is not None and not core.matches(state.core):
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail="State was made by a different RetroArch core",
|
|
)
|
|
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
|
|
|
|
|
|
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)
|
|
|
|
|
|
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
|
|
|
|
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")
|
|
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)
|
|
|
|
|
|
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.
|
|
|
|
`core` narrows them to what a RetroArch core can load. Prune and dedup
|
|
leave it out: they work on the whole history, whichever core wrote it.
|
|
"""
|
|
states = [
|
|
s
|
|
for s in db_state_handler.get_states(user_id=user_id, rom_ids=[rom_id])
|
|
if (s.emulator or "").lower() == emulator
|
|
and (core is None or core.matches(s.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. Returns how many went.
|
|
|
|
A file already gone from disk still loses its row, since a stale entry that
|
|
no longer opens is worse than a missing file. `history` is the newest-first
|
|
list a caller already holds, saving a second fetch and sort of the same rows.
|
|
"""
|
|
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:]
|
|
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,
|
|
) -> 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.
|
|
"""
|
|
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, emulator, 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 = 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
|
|
)
|
|
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 state_core.matches(resume_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: put back the disc a resumed state was captured on.
|
|
|
|
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
|