feat(core): persist viewer state and integrate Cesium services and profiles

This commit is contained in:
DCCONSTRUCTIONS
2026-11-17 17:20:15 +03:00
parent 9cbdd4ea5c
commit 29ef038a43
52 changed files with 2943 additions and 72 deletions
+5 -1
View File
@@ -540,7 +540,11 @@ try:
except (OSError, ValueError):
lab_gateway_configuration = None
laboratory_worker_gateway = LaboratoryWorkerGateway(lab_gateway_configuration)
map_gateway_proxy = MapGatewayProxy(MapGatewayConfiguration.from_environment())
map_gateway_proxy = MapGatewayProxy(
MapGatewayConfiguration.from_environment(),
settings_path=session_store.data_dir / "services" / "cesium-ion" / "settings.json",
fleet_root=session_store.data_dir / "fleet",
)
recording_reconciler_readiness = BackgroundReconcilerReadiness()
+2 -1
View File
@@ -14,8 +14,9 @@ from k1link.web.fleet_api import local_operator
router = APIRouter(prefix="/api/v1/fleet/installers", tags=["installers"])
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
KINDS = {"node", "vps-arnavi", "vps-wireguard", "vps-netbird", "vps-librespeed"}
KINDS = {"node", "vps-arnavi", "vps-wireguard", "vps-netbird", "vps-librespeed", "vps-egress"}
DOWNLOAD_NAMES = {
"vps-egress": "mission-core-egress-vps.pyz",
"vps-librespeed": "mission-core-librespeed-vps.pyz",
"node": "mission-core-node-install.pyz",
"vps-arnavi": "mission-core-vps-install.pyz",
+25 -1
View File
@@ -5,6 +5,7 @@ import re
from collections.abc import AsyncIterator, Mapping
from dataclasses import dataclass
from ipaddress import ip_address
from pathlib import Path as FilePath
from typing import Annotated, Any, Final
from urllib.parse import parse_qsl, urlsplit
@@ -12,6 +13,11 @@ import httpx
from fastapi import APIRouter, HTTPException, Path, Query, Request
from fastapi.responses import JSONResponse, Response, StreamingResponse
from k1link.maps.direct import json_response
from k1link.maps.routing import MapServiceRoutes
from k1link.maps.settings import CesiumSettingsStore, MapServiceError
from k1link.web.map_services_api import build_map_services_router
MAP_GATEWAY_URL_ENV: Final = "MISSIONCORE_MAP_GATEWAY_INTERNAL_URL"
MAP_SANDBOX_HIDE_CREDITS_ENV: Final = "MISSIONCORE_MAP_SANDBOX_HIDE_CREDITS"
MAP_SCHEMA_VERSION: Final = "missioncore.map-gateway/v1"
@@ -46,6 +52,7 @@ RESPONSE_HEADER_ALLOWLIST: Final = frozenset(
"expires",
"last-modified",
"vary",
"x-nodedc-map-route",
}
)
SENSITIVE_JSON_KEYS: Final = frozenset(
@@ -100,6 +107,8 @@ class MapGatewayProxy:
configuration: MapGatewayConfiguration,
*,
client: httpx.AsyncClient | None = None,
settings_path: FilePath | None = None,
fleet_root: FilePath | None = None,
) -> None:
self._configuration = configuration
self._owns_client = client is None
@@ -117,10 +126,14 @@ class MapGatewayProxy:
keepalive_expiry=30.0,
),
)
self.routes = (MapServiceRoutes(CesiumSettingsStore(settings_path),
configuration.internal_url, self._client, fleet_root=fleet_root)
if settings_path is not None else None)
@property
def configured(self) -> bool:
return self._configuration.internal_url is not None
return (self.routes.configured if self.routes is not None
else self._configuration.internal_url is not None)
def runtime_configuration(self) -> Response:
if not self.configured:
@@ -249,6 +262,15 @@ class MapGatewayProxy:
query: Mapping[str, str] | None = None,
) -> httpx.Response:
_require_loopback_request(request)
if self.routes is not None:
headers = {name: value for name, value in request.headers.items()
if name.lower() in REQUEST_HEADER_ALLOWLIST}
headers["x-nodedc-user-id"] = MAP_GATEWAY_SUBJECT
try:
return await self.routes.send(request.method, upstream_path,
dict(query) if query else None, headers)
except MapServiceError as exc:
return json_response({"code": exc.code, "retryable": exc.status >= 500}, exc.status)
base_url = self._configuration.internal_url
if base_url is None:
raise HTTPException(
@@ -452,6 +474,8 @@ def _filtered_response_headers(headers: httpx.Headers) -> dict[str, str]:
def build_map_router(service: MapGatewayProxy) -> APIRouter:
router = APIRouter(prefix="/api/v1/map", tags=["map"])
if service.routes is not None:
router.include_router(build_map_services_router(service.routes, _require_loopback_request))
@router.get("/runtime-config")
async def runtime_config(request: Request) -> Response:
+102
View File
@@ -0,0 +1,102 @@
from __future__ import annotations
import json
from collections.abc import Callable
from typing import Any
from urllib.parse import urlsplit
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from k1link.maps.routing import MapServiceRoutes
from k1link.maps.settings import MODES, MapServiceError, validate_egress, validate_token
def reply(value: dict[str, Any], status: int = 200) -> JSONResponse:
return JSONResponse(value, status_code=status, headers={"Cache-Control": "no-store"})
async def payload(request: Request) -> dict[str, Any]:
host = urlsplit(str(request.url)).hostname
origin = request.headers.get("origin")
if (
host not in {"127.0.0.1", "localhost", "::1"}
or request.headers.get("sec-fetch-site") == "cross-site"
or (origin is not None and origin != str(request.base_url).rstrip("/"))
):
raise MapServiceError("cesium_settings_local_only", 403)
if request.headers.get("content-type", "").split(";", 1)[0] != "application/json":
raise MapServiceError("cesium_settings_invalid_request", 415)
body = bytearray()
async for chunk in request.stream():
body.extend(chunk)
if len(body) > 16384:
raise MapServiceError("cesium_settings_invalid_request", 413)
try:
value = json.loads(body)
if not isinstance(value, dict):
raise ValueError
return value
except (ValueError, UnicodeError) as exc:
raise MapServiceError("cesium_settings_invalid_request", 422) from exc
def build_map_services_router(
service: MapServiceRoutes, require_local: Callable[[Request], None]
) -> APIRouter:
router = APIRouter(prefix="/services/cesium-ion")
@router.get("")
async def status(request: Request) -> JSONResponse:
require_local(request)
try:
return reply(service.status())
except MapServiceError as exc:
return reply({"code": exc.code}, exc.status)
@router.post("/verify")
async def verify(request: Request) -> JSONResponse:
require_local(request)
try:
value = await payload(request)
if set(value) - {"token", "egress_id"}:
raise MapServiceError("cesium_settings_invalid_request", 422)
token = validate_token(value["token"]) if "token" in value else None
return reply(
await service.verify(
token, validate_egress(value["egress_id"]) if "egress_id" in value else None
)
)
except MapServiceError as exc:
return reply({"code": exc.code}, exc.status)
@router.put("")
async def save(request: Request) -> JSONResponse:
require_local(request)
try:
value = await payload(request)
if (
set(value) - {"revision", "mode", "token", "remove_token", "egress_id"}
or type(value.get("revision")) is not int
or value["revision"] < 0
or not isinstance(value.get("mode"), str)
or value["mode"] not in MODES
or type(value.get("remove_token", False)) is not bool
or (value.get("remove_token") and "token" in value)
):
raise MapServiceError("cesium_settings_invalid_request", 422)
token = validate_token(value["token"]) if "token" in value else None
return reply(
await service.save(
value["revision"],
value["mode"],
token,
remove=value.get("remove_token", False),
egress_id=validate_egress(value["egress_id"]) if "egress_id" in value else None,
)
)
except MapServiceError as exc:
# Never reflect upstream bodies, validation input or secret values.
return reply({"code": exc.code}, exc.status)
return router
+26 -1
View File
@@ -11,6 +11,8 @@ from typing import Annotated, Literal
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel, ConfigDict, Field
from k1link.fleet.egress import Egress
from k1link.fleet.egress import invitation as egress_invitation
from k1link.fleet.librespeed import LibreSpeed
from k1link.fleet.librespeed import invitation as speed_invitation
from k1link.fleet.network_profiles import parse_file
@@ -40,7 +42,7 @@ class Update(Details):
class ServiceImport(BaseModel):
model_config = ConfigDict(extra="forbid")
kind: Literal["arnavi", "wireguard", "librespeed"]
kind: Literal["arnavi", "wireguard", "librespeed", "egress"]
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)
@@ -94,6 +96,23 @@ def services(fleet: FleetRegistry) -> list[Document]:
details={**item, "name": "LibreSpeed", "boards": 0, "last_verified": None},
)
)
for item in Egress(fleet.root).listing():
result.append(
dict(
kind="egress",
id=item["id"],
endpoint=item["endpoint"],
name="Маршрутизация трафика",
state=item["state"],
last_seen=None,
details={
**item,
"name": "Маршрутизация трафика",
"boards": 0,
"last_verified": None,
},
)
)
return result
@@ -133,6 +152,8 @@ async def health(key: str, request: Request, response: Response, fleet: Fleet) -
("librespeed", r) for r in LibreSpeed(fleet.root).rows() if ("librespeed", r["id"]) in known
]
rows += [("egress", r) for r in Egress(fleet.root).rows() if ("egress", r["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}
@@ -189,6 +210,8 @@ def connect_service(key: str, body: ServiceImport, fleet: Fleet) -> Document:
parsed = (
parse_file(body.document) # type: ignore[no-untyped-call] # existing invitation validator
if body.kind == "wireguard"
else egress_invitation(body.document)
if body.kind == "egress"
else speed_invitation(body.document)
if body.kind == "librespeed"
else invitation(body.document.strip())
@@ -199,6 +222,8 @@ def connect_service(key: str, body: ServiceImport, fleet: Fleet) -> Document:
fleet.network_profiles.import_file( # type: ignore[no-untyped-call] # existing admission authority
body.document, host["name"], body.network_interface
)
elif body.kind == "egress":
Egress(fleet.root).pair(body.document, body.network_interface)
elif body.kind == "librespeed":
LibreSpeed(fleet.root).pair(body.document, body.network_interface)
else:
+2 -2
View File
@@ -14,9 +14,9 @@ def probe(kind: str, row: Document, verify: Callable[[Document, Document], Docum
value = request(row, "GET", "/v1/status")
if kind == "wireguard":
verify(row, value)
elif kind == "librespeed":
elif kind in {"librespeed", "egress"}:
if (
value.get("schema") != "missioncore.librespeed/v1"
value.get("schema") != f"missioncore.{kind}/v1"
or value.get("server_id") != row["id"]
):
raise ValueError("Service identity mismatch")