"""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()