Files

57 lines
2.0 KiB
Python

"""Manual bidirectional sync between Home and Neutron Trekker instances.
MVP conflict policy: newest updated_at wins, per record. Each side exposes
GET /api/sync/bundle and POST /api/sync/bundle; "Sync" pulls the peer's
bundle, merges it locally, then pushes the local bundle to the peer.
"""
from __future__ import annotations
import logging
from typing import Any
import httpx
from app.models.route import TrekkerRoute
from app.models.trail_guide import TrailGuide
from app.storage.route_store import Store
log = logging.getLogger("trekker.sync")
def build_bundle(store: Store) -> dict[str, Any]:
return {
"routes": [r.model_dump() for r in store.list_routes()],
"trail_guides": [g.model_dump() for g in store.list_trail_guides()],
}
def merge_bundle(store: Store, bundle: dict[str, Any]) -> dict[str, int]:
"""Apply a peer bundle locally; newest updated_at wins. Returns counts."""
applied = {"routes": 0, "trail_guides": 0}
for raw in bundle.get("trail_guides", []):
incoming = TrailGuide.model_validate(raw)
local = store.get_trail_guide(incoming.id)
if local is None or incoming.updated_at > local.updated_at:
store.save_trail_guide(incoming)
applied["trail_guides"] += 1
for raw in bundle.get("routes", []):
incoming = TrekkerRoute.model_validate(raw)
local = store.get_route(incoming.id)
if local is None or incoming.updated_at > local.updated_at:
store.save_route(incoming)
applied["routes"] += 1
return applied
def sync_with_peer(store: Store, peer_url: str) -> dict[str, Any]:
base = peer_url.rstrip("/")
with httpx.Client(timeout=60) as client:
resp = client.get(f"{base}/api/sync/bundle")
resp.raise_for_status()
pulled = merge_bundle(store, resp.json())
push = client.post(f"{base}/api/sync/bundle", json=build_bundle(store))
push.raise_for_status()
pushed = push.json()
return {"pulled": pulled, "pushed": pushed.get("applied", pushed)}