# -*- coding: utf-8 -*- """Ops-neko edge ↔ hub realtime sync (heartbeat). Physical (edge): once hub URL + token are saved, continuously push instance catalog (+ existing binds) to VPS. No manual「配对同步」needed after connect. """ from __future__ import annotations import asyncio import time from typing import Any _state: dict[str, Any] = { "enabled": False, "connected": False, "last_ok_at": 0.0, "last_error": "", "last_result": {}, "interval_sec": 5.0, "ticks": 0, } _kick: asyncio.Event | None = None def status() -> dict[str, Any]: st = dict(_state) age = None if st.get("last_ok_at"): age = max(0.0, time.time() - float(st["last_ok_at"])) st["last_ok_age_sec"] = age return {"ok": True, **st} def kick() -> None: """Wake the loop for an immediate sync (after create/start/stop/pair).""" ev = _kick if ev is not None: ev.set() def sync_once() -> dict[str, Any]: """One edge→hub push. No-op when not configured as edge.""" from . import ops_neko from . import ops_neko_db peer = ops_neko_db.peer_status() if peer.get("role") != "edge": _state["enabled"] = False _state["connected"] = False return {"ok": True, "skipped": "not_edge", "role": peer.get("role")} if not peer.get("peer_base_url") or not peer.get("has_token"): _state["enabled"] = True _state["connected"] = False _state["last_error"] = "缺少 hub 域名或 token" return {"ok": False, "error": "缺少 hub 域名或 token"} _state["enabled"] = True # Keep YouTube Live Control Room open on bound ops-neko Chrome before catalog push. try: live = ops_neko.ensure_bound_slots_live_studio() except Exception as exc: live = {"ok": False, "error": str(exc)[:200]} catalog = ops_neko.push_catalog_to_hub() binds: list[dict[str, Any]] = [] for row in ops_neko_db.list_instances(): gid = str(row.get("bind_remote_group_id") or "").strip() if not gid: continue try: binds.append(ops_neko.push_bind_to_hub(str(row.get("id") or ""), also_catalog=False)) except Exception as exc: binds.append({"ok": False, "error": str(exc)[:200], "id": row.get("id")}) ok = bool(catalog.get("ok")) _state["ticks"] = int(_state.get("ticks") or 0) + 1 _state["last_result"] = { "catalog_ok": ok, "catalog_count": (catalog.get("count") if isinstance(catalog, dict) else None), "binds_ok": sum(1 for b in binds if b.get("ok")), "live_ensured": (live.get("ensured") if isinstance(live, dict) else None), } if ok: _state["connected"] = True _state["last_ok_at"] = time.time() _state["last_error"] = "" else: _state["connected"] = False _state["last_error"] = str(catalog.get("error") or "catalog push failed")[:300] return {"ok": ok, "catalog": catalog, "binds": binds} async def edge_sync_loop(*, interval_sec: float = 5.0) -> None: """Background loop — only does work when peer role is edge.""" global _kick _kick = asyncio.Event() _state["interval_sec"] = float(interval_sec) while True: try: await asyncio.to_thread(sync_once) except asyncio.CancelledError: raise except Exception as exc: _state["connected"] = False _state["last_error"] = str(exc)[:300] assert _kick is not None try: await asyncio.wait_for(_kick.wait(), timeout=float(interval_sec)) _kick.clear() except asyncio.TimeoutError: pass except asyncio.CancelledError: raise