feat(system): add worker and VPS catalogs with guarded local removal

This commit is contained in:
DCCONSTRUCTIONS
2026-11-10 01:11:24 +03:00
parent ad5a929e06
commit e8025bc99f
25 changed files with 1556 additions and 116 deletions
+3
View File
@@ -158,6 +158,7 @@ from k1link.web.simulation_world_provider_api import build_simulation_world_prov
from k1link.web.system_telemetry_api import build_system_telemetry_router
from k1link.web.viewer_diagnostics_api import build_viewer_diagnostics_router
from k1link.web.vps_host_api import router as vps_host_router
from k1link.web.server_catalog_api import router as server_catalog_router
from k1link.web.vps_host_api import start as start_vps_hosts
REPOSITORY_ROOT = Path(__file__).resolve().parents[3]
@@ -856,6 +857,8 @@ app.include_router(fleet_router)
app.include_router(equipment_router)
app.include_router(equipment_firmware_router)
app.include_router(vps_host_router)
app.state.system_connections_root = REPOSITORY_ROOT / ".runtime" / "system"
app.include_router(server_catalog_router)
app.include_router(installer_router)
app.include_router(rover_router)
+188
View File
@@ -0,0 +1,188 @@
"""Global VPS inventory; existing ARNavi/WireGuard authorities perform admission."""
import asyncio
import copy
import http.client
import sqlite3
import threading
from collections.abc import Callable
from typing import Annotated, Literal
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel, ConfigDict, Field
from k1link.fleet.network_profiles import parse_file
from k1link.fleet.registry import FleetRegistry
from k1link.fleet.server_catalog import Document, ServerCatalog, endpoint_address
from k1link.fleet.server_removal import ServerRemoval
from k1link.fleet.vps_transport import invitation
from k1link.web.fleet_api import local_operator
from k1link.web.server_health import ServerHealth
from k1link.web.vps_host_api import store as arnavi_store
router = APIRouter(prefix="/api/v1/system/servers", tags=["system-servers"])
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
# Serialize this catalog's edits and imports, including the remote admission.
lock = threading.RLock()
class Details(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str = Field(min_length=1, max_length=80)
address: str = Field(min_length=1, max_length=253)
class Update(Details):
expected_revision: int = Field(ge=1, strict=True)
class ServiceImport(BaseModel):
model_config = ConfigDict(extra="forbid")
kind: Literal["arnavi", "wireguard"]
document: str = Field(min_length=1, max_length=16384)
network_interface: str | None = Field(default=None, max_length=20)
expected_revision: int = Field(ge=1, strict=True)
class RemovalPreview(BaseModel):
model_config = ConfigDict(extra="forbid")
expected_revision: int = Field(ge=1, strict=True)
class Removal(RemovalPreview):
confirmation: str = Field(pattern=r"^[a-f0-9]{64}$")
def services(fleet: FleetRegistry) -> list[Document]:
# Do not silently show missing service stores as an empty inventory.
result = []
for h in arnavi_store(fleet).listing():
result.append(
dict(
kind="arnavi",
id=h["id"],
endpoint=h["endpoint"],
name="ARNavi",
state=h["state"],
last_seen=h["last_sync_at"],
details=h,
)
)
for p in fleet.network_profiles.listing(): # type: ignore[no-untyped-call] # existing network authority
result.append(
dict(
kind="wireguard",
id=p["id"],
endpoint=p["endpoint"],
name="WireGuard",
state=p["state"],
last_seen=p.get("last_verified"),
details=p,
)
)
return result
def perform(callback: Callable[[], Document]) -> Document:
try:
with lock:
return callback()
except ValueError as error:
raise HTTPException(409, str(error)) from None
except (OSError, sqlite3.Error, http.client.HTTPException):
raise HTTPException(503, "Операция VPS не завершена. Повторите действие.") from None
@router.get("")
def listing(response: Response, fleet: Fleet) -> Document:
response.headers["Cache-Control"] = "no-store"
return perform(lambda: {"items": ServerCatalog(fleet.root).listing(services(fleet))})
@router.get("/{key}/health")
async def health(key: str, request: Request, response: Response, fleet: Fleet) -> Document:
response.headers["Cache-Control"] = "no-store"
host = perform(lambda: ServerCatalog(fleet.root).find(key, services(fleet)))
observer = getattr(request.app.state, "server_health", None)
if observer is None:
observer = request.app.state.server_health = ServerHealth()
known = {(s["kind"], s["id"]) for s in host["services"]}
rows = [("arnavi", r) for r in arnavi_store(fleet).rows() if ("arnavi", r["id"]) in known]
with fleet.network_profiles.lock:
rows += [
("wireguard", copy.deepcopy(r))
for r in fleet.network_profiles.profiles.values()
if ("wireguard", r["server_id"]) in known
]
async def inspect(kind: str, row: Document) -> Document:
observed = await observer.observe(kind, row, fleet.network_profiles.verify_status)
return {"kind": kind, "id": row.get("id", row.get("server_id")), **observed}
return {"items": await asyncio.gather(*(inspect(kind, row) for kind, row in rows))}
@router.post("")
def create(body: Details, fleet: Fleet) -> Document:
return perform(lambda: ServerCatalog(fleet.root).save(body.name, body.address, services(fleet)))
def removal_target(key: str, revision: int, fleet: FleetRegistry) -> Document:
host = ServerCatalog(fleet.root).find(key, services(fleet))
if host["revision"] != revision:
raise ValueError("Настройки VPS изменились. Откройте их повторно.")
return host
@router.post("/{key}/removal")
def prepare_removal(key: str, body: RemovalPreview, request: Request, fleet: Fleet) -> Document:
return perform(
lambda: ServerRemoval(fleet, request.app.state.system_connections_root).preview(
removal_target(key, body.expected_revision, fleet)
)
)
@router.delete("/{key}")
def remove(key: str, body: Removal, request: Request, fleet: Fleet) -> Document:
return perform(
lambda: ServerRemoval(fleet, request.app.state.system_connections_root).remove(
removal_target(key, body.expected_revision, fleet), body.confirmation
)
)
@router.put("/{key}")
def update(key: str, body: Update, fleet: Fleet) -> Document:
return perform(
lambda: ServerCatalog(fleet.root).save(
body.name, body.address, services(fleet), key, body.expected_revision
)
)
@router.post("/{key}/services")
def connect_service(key: str, body: ServiceImport, fleet: Fleet) -> Document:
def connect() -> Document:
catalog = ServerCatalog(fleet.root)
host = catalog.find(key, services(fleet))
if host["revision"] != body.expected_revision:
raise ValueError("Настройки VPS изменились. Откройте их повторно.")
parsed = (
parse_file(body.document) # type: ignore[no-untyped-call] # existing invitation validator
if body.kind == "wireguard"
else invitation(body.document.strip())
)
if endpoint_address(parsed["endpoint"]) != host["address"]:
raise ValueError("Приглашение выдано другим VPS. Проверьте адрес выбранного сервера.")
if body.kind == "wireguard":
fleet.network_profiles.import_file( # type: ignore[no-untyped-call] # existing admission authority
body.document, host["name"], body.network_interface
)
else:
arnavi_store(fleet).pair(body.document, host["name"], [], body.network_interface)
# Membership derives from the authoritative registries: no second commit
# can orphan a successfully paired service, including after a lost response.
return catalog.find(key, services(fleet))
return perform(connect)
+59
View File
@@ -0,0 +1,59 @@
"""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 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)