Files
romm/backend/endpoints/snapshots.py
Georges-Antoine Assi 3b14dddd88 chore(prose): fix the prose-check findings on master (#5826)
The scheduled Trunk Check (all files) run fails on 79 prose-check issues
that predate the linter: clipped 'X, else Y' chains, 'internal id' in
API descriptions, and clipped 'Left out, ...' conditionals.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 08:17:01 -05:00

772 lines
27 KiB
Python

import asyncio
import json
import re
import uuid
from collections.abc import Iterable
from typing import Annotated, Any, Self
from fastapi import HTTPException
from fastapi import Path as PathVar
from fastapi import Query, Request, status
from fastapi.responses import JSONResponse
from pydantic import (
Field,
StringConstraints,
ValidationError,
model_validator,
)
from starlette.datastructures import UploadFile
from decorators.auth import protected_route
from endpoints.responses.base import BaseModel
from endpoints.responses.snapshots import (
MissingContentSchema,
SnapshotConflictSchema,
SnapshotSchema,
build_snapshot_schema,
build_snapshot_schemas,
)
from handler.auth.constants import Scope
from handler.auth.dependencies import assert_rom_visible, get_rom_visibility_filter
from handler.database import (
db_device_handler,
db_rom_handler,
db_save_handler,
db_snapshot_handler,
)
from handler.filesystem import fs_asset_handler
from handler.filesystem.assets_handler import (
UnsafeArchive,
check_upload,
save_shape_of,
)
from handler.snapshots.file_key import FileKey
from handler.snapshots.manifest import CARRY, Manifest, SaveEntry
from handler.snapshots.neutral import NeutralUnitRejected, check_neutral_unit
from handler.snapshots.shared_card import own_saves_only
from handler.snapshots.write import (
INFER,
SAVE_PART,
ChannelTarget,
ContentMismatch,
ContentMissing,
FileMismatch,
HardcoreDowngrade,
LabelRequired,
NotVisible,
Outcome,
SnapshotWrite,
UploadPart,
WriteResult,
copied_part,
write_snapshot,
)
from models.assets import (
EMULATOR_MAX_LENGTH,
EMULATOR_VERSION_MAX_LENGTH,
Save,
SaveFormat,
SaveShape,
)
from models.channel import CHANNEL_LABEL_MAX_LENGTH, Channel
from models.device import Device
from models.rom import Rom, RomFile
from models.snapshot import STATE_SLOT_MAX_LENGTH, Snapshot, SnapshotKind
from models.user import User
from utils.auth import create_or_find_web_device, require_device, token_device_id
from utils.router import APIRouter
from utils.uploads import check_asset_upload_size, check_emulator_folder_name
router = APIRouter(prefix="/snapshots", tags=["snapshots"])
HISTORY_PAGE_MAX = 100
FEED_DEVICE_DESCRIPTION = (
"The device fetching the feed, else the client token's. Listing a channel's "
"current for a device records it as the current the device knows, which a "
"push without `expected_current_id` expects. Naming one takes `devices.write`."
)
SnapshotIdPath = Annotated[int, PathVar(description="The ID of the snapshot.")]
DEVICE_FORBIDDEN = (
"The request sets `device_id` to a device other than the client token's own,"
" and the caller lacks the `devices.write` scope."
)
SCREENSHOT_SUFFIX = ":screenshot"
SAVE_SCREENSHOT_PART = "save_screenshot"
STATE_PART_PATTERN = re.compile(r"^state:([^:]+):([^:]+)$")
ContentHash = Annotated[
str, StringConstraints(pattern=r"^[0-9a-fA-F]{32}$", to_lower=True)
]
CoreName = Annotated[
str, StringConstraints(pattern=r"^[^:]+$", max_length=EMULATOR_MAX_LENGTH)
]
SlotName = Annotated[
str, StringConstraints(pattern=r"^[^:]+$", max_length=STATE_SLOT_MAX_LENGTH)
]
class SaveEntryPayload(BaseModel):
"""A save by its hash, or by `copy_of`: a save of yours the server copies in."""
hash: ContentHash | None = None
copy_of: int | None = None
shape: SaveShape | None = None
format: SaveFormat | None = None
@model_validator(mode="after")
def _one_source(self) -> Self:
if (self.hash is None) == (self.copy_of is None):
raise ValueError("a save names exactly one of `hash` and `copy_of`")
if self.hash is not None and (self.shape is None or self.format is None):
raise ValueError("a save by hash declares its `shape` and `format`")
return self
class ManifestPayload(BaseModel):
rom_file_id: int
channel_id: uuid.UUID | None = None
label: str | None = Field(
default=None, min_length=1, max_length=CHANNEL_LABEL_MAX_LENGTH
)
expected_current_id: int | None = None
"""The ID of the snapshot the push expects to be the channel's current one. Null means the push expects an empty channel. If left out, the server uses the latest current snapshot the device has seen through a feed, push or download, or else `parent_snapshot_id`, or else expects an empty channel."""
parent_snapshot_id: int | None = None
save: SaveEntryPayload | None = None
states: dict[CoreName, dict[SlotName, ContentHash]] = {}
is_hardcore: bool = False
approve_hardcore_downgrade: bool = False
emulator: str | None = Field(default=None, max_length=EMULATOR_MAX_LENGTH)
emulator_version: str | None = Field(
default=None, max_length=EMULATOR_VERSION_MAX_LENGTH
)
core: str | None = Field(default=None, max_length=EMULATOR_MAX_LENGTH)
core_version: str | None = Field(
default=None, max_length=EMULATOR_VERSION_MAX_LENGTH
)
def to_manifest(
self, copied: SaveEntry | None = None, source: Save | None = None
) -> Manifest:
"""The manifest, with `copied` standing for `copy_of` and lending its emulator when the push names none."""
ran = (self.emulator, self.emulator_version, self.core, self.core_version)
if source is not None and not any(ran):
ran = (
source.emulator,
source.emulator_version,
source.core,
source.core_version,
)
emulator, emulator_version, core, core_version = ran
save: Any = CARRY
if "save" in self.model_fields_set:
save = None
if copied is not None:
save = copied
elif self.save and self.save.hash:
save = SaveEntry(
hash=self.save.hash, shape=self.save.shape, format=self.save.format
)
return Manifest(
save=save,
states=self.states,
is_hardcore=self.is_hardcore,
approve_hardcore_downgrade=self.approve_hardcore_downgrade,
emulator=emulator,
emulator_version=emulator_version,
core=core,
core_version=core_version,
)
class SnapshotUpdatePayload(BaseModel):
is_pinned: bool | None = None
is_public: bool | None = None
def _not_found(what: str = "Snapshot") -> HTTPException:
return HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=f"{what} not found"
)
def rom_hidden(request: Request, rom_id: int | None) -> bool:
"""Whether the ROM a channel or snapshot is on is hidden from the caller,
which hides the channel and its snapshots too."""
if rom_id is None:
return False
# Channels of one file share their ROM, so a listing asks once per ROM.
known: dict[int, bool] | None = getattr(request.state, "rom_hidden", None)
if known is None:
known = request.state.rom_hidden = {}
if rom_id not in known:
rom = db_rom_handler.get_rom_visibility(rom_id)
known[rom_id] = rom is not None and not get_rom_visibility_filter(
request
).allows(rom)
return known[rom_id]
def readable_channel(request: Request, channel: Channel) -> bool:
return (channel.user_id == request.user.id or channel.is_public) and not rom_hidden(
request, channel.rom_id
)
def readable_channel_or_404(
request: Request, id: uuid.UUID, owner_only: bool = False
) -> Channel:
channel = db_snapshot_handler.get_channel(id)
if (
channel is None
or not readable_channel(request, channel)
or (owner_only and channel.user_id != request.user.id)
):
raise _not_found("Channel")
return channel
def channels_on_files(
request: Request, rom_file_ids: Iterable[int], channel_ids: Iterable[uuid.UUID]
) -> dict[uuid.UUID, Channel]:
"""The caller's readable channels on the named files, plus those named by id."""
channels: dict[uuid.UUID, Channel] = {}
file_ids = list(dict.fromkeys(rom_file_ids))
files = {f.id: f for f in db_rom_handler.get_rom_files_by_ids(file_ids)}
for file_id in file_ids:
found = files.get(file_id)
rom_file, rom = _visible_rom_file_or_404(
request, found, found.rom if found else None
)
for channel in db_snapshot_handler.get_channels_for_file(
request.user.id, rom.platform_id, FileKey.of_file(rom_file)
):
if readable_channel(request, channel):
channels[channel.id] = channel
for id in channel_ids:
channels[id] = readable_channel_or_404(request, id)
return channels
def _readable_snapshot_or_404(
request: Request, id: int
) -> tuple[Snapshot, Channel | None]:
snapshot = db_snapshot_handler.get_snapshot(id)
if snapshot is None:
raise _not_found()
channel = (
db_snapshot_handler.get_channel(snapshot.channel_id)
if snapshot.channel_id
else None
)
if not snapshot.readable_by(request.user.id, channel) or rom_hidden(
request, snapshot.rom_id
):
raise _not_found()
return snapshot, channel
def visible_rom_file(request: Request, rom_file_id: int) -> tuple[RomFile, Rom]:
rom_file = db_rom_handler.get_rom_file_by_id(rom_file_id)
rom = db_rom_handler.get_rom(rom_file.rom_id) if rom_file else None
return _visible_rom_file_or_404(request, rom_file, rom)
def _visible_rom_file_or_404(
request: Request, rom_file: RomFile | None, rom: Rom | None
) -> tuple[RomFile, Rom]:
if rom_file is None or rom is None:
raise _not_found("ROM file")
assert_rom_visible(request, rom, not_found_detail="ROM file not found")
return rom_file, rom
def _own_device(request: Request, device_id: str | None) -> Device | None:
"""The caller's device a write is attributed to. Naming one takes
`devices.write` unless it is the device the client token is bound to."""
if device_id is None:
return None
if Scope.DEVICES_WRITE not in request.auth.scopes and device_id != token_device_id(
request
):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
return require_device(request, device_id)
def request_device(request: Request, device_id: str | None) -> Device | None:
"""The device a request acts for: `device_id`, on `_own_device`'s terms,
or else the device its client token is bound to, which needs no `devices.write`."""
if device_id is not None:
return _own_device(request, device_id)
bound = token_device_id(request)
if bound is None:
return None
return db_device_handler.get_device(device_id=bound, user_id=request.user.id)
def required_device(request: Request, device_id: str | None) -> Device:
"""`request_device`, which a request that acts on a device's state needs.
Raises:
HTTPException: 400 when the request names no device and its token has none.
"""
device = request_device(request, device_id)
if device is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail="A device is required"
)
return device
@protected_route(
router.get,
"",
[Scope.ASSETS_READ],
responses={
status.HTTP_400_BAD_REQUEST: {
"description": "The cursor is not a snapshot ID."
},
status.HTTP_403_FORBIDDEN: {"description": DEVICE_FORBIDDEN},
status.HTTP_404_NOT_FOUND: {
"description": (
"No channel the caller can read has this `channel_id`, or the caller"
" has no device with this `device_id`."
)
},
},
)
def get_snapshots(
request: Request,
channel_id: Annotated[
uuid.UUID,
Query(
description=(
"The ID of the channel whose history to list. A channel is one"
" playthrough of one rom file."
)
),
],
save_target: str | None = None,
limit: Annotated[
int,
Query(
ge=1,
le=HISTORY_PAGE_MAX,
),
] = 50,
cursor: Annotated[
str | None,
Query(
description=(
"The ID of the last snapshot on the previous page. The response"
" holds the snapshots older than it. Omit it for the first page."
)
),
] = None,
device_id: Annotated[str | None, Query(description=FEED_DEVICE_DESCRIPTION)] = None,
) -> list[SnapshotSchema]:
"""One channel's history, newest first. A first page that shows the current records it as the device's latest known."""
viewer = request.user
device = request_device(request, device_id)
history = readable_channel_or_404(request, channel_id)
try:
before_id = int(cursor) if cursor else None
except ValueError:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid cursor"
) from None
page = db_snapshot_handler.get_channel_history(
history.id, limit, before_id=before_id, save_target=save_target
)
if (
device is not None
and cursor is None
and (
history.current_snapshot_id is None
or any(snapshot.id == history.current_snapshot_id for snapshot in page)
)
):
db_snapshot_handler.record_device_seen(
device.id, {history.id: history.current_snapshot_id}
)
return build_snapshot_schemas(page, viewer)
@protected_route(
router.get,
"/{id}",
[Scope.ASSETS_READ],
responses={
status.HTTP_400_BAD_REQUEST: {
"description": (
"`hold` is true, but the request names no device and its client"
" token is not bound to one."
)
},
status.HTTP_403_FORBIDDEN: {"description": DEVICE_FORBIDDEN},
status.HTTP_404_NOT_FOUND: {
"description": (
"No snapshot the caller can read has this ID, or the caller has no"
" device with this `device_id`."
)
},
},
)
def get_snapshot(
request: Request,
id: SnapshotIdPath,
device_id: Annotated[
str | None,
Query(
description="The device `hold` records for, which requires `devices.write`. Defaults to the client token's device."
),
] = None,
hold: Annotated[
bool,
Query(
description="Records the snapshot as the one the device holds, as a download it applies."
),
] = False,
) -> SnapshotSchema:
"""One snapshot; `hold=true` makes it the device's held snapshot in its channel."""
device = required_device(request, device_id) if hold else None
snapshot, channel = _readable_snapshot_or_404(request, id)
if device is not None and channel is not None:
db_snapshot_handler.record_device_base(device.id, channel.id, snapshot.id)
return build_snapshot_schema(snapshot, request.user)
def _assert_shape(is_zip: bool, shape: SaveShape) -> None:
"""A SINGLE save travels raw; MULTI and FOLDER travel as a zip."""
if is_zip != (shape != SaveShape.SINGLE):
raise _unprocessable("save", f"the bytes are not a {shape.value} unit")
def _unprocessable(key: str, reason: str) -> HTTPException:
return HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail={key: reason}
)
def _upload_members(key: str, upload: UploadFile) -> tuple[list[str], bool]:
"""The upload's archive entries, or its own name for a raw file, and
whether it is an archive."""
try:
names = check_upload(upload.file)
except UnsafeArchive as exc:
raise _unprocessable(key, str(exc)) from exc
if names is None:
return [upload.filename or key], False
return names, True
async def _read_push(
request: Request,
) -> tuple[ManifestPayload, dict[str, UploadPart], list[str]]:
"""The push's manifest, its content parts, and the save part's members."""
form = await request.form()
raw = form.get("manifest")
if not isinstance(raw, str):
if raw is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A manifest part is required",
)
raw = (await raw.read()).decode()
try:
payload = ManifestPayload.model_validate(json.loads(raw))
except (json.JSONDecodeError, ValidationError) as exc:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
detail=(
json.loads(exc.json()) if isinstance(exc, ValidationError) else str(exc)
),
) from exc
uploads: dict[str, UploadFile] = {}
for key, value in form.multi_items():
if isinstance(value, str) or key == "manifest":
continue
check_asset_upload_size(value, key)
uploads[key] = value
parts: dict[str, UploadPart] = {}
save_members: list[str] = []
save_archived = False
for key, upload in uploads.items():
if key == SAVE_SCREENSHOT_PART or key.endswith(SCREENSHOT_SUFFIX):
content_key = (
SAVE_PART
if key == SAVE_SCREENSHOT_PART
else key.removesuffix(SCREENSHOT_SUFFIX)
)
if content_key not in uploads:
if content_key != SAVE_PART and not STATE_PART_PATTERN.match(
content_key
):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Unknown part {key}",
)
parts[content_key] = UploadPart(
content=None,
file_name=content_key.rsplit(":", 1)[-1],
screenshot=upload.file,
screenshot_name=upload.filename,
)
continue
if key != SAVE_PART and not STATE_PART_PATTERN.match(key):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=f"Unknown part {key}"
)
members, archived = _upload_members(key, upload)
if key == SAVE_PART:
save_members, save_archived = members, archived
screenshot = uploads.get(
SAVE_SCREENSHOT_PART if key == SAVE_PART else f"{key}{SCREENSHOT_SUFFIX}"
)
parts[key] = UploadPart(
content=upload.file,
file_name=upload.filename or key.rsplit(":", 1)[-1],
screenshot=screenshot.file if screenshot else None,
screenshot_name=screenshot.filename if screenshot else None,
)
if payload.save and payload.save.shape and SAVE_PART in uploads:
_assert_shape(save_archived, payload.save.shape)
return payload, parts, save_members
def _named_parent(payload: ManifestPayload) -> Snapshot | None:
"""The parent the push names, or else the expected current it carries from."""
parent_id = (
payload.parent_snapshot_id
if "parent_snapshot_id" in payload.model_fields_set
else payload.expected_current_id
)
return db_snapshot_handler.get_snapshot(parent_id) if parent_id else None
def _clone_origin(
request: Request,
payload: ManifestPayload,
parts: dict[str, UploadPart],
source: Save | None,
) -> str:
"""The device a push with no device attributes its snapshot to: the
caller's device that wrote the bytes it copies or reuses, or else the web UI."""
if source is not None:
if source.origin_device_id:
return source.origin_device_id
elif all(part.content is None for part in parts.values()):
parent = _named_parent(payload)
if (
parent is not None
and parent.origin_device_id
and db_device_handler.get_device(
device_id=parent.origin_device_id, user_id=request.user.id
)
):
return parent.origin_device_id
return create_or_find_web_device(request, request.user).id
def _respond(result: WriteResult, viewer: User) -> JSONResponse:
body = build_snapshot_schema(result.snapshot, viewer)
if result.outcome == Outcome.BRANCHED:
assert result.conflict is not None, "a branched write names its conflict"
conflict = SnapshotConflictSchema(
current=(
build_snapshot_schema(result.current, viewer)
if result.current
else None
),
branch=body,
reason=result.conflict,
)
return JSONResponse(
status_code=status.HTTP_409_CONFLICT,
content=conflict.model_dump(mode="json"),
)
code = (
status.HTTP_200_OK
if result.outcome == Outcome.UNCHANGED
else status.HTTP_201_CREATED
)
return JSONResponse(status_code=code, content=body.model_dump(mode="json"))
@protected_route(
router.post,
"",
[Scope.ASSETS_WRITE],
response_model=SnapshotSchema,
status_code=status.HTTP_201_CREATED,
responses={
status.HTTP_200_OK: {"model": SnapshotSchema},
status.HTTP_400_BAD_REQUEST: {
"model": MissingContentSchema,
"description": (
"The `manifest` part is missing, a part has an unknown name, or the"
" manifest names content that the server lacks and the push did not"
" upload, which the response lists in `missing`."
),
},
status.HTTP_403_FORBIDDEN: {"description": DEVICE_FORBIDDEN},
status.HTTP_404_NOT_FOUND: {
"description": (
"No rom file, channel, parent snapshot or `copy_of` save that the"
" caller can see has the given ID, the copied save's file is"
" missing, or the caller has no device with this `device_id`."
)
},
status.HTTP_409_CONFLICT: {
"model": SnapshotConflictSchema,
"description": (
"The channel has a newer snapshot than the one the push expected, so"
" the push is kept as a branch, or the push would replace a hardcore save and"
" `approve_hardcore_downgrade` is false."
),
},
status.HTTP_413_CONTENT_TOO_LARGE: {
"description": "An uploaded part is larger than the server allows."
},
},
)
async def push_snapshot(
request: Request,
device_id: Annotated[
str | None,
Query(
description=(
"The ID of the device pushing the snapshot. Defaults to the"
" device bound to the client token. Any other device needs the"
" `devices.write` scope."
)
),
] = None,
) -> JSONResponse:
"""Write a snapshot into a channel: a `manifest` part plus `save`, `state:<core>:<slot>` and screenshot parts for hashes the server lacks."""
viewer = request.user
device = request_device(request, device_id)
payload, parts, save_members = await _read_push(request)
check_emulator_folder_name(payload.emulator)
rom_file, rom = visible_rom_file(request, payload.rom_file_id)
save_part = parts.get(SAVE_PART)
if (
payload.save
and payload.save.format == SaveFormat.NEUTRAL
and payload.save.shape
and save_part is not None
and save_part.content is not None
):
try:
check_neutral_unit(rom.platform_slug, payload.save.shape, save_members)
except NeutralUnitRejected as exc:
raise _unprocessable("save", str(exc)) from exc
copied: SaveEntry | None = None
source: Save | None = None
if payload.save and payload.save.copy_of is not None:
source = db_save_handler.get_save(user_id=viewer.id, id=payload.save.copy_of)
if source is None or rom_hidden(request, source.rom_id):
raise _not_found("Save")
content_hash = await fs_asset_handler.compute_content_hash(source.full_path)
if content_hash is None:
raise _not_found("Save file")
copied = SaveEntry(
hash=content_hash,
shape=payload.save.shape
or await asyncio.to_thread(
save_shape_of, fs_asset_handler.validate_path(source.full_path)
),
format=payload.save.format or SaveFormat.NATIVE,
)
# A copy, so a legacy writer overwriting `source` in place never touches the snapshot's bytes.
parts[SAVE_PART] = await copied_part(source)
write = SnapshotWrite(
author=viewer,
rom=rom,
rom_file=rom_file,
visibility=get_rom_visibility_filter(request),
manifest=payload.to_manifest(copied, source),
channel=ChannelTarget(
expected_current_id=(
payload.expected_current_id
if "expected_current_id" in payload.model_fields_set
else INFER
),
id=payload.channel_id,
label=payload.label,
),
parent_snapshot_id=(
payload.parent_snapshot_id
if "parent_snapshot_id" in payload.model_fields_set
else CARRY
),
device_id=device.id if device else None,
origin_device_id=(
device.id if device else _clone_origin(request, payload, parts, source)
),
parts=parts,
)
try:
result = await write_snapshot(await own_saves_only(write))
except ContentMissing as exc:
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST,
content=MissingContentSchema(missing=exc.keys).model_dump(),
)
except NotVisible as exc:
raise _not_found(exc.what.capitalize()) from exc
except (FileMismatch, ContentMismatch, LabelRequired) as exc:
field = "rom_file_id" if isinstance(exc, FileMismatch) else "manifest"
raise _unprocessable(field, str(exc)) from exc
except HardcoreDowngrade:
return JSONResponse(
status_code=status.HTTP_409_CONFLICT, content={"hardcore_downgrade": True}
)
return _respond(result, viewer)
@protected_route(
router.patch,
"/{id}",
[Scope.ASSETS_WRITE],
responses={
status.HTTP_403_FORBIDDEN: {
"description": (
"The request sets `is_public` on a snapshot that the caller does not"
" own or that is not archival."
)
},
status.HTTP_404_NOT_FOUND: {
"description": "No snapshot the caller can read has this ID."
},
},
)
def update_snapshot(
request: Request, id: SnapshotIdPath, payload: SnapshotUpdatePayload
) -> SnapshotSchema:
"""Pin or unpin a snapshot for the caller, which any reader may do, or share
an archival one, which only its owner may do."""
viewer = request.user
snapshot, channel = _readable_snapshot_or_404(request, id)
if payload.is_public is not None:
if snapshot.user_id != viewer.id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only the owner of a snapshot shares it",
)
if snapshot.kind != SnapshotKind.ARCHIVAL:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only an archival snapshot is shared on its own",
)
if payload.is_pinned is not None:
db_snapshot_handler.set_pin(snapshot.id, viewer.id, payload.is_pinned)
if payload.is_public is not None:
snapshot = db_snapshot_handler.update_snapshot(
snapshot.id, {"is_public": payload.is_public}
)
return build_snapshot_schema(snapshot, viewer)