Files
romm/backend/handler/streaming/lifecycle.py
Georges-Antoine Assi 63faff8883 fix(misc): Rename paths, rescan artwork, scan lookups and streaming teardown fixes (#5396)
* fix(roms): rewrite only the moved part of a renamed rom's file paths

Renaming a rom rewrote each of its files with
`str.replace(old fs_name, new fs_name)` on both the name and the path. On
disk, rename_fs_rom moves only `fs_path/old` to `fs_path/new`, so:

- a folder rom's inner file named after the folder (`Game (Disc 1).bin`
  in `Game/`) was renamed in the database but not on disk;
- an fs_name that also appears in the platform path (a rom named `n64`
  under `n64/roms`) rewrote the platform path too.

_moved_file_location mirrors the move instead: a single-file rom's name
changes, a folder rom's files keep their names under the renamed folder,
and anything else is left alone.

_refetch_changed_matches now returns the ids it refetched, so the
RetroAchievements badge download keys off that rather than repeating the
comparison, and the shared-media rematch uses the same _match_changed
check as the refetch loop.

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

* fix(scan): keep artwork a complete rescan has nothing to replace with

A complete rescan deleted the rom's cover, manual, screenshots and every
provider media folder before asking any provider, then reset the stored
paths. A provider that was down, rate limited or no longer had the art
left the rom with none.

The wipe is gone, and scan_rom no longer resets the path columns on a
complete rescan. The download step already replaces what changed:
covers, manuals and screenshots refetch when their URL differs, and
remove_stale_media drops provider media whose owner or URL changed. The
URLs and locks are still cleared, so whatever answers now can replace a
file; a file nothing replaces stays where it was.

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

* refactor(scan): move scan_rom's provider lookups onto a _RomLookups class

scan_rom defined 16 provider lookups as closures over its own locals
(scan type, platform, rom, rom_attrs, enabled sources, the attempted and
inconclusive sets), so none of them could be read or tested apart from
the 1,000-line function around them.

They are now methods of _RomLookups, a dataclass holding exactly what
they used to capture, along with the helpers they share (consults,
note_inconclusive, resolve_fetch and the cached match files). scan_rom
builds one instance and keeps its local names for the shared sets, so its
body is unchanged apart from the calls. SteamGridDB's lookup stays nested
because it reads the other providers' results.

scan_rom drops from 977 to 664 lines. Its own complexity is unchanged:
that comes from the merge after the lookups, not the lookups themselves.

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

* refactor(streaming): one teardown order for every way a session ends

A session could be torn down three ways, each spelling out its steps:

- teardown_released_session (owner release and single admin release)
- teardown_abandoned_session (stale takeover and the reaper)
- force_release_all's inline _teardown

The first two ran the same stop/playtime/activity/state/saves sequence
in two copies. The sweep differed in ways that mattered: it held no drain
marker while it worked, recorded the termination after the stop (so a
polling tab could miss it), marked the exit save pull pending only after
the stop, and deleted the key unconditionally, even if a newer claim had
replaced the one it read.

_stop_and_collect now holds the shared sequence, and both lifecycle
teardowns call it after their own opening (a drain marker for a release,
a staleness-checked marker for an abandoned session). The sweep runs
teardown_released_session for each session, like a single admin release.
With no container config left, it still records the termination, then
frees the key through the guarded release_own_session.

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

* fix: apply code-review findings (pr-ready step 2)

Record playtime and clear the activity entry when force-release-all frees
a session whose container config is gone, and let the PICO-8 cartridge
fallback see a cover a complete rescan keeps.

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

* refactor: apply simplify findings (pr-ready step 3)

Let _RomLookups.attempts() record the attempt it gates, drop scan_rom's
local aliases for the lookups' state, read the platform slug off the
lookups in fetch_launchbox_rom, seed the kept artwork paths into
rom_attrs for every rescan so the PICO-8 fallback reads them directly,
return None from _moved_file_location when a file did not move, and
share the playtime and activity steps through close_session_record.

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

* fix: address Greptile review on #5396

Drop a cover's other formats once a new one is stored, so a kept upload
in another extension can't shadow it, and move the rename path rule onto
FSRomsHandler next to rename_fs_rom.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 11:06:52 -04:00

593 lines
22 KiB
Python

