Files
romm/backend/tasks/sync_push_pull_task.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

494 lines
17 KiB
Python

"""Background task for Push-Pull sync mode.
Connects to devices via SSH/SFTP, scans their save directories,
and performs bidirectional sync operations.
"""
import os
from typing import Any
import asyncssh
from anyio import Path as AnyioPath
from anyio import open_file
from handler.auth.rom_visibility import RomVisibilityFilter
from handler.database import (
db_deleted_asset_handler,
db_device_handler,
db_device_save_sync_handler,
db_permission_handler,
db_platform_handler,
db_save_handler,
db_sync_session_handler,
)
from handler.filesystem import fs_asset_handler
from handler.sync.comparison import compare_save_state, for_held_save
from handler.sync.ssh_handler import RemoteSaveInfo, get_ssh_sync_handler
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 tasks.registry import SYNC_PUSH_PULL_SPEC
from tasks.tasks import PeriodicTask
async def run_push_pull_sync(
device_id: str | None = None,
session_id: int | None = None,
force: bool = False,
) -> dict[str, Any]:
"""Execute push-pull sync for one or all push_pull devices."""
if not SYNC_PUSH_PULL_SPEC.enabled and not force:
log.info("Push-pull sync not enabled, skipping")
return {"status": "disabled"}
if device_id:
device = db_device_handler.get_device_by_id(device_id)
if not device:
return {"status": "error", "message": f"Device {device_id} not found"}
devices = [device]
else:
devices = list(
db_device_handler.get_all_devices_by_sync_mode(SyncMode.PUSH_PULL)
)
if not devices:
log.info("No push_pull devices found")
return {"status": "no_devices"}
results = []
for device in devices:
if not device.sync_enabled:
continue
result = await _sync_device(device, session_id=session_id)
results.append(result)
return {"status": "completed", "device_results": results}
async def _sync_device(device: Device, session_id: int | None = None) -> dict[str, Any]:
"""Perform push-pull sync for a single device."""
sync_config = device.sync_config or {}
if not sync_config.get("ssh_host"):
log.warning(f"Push-pull device {device.id} has no ssh_host configured")
return {"device_id": device.id, "status": "error", "message": "No ssh_host"}
visibility = db_permission_handler.get_user_visibilities([device.user_id]).get(
device.user_id
)
if visibility is None:
log.warning(
f"Push-pull: owner {device.user_id} of device {device.id} "
"is missing or disabled"
)
return {"device_id": device.id, "status": "error", "message": "No owner"}
from endpoints.sockets.sync import (
emit_sync_completed,
emit_sync_error,
emit_sync_progress,
emit_sync_started,
)
if session_id:
sync_session = db_sync_session_handler.get_session(
session_id=session_id, user_id=device.user_id
)
if not sync_session:
log.warning(
f"Push-pull: session {session_id} not found, creating new session"
)
sync_session = db_sync_session_handler.create_session(
device_id=device.id, user_id=device.user_id
)
else:
sync_session = db_sync_session_handler.create_session(
device_id=device.id, user_id=device.user_id
)
await emit_sync_started(
user_id=device.user_id,
device_id=device.id,
session_id=sync_session.id,
sync_mode="push_pull",
)
try:
ssh_sync_handler = get_ssh_sync_handler()
conn = await ssh_sync_handler.connect(sync_config, device_id=device.id)
except Exception as e:
log.error(f"Push-pull: failed to connect to device {device.id}: {e}")
db_sync_session_handler.fail_session(
session_id=sync_session.id, error_message=str(e)
)
await emit_sync_error(
user_id=device.user_id,
device_id=device.id,
session_id=sync_session.id,
error_message=str(e),
)
return {"device_id": device.id, "status": "connection_failed", "error": str(e)}
completed = 0
failed = 0
try:
save_directories = sync_config.get("save_directories", [])
if not save_directories:
log.warning(
f"Push-pull device {device.id} has no save_directories configured"
)
db_sync_session_handler.complete_session(session_id=sync_session.id)
return {"device_id": device.id, "status": "no_directories"}
remote_saves = await ssh_sync_handler.list_remote_saves(conn, save_directories)
log.info(
f"Push-pull: found {len(remote_saves)} remote saves on device {device.id}"
)
db_sync_session_handler.update_session(
session_id=sync_session.id,
data={
"status": SyncSessionStatus.IN_PROGRESS,
"operations_planned": len(remote_saves),
},
)
operations_planned = len(remote_saves)
for remote_save in remote_saves:
try:
action = await _process_remote_save(
device,
conn,
remote_save,
session_id=sync_session.id,
visibility=visibility,
)
if action != "skipped":
completed += 1
except Exception:
log.error(
f"Push-pull: failed to process {remote_save.file_name} "
f"on device {device.id}",
exc_info=True,
)
failed += 1
await emit_sync_progress(
user_id=device.user_id,
device_id=device.id,
session_id=sync_session.id,
operations_completed=completed + failed,
operations_planned=operations_planned,
current_file=remote_save.file_name,
)
pushed, push_failed = await _push_missing_saves(
device, conn, remote_saves, save_directories, visibility=visibility
)
completed += pushed
failed += push_failed
if pushed or push_failed:
db_sync_session_handler.update_session(
session_id=sync_session.id,
data={"operations_planned": operations_planned + pushed + push_failed},
)
except Exception as e:
log.error(f"Push-pull sync failed for device {device.id}: {e}", exc_info=True)
db_sync_session_handler.fail_session(
session_id=sync_session.id, error_message=str(e)
)
await emit_sync_error(
user_id=device.user_id,
device_id=device.id,
session_id=sync_session.id,
error_message=str(e),
)
return {"device_id": device.id, "status": "failed", "error": str(e)}
finally:
conn.close()
db_sync_session_handler.complete_session(
session_id=sync_session.id,
operations_completed=completed,
operations_failed=failed,
)
db_device_handler.update_last_seen(device_id=device.id, user_id=device.user_id)
await 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"Push-pull sync for device {device.id}: "
f"{completed} completed, {failed} failed"
)
return {
"device_id": device.id,
"status": "completed",
"completed": completed,
"failed": failed,
}
async def _process_remote_save(
device: Device,
conn: asyncssh.SSHClientConnection,
remote_save: RemoteSaveInfo,
session_id: int,
visibility: RomVisibilityFilter,
) -> str:
"""Process a single remote save file. Returns action taken."""
from endpoints.sockets.sync import emit_sync_conflict
ssh_sync_handler = get_ssh_sync_handler()
# Look up platform
platform = db_platform_handler.get_platform_by_fs_slug(remote_save.platform_slug)
if not platform:
log.debug(f"Unknown platform slug: {remote_save.platform_slug}")
return "skipped"
# Find matching server save. 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 = db_save_handler.get_saves(
user_id=device.user_id,
platform_id=platform.id,
slot_not_null=True,
visibility=visibility,
)
matched_save = None
for save in saves:
if save.file_name == remote_save.file_name:
matched_save = save
break
if not matched_save:
log.info(
f"Push-pull: remote save {hl(remote_save.file_name)} "
f"on platform {remote_save.platform_slug} - no matching server save, skipping"
)
return "skipped"
# Compare with existing save
device_sync = db_device_save_sync_handler.get_sync(
device_id=device.id, save_id=matched_save.id
)
# Download remote file to get its hash
local_path, remote_hash = await ssh_sync_handler.download_save(
conn, remote_save.path
)
try:
result = compare_save_state(
client_hash=remote_hash,
client_updated_at=remote_save.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 remote_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":
# A timestamp-only no-op can leave the two sides different, so only
# identical content is recorded as the baseline.
identical = (
remote_hash if remote_hash == matched_save.content_hash else None
)
db_device_save_sync_handler.upsert_sync(
device_id=device.id,
save_id=matched_save.id,
last_sync_hash=identical,
last_sync_server_hash=identical,
)
return "no_op"
if action == "upload":
# Remote is newer - pull to server
log.info(
f"Push-pull: pulling {hl(remote_save.file_name)} from device {device.id}"
)
async with await open_file(local_path, "rb") as f:
file_data = await f.read()
replaced_hash = await fs_asset_handler.unrecorded_hash(matched_save)
await 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": remote_save.file_size,
"content_hash": remote_hash,
},
replaced_hash=replaced_hash,
)
# The server save's hash was just set to remote_hash, so both sides hold it.
db_device_save_sync_handler.upsert_sync(
device_id=device.id,
save_id=matched_save.id,
last_sync_hash=remote_hash,
last_sync_server_hash=remote_hash,
)
return "pulled"
if action == "download":
# Server is newer - push to device
log.info(
f"Push-pull: pushing {hl(matched_save.file_name)} to device {device.id}"
)
server_file_path = f"{matched_save.file_path}/{matched_save.file_name}"
server_full_path = fs_asset_handler.validate_path(server_file_path)
await ssh_sync_handler.upload_save(
conn, str(server_full_path), remote_save.path
)
# The device now holds the server file, so both halves are its hash.
db_device_save_sync_handler.upsert_sync(
device_id=device.id,
save_id=matched_save.id,
last_sync_hash=matched_save.content_hash,
last_sync_server_hash=matched_save.content_hash,
)
return "pushed"
if action == "conflict":
log.warning(
f"Push-pull: conflict for {remote_save.file_name} "
f"on device {device.id}: {reason}"
)
await emit_sync_conflict(
user_id=device.user_id,
device_id=device.id,
session_id=session_id,
file_name=remote_save.file_name,
rom_id=matched_save.attached_rom_id,
rom_name=matched_save.attached_rom.name
or matched_save.attached_rom.fs_name,
reason=reason,
)
return "conflict"
finally:
if await AnyioPath(local_path).exists():
os.unlink(local_path)
return "skipped"
async def _push_missing_saves(
device: Device,
conn: asyncssh.SSHClientConnection,
remote_saves: list[RemoteSaveInfo],
save_directories: list[dict[str, Any]],
*,
visibility: RomVisibilityFilter,
) -> tuple[int, int]:
"""Push server saves that are missing from the device; returns (pushed, failed)."""
ssh_sync_handler = get_ssh_sync_handler()
pushed = 0
failed = 0
# Build set of remote filenames per platform
remote_files: dict[str, set[str]] = {}
for rs in remote_saves:
remote_files.setdefault(rs.platform_slug, set()).add(rs.file_name)
# Build path lookup from save_directories config
platform_paths: dict[str, str] = {}
for dir_config in save_directories:
platform_paths[dir_config["platform_slug"]] = dir_config["path"]
# Check server saves for each configured platform
for dir_config in save_directories:
platform_slug = dir_config["platform_slug"]
platform = db_platform_handler.get_platform_by_fs_slug(platform_slug)
if not platform:
continue
# Only slot-bound saves participate in sync; null-slot saves are
# web-UI / archival uploads and must never be pushed to a device.
# Filter in SQL so archival rows never load.
server_saves = db_save_handler.get_saves(
user_id=device.user_id,
platform_id=platform.id,
slot_not_null=True,
visibility=visibility,
)
remote_set = remote_files.get(platform_slug, set())
remote_dir = platform_paths.get(platform_slug, "")
for save in server_saves:
if save.file_name in remote_set:
continue
# Check if device has synced this before (intentional delete)
device_sync = db_device_save_sync_handler.get_sync(
device_id=device.id, save_id=save.id
)
if device_sync and device_sync.is_untracked:
continue
# Push to device
if remote_dir:
try:
server_file_path = f"{save.file_path}/{save.file_name}"
server_full_path = fs_asset_handler.validate_path(server_file_path)
remote_path = f"{remote_dir}/{save.file_name}"
await ssh_sync_handler.upload_save(
conn, str(server_full_path), remote_path
)
db_device_save_sync_handler.upsert_sync(
device_id=device.id,
save_id=save.id,
last_sync_hash=save.content_hash,
last_sync_server_hash=save.content_hash,
)
pushed += 1
log.info(
f"Push-pull: pushed missing save {hl(save.file_name)} "
f"to device {device.id}"
)
except Exception:
log.error(
f"Push-pull: failed to push {save.file_name} to device {device.id}",
exc_info=True,
)
failed += 1
return pushed, failed
class SyncPushPullTask(PeriodicTask):
"""Periodic task to run push-pull sync for all configured devices."""
def __init__(self) -> None:
super().__init__(SYNC_PUSH_PULL_SPEC)
async def run(self, *args: Any, **kwargs: Any) -> Any:
return await run_push_pull_sync(**kwargs)
sync_push_pull_task = SyncPushPullTask()