Files
ai-agent/backend/plugins/services_bridge.py

185 lines
6.6 KiB
Python

"""The hub's read of the homelab services catalogue, now a live plugin.
``backend/services/`` (the index, the ``service.cards`` merge, ``/api/services``
and ``/api/service``) left the core on 2026-11-28: the ``services`` plugin owns
the whole catalogue. Core code that still needs the list — the tag registry
and the composer's service chips (``GET /api/plugins/services-index``), the
Goals board (``goals/routes.py``), the Graph plugin's ``graph.read`` bridge,
``ai-agent tags`` — asks the plugin declaring
``provides: {"services.index": "<action>"}``, as the owner.
The twin of :mod:`plugins.memories_bridge` / :mod:`plugins.plans_bridge`, with
one difference: the answer is cached 30 s, stale-while-revalidate (the plugin
walks compose and Traefik files of ~60 dirs; the old core index had the same
TTL), keyed on the provider's id, fingerprint, dir and the store's version —
a plugin install, update or toggle reads afresh. With no provider installed,
disabled or failing, :func:`list_services` is ``[]``: a hub without the plugin
simply has no services.
"""
from __future__ import annotations
import logging
import threading
import time
from typing import Any
from plugins.store import OWNER_UID
log = logging.getLogger(__name__)
PROVIDES = "services.index"
TTL_SECS = 30.0
# What a service record may carry (anything else the plugin returns is dropped).
_STR = ("dir", "name", "description", "updatedAt", "icon", "group")
_LISTS = ("urls", "containers", "images", "profiles")
_INTS = ("containerCount", "routerCount")
_BOOLS = ("hasCompose", "hasTraefik")
_AUTH = frozenset({"auth", "public", "api", "mixed"})
_lock = threading.Lock()
_cache: dict[str, tuple[float, list[dict[str, Any]]]] = {}
_refreshing: set[str] = set()
def _provider(deps) -> tuple[dict[str, Any], str] | None:
"""The owner's active plugin providing ``services.index`` → (rec, action)."""
from plugins.waiting import _providers_for
try:
found = _providers_for(deps, OWNER_UID, PROVIDES)
except Exception: # noqa: BLE001 — no plugin store (tests, early boot)
return None
for rec, _grant in found:
mf = rec.get("manifest") or {}
act = (mf.get("provides") or {}).get(PROVIDES)
if act in (mf.get("actions") or {}):
return rec, act
return None
def has_provider(deps) -> bool:
return _provider(deps) is not None
available = has_provider
def _key(deps, rec: dict[str, Any]) -> str:
version = getattr(getattr(deps, "plugin_store", None), "version", 0)
return f"{rec.get('id')}@{rec.get('fingerprint') or ''}:{rec.get('dir') or ''}#{version}"
def _clean_one(raw: Any) -> dict[str, Any] | None:
if not isinstance(raw, dict) or not isinstance(raw.get("dir"), str) or not raw["dir"]:
return None
out: dict[str, Any] = {}
for k in _STR:
v = raw.get(k)
if isinstance(v, str):
out[k] = v[:500]
out.setdefault("name", out["dir"])
out.setdefault("description", "")
for k in _LISTS:
v = raw.get(k)
if isinstance(v, list):
out[k] = [str(x)[:500] for x in v][:200]
for k in _INTS:
v = raw.get(k)
if isinstance(v, int) and not isinstance(v, bool):
out[k] = v
for k in _BOOLS:
if k in raw and raw[k] is not None:
out[k] = bool(raw[k])
if raw.get("auth") in _AUTH:
out["auth"] = raw["auth"]
g = raw.get("goal")
if isinstance(g, dict) and isinstance(g.get("done"), int) and isinstance(g.get("total"), int):
out["goal"] = {"done": g["done"], "total": g["total"]}
else:
out["goal"] = None
return out
def _clean(res: Any) -> list[dict[str, Any]]:
svc = res.get("services") if isinstance(res, dict) else None
if not isinstance(svc, list):
return []
seen: set[str] = set()
out = []
for raw in svc:
rec = _clean_one(raw)
if rec is None or rec["dir"] in seen:
continue
seen.add(rec["dir"])
out.append(rec)
return out
def _run(deps, rec: dict[str, Any], action: str) -> list[dict[str, Any]]:
from plugins.runner import run_script
act = (rec.get("manifest") or {}).get("actions", {}).get(action) or {}
try:
res = run_script(deps, deps.plugin_store, OWNER_UID, rec, act["script"],
payload={"trigger": PROVIDES},
timeout_sec=int(act.get("timeoutSec") or 30))
except Exception as e: # noqa: BLE001 — a broken plugin never breaks the hub
log.warning("services.index via %s failed: %s", rec.get("id"), e)
return []
return _clean(res)
def _refresh_bg(deps, rec: dict[str, Any], action: str, key: str) -> None:
try:
data = _run(deps, rec, action)
with _lock:
# One entry per provider: the new key replaces the older ones.
prefix = key.split("@", 1)[0] + "@"
for k in [k for k in _cache if k.startswith(prefix) and k != key]:
_cache.pop(k, None)
_cache[key] = (time.monotonic(), data)
finally:
with _lock:
_refreshing.discard(key)
def list_services(deps) -> list[dict[str, Any]]:
"""Every service (dir, name, description, goal, updatedAt, icon, group,
urls, containers, containerCount, images, profiles, auth, hasCompose,
hasTraefik, routerCount), newest commit first — as the plugin sorts them;
``[]`` without the plugin. Copies: callers may mutate them."""
hit = _provider(deps)
if hit is None:
return []
rec, action = hit
key = _key(deps, rec)
now = time.monotonic()
prefix = key.split("@", 1)[0] + "@"
with _lock:
cached = _cache.get(key)
stale = cached is None or now - cached[0] >= TTL_SECS
if cached is None:
# A plugin write moved the key: serve the provider's previous
# answer while the new one is read (a plugin write is frequent —
# job stamps — and must not make a request wait on the plugin).
older = [v for k, v in _cache.items() if k.startswith(prefix)]
cached = older[0] if older else None
if cached is not None:
if stale and key not in _refreshing:
_refreshing.add(key)
threading.Thread(target=_refresh_bg, args=(deps, rec, action, key),
daemon=True, name="services-index-refresh").start()
return [dict(it) for it in cached[1]]
data = _run(deps, rec, action)
with _lock:
_cache[key] = (time.monotonic(), data)
return [dict(it) for it in data]
def invalidate() -> None:
"""Drop every cached answer (tests; a plugin write also moves the key)."""
with _lock:
_cache.clear()