Files
romm/backend/tasks/sync_push_pull_task.py
Sam Dornan 5a6c895d33 chore(mypy): give every generic its type arguments (#4818)
* chore(mypy): switch to strict mode with listed exceptions

Replace the hand-picked flags with `strict = True`, turning off only the
four flags that aren't clean yet (disallow_any_generics,
warn_return_any, disallow_untyped_calls, disallow_untyped_decorators).
Any other strict flag, including those future mypy releases add to the
preset, is on by default.

That turns on no_implicit_reexport, strict_equality and extra_checks:
- Import each name from the module that defines it. About 240 test
  sites patched a dependency through the module that imported it
  (`scan_module.fs_rom_handler`); they now import the same object from
  its source, so every patch targets what it did before. Tests that
  replace a module attribute are unchanged.
- handler.streaming.memory_cards re-exports store_memory_card_version
  explicitly, since endpoints call it there and tests patch it there.
- mutagen gets implicit_reexport, as it re-exports without __all__.
- Test comparisons build typed values (CoverResult, a typed expected
  dict, enum .value) and the CORS lookup casts for its identity check.
- One ss_handler ** spread keeps a coded ignore: extra_checks wants its
  NotRequired dump_* keys spelled out, and the media dict never has them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* chore(mypy): give every generic its type arguments

Drop disallow_any_generics from the strict-mode exceptions and fix the
347 bare generics it reports, 230 of them in app code.

- Bare `dict` becomes `dict[str, Any]`: update payloads, raw provider
  JSON and endpoint bodies map string keys to mixed values, so the Any is
  real and now written down. The OpenAPI document is unchanged.
- Rom query filters take and return RomSelect; _music_facet_joins and
  _exclude_hidden are generic over the Select they're given, and
  _build_hash_selects returns id-only selects.
- Redis clients are typed by what they return: the decoding caches are
  Redis[str], the RQ connection and binary cache Redis[bytes].
- The rest get explicit parameters: Row, Pattern, ColumnElement,
  QueryableAttribute, SpooledTemporaryFile, Task, Future and friends.

Precise types reached callers that had been getting Any, which surfaced:
- The LaunchBox cache writer is fed binary-cache pipelines.
- The flashpoint and IGDB request helpers return raw JSON of varying
  shape, not always a dict.
- The rom search endpoint returned dicts under a list[SearchRomSchema]
  annotation; it now validates them into that schema.
- The audit filter's id subquery selects strings.
- In tests the binary cache is the non-decoding fake shared with
  async_cache, so it is cast to Redis[bytes] rather than changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* test(upload): assert cleanup against the patched upload directory

The 409 test checked config's ROM_UPLOAD_TMP_BASE while the fixture patches
the endpoint's copy to tmp_path/uploads, so it passed even if cleanup failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

* chore(mypy): keep the row type through the ROM filter helpers

filter_roms and its helpers also receive select(Rom.id) membership queries,
so they now take and return the caller's Select type instead of narrowing to
RomSelect. merged_ra_metadata mixes scalar and list values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 16:32:29 -05:00

464 lines
16 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 config import ENABLE_SYNC_PUSH_PULL, SYNC_PUSH_PULL_CRON
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
from handler.sync.comparison import compare_save_state
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.tasks import PeriodicTask, TaskType
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 ENABLE_SYNC_PUSH_PULL 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"}
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
)
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,
)
push_count = await _push_missing_saves(
device, conn, remote_saves, save_directories
)
completed += push_count
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,
) -> 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
)
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.rom_id, matched_save.slot
)
if remote_hash != matched_save.content_hash
else None
),
)
if result.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 result.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 result.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 result.action == "conflict":
log.warning(
f"Push-pull: conflict for {remote_save.file_name} "
f"on device {device.id}: {result.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.rom_id,
rom_name=matched_save.rom.name or matched_save.rom.fs_name,
reason=result.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]],
) -> int:
"""Push server saves that are missing from the device."""
ssh_sync_handler = get_ssh_sync_handler()
pushed = 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
)
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,
)
return pushed
class SyncPushPullTask(PeriodicTask):
"""Periodic task to run push-pull sync for all configured devices."""
def __init__(self) -> None:
super().__init__(
title="Push-Pull Sync",
description="Sync saves with devices via SSH/SFTP",
task_type=TaskType.SYNC,
enabled=ENABLE_SYNC_PUSH_PULL,
cron_string=SYNC_PUSH_PULL_CRON,
)
async def run(self, *args: Any, **kwargs: Any) -> Any:
return await run_push_pull_sync(**kwargs)
sync_push_pull_task = SyncPushPullTask()