Files
romm/backend/sync_watcher.py
Terri 8a1e6280b1 feat(saves): add save channels and snapshots (#5198)
* feat(saves): add save channels and snapshots

* feat(saves): close spec gaps in save channels and hash with sigil

* feat(saves): play snapshots in the v2 player, which pushes snapshots

* fix(saves): code review: authorization, retention losses, held-save sync, batched responses

* refactor(saves): simplify pass

* refactor(saves): review-polish pass

* docs(saves): humanizer pass

* feat(saves): run every EmulatorJS page on the v2 player

* feat(saves): per-user snapshot pins

* feat(sigil): store the identity a save restore needs and pin sigil 0f05f25

* fix(saves): meet type-aware lint in the v2 player

* feat(sigil): store N64 header and playlist title ids, pin sigil 0847fda

* feat(saves): convert saves for a core on download and list save layouts

* feat(saves): prune unreachable archival snapshots and empty detached channels on delete

* feat(saves): device sync from the token, held snapshots and shared-card pushes

* feat(saves): arc restores past abandoned snapshots and color channels by age

* fix(saves): code-review and security-audit fixes

* refactor(saves): simplify pass

* chore(saves): review-polish pass

* docs(saves): humanizer pass

* fix(sync): file RetroArch autosave versions as their channel's next snapshot

* fix(saves): address review findings and trim docstrings

* fix(saves): share-lock planned rows by id so PostgreSQL accepts the lock

* test(saves): stub the detached-channels fetch in SaveDataTab stories

* feat(saves): carry the full current snapshot in a 409, pin sigil 2071dff

* chore(sigil): pin 5d4ddb4, which reads .cue and .gdi sheets

* docs(saves): drop v2 wording now that one UI remains

* chore(sigil): pin 0190443, which reads PS2 raw BIN images and cue sheets

* fix(sigil): treat a file too short for its format as routine during scans

* chore(migrations): renumber save channel migrations after upstream's 0154

* fix(snapshots): a hardcore switch on unchanged content makes a new current

* fix(sync): decide a channel's slot from its history and the device's snapshot

* chore(docker): pin sigil at 794d99f for PSP Store release save prefixes

* refactor(db): squash the save channel migrations into 0161

Fold the slot linking (0162) and the rom_files sigil identity columns (0163)
into 0161_save_channels, so the feature ships as one revision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(saves): close visibility and input gaps found in review (pr-ready step 2)

code-review --fix:
- negotiate_sync drops channel slots on ROMs hidden from the caller
- channel PATCH/attach/DELETE answer 404 when the channel's ROM is hidden
- a push copying a save from a hidden ROM answers 404
- _own_device applies require_token_device to bound client tokens
- adopting a legacy save syncs its sharing with the channel it joins

security-audit follow-ups:
- another user's detached public save or state is no longer downloadable
- profile and option values must be a single path segment
- companions are de-duplicated and capped at 8

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(saves): share channel and asset lookups, drop duplicates (pr-ready step 3)

simplify:
- readable_channel_or_404 and channels_on_files replace four copies of the
  channel 404 check and two copies of the file-fed channel listing
- readable_rom_asset_or_404 serves both public save and state downloads
- _own_device resolves through require_device; _clone_origin takes the source
- reuse _unprocessable, DESCRIPTOR_EXTENSIONS, SAVE_SLOT_MAX_LENGTH, uniqueBy
  and uuidv7; neutral forms default their required pattern to the allowed one
- RetroArch delete checks held rows in one query, a guarded upload lists the
  slot only without a channel head, and uploads are read off the event loop
- snapshotSession builds push requests once; player comment cleanups

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(saves): trim two docstrings to two lines (pr-ready step 4)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(saves): answer held RetroArch paths with 423, mirror slot labels

- RetroArch Cloud Sync answers 423 Locked for a PUT over a held unslotted save
  and for a DELETE where only held rows sit at the path, instead of 409 and 404
- channelLabelForSlot returns null for blank and state_ slots, as the backend's
  channel_label does, so the player files them under no channel either
- document that sharing a channel lets every user read and push into it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(docker): pin sigil at 85f88a8 for Switch .nup containers

* fix(snapshots): a save pushed in another shape or format makes a new current

* refactor(saves): drop the always-true SAVE_SYNC.SNAPSHOTS heartbeat flag

Nothing reads it, and the SAVE_SYNC block's presence already tells a
client the server speaks the snapshot API. Also trim the rom detail
channel field comments to one line each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(frontend): use uuidv7 for every client-generated id

Drop the randomToken wrapper and the notification inbox's Math.random tab
id, so uuidv7 is the one helper that works outside a secure context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(saves): trim redundant snapshot API surface, dead code and duplicate logic

API:
- Drop PUT /snapshots/{id}/devices/{device_id}; GET /snapshots/{id}?hold=true holds.
- GET /snapshots is history only (channel_id required); GET /channels serves currents.
- A snapshot carries channel_id instead of an embedded channel.
- POST /saves/{id}/content takes the same query parameters as the GET, plus container_path.

Backend:
- Remove the archival write path, clone.py, DBStatesHandler.get_state, the sigil
  identity-hash path, unused relationships and composite snapshot indexes.
- One held/frozen lookup, one bulk-delete guard, SQLAlchemy dialect upserts, and
  the shared reserve_version_name in the writer.
- The writer takes a visibility filter and checks the channel and parent itself.
- The restore handler picks per-game or merge; fewer wrapper types and tables.

Frontend:
- Channel delete uses the shared typed confirm; DeleteChannelDialog is gone.
- Held offline pushes go through a per-channel SnapshotSession.
- Remove the slot-based pending upload path.
- The timeline shares the fan's badge logic.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* refactor(saves): release archival backups through module functions

The saves and states handlers each built a private DBSnapshotsHandler to
call release_backup and refresh_backup_digests, since they can't import
the shared instance. Both only ever ran inside the caller's session, so
they are now module functions taking it, like channel_for_slot.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* refactor(saves): share one deleted-assets handler instance

The saves handler built its own DBDeletedAssetsHandler because it can't
import the package's instance. The instance is now built in
deleted_assets_handler.py and re-exported by the package, so both use it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 21:59:19 -05:00

371 lines
13 KiB
Python

"""Sync folder watcher for File Transfer mode.
This module is invoked by watchfiles when changes are detected in the sync
folder. It processes incoming save files from devices that use file_transfer
sync mode.
The watcher is configured to run as a separate watchfiles process monitoring
the sync base path. When files appear in a device's incoming/ directory, they
are matched to ROMs and processed as save uploads.
"""
import asyncio
import json
import os
import shutil
from collections.abc import Sequence
from datetime import datetime, timezone
from typing import cast
from config import ENABLE_SYNC_FOLDER_WATCHER
from handler.auth.rom_visibility import UNRESTRICTED
from handler.database import (
db_deleted_asset_handler,
db_device_handler,
db_device_save_sync_handler,
db_platform_handler,
db_save_handler,
db_sync_session_handler,
)
from handler.filesystem import fs_asset_handler, get_fs_sync_handler
from handler.sync.comparison import compare_save_state, for_held_save
from logger.formatter import highlight as hl
from logger.logger import log
from models.device import Device, SyncMode
from models.sync_session import SyncSessionStatus
from utils.sentry import init_sentry
init_sentry()
Change = tuple[str, str]
def _extract_device_and_platform(path: str) -> tuple[str, str, str] | None:
"""Extract device_id, platform_slug, and filename from a sync incoming path.
Expected path format: {ROMM_BASE_PATH}/sync/{device_id}/incoming/{platform_slug}/filename.ext
"""
fs_sync_handler = get_fs_sync_handler()
try:
rel_path = os.path.relpath(path, start=str(fs_sync_handler.base_path))
parts = rel_path.split(os.sep)
if len(parts) < 4 or parts[1] != "incoming":
return None
device_id = parts[0]
platform_slug = parts[2]
filename = parts[-1]
return (device_id, platform_slug, filename)
except ValueError, IndexError:
return None
def _ensure_conflicts_dir(device_id: str, platform_slug: str) -> str:
fs_sync_handler = get_fs_sync_handler()
conflicts_dir = str(
fs_sync_handler.base_path
/ fs_sync_handler.build_conflicts_path(device_id, platform_slug)
)
os.makedirs(conflicts_dir, exist_ok=True)
return conflicts_dir
def process_sync_changes(changes: Sequence[Change]) -> None:
"""Process file changes detected in the sync folder."""
if not ENABLE_SYNC_FOLDER_WATCHER:
return
# Only process added/modified files in incoming directories
added_files: list[tuple[str, str, str, str]] = (
[]
) # (device_id, platform_slug, filename, full_path)
for _event_type, change_path in changes:
src_path = os.fsdecode(change_path)
# Only process files (not directories)
if not os.path.isfile(src_path):
continue
parsed = _extract_device_and_platform(src_path)
if not parsed:
continue
device_id, platform_slug, filename = parsed
added_files.append((device_id, platform_slug, filename, src_path))
if not added_files:
return
# Group by device
by_device: dict[str, list[tuple[str, str, str]]] = {}
for device_id, platform_slug, filename, full_path in added_files:
by_device.setdefault(device_id, []).append((platform_slug, filename, full_path))
for device_id, files in by_device.items():
_process_device_incoming(device_id, files)
def _process_device_incoming(
device_id: str,
files: list[tuple[str, str, str]], # (platform_slug, filename, full_path)
) -> None:
"""Process incoming files for a single device."""
from endpoints.sockets.sync import (
emit_sync_completed,
emit_sync_error,
emit_sync_started,
)
# Look up device - try all users since file transfer is server-side
device = db_device_handler.get_device_by_id(device_id)
if not device:
log.warning(f"Sync watcher: unknown device {device_id}, skipping")
return
if device.sync_mode != SyncMode.FILE_TRANSFER:
log.warning(
f"Sync watcher: device {device_id} is not in file_transfer mode, skipping"
)
return
if not device.sync_enabled:
log.info(f"Sync watcher: device {device_id} sync is disabled, skipping")
return
# Create a sync session
sync_session = db_sync_session_handler.create_session(
device_id=device.id, user_id=device.user_id
)
db_sync_session_handler.update_session(
session_id=sync_session.id,
data={
"status": SyncSessionStatus.IN_PROGRESS,
"operations_planned": len(files),
},
)
asyncio.run(
emit_sync_started(
user_id=device.user_id,
device_id=device.id,
session_id=sync_session.id,
sync_mode="file_transfer",
)
)
completed = 0
failed = 0
for platform_slug, filename, full_path in files:
try:
_process_incoming_file(
device, sync_session.id, platform_slug, filename, full_path
)
completed += 1
except Exception:
log.error(
f"Sync watcher: failed to process {filename} for device {device_id}",
exc_info=True,
)
failed += 1
# Complete the session
db_sync_session_handler.complete_session(
session_id=sync_session.id,
operations_completed=completed,
operations_failed=failed,
)
if failed > 0:
asyncio.run(
emit_sync_error(
user_id=device.user_id,
device_id=device.id,
session_id=sync_session.id,
error_message=f"{failed} file(s) failed to process",
)
)
asyncio.run(
emit_sync_completed(
user_id=device.user_id,
device_id=device.id,
session_id=sync_session.id,
operations_completed=completed,
operations_failed=failed,
)
)
log.info(
f"Sync watcher: device {device_id} processed {completed} files, {failed} failures"
)
def _process_incoming_file(
device: Device,
session_id: int,
platform_slug: str,
filename: str,
full_path: str,
) -> None:
"""Process a single incoming file from a device's sync folder."""
from endpoints.sockets.sync import emit_sync_conflict
fs_sync_handler = get_fs_sync_handler()
# Look up platform
platform = db_platform_handler.get_platform_by_fs_slug(platform_slug)
if not platform:
log.warning(f"Sync watcher: unknown platform slug {platform_slug}")
return
# Compute hash of incoming file
file_hash = fs_sync_handler.compute_file_hash(full_path)
file_size = os.path.getsize(full_path)
file_mtime = datetime.fromtimestamp(os.path.getmtime(full_path), tz=timezone.utc)
# Try to find matching saves on this platform for this user. Only
# slot-bound saves participate in sync; null-slot saves are web-UI /
# archival uploads and must never be paired with a device push. Filter
# in SQL so archival rows never load.
saves_on_platform = db_save_handler.get_saves(
user_id=device.user_id,
platform_id=platform.id,
slot_not_null=True,
visibility=UNRESTRICTED,
)
matched_save = None
for save in saves_on_platform:
if save.file_name == filename:
matched_save = save
break
if matched_save:
# Compare with existing save
device_sync = db_device_save_sync_handler.get_sync(
device_id=device.id, save_id=matched_save.id
)
result = compare_save_state(
client_hash=file_hash,
client_updated_at=file_mtime,
server_hash=matched_save.content_hash,
server_updated_at=matched_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
),
# Identical content is a no_op, which never reads removals.
removed_at=(
db_deleted_asset_handler.removal_times(
device.user_id, matched_save.attached_rom_id, matched_save.slot
)
if file_hash != matched_save.content_hash
else None
),
)
result = for_held_save(result, matched_save.id)
action, reason = result.action, result.reason
if action == "no_op":
log.debug(f"Sync watcher: {filename} is already in sync, skipping")
if file_hash == matched_save.content_hash:
db_device_save_sync_handler.record_identical_content(
device.id, matched_save.id, file_hash
)
fs_sync_handler.remove_incoming_file(full_path)
return
if action == "upload":
# Client file is newer - update server save
log.info(
f"Sync watcher: updating save {hl(filename)} from device {device.id}"
)
with open(full_path, "rb") as f:
file_data = f.read()
replaced_hash = asyncio.run(fs_asset_handler.unrecorded_hash(matched_save))
asyncio.run(
fs_asset_handler.write_file(
file=file_data,
path=matched_save.file_path,
filename=matched_save.file_name,
)
)
db_save_handler.update_save(
matched_save.id,
{
"file_size_bytes": file_size,
"content_hash": file_hash,
},
replaced_hash=replaced_hash,
)
# This path hashes the device's file itself, so both sides hold file_hash.
db_device_save_sync_handler.upsert_sync(
device_id=device.id,
save_id=matched_save.id,
last_sync_hash=file_hash,
last_sync_server_hash=file_hash,
)
fs_sync_handler.remove_incoming_file(full_path)
elif action == "conflict":
log.warning(
f"Sync watcher: conflict detected for {filename} "
f"on device {device.id}: {reason}"
)
# Move conflicting file to conflicts directory
conflicts_dir = _ensure_conflicts_dir(device.id, platform_slug)
conflict_path = os.path.join(conflicts_dir, filename)
shutil.move(full_path, conflict_path)
log.info(f"Sync watcher: moved conflicting file to {conflict_path}")
# Emit socket notification for conflict
asyncio.run(
emit_sync_conflict(
user_id=device.user_id,
device_id=device.id,
session_id=session_id,
file_name=filename,
rom_id=matched_save.attached_rom_id,
rom_name=matched_save.attached_rom.name
or matched_save.attached_rom.fs_name,
reason=reason,
)
)
elif action == "download":
# Server is newer - write server save to device's outgoing directory
log.info(
f"Sync watcher: server save is newer for {filename}, "
f"writing to outgoing"
)
server_file_path = f"{matched_save.file_path}/{matched_save.file_name}"
server_full_path = fs_asset_handler.validate_path(server_file_path)
with open(str(server_full_path), "rb") as f:
server_data = f.read()
fs_sync_handler.write_outgoing_file(
device_id=device.id,
platform_slug=platform_slug,
file_name=filename,
data=server_data,
)
# The device has no bytes yet, so only the server half is known.
db_device_save_sync_handler.upsert_sync(
device_id=device.id,
save_id=matched_save.id,
last_sync_server_hash=matched_save.content_hash,
)
fs_sync_handler.remove_incoming_file(full_path)
else:
log.info(
f"Sync watcher: new file {hl(filename)} from device {device.id} "
f"on platform {platform_slug} - no matching save found, skipping"
)
if __name__ == "__main__":
changes = cast(list[Change], json.loads(os.getenv("WATCHFILES_CHANGES", "[]")))
if changes:
process_sync_changes(changes)