"""What every teardown path does, and in what order.
Stopping the emulator, evacuating and wiping the card, crediting the playtime,
filing the exit state and saves, and only then giving the container back. The
order is load-bearing and lives here once rather than in each route that ends
a session.
"""
import asyncio
import secrets
from collections.abc import Coroutine
from datetime import datetime, timezone
from typing import Any
from handler.activity_handler import activity_handler
from handler.database import db_user_handler
from handler.play_session_handler import ingest_play_sessions
from handler.redis_handler import streaming_queue
from handler.streaming import background, commands, memory_cards, saves, states
from handler.streaming.config import (
ResolvedContainer,
container_for_session,
containers_by_key,
)
from handler.streaming.session_store import (
DRAIN_MARKER_TTL,
DiscSwap,
StreamingSession,
StreamingSessionContended,
broker_session_id,
claim_drain_marker,
drain_marker,
drop_drain_marker,
hold_drain_marker,
hold_session_claim,
record_termination,
release_own_session,
replace_session_if,
restore_drained_session,
same_claim,
session_disc_id,
session_disc_swaps,
session_is_stale,
)
from logger.logger import log
async def abort_claim(
session_key: str,
claim: StreamingSession,
blank_card_id: int | None = None,
) -> None:
"""Undo a claim that will not become a session.
Every exit from `claim_session` that is not a started session goes through
here: leaving the key behind wedges the container until the TTL lapses, and
leaving an auto-created blank card behind orphans a row nobody asked for.
Guarded like every other release: a card probe or an activate blocks for
minutes, and an unguarded delete would free a container an admin release
and a fresh claim had already handed to somebody else.
"""
if not await release_own_session(session_key, claim):
log.warning("aborted claim on %s was no longer ours", session_key)
if blank_card_id is not None:
await memory_cards.discard_blank_card(blank_card_id)
def _hold_reservation(
session_key: str, token: str | None, claim: StreamingSession
) -> asyncio.Future[None]:
"""Keep a container reserved while a teardown runs.
The drain marker holds it where one landed; where it did not, nothing took
the container over and the claim itself still reserves it. Either way the
stamp is kept current, since the player who owned it has left and an
unrefreshed reservation reads as abandoned to the next claimant.
"""
return asyncio.ensure_future(
hold_drain_marker(session_key, token)
if token is not None
else hold_session_claim(session_key, claim)
)
async def _drop_reservation(
session_key: str, token: str | None, claim: StreamingSession
) -> None:
"""Free whatever `_hold_reservation` was holding. `token` keeps the release
aimed at this drain, so an overrun that outlived its own marker cannot free
whoever took the container afterwards."""
if token is not None:
await drop_drain_marker(session_key, token)
elif not await release_own_session(session_key, claim):
log.error("session %s survived its own exit", session_key)
async def release_after_state_pull(
session_key: str,
pull: Coroutine[Any, Any, Any],
token: str | None,
claim: StreamingSession,
) -> None:
"""Run the exit state pull, then free the container it was holding.
The reservation goes even when the pull raised: the state is recoverable
from the container on the next claim, a container nothing releases is not.
"""
keepalive = _hold_reservation(session_key, token, claim)
try:
await pull
finally:
keepalive.cancel()
await _drop_reservation(session_key, token, claim)
async def quiesce_container(
container: ResolvedContainer, session: StreamingSession, *, save: bool = True
) -> commands.StopOutcome:
"""Stop the emulator, then evacuate and wipe its memory card.
Every teardown path opens this way, and the order is load-bearing: stopping
first is what makes the card quiescent, and the wipe runs only where the
evacuation captured the card. Returns what the stop left to collect.
"""
stopped = await asyncio.to_thread(commands.stop, container, save)
if await memory_cards.evacuate_session_card(session, container):
await memory_cards.wipe_session_card(container)
return stopped
async def pull_exit_saves(
*,
user_id: int,
rom_id: int,
token: str,
container_key: str,
platform: str,
broker_session: str | None,
settled: bool,
disc_file_id: int | None = None,
disc_swaps: list[DiscSwap] | None = None,
) -> None:
"""The RQ job behind `collect_exit_saves`, which lets the next claim through
however the pull ended."""
try:
container = container_for_session(containers_by_key(), container_key, platform)
if container is None:
log.warning("skipping the exit save pull, %s is gone", container_key)
return
await saves.pull_saves_to_library(
user_id,
rom_id,
container,
broker_session,
settled=settled,
disc_file_id=disc_file_id,
disc_swaps=disc_swaps or [],
)
finally:
await saves.clear_save_pull_pending(saves.SavePullMark(user_id, rom_id, token))
async def mark_exit_saves_pending(
container: ResolvedContainer, session: StreamingSession
) -> saves.SavePullMark | None:
"""Hold the owner's next claim on this ROM until the exit pull has filed.
Returns:
The mark for `collect_exit_saves`, or None when no pull will run: a
whole-card sync container evacuates the card instead, and a desktop ran
no ROM to file one under.
"""
rom_id = session.get("rom_id")
user_id = session.get("user_id")
if (
container.memory_card_sync
or not isinstance(rom_id, int)
or not isinstance(user_id, int)
):
return None
return await saves.mark_save_pull_pending(user_id, rom_id)
async def collect_exit_saves(
container: ResolvedContainer,
session: StreamingSession,
mark: saves.SavePullMark | None,
*,
settled: bool,
) -> None:
"""Queue the pull of a stopped session's save archive, since the broker keeps
it after the emulator dies, filing it under the owner whoever ended it.
Args:
mark: cleared by the pull however it ends.
settled: the broker confirmed the emulator is done writing, so the first
answer is final.
"""
if mark is None:
return
try:
# On the streaming worker, so a web restart cannot cut a pull short.
streaming_queue.enqueue(
pull_exit_saves,
kwargs={
"user_id": mark.user_id,
"rom_id": mark.rom_id,
"token": mark.token,
"container_key": container.key,
"platform": container.platform,
"broker_session": broker_session_id(session),
"settled": settled,
"disc_file_id": session_disc_id(session),
"disc_swaps": session_disc_swaps(session),
},
job_timeout=saves.SAVE_PULL_TTL_SECONDS,
result_ttl=0,
meta={"task_name": "Streaming exit save pull"},
)
except Exception:
log.exception("could not queue the exit save pull for %s", container.key)
await saves.clear_save_pull_pending(mark)
async def start_exit_save_pull(
container: ResolvedContainer, session: StreamingSession, *, settled: bool
) -> None:
"""Mark the exit pull pending, then start it, for a stop that is already done."""
mark = await mark_exit_saves_pending(container, session)
await collect_exit_saves(container, session, mark, settled=settled)
async def collect_exit_state(
container: ResolvedContainer, session: StreamingSession, state_slot: int | None
) -> None:
"""File the state the stop wrote, while the claim still guards the container.
The broker keeps an exited session's state only until the next activate, and
dropping the claim is what lets that activate happen.
"""
rom_id = session.get("rom_id")
user_id = session.get("user_id")
if (
state_slot is None
or not isinstance(rom_id, int)
or not isinstance(user_id, int)
):
return
await states.pull_state_to_library(
user_id,
rom_id,
container,
state_slot,
disc_file_id=session_disc_id(session),
)
# Streaming sessions shorter than this are treated as accidental (a claim that
# was released almost immediately) and not recorded as playtime.
_MIN_PLAY_SESSION_MS = 5_000
# A streaming session is a play session like any other, so it goes on the
# activity board next to the devices. The container key stands in for a device
# id: a user holds at most one session per container, which is what
# clear_active needs to find the entry again.
_DEVICE_TYPE = "streaming"
async def publish_session_activity(session_key: str, session: StreamingSession) -> None:
"""Put a live streaming session on the activity board.
Best-effort: the board is a view, never a reason to fail a launch.
"""
user_id = session.get("user_id")
rom_id = session.get("rom_id")
if not isinstance(user_id, int) or not isinstance(rom_id, int):
return
try:
entry = await activity_handler.build_entry(
user_id=user_id,
device_id=session_key,
rom_id=rom_id,
preserve_started_at=True,
device_type=_DEVICE_TYPE,
)
if entry is not None:
await activity_handler.publish_active(entry)
except Exception:
log.exception("failed to publish streaming session activity")
async def refresh_session_activity(session_key: str, session: StreamingSession) -> None:
"""Keep the activity entry alive on the player's heartbeat.
Re-stores what is already there instead of rebuilding it: nothing on the
entry changes for the length of a session, and a beat every 30s per session
would otherwise cost two queries and a broadcast each time. An entry that
has gone (expired while the backend was down) is rebuilt.
"""
user_id = session.get("user_id")
if not isinstance(user_id, int):
return
try:
existing = await activity_handler.get_active(user_id, session_key)
except Exception:
log.exception("failed to read streaming session activity")
return
if existing is None:
await publish_session_activity(session_key, session)
return
try:
await activity_handler.set_active(existing)
except Exception:
log.exception("failed to refresh streaming session activity")
async def clear_session_activity(session_key: str, session: StreamingSession) -> None:
"""Take a finished streaming session off the activity board.
Every teardown path calls this: the board is socket-driven, so an entry left
behind sits on an open board until its TTL runs out.
"""
user_id = session.get("user_id")
if not isinstance(user_id, int):
return
try:
await activity_handler.publish_clear(user_id, session_key)
except Exception:
log.exception("failed to clear streaming session activity")
async def record_play_session(session: StreamingSession) -> None:
"""Record a finished streaming session as RomM playtime.
Reuses the same ingest path as device sync (dedup on user+rom+start_time,
updates the ROM's last_played). The session's stored claimed_at is the
start and now is the end. Best-effort: any failure is logged, never fatal,
so playtime accounting cannot block or fail a teardown.
"""
user_id = session.get("user_id")
rom_id = session.get("rom_id")
claimed_at = session.get("claimed_at")
if (
not isinstance(user_id, int)
or not isinstance(rom_id, int)
or not isinstance(claimed_at, str)
):
return
try:
start = datetime.fromisoformat(claimed_at)
except ValueError:
return
if start.tzinfo is None:
start = start.replace(tzinfo=timezone.utc)
end = datetime.now(timezone.utc)
duration_ms = int((end - start).total_seconds() * 1000)
if duration_ms < _MIN_PLAY_SESSION_MS:
return
try:
user = db_user_handler.get_user(user_id)
ingest_play_sessions(
user_id=user_id,
username=user.username if user else str(user_id),
entries=[
{
"rom_id": rom_id,
"save_slot": None,
"start_time": start,
"end_time": end,
"duration_ms": duration_ms,
}
],
# The rom was checked against the user when the stream was claimed.
perms=None,
)
except Exception:
log.exception("failed to record play session")
async def close_session_record(session_key: str, session: StreamingSession) -> None:
"""Credit a finished session's playtime and take it off the activity board."""
await record_play_session(session)
await clear_session_activity(session_key, session)
async def _stop_and_collect(
container: ResolvedContainer,
session: StreamingSession,
session_key: str,
pull_mark: saves.SavePullMark | None,
*,
save: bool = True,
) -> None:
"""Run every teardown's steps, in order, once it holds the container."""
stopped = await quiesce_container(container, session, save=save)
await close_session_record(session_key, session)
await collect_exit_state(container, session, stopped.state_slot)
await collect_exit_saves(container, session, pull_mark, settled=stopped.settled)
async def teardown_released_session(
container: ResolvedContainer,
session: StreamingSession,
session_key: str,
platform: str,
*,
acting_user_id: int,
acting_username: str,
reason: str | None,
save: bool = True,
) -> None:
"""Stop the emulator, evacuate the card, then release the claim.
Ordering is load-bearing (see the inline notes). Runs detached from the
release request; every step is best-effort so a teardown hiccup cannot wedge
the claim, which the stale-session takeover reclaims if this never finishes.
"""
# Take the claim into a drain marker first. Everything below runs detached
# and blocks on the broker for as long as the emulator takes to die, so a
# takeover landing in that window would otherwise have its emulator stopped
# and its claim deleted along with the session it replaced.
try:
token = await claim_drain_marker(session_key, session)
except StreamingSessionContended:
# The claim is still ours, it just could not be marked: it is what
# reserves the container below, and the delete at the end is guarded on
# it anyway.
log.error("could not drain released session %s", session_key)
token = None
else:
if token is None:
log.warning("skipping teardown, session %s was taken over", session_key)
return
keepalive = _hold_reservation(session_key, token, session)
pull_mark: saves.SavePullMark | None = None
try:
# Before anything slow: on a pool the player's next claim can land on a
# free sibling while this container drains.
pull_mark = await mark_exit_saves_pending(container, session)
# A force-release rather than the player quitting: another user, or a reason,
# which only the admin panel sends. Before the quiesce, so a poll finds it.
if session.get("user_id") != acting_user_id or reason is not None:
await record_termination(
session,
session_key,
ended_by=acting_username,
reason=reason,
ended_by_user_id=acting_user_id,
)
log.info(
"session force-released, platform=%s by=%s user_id=%s reason=%s",
platform,
acting_username,
session.get("user_id"),
reason or "-",
)
# The marker, or the claim it could not replace, holds the container
# throughout, so no concurrent claim can interleave.
await _stop_and_collect(container, session, session_key, pull_mark, save=save)
# The pull clears it from here.
pull_mark = None
log.info("session released, platform=%s", platform)
except Exception:
log.exception("session teardown failed, platform=%s", platform)
finally:
# The claim goes even when a step above raised. The API already told the
# caller the session was released, so a key left behind blocks every
# later claim until stale takeover or the TTL expires. A card left
# un-evacuated is recoverable, since the next claim prompts to adopt
# whatever is still on the container; a phantom claim is not.
keepalive.cancel()
await _drop_reservation(session_key, token, session)
if pull_mark is not None:
# No pull is coming, so a claim has nothing to wait for.
await saves.clear_save_pull_pending(pull_mark)
async def teardown_abandoned_session(
container: ResolvedContainer,
session_key: str,
session: StreamingSession,
*,
claimed_by: int | None,
) -> bool:
"""Free a container whose owner vanished without releasing (heartbeat went
stale). Same order as an owner release: stop the emulator so the card is
quiescent, evacuate and wipe it, credit the owner's playtime, then drop
the claim.
Args:
claimed_by: the user whose claim found the session, None for the reaper.
Returns:
Whether the emulator was stopped: False when the session stopped looking
abandoned first, or a step before the stop failed and it was put back.
"""
# Claim the teardown before touching the broker. The work below runs for
# seconds, and the staleness check that led here is older still, so without
# the marker a heartbeat landing in that window would refresh a claim whose
# container is already being wiped. Re-checking staleness under the same
# watch is what makes the decision current rather than the caller's, and the
# marker's own token is what keeps a second claim from running all of this
# a second time over the same container.
token = secrets.token_hex(8)
try:
marked = await replace_session_if(
session_key,
lambda current: session_is_stale(current) and same_claim(current, session),
drain_marker(token),
DRAIN_MARKER_TTL,
)
except StreamingSessionContended:
# Somebody is writing to this key, so it is not the derelict session
# this path exists to clean up.
return False
if not marked:
return False
keepalive = asyncio.ensure_future(hold_drain_marker(session_key, token))
pull_mark: saves.SavePullMark | None = None
stopping = False
try:
# Before anything slow, as a release does.
pull_mark = await mark_exit_saves_pending(container, session)
# That tab may still be showing the stream, so leave a force-release's note,
# but not for the owner coming back, whose new tab it would end.
if session.get("user_id") != claimed_by:
await record_termination(
session, session_key, ended_by=None, reason="abandoned"
)
stopping = True
await _stop_and_collect(container, session, session_key, pull_mark)
pull_mark = None
except Exception:
log.exception("abandoned session teardown failed, key=%s", session_key)
finally:
keepalive.cancel()
# Past the stop, free the container rather than park it until the marker
# lapses. Before it, a claim would launch over the running emulator.
if stopping:
await drop_drain_marker(session_key, token)
else:
await restore_drained_session(session_key, token, session)
if pull_mark is not None:
await saves.clear_save_pull_pending(pull_mark)
return stopping
# How long a claim waits for stale sessions to be torn down before it gives up.
# The teardown stops a broker, evacuates and wipes a card and pulls the exit
# state, each with its own timeout and retries, so on a sick container it can
# run for minutes. A claim is an interactive request and must not, so this is
# the budget for the whole sweep rather than for each container in it.
ABANDONED_TEARDOWN_WAIT = 30.0
async def await_teardown_within_budget(
container: ResolvedContainer,
session_key: str,
session: StreamingSession,
budget: float,
*,
claimed_by: int,
) -> bool:
"""Tear down an abandoned session, but only wait `budget` seconds for it.
A teardown that overruns keeps running, shielded, and frees the container
when it lands. It is never cancelled part-way: the card evacuation and the
state pull are the abandoned player's only copies, and the drain marker
this leaves behind blocks a claim until the teardown drops it.
"""
task = background.spawn_sync_task(
teardown_abandoned_session(
container, session_key, session, claimed_by=claimed_by
)
)
try:
return await asyncio.wait_for(asyncio.shield(task), timeout=budget)
except asyncio.TimeoutError:
log.warning(
"stale session teardown is taking too long, leaving it to finish, key=%s",
session_key,
)
return False