Files
romm/backend/handler/database/snapshots_handler.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

1295 lines
45 KiB
Python

import uuid
from collections.abc import Collection, Mapping, Sequence
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any
from sqlalchemy import (
ColumnElement,
Exists,
Insert,
and_,
delete,
exists,
func,
or_,
select,
update,
)
from sqlalchemy.dialects import mysql as sa_mysql
from sqlalchemy.dialects import postgresql as sa_pg
from sqlalchemy.orm import Session
from decorators.database import INJECTED_SESSION, begin_session
from handler.snapshots.file_key import FileKey
from handler.snapshots.legacy import (
channel_label,
may_load,
slot_for_label,
sync_key,
)
from handler.snapshots.manifest import Resolved, SaveEntry
from models.assets import Save, SaveFormat, Screenshot, State
from models.channel import Channel
from models.device import Device
from models.device_channel_sync import DeviceChannelSync
from models.rom import Rom, RomFile
from models.snapshot import Snapshot, SnapshotKind, SnapshotPin, SnapshotState
from utils.database import is_postgresql
from .base_handler import DBBaseHandler
@dataclass
class ReleasedContent:
"""Rows deleted with the snapshots that held them, whose files the caller removes."""
saves: list[Save] = field(default_factory=list)
states: list[State] = field(default_factory=list)
screenshots: list[Screenshot] = field(default_factory=list)
@dataclass(frozen=True)
class SlotHead:
"""A legacy slot's channel current: the save it serves, and since when."""
save: Save
channel_id: uuid.UUID
snapshot_id: int
current_since: datetime
@dataclass
class ChannelVersions:
"""The save hashes a channel has held as its current, and those its branches hold."""
currents: set[str] = field(default_factory=set)
branches: set[str] = field(default_factory=set)
@dataclass
class StoredContent:
"""A snapshot's content rows, keyed the way its manifest is."""
save: Save | None = None
states: dict[str, dict[str, State]] = field(default_factory=dict)
@property
def state_rows(self) -> list[State]:
"""Every state the bank holds, across cores and slots."""
return [state for slots in self.states.values() for state in slots.values()]
def resolved(self) -> Resolved:
save = (
SaveEntry(
hash=self.save.content_hash or "",
shape=self.save.shape,
format=self.save.format,
)
if self.save
else None
)
bank = {
core: {slot: state.content_hash or "" for slot, state in slots.items()}
for core, slots in self.states.items()
}
return Resolved(save=save, bank=bank)
def _keyed_to(key: FileKey) -> ColumnElement[bool]:
"""Channels keyed to this file, in SQL, as `FileKey.matches` decides in Python."""
by_name = and_(
Channel.target_file_name == key.name,
Channel.target_file_size == key.size,
)
if not key.sha1:
return by_name
# A channel made before the file was hashed is still keyed by name.
return or_(
Channel.target_file_hash == key.sha1,
and_(Channel.target_file_hash.is_(None), by_name),
)
def _reattach(
session: Session,
snapshots: ColumnElement[bool],
rom_id: int,
channel_id: uuid.UUID | None = None,
) -> None:
"""Bring the detached snapshots `snapshots` selects back to `rom_id`, with
the rows they hold and, given `channel_id`, the rows filed under it."""
held_saves = select(Snapshot.save_id).where(snapshots)
held_states = (
select(SnapshotState.state_id)
.join(Snapshot, SnapshotState.snapshot_id == Snapshot.id)
.where(snapshots)
)
for model, held in ((Save, held_saves), (State, held_states)):
owned: ColumnElement[bool] = model.id.in_(held)
if channel_id is not None:
owned = or_(owned, model.channel_id == channel_id)
session.execute(
update(model)
.where(model.rom_id.is_(None), owned)
.values(rom_id=rom_id)
.execution_options(synchronize_session=False)
)
session.execute(
update(Snapshot)
.where(snapshots, Snapshot.rom_id.is_(None))
.values(rom_id=rom_id)
.execution_options(synchronize_session=False)
)
def link_channels_to_files(
session: Session, rom_id: int, platform_id: int, files: Sequence[RomFile]
) -> None:
"""After a scan: reattach detached channels whose file is back, and rekey
the ROM's name-keyed channels to a hash the scan just computed."""
keys = [FileKey.of_file(rom_file) for rom_file in files]
if not keys:
return
candidates = session.scalars(
select(Channel).where(
or_(
and_(Channel.rom_id.is_(None), Channel.platform_id == platform_id),
and_(Channel.rom_id == rom_id, Channel.target_file_hash.is_(None)),
)
)
).all()
for channel in candidates:
channel_key = FileKey.of_channel(channel)
matches = [key for key in keys if channel_key.matches(key)]
if not matches:
continue
if channel.rom_id is None:
channel.rom_id = rom_id
_reattach(session, Snapshot.channel_id == channel.id, rom_id, channel.id)
if channel.target_file_hash is None:
hashed = next((key.sha1 for key in matches if key.sha1), None)
if hashed:
channel.target_file_hash = hashed
reattach_archival_snapshots(session, rom_id, [key.sha1 for key in keys if key.sha1])
def reattach_archival_snapshots(
session: Session, rom_id: int, hashes: Sequence[str]
) -> None:
"""Bring archival snapshots of a removed ROM back to `rom_id` once a scan
finds a file with the hash they were written with, content included."""
if not hashes:
return
ids = session.scalars(
select(Snapshot.id).where(
Snapshot.channel_id.is_(None),
Snapshot.rom_id.is_(None),
Snapshot.rom_sha1.in_(hashes),
)
).all()
if ids:
_reattach(session, Snapshot.id.in_(ids), rom_id)
def _stored_contents(
session: Session, snapshots: Sequence[Snapshot]
) -> dict[int, StoredContent]:
"""Each snapshot's content rows, in two queries however many there are."""
save_ids = {s.save_id for s in snapshots if s.save_id is not None}
saves = (
{
save.id: save
for save in session.scalars(select(Save).where(Save.id.in_(save_ids))).all()
}
if save_ids
else {}
)
contents = {
s.id: StoredContent(save=saves.get(s.save_id) if s.save_id else None)
for s in snapshots
}
if not contents:
return contents
rows = session.execute(
select(SnapshotState, State)
.join(State, SnapshotState.state_id == State.id)
.where(SnapshotState.snapshot_id.in_(contents.keys()))
).all()
for entry, state in rows:
contents[entry.snapshot_id].states.setdefault(entry.core, {})[
entry.slot
] = state
return contents
def _archival_holding(
session: Session, save_id: int | None, state_id: int | None
) -> Sequence[Snapshot]:
query = select(Snapshot).where(Snapshot.kind == SnapshotKind.ARCHIVAL)
if save_id is not None:
return session.scalars(query.where(Snapshot.save_id == save_id)).all()
return session.scalars(
query.join(SnapshotState, SnapshotState.snapshot_id == Snapshot.id).where(
SnapshotState.state_id == state_id
)
).all()
def release_backup(
session: Session, save_id: int | None = None, state_id: int | None = None
) -> None:
"""Take a backup row out of the archival snapshots holding it, so it can be
deleted. A snapshot left with nothing is deleted with it."""
for snapshot in _archival_holding(session, save_id, state_id):
if save_id is not None:
snapshot.save_id = None
else:
session.execute(
delete(SnapshotState).where(
SnapshotState.snapshot_id == snapshot.id,
SnapshotState.state_id == state_id,
)
)
session.flush()
session.refresh(snapshot)
content = _stored_contents(session, [snapshot])[snapshot.id]
if content.save is None and not content.states:
session.delete(snapshot)
else:
snapshot.digest = content.resolved().digest
session.flush()
def refresh_backup_digests(
session: Session, save_id: int | None = None, state_id: int | None = None
) -> None:
"""Recompute the digest of each archival snapshot holding a backup whose bytes changed."""
for snapshot in _archival_holding(session, save_id, state_id):
snapshot.digest = (
_stored_contents(session, [snapshot])[snapshot.id].resolved().digest
)
session.flush()
def channel_for_slot(
session: Session, user_id: int, rom_id: int, slot: str, create: bool = True
) -> uuid.UUID | None:
"""The channel a legacy upload to `slot` files its save under, created on
first use when `create` is set. A linked slot keeps its channel."""
label = channel_label(slot)
if label is None:
return None
linked = session.scalar(
select(Save.channel_id)
.where(
Save.user_id == user_id,
Save.rom_id == rom_id,
Save.slot == slot,
Save.channel_id.is_not(None),
)
.order_by(Save.updated_at.desc())
.limit(1)
)
if linked is not None:
return linked
platform_id = session.scalar(select(Rom.platform_id).where(Rom.id == rom_id))
key = sync_key(session.scalars(select(RomFile).where(RomFile.rom_id == rom_id)))
if platform_id is None or key is None:
return None
existing = session.scalar(
select(Channel.id)
.where(
Channel.user_id == user_id,
Channel.platform_id == platform_id,
# Clients vary a slot's case; MariaDB's collation ignores it, PostgreSQL's doesn't.
func.lower(Channel.label) == label.lower(),
_keyed_to(key),
)
.order_by(Channel.created_at)
.limit(1)
)
if existing is not None or not create:
return existing
channel = key.new_channel(user_id, rom_id, platform_id, label)
session.add(channel)
session.flush()
return channel.id
_FREEZING_KINDS = (SnapshotKind.CHANNEL, SnapshotKind.BRANCH)
_PINNED = exists().where(SnapshotPin.snapshot_id == Snapshot.id)
def _held_ids(
session: Session,
model: type[Save | State],
ids: Collection[int],
kinds: Sequence[SnapshotKind] | None = None,
) -> set[int]:
"""Which of these save or state rows a snapshot holds, of `kinds` when given."""
if not ids:
return set()
query = (
select(Snapshot.save_id).where(Snapshot.save_id.in_(ids))
if model is Save
else select(SnapshotState.state_id)
.join(Snapshot, SnapshotState.snapshot_id == Snapshot.id)
.where(SnapshotState.state_id.in_(ids))
)
if kinds is not None:
query = query.where(Snapshot.kind.in_(kinds))
return {id for id in session.scalars(query.distinct()).all() if id is not None}
def _upsert_device_sync(
session: Session, rows: Sequence[Mapping[str, Any]], update: Sequence[str]
) -> None:
"""Insert device sync rows, setting `update` from the new row where one exists."""
upsert: Insert
if is_postgresql(session.get_bind()):
pg_insert = sa_pg.insert(DeviceChannelSync).values(rows)
upsert = pg_insert.on_conflict_do_update(
index_elements=["device_id", "channel_id"],
set_={name: pg_insert.excluded[name] for name in update},
)
else:
mysql_insert = sa_mysql.insert(DeviceChannelSync).values(rows)
upsert = mysql_insert.on_duplicate_key_update(
{name: mysql_insert.inserted[name] for name in update}
)
session.execute(upsert)
def held_save_ids(session: Session, save_ids: Collection[int]) -> set[int]:
return _held_ids(session, Save, save_ids)
def _held_by_hash[ContentT: (Save, State)](
session: Session,
model: type[ContentT],
held: Exists,
user_id: int,
rom_id: int,
hashes: Collection[str],
) -> dict[str, ContentT]:
"""The oldest of the user's `held` rows on a ROM for each content hash."""
if not hashes:
return {}
# A row no snapshot holds may still be overwritten by a legacy writer.
rows = session.scalars(
select(model)
.where(
model.user_id == user_id,
model.rom_id == rom_id,
model.content_hash.in_(hashes),
held,
)
.order_by(model.id)
).all()
found: dict[str, ContentT] = {}
for row in rows:
if row.content_hash:
found.setdefault(row.content_hash, row)
return found
class DBSnapshotsHandler(DBBaseHandler):
@begin_session
def slot_heads(
self,
user_id: int,
slots: Collection[tuple[int, str]],
emulators: Collection[str | None] | None = None,
cores: Collection[str | None] | None = None,
include_hardcore: bool = True,
session: Session = INJECTED_SESSION,
) -> dict[tuple[int, str], SlotHead]:
"""The current of each legacy slot's channel by (rom_id, slot), leaving
out neutral saves and any `may_load` rules out for the client."""
rom_ids = {rom_id for rom_id, _ in slots}
if not rom_ids:
return {}
kept = set(
session.scalars(
select(Channel.rom_id).where(
Channel.user_id == user_id,
Channel.rom_id.in_(rom_ids),
Channel.current_snapshot_id.is_not(None),
)
).all()
)
heads: dict[tuple[int, str], SlotHead] = {}
for rom_id, slot in slots:
if rom_id not in kept:
continue
channel_id = channel_for_slot(session, user_id, rom_id, slot, create=False)
if channel_id is None:
continue
query = (
select(Save, Snapshot.id, Snapshot.created_at)
.join(Snapshot, Snapshot.save_id == Save.id)
.join(Channel, Channel.current_snapshot_id == Snapshot.id)
.where(
Channel.id == channel_id,
or_(Save.format.is_(None), Save.format == SaveFormat.NATIVE),
)
)
if not include_hardcore:
query = query.where(Channel.is_hardcore.is_(False))
row = session.execute(query).first()
if row is None or not may_load(row[0], emulators, cores):
continue
save, snapshot_id, current_since = row
heads[(rom_id, slot)] = SlotHead(
save, channel_id, snapshot_id, current_since
)
return heads
@begin_session
def channel_slots(
self,
user_id: int,
rom_ids: Collection[int] | None,
session: Session = INJECTED_SESSION,
) -> set[tuple[int, str]]:
"""The (rom_id, slot) each of the user's channels with a current answers
to, on `rom_ids` or every ROM: its newest linked slot, else its label's."""
query = select(Channel.id, Channel.rom_id, Channel.label).where(
Channel.user_id == user_id,
Channel.rom_id.is_not(None),
Channel.current_snapshot_id.is_not(None),
)
if rom_ids is not None:
query = query.where(Channel.rom_id.in_(rom_ids))
channels = session.execute(query).all()
if not channels:
return set()
linked: dict[uuid.UUID, str] = {}
for channel_id, slot in session.execute(
select(Save.channel_id, Save.slot)
.where(
Save.channel_id.in_([channel_id for channel_id, _, _ in channels]),
Save.slot.is_not(None),
)
.order_by(Save.updated_at.desc())
).all():
if channel_id is not None and slot:
linked.setdefault(channel_id, slot)
return {
(rom_id, linked.get(channel_id) or slot_for_label(label))
for channel_id, rom_id, label in channels
if rom_id is not None
}
@begin_session
def channel_versions(
self,
channel_ids: Collection[uuid.UUID],
session: Session = INJECTED_SESSION,
) -> dict[uuid.UUID, ChannelVersions]:
"""The save hashes each channel has held as its current, and its branches'."""
versions: dict[uuid.UUID, ChannelVersions] = {
channel_id: ChannelVersions() for channel_id in channel_ids
}
if not versions:
return versions
rows = session.execute(
select(Snapshot.channel_id, Snapshot.kind, Save.content_hash)
.join(Save, Save.id == Snapshot.save_id)
.where(
Snapshot.channel_id.in_(versions),
Snapshot.kind.in_(_FREEZING_KINDS),
Save.content_hash.is_not(None),
)
).all()
for channel_id, kind, content_hash in rows:
if channel_id is None or content_hash is None:
continue
held = versions[channel_id]
target = held.branches if kind == SnapshotKind.BRANCH else held.currents
target.add(content_hash)
return versions
@begin_session
def device_bases(
self,
device_id: str,
channel_ids: Collection[uuid.UUID],
session: Session = INJECTED_SESSION,
) -> dict[uuid.UUID, int]:
"""The snapshot the device holds in each channel it has a record of."""
if not channel_ids:
return {}
rows = session.execute(
select(
DeviceChannelSync.channel_id, DeviceChannelSync.base_snapshot_id
).where(
DeviceChannelSync.device_id == device_id,
DeviceChannelSync.channel_id.in_(channel_ids),
DeviceChannelSync.base_snapshot_id.is_not(None),
)
).all()
return {
channel_id: base_id for channel_id, base_id in rows if base_id is not None
}
@begin_session
def record_device_holds_save(
self, device_id: str, save: Save, session: Session = INJECTED_SESSION
) -> None:
"""Record the device as holding its channel's current, when `save` is it."""
if save.channel_id is None:
return
current_id = session.scalar(
select(Channel.current_snapshot_id)
.join(Snapshot, Snapshot.id == Channel.current_snapshot_id)
.where(Channel.id == save.channel_id, Snapshot.save_id == save.id)
)
if current_id is not None:
self.record_device_base(
device_id, save.channel_id, current_id, session=session
)
@begin_session
def get_snapshot(
self, id: int, session: Session = INJECTED_SESSION
) -> Snapshot | None:
return session.get(Snapshot, id)
@begin_session
def get_channel(
self, id: uuid.UUID, session: Session = INJECTED_SESSION
) -> Channel | None:
return session.get(Channel, id)
@begin_session
def lock_channel(
self, id: uuid.UUID, session: Session = INJECTED_SESSION
) -> Channel | None:
"""The channel, locked until the caller's transaction ends."""
return session.scalar(select(Channel).where(Channel.id == id).with_for_update())
@begin_session
def get_stored_content(
self, snapshot: Snapshot, session: Session = INJECTED_SESSION
) -> StoredContent:
return self.get_stored_contents([snapshot], session=session)[snapshot.id]
@begin_session
def get_stored_contents(
self, snapshots: Sequence[Snapshot], session: Session = INJECTED_SESSION
) -> dict[int, StoredContent]:
return _stored_contents(session, snapshots)
@begin_session
def get_saves_by_hash(
self,
user_id: int,
rom_id: int,
hashes: Collection[str],
channel_id: uuid.UUID | None = None,
session: Session = INJECTED_SESSION,
) -> dict[str, Save]:
"""The user's snapshot-held saves on a ROM by content hash, only those
`channel_id`'s snapshots hold when given."""
held = exists().where(Snapshot.save_id == Save.id)
if channel_id is not None:
held = held.where(Snapshot.channel_id == channel_id)
return _held_by_hash(session, Save, held, user_id, rom_id, hashes)
@begin_session
def get_states_by_hash(
self,
user_id: int,
rom_id: int,
hashes: Collection[str],
channel_id: uuid.UUID | None = None,
session: Session = INJECTED_SESSION,
) -> dict[str, State]:
"""The user's snapshot-held states on a ROM by content hash, only those
`channel_id`'s snapshots hold when given."""
held = exists().where(SnapshotState.state_id == State.id)
if channel_id is not None:
held = held.where(
SnapshotState.snapshot_id.in_(
select(Snapshot.id).where(Snapshot.channel_id == channel_id)
)
)
return _held_by_hash(session, State, held, user_id, rom_id, hashes)
@begin_session
def get_channels_for_file(
self,
user_id: int,
platform_id: int,
key: FileKey,
session: Session = INJECTED_SESSION,
) -> Sequence[Channel]:
"""The user's channels on a file: by hash, or by name and size for unhashed ones."""
return session.scalars(
select(Channel)
.where(
Channel.user_id == user_id,
Channel.platform_id == platform_id,
_keyed_to(key),
)
.order_by(Channel.updated_at.desc())
).all()
@begin_session
def get_channels_for_rom(
self, rom_id: int, user_id: int, session: Session = INJECTED_SESSION
) -> Sequence[Channel]:
"""The user's channels on a ROM, then other users' public ones."""
return session.scalars(
select(Channel)
.where(
Channel.rom_id == rom_id,
or_(Channel.user_id == user_id, Channel.is_public.is_(True)),
)
.order_by((Channel.user_id != user_id), Channel.updated_at.desc())
).all()
@begin_session
def get_detached_channels(
self, user_id: int, platform_id: int, session: Session = INJECTED_SESSION
) -> Sequence[Channel]:
"""The user's channels on a platform whose ROM was removed and no scan
has found again."""
return session.scalars(
select(Channel)
.where(
Channel.user_id == user_id,
Channel.platform_id == platform_id,
Channel.rom_id.is_(None),
)
.order_by(Channel.updated_at.desc())
).all()
@begin_session
def attach_channel(
self,
channel_id: uuid.UUID,
rom_file: RomFile,
session: Session = INJECTED_SESSION,
) -> Channel:
"""Key a detached channel to `rom_file` and bring its content back to
that file's ROM."""
channel = session.get_one(Channel, channel_id)
channel.rom_id = rom_file.rom_id
for column, value in FileKey.of_file(rom_file).channel_columns().items():
setattr(channel, column, value)
_reattach(
session, Snapshot.channel_id == channel_id, rom_file.rom_id, channel_id
)
session.flush()
return channel
@begin_session
def count_snapshots_by_channel(
self, channel_ids: Collection[uuid.UUID], session: Session = INJECTED_SESSION
) -> dict[uuid.UUID, int]:
if not channel_ids:
return {}
rows = session.execute(
select(Snapshot.channel_id, func.count(Snapshot.id))
.where(Snapshot.channel_id.in_(channel_ids))
.group_by(Snapshot.channel_id)
).all()
return {channel_id: count for channel_id, count in rows if channel_id}
@begin_session
def get_snapshots(
self, ids: Collection[int], session: Session = INJECTED_SESSION
) -> dict[int, Snapshot]:
if not ids:
return {}
return {
snapshot.id: snapshot
for snapshot in session.scalars(
select(Snapshot).where(Snapshot.id.in_(ids))
).all()
}
@begin_session
def get_devices(
self, ids: Collection[str], session: Session = INJECTED_SESSION
) -> dict[str, Device]:
if not ids:
return {}
return {
device.id: device
for device in session.scalars(
select(Device).where(Device.id.in_(ids))
).all()
}
@begin_session
def add_channel(
self, channel: Channel, session: Session = INJECTED_SESSION
) -> Channel:
session.add(channel)
session.flush()
return channel
@begin_session
def get_channel_history(
self,
channel_id: uuid.UUID,
limit: int,
before_id: int | None = None,
save_target: str | None = None,
session: Session = INJECTED_SESSION,
) -> Sequence[Snapshot]:
query = select(Snapshot).where(Snapshot.channel_id == channel_id)
if before_id is not None:
query = query.where(Snapshot.id < before_id)
if save_target is not None:
query = query.where(Snapshot.save_target == save_target)
return session.scalars(query.order_by(Snapshot.id.desc()).limit(limit)).all()
@begin_session
def get_holders_by_snapshot(
self,
snapshot_ids: Collection[int],
user_id: int,
session: Session = INJECTED_SESSION,
) -> dict[int, list[tuple[DeviceChannelSync, Device]]]:
"""The user's own devices whose last sync in the channel was each
snapshot, by snapshot id, in one query."""
if not snapshot_ids:
return {}
rows = session.execute(
select(DeviceChannelSync, Device)
.join(Device, DeviceChannelSync.device_id == Device.id)
.where(
DeviceChannelSync.base_snapshot_id.in_(snapshot_ids),
Device.user_id == user_id,
)
.order_by(DeviceChannelSync.synced_at.desc())
).all()
holders: dict[int, list[tuple[DeviceChannelSync, Device]]] = {}
for sync, device in rows:
if sync.base_snapshot_id is not None:
holders.setdefault(sync.base_snapshot_id, []).append((sync, device))
return holders
@begin_session
def get_pins(
self,
snapshot_ids: Collection[int],
user_id: int,
session: Session = INJECTED_SESSION,
) -> tuple[dict[int, int], set[int]]:
"""How many users pinned each snapshot, and which of them `user_id` pinned."""
if not snapshot_ids:
return {}, set()
rows = session.execute(
select(SnapshotPin.snapshot_id, SnapshotPin.user_id).where(
SnapshotPin.snapshot_id.in_(snapshot_ids)
)
).all()
counts: dict[int, int] = {}
mine: set[int] = set()
for snapshot_id, pinner in rows:
counts[snapshot_id] = counts.get(snapshot_id, 0) + 1
if pinner == user_id:
mine.add(snapshot_id)
return counts, mine
@begin_session
def set_pin(
self,
snapshot_id: int,
user_id: int,
pinned: bool,
session: Session = INJECTED_SESSION,
) -> None:
pin = session.get(SnapshotPin, (snapshot_id, user_id))
if pinned and pin is None:
session.add(SnapshotPin(snapshot_id=snapshot_id, user_id=user_id))
elif not pinned and pin is not None:
session.delete(pin)
session.flush()
@begin_session
def drop_foreign_pins(
self,
owner_id: int,
channel_id: uuid.UUID | None = None,
snapshot_id: int | None = None,
session: Session = INJECTED_SESSION,
) -> None:
"""Delete every pin but the owner's on a channel's snapshots, or on one
snapshot, once other users can no longer read them."""
held = (
select(Snapshot.id).where(Snapshot.channel_id == channel_id)
if channel_id is not None
else select(Snapshot.id).where(Snapshot.id == snapshot_id)
)
session.execute(
delete(SnapshotPin)
.where(SnapshotPin.snapshot_id.in_(held), SnapshotPin.user_id != owner_id)
.execution_options(synchronize_session=False)
)
@begin_session
def get_thumbnails(
self,
save_ids: Collection[int],
state_ids: Collection[int],
session: Session = INJECTED_SESSION,
) -> tuple[dict[int, Screenshot], dict[int, Screenshot]]:
"""Screenshots linked to these saves and states, by row id."""
by_save: dict[int, Screenshot] = {}
by_state: dict[int, Screenshot] = {}
if not save_ids and not state_ids:
return by_save, by_state
rows = session.scalars(
select(Screenshot).where(
or_(
Screenshot.save_id.in_(save_ids),
Screenshot.state_id.in_(state_ids),
)
)
).all()
for shot in rows:
if shot.save_id is not None:
by_save[shot.save_id] = shot
if shot.state_id is not None:
by_state[shot.state_id] = shot
return by_save, by_state
@begin_session
def get_channel_file(
self, channel: Channel, session: Session = INJECTED_SESSION
) -> RomFile | None:
"""The library file a channel is keyed to today, if its ROM still holds one."""
return self.get_channel_files([channel], session=session).get(channel.id)
@begin_session
def get_channel_files(
self, channels: Collection[Channel], session: Session = INJECTED_SESSION
) -> dict[uuid.UUID, RomFile]:
"""`get_channel_file` for each channel that has one, by channel id."""
rom_ids = {c.rom_id for c in channels if c.rom_id is not None}
if not rom_ids:
return {}
files_by_rom: dict[int, list[RomFile]] = {}
for rom_file in session.scalars(
select(RomFile).where(RomFile.rom_id.in_(rom_ids)).order_by(RomFile.id)
).all():
files_by_rom.setdefault(rom_file.rom_id, []).append(rom_file)
found: dict[uuid.UUID, RomFile] = {}
for channel in channels:
key = FileKey.of_channel(channel)
match = next(
(
rom_file
for rom_file in files_by_rom.get(channel.rom_id or -1, [])
if key.matches(FileKey.of_file(rom_file))
),
None,
)
if match is not None:
found[channel.id] = match
return found
@begin_session
def sync_content_visibility(
self,
save_ids: Collection[int],
state_ids: Collection[int],
session: Session = INJECTED_SESSION,
) -> None:
"""Set each row and its screenshot public exactly when a public channel or
public archival snapshot holds the row."""
shared = or_(
Channel.is_public.is_(True),
and_(Snapshot.kind == SnapshotKind.ARCHIVAL, Snapshot.is_public.is_(True)),
)
public_saves = set(
session.scalars(
select(Snapshot.save_id)
.outerjoin(Channel, Snapshot.channel_id == Channel.id)
.where(Snapshot.save_id.in_(save_ids), shared)
).all()
)
public_states = set(
session.scalars(
select(SnapshotState.state_id)
.join(Snapshot, SnapshotState.snapshot_id == Snapshot.id)
.outerjoin(Channel, Snapshot.channel_id == Channel.id)
.where(SnapshotState.state_id.in_(state_ids), shared)
).all()
)
for model, column, ids, public in (
(Save, Save.id, save_ids, public_saves),
(State, State.id, state_ids, public_states),
(Screenshot, Screenshot.save_id, save_ids, public_saves),
(Screenshot, Screenshot.state_id, state_ids, public_states),
):
if ids:
session.execute(
update(model)
.where(column.in_(ids))
.values(is_public=column.in_(public))
.execution_options(synchronize_session=False)
)
@begin_session
def get_content_ids(
self, channel_id: uuid.UUID, session: Session = INJECTED_SESSION
) -> tuple[set[int], set[int]]:
"""Every save and state row a channel's snapshots hold."""
save_ids = set(
session.scalars(
select(Snapshot.save_id).where(
Snapshot.channel_id == channel_id, Snapshot.save_id.is_not(None)
)
).all()
)
state_ids = set(
session.scalars(
select(SnapshotState.state_id)
.join(Snapshot, SnapshotState.snapshot_id == Snapshot.id)
.where(Snapshot.channel_id == channel_id)
).all()
)
return {i for i in save_ids if i is not None}, state_ids
def _delete_snapshots(
self, session: Session, ids: Sequence[int]
) -> ReleasedContent:
"""Delete snapshots, then the content rows and screenshots only they held.
A row another snapshot still holds stays public only while a shared one does."""
if not ids:
return ReleasedContent()
save_ids = set(
session.scalars(
select(Snapshot.save_id).where(
Snapshot.id.in_(ids), Snapshot.save_id.is_not(None)
)
).all()
)
state_ids = set(
session.scalars(
select(SnapshotState.state_id).where(SnapshotState.snapshot_id.in_(ids))
).all()
)
session.execute(
delete(Snapshot)
.where(Snapshot.id.in_(ids))
.execution_options(synchronize_session=False)
)
released = ReleasedContent(
saves=list(
session.scalars(
select(Save).where(
Save.id.in_(save_ids),
~exists().where(Snapshot.save_id == Save.id),
)
).all()
),
states=list(
session.scalars(
select(State).where(
State.id.in_(state_ids),
~exists().where(SnapshotState.state_id == State.id),
)
).all()
),
)
save_shots, state_shots = self.get_thumbnails(
[save.id for save in released.saves],
[state.id for state in released.states],
session=session,
)
released.screenshots = [*save_shots.values(), *state_shots.values()]
for model, rows in (
(Screenshot, released.screenshots),
(Save, released.saves),
(State, released.states),
):
if rows:
session.execute(
delete(model)
.where(model.id.in_([row.id for row in rows]))
.execution_options(synchronize_session=False)
)
gone_saves = {save.id for save in released.saves}
gone_states = {state.id for state in released.states}
self.sync_content_visibility(
{
save_id
for save_id in save_ids
if save_id is not None and save_id not in gone_saves
},
state_ids - gone_states,
session=session,
)
return released
@begin_session
def prune_channel(
self, channel_id: uuid.UUID, keep: int, session: Session = INJECTED_SESSION
) -> ReleasedContent:
"""Delete the channel's unpinned snapshots past its newest `keep`, never the
current. A detached channel keeps everything."""
channel = session.get(Channel, channel_id, with_for_update=True)
if channel is None or channel.rom_id is None:
return ReleasedContent()
candidates = session.scalars(
select(Snapshot.id)
.where(
Snapshot.channel_id == channel_id,
Snapshot.kind == SnapshotKind.CHANNEL,
~_PINNED,
)
.order_by(Snapshot.id.desc())
).all()
doomed = [id for id in candidates[keep:] if id != channel.current_snapshot_id]
return self._delete_snapshots(session, doomed)
@begin_session
def prune_branches(
self, older_than: datetime, session: Session = INJECTED_SESSION
) -> ReleasedContent:
"""Delete branches created before `older_than`, except in detached channels."""
doomed = session.scalars(
select(Snapshot.id)
.join(Channel, Snapshot.channel_id == Channel.id)
.where(
Snapshot.kind == SnapshotKind.BRANCH,
~_PINNED,
Snapshot.created_at < older_than,
Channel.rom_id.is_not(None),
)
).all()
return self._delete_snapshots(session, doomed)
@begin_session
def prune_unreachable_archival(
self, session: Session = INJECTED_SESSION
) -> ReleasedContent:
"""Delete archival snapshots with no ROM and no file hash: no view lists
them and no scan can bring them back."""
doomed = session.scalars(
select(Snapshot.id).where(
Snapshot.kind == SnapshotKind.ARCHIVAL,
Snapshot.rom_id.is_(None),
Snapshot.rom_sha1.is_(None),
)
).all()
return self._delete_snapshots(session, doomed)
@begin_session
def update_channel(
self,
id: uuid.UUID,
data: dict[str, Any],
session: Session = INJECTED_SESSION,
) -> Channel:
"""Write `data` onto a channel, carrying a visibility change to its
content rows and to other users' pins."""
channel = session.get_one(Channel, id)
for key, value in data.items():
setattr(channel, key, value)
session.flush()
if "is_public" in data:
self.sync_content_visibility(
*self.get_content_ids(id, session=session), session=session
)
if not channel.is_public:
self.drop_foreign_pins(channel.user_id, channel_id=id, session=session)
return channel
@begin_session
def delete_channel(
self, id: uuid.UUID, session: Session = INJECTED_SESSION
) -> ReleasedContent:
"""Delete a channel, keeping its current and the owner's pinned snapshots
as archival unless it is detached. Legacy saves filed under it become backups.
"""
channel = session.get_one(Channel, id, with_for_update=True)
owner_pinned = exists().where(
SnapshotPin.snapshot_id == Snapshot.id,
SnapshotPin.user_id == channel.user_id,
)
reachable = channel.rom_id is not None
kept = (
session.scalars(
select(Snapshot).where(
Snapshot.channel_id == id,
or_(Snapshot.id == channel.current_snapshot_id, owner_pinned),
)
).all()
if reachable
else []
)
for snapshot in kept:
snapshot.channel_id = None
snapshot.kind = SnapshotKind.ARCHIVAL
snapshot.is_public = channel.is_public
# A snapshot written before a scan hashed the file carries no hash to reattach by.
snapshot.rom_sha1 = snapshot.rom_sha1 or channel.target_file_hash
channel.current_snapshot_id = None
session.flush()
released = self._delete_snapshots(
session,
session.scalars(select(Snapshot.id).where(Snapshot.channel_id == id)).all(),
)
session.delete(channel)
session.flush()
return released
@begin_session
def update_snapshot(
self,
id: int,
data: dict[str, Any],
session: Session = INJECTED_SESSION,
) -> Snapshot:
"""Write `data` onto a snapshot, carrying a visibility change to its
content rows and to other users' pins."""
snapshot = session.get_one(Snapshot, id)
for key, value in data.items():
setattr(snapshot, key, value)
session.flush()
if "is_public" in data:
if not snapshot.is_public:
self.drop_foreign_pins(
snapshot.user_id, snapshot_id=id, session=session
)
content = self.get_stored_content(snapshot, session=session)
self.sync_content_visibility(
[content.save.id] if content.save else [],
[state.id for state in content.state_rows],
session=session,
)
return snapshot
@begin_session
def record_device_base(
self,
device_id: str,
channel_id: uuid.UUID,
snapshot_id: int,
session: Session = INJECTED_SESSION,
) -> None:
"""Record the snapshot the device holds in the channel, and the
channel's current as the one it knows."""
now = datetime.now(timezone.utc)
channel = session.get(Channel, channel_id)
current = channel.current_snapshot_id if channel is not None else None
_upsert_device_sync(
session,
[
{
"device_id": device_id,
"channel_id": channel_id,
"base_snapshot_id": snapshot_id,
"synced_at": now,
"latest_known_id": current,
"updated_at": now,
}
],
["base_snapshot_id", "synced_at", "latest_known_id", "updated_at"],
)
self._touch_device(session, device_id, now)
@begin_session
def record_device_seen(
self,
device_id: str,
currents: Mapping[uuid.UUID, int | None],
session: Session = INJECTED_SESSION,
) -> None:
"""Record each channel's current, by channel id, as the one the device
knows, leaving what it holds, and since when, as it was."""
if not currents:
return
now = datetime.now(timezone.utc)
_upsert_device_sync(
session,
[
{
"device_id": device_id,
"channel_id": channel_id,
# A new row holds nothing; synced_at only needs a value.
"synced_at": now,
"latest_known_id": current_id,
"updated_at": now,
}
for channel_id, current_id in currents.items()
],
["latest_known_id", "updated_at"],
)
self._touch_device(session, device_id, now)
@staticmethod
def _touch_device(session: Session, device_id: str, now: datetime) -> None:
session.execute(
update(Device)
.where(Device.id == device_id)
.values(last_seen=now)
.execution_options(synchronize_session=False)
)
@begin_session
def get_device_sync(
self,
device_id: str,
channel_id: uuid.UUID,
session: Session = INJECTED_SESSION,
) -> DeviceChannelSync | None:
return session.get(DeviceChannelSync, (device_id, channel_id))
@begin_session
def clear_device_sync(
self,
device_id: str,
channel_id: uuid.UUID,
session: Session = INJECTED_SESSION,
) -> None:
session.execute(
delete(DeviceChannelSync).where(
DeviceChannelSync.device_id == device_id,
DeviceChannelSync.channel_id == channel_id,
)
)
@begin_session
def get_held_save_ids(
self, save_ids: Collection[int], session: Session = INJECTED_SESSION
) -> set[int]:
"""Which of these saves a snapshot holds."""
return held_save_ids(session, save_ids)
def is_asset_frozen(self, asset: Save | State) -> bool:
"""Whether a channel or branch snapshot holds the row, so its bytes must not change."""
return bool(self.get_frozen_ids([asset])) # type: ignore[arg-type]
def get_frozen_ids(self, assets: Sequence[Save] | Sequence[State]) -> set[int]:
"""The ids of the saves, or of the states, a channel or branch snapshot holds."""
ids = [asset.id for asset in assets]
if assets and isinstance(assets[0], State):
return self.get_frozen_state_ids(ids)
return self.get_frozen_save_ids(ids)
@begin_session
def get_frozen_save_ids(
self, save_ids: Collection[int], session: Session = INJECTED_SESSION
) -> set[int]:
"""Which of these saves a channel or branch snapshot holds."""
return _held_ids(session, Save, save_ids, _FREEZING_KINDS)
@begin_session
def get_frozen_state_ids(
self, state_ids: Collection[int], session: Session = INJECTED_SESSION
) -> set[int]:
"""Which of these states a channel or branch snapshot holds."""
return _held_ids(session, State, state_ids, _FREEZING_KINDS)