Discover Ethernet routers under the board, map physical SIM slots, expose vendor controls and real telemetry, and provide packaged VPS speed tests with a live monochrome gauge. Enforce compact typography across Core and Node UI.
75 lines
2.7 KiB
Python
75 lines
2.7 KiB
Python
"""Read-only, bounded live observations of already trusted VPS services."""
|
|
|
|
import asyncio
|
|
import http.client
|
|
import time
|
|
from collections.abc import Callable
|
|
|
|
from k1link.fleet.server_catalog import Document
|
|
from k1link.fleet.vps_transport import request
|
|
|
|
|
|
def probe(kind: str, row: Document, verify: Callable[[Document, Document], Document]) -> Document:
|
|
try:
|
|
value = request(row, "GET", "/v1/status")
|
|
if kind == "wireguard":
|
|
verify(row, value)
|
|
elif kind == "librespeed":
|
|
if (
|
|
value.get("schema") != "missioncore.librespeed/v1"
|
|
or value.get("server_id") != row["id"]
|
|
):
|
|
raise ValueError("Service identity mismatch")
|
|
elif value.get("schema") != "missioncore.vps-host/v1" or value.get("host_id") != row["id"]:
|
|
raise ValueError("Service identity mismatch")
|
|
state = "online"
|
|
except (OSError, ValueError, KeyError, TypeError, http.client.HTTPException):
|
|
state = "unavailable"
|
|
return {"state": state, "checked_at": time.time()}
|
|
|
|
|
|
class ServerHealth:
|
|
"""RAM-only observations; no enrollment, tunnel apply, or profile writes."""
|
|
|
|
def __init__(self) -> None:
|
|
self.slots = asyncio.Semaphore(4)
|
|
self.cache: dict[tuple[str, ...], tuple[float, Document]] = {}
|
|
self.pending: dict[tuple[str, ...], asyncio.Task[Document]] = {}
|
|
|
|
async def observe(
|
|
self, kind: str, row: Document, verify: Callable[[Document, Document], Document]
|
|
) -> Document:
|
|
# Changes to the trusted binding must invalidate its prior observation.
|
|
key = tuple(
|
|
str(x)
|
|
for x in (
|
|
kind,
|
|
row.get("id", row.get("server_id")),
|
|
row["endpoint"],
|
|
row.get("fingerprint"),
|
|
row.get("token"),
|
|
row.get("network_interface"),
|
|
)
|
|
)
|
|
now = time.monotonic()
|
|
self.cache = {k: v for k, v in self.cache.items() if now - v[0] < 15}
|
|
if key in self.cache:
|
|
return self.cache[key][1]
|
|
task = self.pending.get(key)
|
|
if task is None:
|
|
|
|
async def run() -> Document:
|
|
try:
|
|
async with self.slots:
|
|
value = await asyncio.to_thread(probe, kind, row, verify)
|
|
if len(self.cache) >= 1024:
|
|
self.cache.pop(next(iter(self.cache)))
|
|
self.cache[key] = (time.monotonic(), value)
|
|
return value
|
|
finally:
|
|
self.pending.pop(key, None)
|
|
|
|
task = asyncio.create_task(run())
|
|
self.pending[key] = task
|
|
return await asyncio.shield(task)
|