mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 10:01:00 +01:00
* fix(sync): cap play sessions on sync completion and require roms.user.write The completion endpoint fed an unbounded play_sessions list to the same ingest as POST /api/play-sessions, which allows 100 per batch and requires roms.user.write. Apply both rules before the session is completed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(config): reject empty platform binding and version values config.yml exits on load when a platforms or versions value is empty, so the API must not write one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(collections): require smart collection criteria to be a JSON object Any other JSON value was stored, then failed the response schema and broke the smart collection list for every user who could see the collection. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(stats): require roms.read on /api/stats Anonymous callers were served counts over the whole library, including platforms and ROMs hidden from users. The UI only calls it after login. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(permissions): apply ROM visibility to filters, saves, play sessions and collection removal /api/roms/filters aggregated facet values over the whole library, GET /api/saves/{id} and GET /api/play-sessions returned the caller's own rows on hidden ROMs, and removing ROMs from a collection could drop members hidden from its owner. The facet visibility clauses move onto RomVisibilityFilter so stats and filters share them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(webhooks): keep non-admin webhooks off the admin's internal metadata origins The SSRF exception for a self-hosted Playmatch or Hasheous applied to every request, so a user's webhook could reach any path on that private origin. Non-admin webhooks now validate and connect with an empty allowlist. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(saves): bound total decompressed size when hashing zip archives Zip content hashing capped each entry but not the archive, so many entries each under the cap could still decompress and hash far more than any real save or memory card holds. Budget the decompressed bytes across the whole archive and cap the entry count; callers keep treating an over-budget archive as an unknown hash. The chunked, budgeted entry reader is shared with the memory card archive check, and the RetroArch store path now hashes off the event loop like its siblings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(psp): clamp LZ4 literal and match copies to the ZISO block size The ZISO block decoder appended literals and copied matches for their full encoded length before checking the output size, and an LZ4 length can be extended without bound by 0xFF bytes. A small crafted block could therefore expand far past the block size before being truncated. Clamp each copy to the room left in the block, stop once it is full, end the block on a truncated match offset, and copy matches with slices instead of a per-byte loop (overlapping matches repeat their pattern). Output for valid blocks is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(auth): revoke OAuth tokens when a user's credentials change A password change, admin reset, reset-link reset or rename cleared the account's web sessions, but its OAuth access tokens kept working until they expired and its refresh tokens could still be exchanged at /api/token. Revoking a user's credentials now also records a per-username revocation time in Redis, kept for the longest token lifetime. Bearer validation and refresh consumption reject any token whose iat is at or before it. OAuth tokens now carry a sub-second iat, so a login right after the change still works; a token without iat counts as older than any revocation. The revocation is keyed by the token's sub, the same username sessions are keyed by, so a rename revokes tokens issued under the old name even if another account later takes it. Client (API) tokens are left alone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(api): reject local file URLs for user-supplied covers and manuals file:// and launchbox-file:// URLs are meant for covers and manuals that a scan records from gamelist.xml or LaunchBox metadata. The collection create/update endpoints and the ROM update endpoint passed a user-supplied url_cover (and url_manual) straight to the resource handler, which copied whatever library file it named into the entity's resources. That let any user with collections.write or roms.write pull files they cannot otherwise read, including those of hidden platforms and ROMs. These endpoints now answer 400 for a local file URL, unless it is the value already stored, which the edit forms echo back on every save. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(resources): bound cover downloads and decodes Remote covers, screenshots, manuals, badges and media files were streamed to disk with no size limit, and a gzip-encoded body was read whole and inflated in memory. Downloads now go through one helper that counts bytes against MAX_ASSET_UPLOAD_SIZE_BYTES, inflates gzip incrementally under the same cap, and aborts past it, so the partial file is removed and any earlier copy kept. Covers are also bounded once on disk: a still image whose header declares more than MAX_COVER_PIXELS is discarded before it is decoded (and an uploaded one is refused with a 400), and a DecompressionBombError while deriving the small cover now discards the download instead of failing the request and leaving the file behind. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: fix mypy errors in the new tests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: address Greptile review on permission and input hardening - Date OAuth tokens to before the credential check, so a password change that lands during the check revokes the tokens it issues. - Apply ROM visibility to play sessions in SQL, before the page slice. - Reject truncated gzip bodies and inflate every gzip member. - Shorten the zip budget comment; stream real httpx2 responses in tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: apply code-review findings on permission hardening Revoke OAuth tokens and sessions on user deletion, apply ROM visibility to GET /states/{id}, validate update_collection rom_ids, run get_rom_filters off the event loop, and reuse the shared httpx client factory for webhooks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: apply simplify pass on permission hardening Read the OAuth revocation stamp through the async cache, share the play-session batch-size check, raise a plain OSError for oversized downloads, and drop a dead slice in the LZ4 decoder. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * style: apply review-polish pass on permission hardening Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: state that ROM visibility is enforced as access control Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(assets): hide saves, states, screenshots and memory cards on hidden ROMs Visibility is access control, so per-id save/state/screenshot routes now 404 when the save's ROM is hidden from the caller (hidden ROM, hidden platform or age limit), and the save/state lists and identifier lists leave those rows out in SQL. GET /api/saves/summary 404s on a hidden ROM. Memory cards on a hidden platform 404 on every per-id route, drop out of both lists, and can't be created against a hidden platform. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(saves): answer a hidden ROM's save summary like a missing one Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(permissions): enforce ROM visibility in sync, installs and feeds Hidden ROMs/platforms and age-limited ROMs are access control, so the paths that skipped the caller's visibility now apply it: - sync negotiate: saves on hidden ROMs are neither offered, paired nor reported as conflicts; a client save on one negotiates like an unknown ROM - push-pull SSH sync: resolves the device owner's visibility and skips saves on hidden ROMs in both directions - device installs: list and claim leave out requests whose ROM became hidden (they stay pending), and outcome notifications don't name it - recommendations: a hidden seed ROM is no longer named - music playlists: track_count counts only tracks on visible ROMs - audit events: firmware targets on hidden platforms are filtered - setup library: supported platforms honour the caller's visibility - feeds: a hidden platform found by slug reads as missing Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(visibility): hide ROMs from virtual collections, stats and scan events Virtual collections apply the caller's visibility in SQL: a collection with no visible member is left out (404 by id), member ids and covers skip hidden ROMs, and the limit counts only visible collections. Stats save, state and screenshot totals skip assets of hidden ROMs. Scan events no longer broadcast to every socket. Progress and end events go to a scan room that sockets of users holding platforms.write or tasks.run join on connect. scanning_rom and scanning_platform go to the user rooms of those followers who can see that ROM or platform, resolved once per scan and grouped by visibility. get_rom_audience now builds on a shared get_user_visibilities. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: apply code-review findings on ROM visibility enforcement Match virtual collection members by ROM id, build the cover visibility clauses once, filter feed platforms by visibility in SQL, resolve every id before a batch save or state delete, filter push-pull saves in the query, and narrow the hides query to the requested users. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor: apply simplify pass on ROM visibility enforcement Require an explicit visibility filter on the saves, states and memory card queries, share one roms_facets visibility join and one owned-asset helper, filter virtual collection members by hidden ids, batch the scan audience's scope lookup, and move the empty-room emit guard into socket_handler. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test: start the scan audience before emitting from scan_rom Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs: apply humanizer pass on the visibility rule Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(streaming): don't mount a memory card on a hidden platform Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: address Greptile review on ROM visibility enforcement Refresh a running scan's audience after a permission change, fix the precedence of the scan-room join assertion, and narrow mock await_args before reading them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * revert: drop per-visibility scan event audience Scan events go back to every socket. Removes handler/scan/audience.py, the scan room join on connect, the permissions generation bump and the batched OAuth scope resolution that only the audience used. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
606 lines
22 KiB
Python
606 lines
22 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_sync_session_handler,
|
|
)
|
|
from handler.play_session_handler import ingest_play_sessions
|
|
from handler.redis_handler import high_prio_queue
|
|
from handler.sync.comparison import (
|
|
compare_missing_server_save,
|
|
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."
|
|
),
|
|
)
|
|
|
|
|
|
# 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 _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.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
|
|
|
|
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.rom_id,
|
|
save_id=server_save.id,
|
|
file_name=server_save.file_name,
|
|
slot=server_save.slot,
|
|
emulator=server_save.emulator,
|
|
reason="Save is untracked on this device",
|
|
)
|
|
)
|
|
continue
|
|
|
|
result = 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,
|
|
)
|
|
|
|
operations.append(
|
|
SyncOperationSchema(
|
|
action=result.action,
|
|
rom_id=server_save.rom_id,
|
|
save_id=server_save.id,
|
|
file_name=server_save.file_name,
|
|
slot=server_save.slot,
|
|
emulator=server_save.emulator,
|
|
reason=result.reason,
|
|
server_updated_at=server_save.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 save in server_save_map.values():
|
|
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
|
|
|
|
# If device has synced this save before and the save hasn't changed,
|
|
# the client intentionally deleted it - treat as no_op
|
|
if device_sync:
|
|
synced_ts = to_utc(device_sync.last_synced_at)
|
|
save_ts = to_utc(save.updated_at)
|
|
if save_ts <= synced_ts and not payload.restore_unlisted:
|
|
# Save hasn't changed since device last synced - client deleted it
|
|
continue
|
|
|
|
# Save changed after device last synced - device should download
|
|
operations.append(
|
|
SyncOperationSchema(
|
|
action="download",
|
|
rom_id=save.rom_id,
|
|
save_id=save.id,
|
|
file_name=save.file_name,
|
|
slot=save.slot,
|
|
emulator=save.emulator,
|
|
reason="Server save updated since last sync, not present on client",
|
|
server_updated_at=save.updated_at,
|
|
server_content_hash=save.content_hash,
|
|
)
|
|
)
|
|
else:
|
|
# Device has never synced this save - download it
|
|
operations.append(
|
|
SyncOperationSchema(
|
|
action="download",
|
|
rom_id=save.rom_id,
|
|
save_id=save.id,
|
|
file_name=save.file_name,
|
|
slot=save.slot,
|
|
emulator=save.emulator,
|
|
reason="Save exists on server but not on client",
|
|
server_updated_at=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.rom_id: save.rom.name or save.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)
|