mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 01:58:41 +01:00
* feat(player): play RPG Maker 2000/2003 games in the browser with EasyRPG Embed the EasyRPG web player for extracted game folders on the rpg-maker platform. The backend generates the player's index.json from the scanned files and merges in the free EasyRPG RTP under every name the official and fan RTPs give its assets, so games that lean on the RTP find them. In-game saves sync with the user's RomM saves through the player's IndexedDB storage. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(easyrpg): read the free RTP from a fixed path instead of an env var The full image always keeps the RTP at /var/www/html/assets/easyrpg/rtp, so the path is a constant beside the web path nginx serves it under. The dev container links its copy there at startup. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(easyrpg): code-review fixes for the save sync and asset endpoint - Wait for an in-flight push before the quit push, so the newest save uploads - Keep Play disabled until the fresh rom (and its saves) is fetched - Stop onPlay and the rom fetch from acting after the view unmounts - Leave through usePlayerExit like the other players - Handle a rejected IDB commit when the run itself fails - Track uploads by the browser's file name - Load only visibility and files per asset request, not the full rom - Serve DEV_MODE files as octet-stream, matching nginx - Make the traversal test actually reach the endpoint Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(easyrpg): simplify pass over the player and asset endpoint - Load only file paths per asset request, and look up RTP folders in O(1) - Reuse RomFile.file_name_for_download and usePlayerFullscreen - Share one dev/prod serve helper for game and RTP files - Derive the save sync's game key from the rom - Have the RTP table tool reuse normalize_name - Make save-module internals private and tidy the prepare/read loops Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat(easyrpg): flag RPG Maker game folders on the rom schemas Gallery lists carry no files, so the frontend guessed that every multi-file rom on the rpg-maker platform was playable, including RPG Maker XP/VX/MV folders. Rom now has a deferred `is_easyrpg_game` subquery (an RPG_RT.ldb at the folder root), loaded with the other gallery file stats and derived from loaded files on the with_files path, and the frontend reads it. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(easyrpg): drop server save sync, keep saves per user in the browser Server sync moves to a follow-up that puts the web players on device sync. Saves now stay in the player's IndexedDB, as js-dos does, with the same note on the start page. The player is launched as `<rom id>-<user id>` so each RomM account sharing a browser profile keeps its own saves; nginx and Vite drop the user id when routing to the backend. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat(sync): let a client ask negotiate to restore the saves it lost Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat(saves): sync web player saves as a browser device A shared layer for the in-browser players: each browser profile registers as a sync device, keeps every account's saves in its own IndexedDB store, negotiates them with the server at launch (restoring any it lost), and pushes changes with the device's conflict guard. Hashes match the server's, including its zip-entry hash. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat(emulatorjs): save as the browser's sync device, with the slot guard EmulatorJS now uploads and downloads as this browser's registered device instead of the IP-based login device, confirms downloads with their hash, and lets a write that continues the slot's head be refused when another device wrote the slot since; that progress is archived and the session keeps writing to the archive. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat(settings): list, rename, pause and remove your devices Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat(player): sync EasyRPG, js-dos, PICO-8 and Ruffle saves with RomM Each player's own storage is restored from the browser's synced copy before boot and captured back during play and on leave: - EasyRPG: its IDBFS saves, one slot per in-game slot - js-dos: its changes zip through fsChanges pull/push, migrating saves it kept in OPFS before - PICO-8: cartdata files, flushed by loading a blank cart on leave - Ruffle: the game's SharedObjects zipped into one save, kept out of localStorage between plays so accounts don't share them Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(easyrpg): address Greptile review - Start timing the play session once the player page loads - Use object-form props in the view test's button mock - Keep the RTP table tool's docstring to one sentence Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(saves): address Greptile review on web device save sync - Remove EasyRPG save files that sync deleted, so the game cannot load them - Keep the stale-device guard on device sync's page-close uploads - Restore only the Ruffle SharedObjects the current SWF can reach Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(saves): code-review pass on web device save sync Restore master's EasyRPG RTP table path lost in the merge, serialize DeviceSaveSync pushes, only mark a no_op synced when the server hash matches, forget the browser device when it is removed, close a late EasyRPG IndexedDB connection, send content_hash on unload updates, and share the IndexedDB helpers and slot-conflict check. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(saves): simplify pass on web device save sync Archive conflicts through uploadArchivedSave and isSlotConflict, skip hashing unchanged bytes, share bytesEqual from saveSync/hash, pass restore_unlisted from DeviceSaveSync, use newest() for the EmulatorJS slot head, and trim one-off Ruffle and PICO-8 helpers. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(saves): review-polish pass on web device save sync Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * docs(saves): humanizer pass on web device save sync comments Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(saves): open every player IndexedDB through openDb The save sync store now rejects when another tab blocks its upgrade instead of waiting forever, as the EasyRPG and pending-asset stores already did. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * feat(sync): let negotiate scope server saves to the client's emulators A browser player's saves load only in that player, so a native save in the same slot must not pair with it or download into it. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(saves): register the browser device on each launch Registration returns the existing device, so calling it every time brings back a device removed from any browser, which EmulatorJS otherwise kept sending as a dead id. The cached id now serves only when offline. DeviceSaveSync also negotiates within its own emulator. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * refactor(player): share web player save sync through useDeviceSaveSync The coalesced polled push, the flush before leaving, the page-close capture and the discard prompt live in one composable, and the player suites share one DeviceSaveSync fake from test-utils. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(saves): update one archive per slot after another device takes it A slot refused mid-session archived every later write as a new save. Later writes now update that archive in place, page-close sends included, and the next launch settles the slot. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * perf(ruffle): skip unchanged polls and upload saves every 5 minutes Polls compare the stored SharedObjects with the last read before zipping them, and keep what changed in the browser, uploading it at most every 5 minutes. Leaving and page close still upload at once. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * perf(ruffle): sync saves like EmulatorJS, polling every second Polls compare the raw stored strings, so an idle second decodes, zips and hashes nothing. A change uploads once two polls agree on it, and a failing upload backs off from 2 to 30 seconds through the retry backoff EmulatorJS uses, now shared from saveSync. Leaving still uploads at once. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
595 lines
22 KiB
Python
595 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
|
|
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
|
|
from handler.database import (
|
|
db_deleted_asset_handler,
|
|
db_device_handler,
|
|
db_device_save_sync_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 SyncSessionStatus
|
|
from tasks.registry import SYNC_PUSH_PULL_SPEC
|
|
from utils.auth import token_device_id
|
|
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"
|
|
)
|
|
|
|
|
|
@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 = db_device_handler.get_device(device_id=device_id, user_id=request.user.id)
|
|
if not device:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Device with ID {device_id} not found",
|
|
)
|
|
|
|
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.
|
|
server_saves = db_save_handler.get_saves(
|
|
user_id=request.user.id, slot_not_null=True, rom_ids=rom_id_scope
|
|
)
|
|
if payload.emulators is not None:
|
|
server_saves = [s for s in server_saves if s.emulator in payload.emulators]
|
|
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),
|
|
)
|
|
}
|
|
|
|
# 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."""
|
|
sync_session = db_sync_session_handler.get_session(
|
|
session_id=session_id, user_id=request.user.id
|
|
)
|
|
if not sync_session:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Sync session with ID {session_id} not found",
|
|
)
|
|
|
|
# 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."""
|
|
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."""
|
|
sync_session = db_sync_session_handler.get_session(
|
|
session_id=session_id, user_id=request.user.id
|
|
)
|
|
if not sync_session:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Sync session with ID {session_id} not found",
|
|
)
|
|
|
|
return SyncSessionSchema.model_validate(sync_session)
|
|
|
|
|
|
# --- 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 = db_device_handler.get_device(device_id=device_id, user_id=request.user.id)
|
|
if not device:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_404_NOT_FOUND,
|
|
detail=f"Device with ID {device_id} not found",
|
|
)
|
|
|
|
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)
|