feat(routers): integrate Banana Pi Client API and onboard LibreSpeed measurements

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.
This commit is contained in:
DCCONSTRUCTIONS
2026-11-11 23:53:46 +03:00
parent 58ac9fe3d2
commit a49fb00b8e
208 changed files with 7007 additions and 881 deletions
+57 -8
View File
@@ -1,5 +1,7 @@
"""Router observation and explicit allowlisted, runtime-bound controls."""
import json
from typing import Annotated
from fastapi import Depends, HTTPException, Request, Response
@@ -8,8 +10,10 @@ from k1link.fleet.trust import PairingError
def register(parent, local_operator):
Operator = Annotated[FleetRegistry, Depends(local_operator)]
@parent.get("/{vehicle_id}/routers")
def read(vehicle_id: str, response: Response, fleet: FleetRegistry = Depends(local_operator)):
def read(vehicle_id: str, response: Response, fleet: Operator):
response.headers["Cache-Control"] = "no-store"
try:
with fleet.lock:
@@ -18,21 +22,33 @@ def register(parent, local_operator):
raise HTTPException(404, "Аппарат не найден.") from None
@parent.get("/{vehicle_id}/routers/journal")
def export(vehicle_id: str, fleet: FleetRegistry = Depends(local_operator)):
def export(vehicle_id: str, fleet: Operator):
try:
with fleet.lock:
state = fleet.routers.view(fleet.find(vehicle_id))
body = {"schema": "missioncore.router-journal/v1", **{k: state[k] for k in ("fresh", "received_at", "events", "journal") if k in state}}
return Response(json.dumps(body, ensure_ascii=False, indent=2), media_type="application/json", headers={"Cache-Control": "no-store", "Content-Disposition": 'attachment; filename="router-journal.json"'})
body = {
"schema": "missioncore.router-journal/v1",
**{
k: state[k] for k in ("fresh", "received_at", "events", "journal") if k in state
},
}
return Response(
json.dumps(body, ensure_ascii=False, indent=2),
media_type="application/json",
headers={
"Cache-Control": "no-store",
"Content-Disposition": 'attachment; filename="router-journal.json"',
},
)
except PairingError:
raise HTTPException(404, "Аппарат не найден.") from None
@parent.post("/{vehicle_id}/routers/access")
async def access(vehicle_id: str, request: Request, response: Response, fleet: FleetRegistry = Depends(local_operator)):
async def access(vehicle_id: str, request: Request, response: Response, fleet: Operator):
response.headers["Cache-Control"] = "no-store"
try:
body = await request.body()
if len(body) > 4096:
if len(body) > 16384:
raise ValueError
return fleet.routers.authorize(fleet, vehicle_id, json.loads(body))
except PairingError as error:
@@ -41,7 +57,7 @@ def register(parent, local_operator):
raise HTTPException(422, "Проверьте данные доступа.") from None
@parent.post("/{vehicle_id}/routers/control")
async def control(vehicle_id: str, request: Request, response: Response, fleet: FleetRegistry = Depends(local_operator)):
async def control(vehicle_id: str, request: Request, response: Response, fleet: Operator):
response.headers["Cache-Control"] = "no-store"
try:
body = await request.body()
@@ -53,11 +69,44 @@ def register(parent, local_operator):
except (ValueError, TypeError):
raise HTTPException(422, "Проверьте команду роутеру.") from None
@parent.post("/{vehicle_id}/routers/inspect")
async def inspect(vehicle_id: str, request: Request, response: Response, fleet: Operator):
response.headers["Cache-Control"] = "no-store"
try:
body = await request.body()
if len(body) > 2048:
raise ValueError
return fleet.routers.inspect(fleet, vehicle_id, json.loads(body))
except PairingError as error:
raise HTTPException(409, str(error)) from None
except (ValueError, TypeError):
raise HTTPException(422, "Проверьте запрос отчёта.") from None
@parent.get("/{vehicle_id}/routers/access/{operation_id}")
def operation(vehicle_id: str, operation_id: str, response: Response, fleet: FleetRegistry = Depends(local_operator)):
def operation(vehicle_id: str, operation_id: str, response: Response, fleet: Operator):
response.headers["Cache-Control"] = "no-store"
try:
with fleet.lock:
return fleet.routers.operation(fleet.find(vehicle_id), operation_id)
except PairingError:
raise HTTPException(404, "Аппарат не найден.") from None
@parent.post("/{vehicle_id}/routers/speedtest")
def speedtest(vehicle_id: str, value: dict, fleet: Operator):
from k1link.fleet.router_speedtest import start
try:
return start(fleet, vehicle_id, value)
except (ValueError, OSError) as error:
raise HTTPException(
409, str(error) if isinstance(error, PairingError) else "Служба замера недоступна."
) from None
@parent.post("/{vehicle_id}/routers/speedtest/{operation_id}/cancel")
def cancel_speedtest(vehicle_id: str, operation_id: str, fleet: Operator):
from k1link.fleet.router_speedtest import cancel
try:
return cancel(fleet, vehicle_id, operation_id)
except PairingError as error:
raise HTTPException(409, str(error)) from None
+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"}
KINDS = {"node", "vps-arnavi", "vps-wireguard", "vps-netbird", "vps-librespeed"}
DOWNLOAD_NAMES = {
"vps-librespeed": "mission-core-librespeed-vps.pyz",
"node": "mission-core-node-install.pyz",
"vps-arnavi": "mission-core-vps-install.pyz",
"vps-wireguard": "mission-core-wireguard-vps.pyz",
+23 -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.librespeed import LibreSpeed
from k1link.fleet.librespeed import invitation as speed_invitation
from k1link.fleet.network_profiles import parse_file
from k1link.fleet.registry import FleetRegistry
from k1link.fleet.server_catalog import Document, ServerCatalog, endpoint_address
@@ -38,7 +40,7 @@ class Update(Details):
class ServiceImport(BaseModel):
model_config = ConfigDict(extra="forbid")
kind: Literal["arnavi", "wireguard"]
kind: Literal["arnavi", "wireguard", "librespeed"]
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)
@@ -80,6 +82,18 @@ def services(fleet: FleetRegistry) -> list[Document]:
details=p,
)
)
for item in LibreSpeed(fleet.root).listing():
result.append(
dict(
kind="librespeed",
id=item["id"],
endpoint=item["endpoint"],
name="LibreSpeed",
state=item["state"],
last_seen=None,
details={**item, "name": "LibreSpeed", "boards": 0, "last_verified": None},
)
)
return result
@@ -115,6 +129,10 @@ async def health(key: str, request: Request, response: Response, fleet: Fleet) -
if ("wireguard", r["server_id"]) in known
]
rows += [
("librespeed", r) for r in LibreSpeed(fleet.root).rows() if ("librespeed", 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}
@@ -171,6 +189,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 speed_invitation(body.document)
if body.kind == "librespeed"
else invitation(body.document.strip())
)
if endpoint_address(parsed["endpoint"]) != host["address"]:
@@ -179,6 +199,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 == "librespeed":
LibreSpeed(fleet.root).pair(body.document, body.network_interface)
else:
arnavi_store(fleet).pair(body.document, host["name"], [], body.network_interface)
# Membership derives from the authoritative registries: no second commit
+19 -4
View File
@@ -14,6 +14,12 @@ 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":
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"
@@ -34,16 +40,24 @@ class ServerHealth:
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"),
))
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:
@@ -54,6 +68,7 @@ class ServerHealth:
return value
finally:
self.pending.pop(key, None)
task = asyncio.create_task(run())
self.pending[key] = task
return await asyncio.shield(task)