mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 10:01:00 +01:00
* 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>
668 lines
25 KiB
Python
668 lines
25 KiB
Python
import asyncio
|
|
from collections import Counter
|
|
from datetime import datetime
|
|
from typing import Annotated
|
|
|
|
from fastapi import BackgroundTasks, Depends, HTTPException, Request, status
|
|
from pydantic import Field
|
|
|
|
from decorators.auth import protected_route
|
|
from endpoints.play_sessions import PlaySessionEntry, assert_batch_size
|
|
from endpoints.responses.base import PAGE_QUERY, BaseModel, PageParams
|
|
from endpoints.responses.play_session import (
|
|
PlaySessionIngestResponse,
|
|
PlaySessionIngestResult,
|
|
)
|
|
from endpoints.responses.sync import (
|
|
SyncCompleteResponse,
|
|
SyncNegotiateResponse,
|
|
SyncOperationSchema,
|
|
SyncSessionSchema,
|
|
)
|
|
from endpoints.sockets.sync import emit_sync_conflict
|
|
from handler.auth.constants import Scope
|
|
from handler.auth.dependencies import get_permissions, get_rom_visibility_filter
|
|
from handler.database import (
|
|
db_deleted_asset_handler,
|
|
db_device_handler,
|
|
db_device_save_sync_handler,
|
|
db_rom_handler,
|
|
db_save_handler,
|
|
db_snapshot_handler,
|
|
db_sync_session_handler,
|
|
)
|
|
from handler.database.snapshots_handler import SlotHead
|
|
from handler.play_session_handler import ingest_play_sessions
|
|
from handler.redis_handler import high_prio_queue
|
|
from handler.sync.comparison import (
|
|
ChannelPosition,
|
|
compare_missing_server_save,
|
|
compare_on_channel,
|
|
compare_save_state,
|
|
roms_to_check_for_removals,
|
|
)
|
|
from logger.logger import log
|
|
from models.assets import Save
|
|
from models.deleted_asset import DeletedAsset
|
|
from models.device import SyncMode
|
|
from models.sync_session import SyncSession, SyncSessionStatus
|
|
from tasks.registry import SYNC_PUSH_PULL_SPEC
|
|
from utils.auth import (
|
|
require_device,
|
|
require_token_device,
|
|
token_device_id,
|
|
token_reaches_device,
|
|
)
|
|
from utils.datetime import to_utc
|
|
from utils.router import APIRouter
|
|
from utils.validation import MAX_ROM_IDS_PER_QUERY, RomIdScope
|
|
|
|
from .retroarch import router as retroarch_router
|
|
|
|
router = APIRouter(
|
|
prefix="/sync",
|
|
tags=["sync"],
|
|
)
|
|
router.include_router(retroarch_router)
|
|
|
|
# A hung broker must not pin the background task forever.
|
|
CONFLICT_NOTIFY_TIMEOUT_S = 2.0
|
|
|
|
|
|
class ClientSaveState(BaseModel):
|
|
rom_id: int = Field(description="ID of the ROM this save belongs to.")
|
|
file_name: str = Field(description="Name of the save file on the client.")
|
|
slot: str | None = Field(
|
|
default=None,
|
|
description=(
|
|
"Save slot name. Saves are paired between client and server on "
|
|
"(rom_id, slot), so provide a stable slot name (e.g. 'autosave') to "
|
|
"keep a save in sync across negotiations. A null slot is treated as "
|
|
"an archival, manual-upload save: it is never paired with slotted "
|
|
"server saves, so a null-slot client save always negotiates as an "
|
|
"'upload' even when an identical file already exists on the server "
|
|
"under a slot."
|
|
),
|
|
)
|
|
emulator: str | None = Field(
|
|
default=None, description="Emulator that produced the save, if known."
|
|
)
|
|
content_hash: str | None = Field(
|
|
default=None,
|
|
description="Hash of the save contents, used to detect identical saves.",
|
|
)
|
|
updated_at: datetime = Field(
|
|
description="Last-modified timestamp of the save on the client."
|
|
)
|
|
file_size_bytes: int = Field(description="Size of the save file in bytes.")
|
|
|
|
|
|
class SyncNegotiatePayload(BaseModel):
|
|
device_id: str | None = Field(
|
|
default=None,
|
|
description=(
|
|
"ID of the syncing device. Optional when the request uses a "
|
|
"device-bound client token, in which case the device is inferred "
|
|
"from the token."
|
|
),
|
|
)
|
|
saves: list[ClientSaveState] = Field(
|
|
description="Current save state on the client."
|
|
)
|
|
rom_ids: RomIdScope = Field(
|
|
default=None,
|
|
description=(
|
|
"IDs of the ROMs installed on the device. When provided, downloads "
|
|
"are offered only for these ROMs (plus any ROM the client sent a "
|
|
"save for) instead of the user's whole save library. This is a "
|
|
"read-only scope: omitting a ROM never deletes or unlinks its "
|
|
f"saves. At most {MAX_ROM_IDS_PER_QUERY} IDs per request."
|
|
),
|
|
)
|
|
restore_unlisted: bool = Field(
|
|
default=False,
|
|
description=(
|
|
"Offer every current server save the client did not list as a "
|
|
"download, even one this device already synced. For clients that "
|
|
"never delete saves themselves (such as a browser, whose storage "
|
|
"can be evicted), so a missing save means lost rather than deleted."
|
|
),
|
|
)
|
|
emulators: list[str] | None = Field(
|
|
default=None,
|
|
description=(
|
|
"Emulators whose saves this client can load. When provided, only "
|
|
"server saves written by one of them are paired or offered, so a "
|
|
"save from another emulator in the same slot is left alone."
|
|
),
|
|
)
|
|
cores: list[str] | None = Field(
|
|
default=None,
|
|
description=(
|
|
"Libretro cores whose saves this client can load. A save from a "
|
|
"snapshot client that names its core is offered only to a client "
|
|
"listing that core, and is matched by emulator otherwise."
|
|
),
|
|
)
|
|
|
|
|
|
# Its own class so the OpenAPI schema keeps the name clients generate from.
|
|
class SyncPlaySessionEntry(PlaySessionEntry):
|
|
pass
|
|
|
|
|
|
class SyncCompletePayload(BaseModel):
|
|
operations_completed: int = 0
|
|
operations_failed: int = 0
|
|
play_sessions: list[SyncPlaySessionEntry] | None = None
|
|
|
|
|
|
async def _notify_conflicts(
|
|
user_id: int,
|
|
device_id: str,
|
|
session_id: int,
|
|
conflict_ops: list[SyncOperationSchema],
|
|
rom_names: dict[int, str],
|
|
) -> None:
|
|
"""Emit one sync:conflict event per operation, within one deadline."""
|
|
try:
|
|
async with asyncio.timeout(CONFLICT_NOTIFY_TIMEOUT_S):
|
|
for op in conflict_ops:
|
|
await emit_sync_conflict(
|
|
user_id=user_id,
|
|
device_id=device_id,
|
|
session_id=session_id,
|
|
file_name=op.file_name,
|
|
rom_id=op.rom_id,
|
|
rom_name=rom_names[op.rom_id],
|
|
reason=op.reason,
|
|
)
|
|
except TimeoutError:
|
|
log.warning(
|
|
f"Gave up on {len(conflict_ops)} sync:conflict events "
|
|
f"after {CONFLICT_NOTIFY_TIMEOUT_S}s"
|
|
)
|
|
|
|
|
|
def _channel_positions(
|
|
device_id: str, heads: dict[tuple[int, str | None], SlotHead]
|
|
) -> dict[tuple[int, str | None], ChannelPosition]:
|
|
"""Each channel-backed slot's history and what this device holds in it."""
|
|
channel_ids = {head.channel_id for head in heads.values()}
|
|
versions = db_snapshot_handler.channel_versions(channel_ids)
|
|
bases = db_snapshot_handler.device_bases(device_id, channel_ids)
|
|
return {
|
|
key: ChannelPosition(
|
|
current_id=head.snapshot_id,
|
|
current_hash=head.save.content_hash,
|
|
current_hashes=frozenset(versions[head.channel_id].currents),
|
|
branch_hashes=frozenset(versions[head.channel_id].branches),
|
|
device_base_id=bases.get(head.channel_id),
|
|
)
|
|
for key, head in heads.items()
|
|
}
|
|
|
|
|
|
def _require_sync_session(request: Request, session_id: int) -> SyncSession:
|
|
"""The caller's sync session, a 404 when a bound token's other device ran it."""
|
|
sync_session = db_sync_session_handler.get_session(
|
|
session_id=session_id, user_id=request.user.id
|
|
)
|
|
if not sync_session or not token_reaches_device(request, sync_session.device_id):
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Sync session with ID {session_id} not found",
|
|
)
|
|
return sync_session
|
|
|
|
|
|
@protected_route(router.post, "/negotiate", [Scope.ASSETS_READ, Scope.DEVICES_READ])
|
|
def negotiate_sync(
|
|
request: Request,
|
|
payload: SyncNegotiatePayload,
|
|
background_tasks: BackgroundTasks,
|
|
) -> SyncNegotiateResponse:
|
|
"""Negotiate sync operations between a client device and the server.
|
|
|
|
The client sends its current save state, and the server returns a list of
|
|
operations (upload, download, conflict, delete, no_op) to bring both sides
|
|
in sync.
|
|
|
|
A client that only holds part of the library can send `rom_ids` to scope the
|
|
negotiation to the ROMs installed on the device, which keeps the response
|
|
from listing downloads for ROMs it cannot play. The scope is read-only: a
|
|
ROM left out is simply outside this negotiation, never a deletion signal.
|
|
|
|
Saves are paired on (rom_id, slot). Clients that want a save to stay in sync
|
|
should send a stable, non-null slot name (e.g. "autosave"). Null-slot saves
|
|
are treated as archival, manual uploads: they are excluded from pairing, so a
|
|
null-slot client save always negotiates as an "upload" even when an identical
|
|
file (same content_hash) already exists on the server under a slot. This is
|
|
intentional, since saves can be cloned across slots and null slots overlap
|
|
with manual uploads.
|
|
"""
|
|
device_id: str | None = payload.device_id or token_device_id(request)
|
|
if not device_id:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=(
|
|
"device_id is required (either in the request payload or "
|
|
"implicit via a device-bound client token)"
|
|
),
|
|
)
|
|
|
|
device = require_device(request, device_id)
|
|
|
|
if not device.sync_enabled:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Sync is disabled for this device",
|
|
)
|
|
|
|
# A session belongs to the launch that negotiated it, not to the device,
|
|
# which can have two games open at once. One nobody closes is left to the
|
|
# scheduled cleanup rather than to the next negotiation.
|
|
sync_session = db_sync_session_handler.create_session(
|
|
device_id=device.id, user_id=request.user.id
|
|
)
|
|
|
|
operations: list[SyncOperationSchema] = []
|
|
|
|
# Widen an explicit ROM scope with the ROMs the client sent saves for, so a
|
|
# client save is never misread as an upload just because its ROM was omitted.
|
|
rom_id_scope = (
|
|
payload.rom_ids + [s.rom_id for s in payload.saves]
|
|
if payload.rom_ids is not None
|
|
else None
|
|
)
|
|
|
|
# Pair on (rom_id, slot), keeping the newest row per slot: slot uploads are datetime-tagged (spec) so tagged filenames never equal the client's untagged name, and a slot accrues many rows over time. Null-slot rows stay archival-only.
|
|
# A save on a hidden ROM negotiates as if the ROM didn't exist.
|
|
visibility = get_rom_visibility_filter(request)
|
|
server_saves = db_save_handler.get_saves(
|
|
user_id=request.user.id,
|
|
slot_not_null=True,
|
|
rom_ids=rom_id_scope,
|
|
visibility=visibility,
|
|
)
|
|
if payload.emulators is not None:
|
|
server_saves = [s for s in server_saves if s.emulator in payload.emulators]
|
|
hidden_rom_ids = db_rom_handler.get_hidden_rom_ids_among(
|
|
[s.rom_id for s in payload.saves], visibility
|
|
)
|
|
server_save_map: dict[tuple[int, str | None], Save] = {}
|
|
for save in server_saves:
|
|
key = (save.attached_rom_id, save.slot)
|
|
current = server_save_map.get(key)
|
|
if current is None or to_utc(save.updated_at) > to_utc(current.updated_at):
|
|
server_save_map[key] = save
|
|
# Once a channel has a current, it is the slot's save, and its history decides.
|
|
slot_keys = {(rom_id, slot) for rom_id, slot in server_save_map if slot}
|
|
slot_keys |= {(s.rom_id, s.slot) for s in payload.saves if s.slot}
|
|
slot_keys |= db_snapshot_handler.channel_slots(request.user.id, rom_id_scope)
|
|
# A channel on a hidden ROM negotiates as if the ROM didn't exist.
|
|
hidden_slot_rom_ids = db_rom_handler.get_hidden_rom_ids_among(
|
|
[rom_id for rom_id, _ in slot_keys], visibility
|
|
)
|
|
slot_keys = {key for key in slot_keys if key[0] not in hidden_slot_rom_ids}
|
|
heads: dict[tuple[int, str | None], SlotHead] = dict(
|
|
db_snapshot_handler.slot_heads(
|
|
request.user.id, slot_keys, payload.emulators, payload.cores
|
|
).items()
|
|
)
|
|
server_save_map.update({key: slot_head.save for key, slot_head in heads.items()})
|
|
positions = _channel_positions(device.id, heads)
|
|
|
|
deleted_map: dict[tuple[int, str | None], DeletedAsset] = {
|
|
(record.rom_id, record.slot): record
|
|
for record in db_deleted_asset_handler.get_deletions(
|
|
user_id=request.user.id,
|
|
rom_ids=roms_to_check_for_removals(payload.saves, server_save_map),
|
|
)
|
|
if record.rom_id not in hidden_rom_ids
|
|
}
|
|
|
|
# Only the newest row per slot is ever looked up, so superseded rows stay out.
|
|
current_save_ids = [s.id for s in server_save_map.values()]
|
|
device_syncs = db_device_save_sync_handler.get_syncs_for_device_and_saves(
|
|
device_id=device.id, save_ids=current_save_ids
|
|
)
|
|
sync_by_save_id = {s.save_id: s for s in device_syncs}
|
|
|
|
# Track which server saves were referenced by the client
|
|
matched_server_save_ids: set[int] = set()
|
|
|
|
# Process each client save
|
|
for client_save in payload.saves:
|
|
key = (client_save.rom_id, client_save.slot)
|
|
server_save = server_save_map.get(key)
|
|
# Without this the client offers a removed version back and the
|
|
# deletion or rollback undoes itself.
|
|
deletion = deleted_map.get(key)
|
|
removed_at = deletion.removal_times() if deletion else {}
|
|
|
|
if server_save is None:
|
|
result = compare_missing_server_save(
|
|
client_save.content_hash, client_save.updated_at, removed_at
|
|
)
|
|
operations.append(
|
|
SyncOperationSchema(
|
|
action=result.action,
|
|
rom_id=client_save.rom_id,
|
|
save_id=None,
|
|
file_name=client_save.file_name,
|
|
slot=client_save.slot,
|
|
emulator=client_save.emulator,
|
|
reason=result.reason,
|
|
)
|
|
)
|
|
continue
|
|
|
|
matched_server_save_ids.add(server_save.id)
|
|
device_sync = sync_by_save_id.get(server_save.id)
|
|
|
|
# Skip untracked saves
|
|
if device_sync and device_sync.is_untracked:
|
|
operations.append(
|
|
SyncOperationSchema(
|
|
action="no_op",
|
|
rom_id=server_save.attached_rom_id,
|
|
save_id=server_save.id,
|
|
file_name=server_save.file_name,
|
|
slot=client_save.slot,
|
|
emulator=server_save.emulator,
|
|
reason="Save is untracked on this device",
|
|
)
|
|
)
|
|
continue
|
|
|
|
head = heads.get(key)
|
|
position = positions.get(key)
|
|
server_updated_at = head.current_since if head else server_save.updated_at
|
|
result = (
|
|
compare_on_channel(
|
|
client_hash=client_save.content_hash,
|
|
client_updated_at=client_save.updated_at,
|
|
position=position,
|
|
removed_at=removed_at,
|
|
)
|
|
if position
|
|
else None
|
|
) or compare_save_state(
|
|
client_hash=client_save.content_hash,
|
|
client_updated_at=client_save.updated_at,
|
|
server_hash=server_save.content_hash,
|
|
server_updated_at=server_save.updated_at,
|
|
device_last_synced_at=device_sync.last_synced_at if device_sync else None,
|
|
device_last_sync_hash=device_sync.last_sync_hash if device_sync else None,
|
|
device_last_sync_server_hash=(
|
|
device_sync.last_sync_server_hash if device_sync else None
|
|
),
|
|
removed_at=removed_at,
|
|
)
|
|
if (
|
|
result.action == "no_op"
|
|
and client_save.content_hash == server_save.content_hash
|
|
):
|
|
db_device_save_sync_handler.record_identical_content(
|
|
device.id,
|
|
server_save.id,
|
|
server_save.content_hash,
|
|
synced_at=server_save.updated_at,
|
|
)
|
|
if head:
|
|
db_snapshot_handler.record_device_base(
|
|
device.id, head.channel_id, head.snapshot_id
|
|
)
|
|
|
|
operations.append(
|
|
SyncOperationSchema(
|
|
action=result.action,
|
|
rom_id=server_save.attached_rom_id,
|
|
save_id=server_save.id,
|
|
file_name=server_save.file_name,
|
|
slot=client_save.slot,
|
|
emulator=server_save.emulator,
|
|
reason=result.reason,
|
|
server_updated_at=server_updated_at,
|
|
server_content_hash=server_save.content_hash,
|
|
)
|
|
)
|
|
|
|
# Check for current saves the client didn't mention (superseded older rows per slot are history, not downloads)
|
|
for key, save in server_save_map.items():
|
|
if save.id in matched_server_save_ids:
|
|
continue
|
|
|
|
device_sync = sync_by_save_id.get(save.id)
|
|
|
|
# Skip untracked saves
|
|
if device_sync and device_sync.is_untracked:
|
|
continue
|
|
|
|
head = heads.get(key)
|
|
position = positions.get(key)
|
|
if position and position.device_base_id is not None:
|
|
# The device held this current and no longer lists it: it deleted it.
|
|
if position.device_holds_current and not payload.restore_unlisted:
|
|
continue
|
|
reason = (
|
|
"Server save updated since last sync, not present on client"
|
|
if not position.device_holds_current
|
|
else "Save exists on server but not on client"
|
|
)
|
|
elif device_sync:
|
|
# If device has synced this save before and the save hasn't changed,
|
|
# the client intentionally deleted it - treat as no_op
|
|
if (
|
|
to_utc(save.updated_at) <= to_utc(device_sync.last_synced_at)
|
|
and not payload.restore_unlisted
|
|
):
|
|
continue
|
|
reason = "Server save updated since last sync, not present on client"
|
|
else:
|
|
reason = "Save exists on server but not on client"
|
|
|
|
operations.append(
|
|
SyncOperationSchema(
|
|
action="download",
|
|
rom_id=save.attached_rom_id,
|
|
save_id=save.id,
|
|
file_name=save.file_name,
|
|
slot=key[1],
|
|
emulator=save.emulator,
|
|
reason=reason,
|
|
server_updated_at=head.current_since if head else save.updated_at,
|
|
server_content_hash=save.content_hash,
|
|
)
|
|
)
|
|
|
|
# Update session with operation counts
|
|
counts = Counter(op.action for op in operations)
|
|
|
|
db_sync_session_handler.update_session(
|
|
session_id=sync_session.id,
|
|
data={
|
|
"status": SyncSessionStatus.IN_PROGRESS,
|
|
"operations_planned": len(operations) - counts["no_op"],
|
|
},
|
|
)
|
|
|
|
# Update device last_seen
|
|
db_device_handler.update_last_seen(device_id=device.id, user_id=request.user.id)
|
|
|
|
log.info(
|
|
f"Sync negotiation for device {device.id}: "
|
|
f"{counts['upload']} uploads, {counts['download']} downloads, "
|
|
f"{counts['conflict']} conflicts, {counts['delete']} deletions, "
|
|
f"{counts['no_op']} no-ops"
|
|
)
|
|
|
|
# Sent after the response on the app's loop, so a slow broker never holds
|
|
# up the client and the shared socket manager stays on one loop.
|
|
conflict_ops = [op for op in operations if op.action == "conflict"]
|
|
if conflict_ops:
|
|
background_tasks.add_task(
|
|
_notify_conflicts,
|
|
user_id=request.user.id,
|
|
device_id=device.id,
|
|
session_id=sync_session.id,
|
|
conflict_ops=conflict_ops,
|
|
rom_names={
|
|
save.attached_rom_id: save.attached_rom.name
|
|
or save.attached_rom.fs_name
|
|
for save in server_save_map.values()
|
|
},
|
|
)
|
|
|
|
return SyncNegotiateResponse(
|
|
session_id=sync_session.id,
|
|
operations=operations,
|
|
total_upload=counts["upload"],
|
|
total_download=counts["download"],
|
|
total_conflict=counts["conflict"],
|
|
total_no_op=counts["no_op"],
|
|
total_delete=counts["delete"],
|
|
)
|
|
|
|
|
|
@protected_route(router.post, "/sessions/{session_id}/complete", [Scope.DEVICES_WRITE])
|
|
def complete_sync_session(
|
|
request: Request,
|
|
session_id: int,
|
|
payload: SyncCompletePayload,
|
|
) -> SyncCompleteResponse:
|
|
"""Mark a sync session as completed, optionally ingesting play sessions."""
|
|
if payload.play_sessions:
|
|
if Scope.ROMS_USER_WRITE not in request.auth.scopes:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden"
|
|
)
|
|
assert_batch_size(len(payload.play_sessions))
|
|
|
|
sync_session = _require_sync_session(request, session_id)
|
|
|
|
# A session the cleanup expired can still be completed: its counts and the
|
|
# play sessions the client carries are worth more than the guess that
|
|
# nobody would ever report them. One closed on purpose is refused.
|
|
completed = db_sync_session_handler.complete_session(
|
|
session_id=session_id,
|
|
operations_completed=payload.operations_completed,
|
|
operations_failed=payload.operations_failed,
|
|
)
|
|
if completed is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=f"Session is already {sync_session.status}",
|
|
)
|
|
|
|
log.info(
|
|
f"Sync session {session_id} completed: "
|
|
f"{payload.operations_completed} succeeded, {payload.operations_failed} failed"
|
|
)
|
|
|
|
play_session_ingest = None
|
|
if payload.play_sessions:
|
|
summary = ingest_play_sessions(
|
|
user_id=request.user.id,
|
|
username=request.user.username,
|
|
perms=get_permissions(request),
|
|
entries=[
|
|
{
|
|
"rom_id": s.rom_id,
|
|
"save_slot": s.save_slot,
|
|
"start_time": s.start_time,
|
|
"end_time": s.end_time,
|
|
"duration_ms": s.duration_ms,
|
|
}
|
|
for s in payload.play_sessions
|
|
],
|
|
device_id=sync_session.device_id,
|
|
)
|
|
play_session_ingest = PlaySessionIngestResponse(
|
|
results=[
|
|
PlaySessionIngestResult(
|
|
index=r["index"],
|
|
status=r["status"],
|
|
id=r.get("id"),
|
|
detail=r.get("detail"),
|
|
)
|
|
for r in summary["results"]
|
|
],
|
|
created_count=summary["created_count"],
|
|
skipped_count=summary["skipped_count"],
|
|
)
|
|
|
|
return SyncCompleteResponse(
|
|
session=SyncSessionSchema.model_validate(completed),
|
|
play_session_ingest=play_session_ingest,
|
|
)
|
|
|
|
|
|
@protected_route(router.get, "/sessions", [Scope.DEVICES_READ])
|
|
def get_sync_sessions(
|
|
request: Request,
|
|
page: Annotated[PageParams, Depends(PAGE_QUERY)],
|
|
device_id: str | None = None,
|
|
) -> list[SyncSessionSchema]:
|
|
"""List sync sessions for the current user."""
|
|
if device_id is not None:
|
|
require_token_device(request, device_id)
|
|
sessions = db_sync_session_handler.get_sessions(
|
|
user_id=request.user.id,
|
|
device_id=device_id,
|
|
limit=page.limit,
|
|
offset=page.offset,
|
|
)
|
|
return [SyncSessionSchema.model_validate(s) for s in sessions]
|
|
|
|
|
|
@protected_route(router.get, "/sessions/{session_id}", [Scope.DEVICES_READ])
|
|
def get_sync_session(
|
|
request: Request,
|
|
session_id: int,
|
|
) -> SyncSessionSchema:
|
|
"""Get a specific sync session."""
|
|
return SyncSessionSchema.model_validate(_require_sync_session(request, session_id))
|
|
|
|
|
|
# --- Push-Pull Mode Endpoints ---
|
|
|
|
|
|
@protected_route(router.post, "/devices/{device_id}/push-pull", [Scope.DEVICES_WRITE])
|
|
def trigger_push_pull(
|
|
request: Request,
|
|
device_id: str,
|
|
) -> SyncSessionSchema:
|
|
"""Manually trigger a push-pull sync for a specific device."""
|
|
device = require_device(request, device_id)
|
|
|
|
if device.sync_mode != SyncMode.PUSH_PULL:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Device is not in push_pull sync mode",
|
|
)
|
|
|
|
if not device.sync_enabled:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail="Sync is disabled for this device",
|
|
)
|
|
|
|
# Create a session and enqueue the job
|
|
sync_session = db_sync_session_handler.create_session(
|
|
device_id=device.id, user_id=request.user.id
|
|
)
|
|
|
|
high_prio_queue.enqueue(
|
|
"tasks.sync_push_pull_task.run_push_pull_sync",
|
|
device_id=device.id,
|
|
session_id=sync_session.id,
|
|
force=True,
|
|
job_timeout=SYNC_PUSH_PULL_SPEC.timeout,
|
|
meta=SYNC_PUSH_PULL_SPEC.job_meta("sync_push_pull"),
|
|
)
|
|
|
|
log.info(f"Enqueued push-pull sync for device {device.id}")
|
|
return SyncSessionSchema.model_validate(sync_session)
|