feat(fleet): integrate independent trackers, VPS pairing and recoverable commands

This commit is contained in:
DCCONSTRUCTIONS
2026-09-28 18:44:12 +03:00
parent d684eb7e05
commit f3a7592d90
45 changed files with 10006 additions and 0 deletions
+9
View File
@@ -112,6 +112,10 @@ from k1link.web.advanced_laboratory_api import build_advanced_laboratory_router
from k1link.web.artifact_health_api import build_artifact_health_router
from k1link.web.compute_contour_api import build_compute_contour_router
from k1link.web.fleet_api import router as fleet_router
from k1link.web.independent_equipment_api import router as equipment_router
from k1link.web.equipment_firmware_api import router as equipment_firmware_router
from k1link.web.installer_api import router as installer_router
from k1link.web.vps_host_api import router as vps_host_router, start as start_vps_hosts
from k1link.web.rover_api import router as rover_router
from k1link.web.device_plugin_composition import load_installed_device_plugins
from k1link.web.e30_engineering_api import build_e30_engineering_router
@@ -939,6 +943,7 @@ async def app_lifespan(application: FastAPI) -> AsyncIterator[None]:
try:
fleet = FleetRegistry(session_store.data_dir / "fleet")
fleet.start()
start_vps_hosts(fleet)
application.state.fleet = fleet
except (OSError, ValueError, sqlite3.Error):
# Fail closed for pairing without taking down unrelated operator work.
@@ -1005,6 +1010,10 @@ app.add_middleware(ResponseCompressionMiddleware, minimum_size=1_024, compressle
app.include_router(fleet_router)
app.include_router(equipment_router)
app.include_router(equipment_firmware_router)
app.include_router(vps_host_router)
app.include_router(installer_router)
app.include_router(rover_router)
+74
View File
@@ -0,0 +1,74 @@
"""Local firmware files only: no USB, VPS, or manufacturer requests."""
import sqlite3
from typing import Annotated, Any
from urllib.parse import quote
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from starlette.concurrency import run_in_threadpool
from k1link.fleet.equipment_firmware import MAX_FIRMWARE_BYTES, FirmwareError
from k1link.fleet.registry import FleetRegistry
from k1link.web.fleet_api import local_operator
from k1link.web.independent_equipment_composition import firmware_archive
router = APIRouter(prefix="/api/v1/fleet/equipment/firmware", tags=["equipment-firmware"])
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
@router.get("/{model}")
def catalog(model: str, response: Response, fleet: Fleet) -> dict[str, Any]:
response.headers["Cache-Control"] = "no-store"
try:
return {"items": firmware_archive(fleet).listing(model), "update_available": False}
except FirmwareError as exc:
raise HTTPException(409, str(exc)) from None
except (OSError, sqlite3.Error):
raise HTTPException(503, "Архив прошивок недоступен.") from None
@router.post("/{model}")
async def upload(
model: str,
request: Request,
fleet: Fleet,
filename: str = Query(min_length=1, max_length=120),
) -> dict[str, Any]:
if request.headers.get("content-type", "").split(";")[0] != "application/octet-stream":
raise HTTPException(415, "Передайте файл .dfw.")
data = bytearray()
async for chunk in request.stream():
if len(data) + len(chunk) > MAX_FIRMWARE_BYTES:
raise HTTPException(413, "Размер файла не должен превышать 4 МБ.")
data.extend(chunk)
def save() -> dict[str, Any]:
return firmware_archive(fleet).add(model, filename, bytes(data))
try:
return await run_in_threadpool(save)
except FirmwareError as exc:
raise HTTPException(422, str(exc)) from None
except (OSError, sqlite3.Error):
raise HTTPException(503, "Не удалось сохранить файл прошивки.") from None
@router.get("/{model}/{digest}/download")
def download(model: str, digest: str, fleet: Fleet) -> Response:
try:
item, data = firmware_archive(fleet).download(model, digest)
except FirmwareError as exc:
raise HTTPException(404, str(exc)) from None
except (OSError, sqlite3.Error):
raise HTTPException(503, "Файл прошивки недоступен.") from None
return Response(
data,
media_type="application/octet-stream",
headers={
"Content-Disposition": "attachment; filename*=UTF-8''"
+ quote(item["filename"], safe=""),
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
"X-Content-SHA256": item["sha256"],
},
)
+258
View File
@@ -0,0 +1,258 @@
"""Local operator API for independent equipment, profiles and assignments."""
from collections.abc import Callable
from typing import Annotated, Literal
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from k1link.fleet.independent_equipment import Document, EquipmentError
from k1link.fleet.registry import FleetRegistry
from k1link.fleet.trust import PairingError
from k1link.web.fleet_api import local_operator
from k1link.web.independent_equipment_composition import equipment_store
router = APIRouter(prefix="/api/v1/fleet/equipment", tags=["independent-equipment"])
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
class ModelRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
model_id: str = Field(min_length=1, max_length=60)
class ProfileRequest(ModelRequest):
name: str = Field(min_length=1, max_length=80)
settings: Document
class AddRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
candidate_id: str = Field(min_length=43, max_length=43)
name: str = Field(min_length=1, max_length=80)
vehicle_id: str = Field(min_length=1, max_length=80)
profile_id: str | None = Field(default=None, min_length=32, max_length=32)
class UpdateRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
expected_revision: int = Field(ge=1, strict=True)
name: str = Field(min_length=1, max_length=80)
vehicle_id: str = Field(min_length=1, max_length=80)
settings: Document
def action(response: Response, callback: Callable[[], Document]) -> Document:
response.headers["Cache-Control"] = "no-store"
try:
return callback()
except (EquipmentError, PairingError) as exc:
raise HTTPException(409, str(exc)) from None
except ValidationError:
raise HTTPException(
422, "Проверьте значения профиля. Уникальные данные и пароли в профиль не входят."
) from None
except ValueError:
raise HTTPException(
422,
"Не удалось проверить настройки или прочитать устройство. "
"Проверьте USB и совместимость профиля.",
) from None
except OSError:
raise HTTPException(503, "Хранилище или USB недоступны. Повторите действие.") from None
@router.get("/catalog")
def catalog(response: Response, fleet: Fleet) -> Document:
return action(response, lambda: equipment_store(fleet).catalog())
@router.get("/profiles")
def profiles(response: Response, fleet: Fleet) -> Document:
return action(response, lambda: {"items": equipment_store(fleet).profiles()})
@router.post("/profiles")
def save_profile(body: ProfileRequest, response: Response, fleet: Fleet) -> Document:
return action(
response,
lambda: equipment_store(fleet).save_profile(body.name, body.model_id, body.settings),
)
@router.post("/inspect")
def inspect(body: ModelRequest, response: Response, fleet: Fleet) -> Document:
return action(response, lambda: equipment_store(fleet).inspect(body.model_id))
@router.get("/instances")
def instances(response: Response, fleet: Fleet, vehicle_id: str | None = None) -> Document:
return action(response, lambda: {"items": equipment_store(fleet).listing(vehicle_id)})
@router.post("/instances")
def add(body: AddRequest, response: Response, fleet: Fleet) -> Document:
def run() -> Document:
with fleet.lock:
fleet.find(body.vehicle_id) # type: ignore[no-untyped-call] # legacy fleet boundary
result = equipment_store(fleet).add(**body.model_dump())
fleet.events.notify() # type: ignore[no-untyped-call] # legacy fleet boundary
return result
return action(response, run)
@router.put("/instances/{identifier}")
def update(identifier: str, body: UpdateRequest, response: Response, fleet: Fleet) -> Document:
def run() -> Document:
with fleet.lock:
fleet.find(body.vehicle_id) # type: ignore[no-untyped-call] # legacy fleet boundary
result = equipment_store(fleet).update(
identifier, body.expected_revision, body.name, body.vehicle_id, body.settings
)
fleet.events.notify() # type: ignore[no-untyped-call] # legacy fleet boundary
return result
return action(response, run)
class ReadRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
expected_revision: int = Field(ge=1, strict=True)
class NetworkApplyRequest(ReadRequest):
select_sim: bool = Field(default=False, strict=True)
class CommandRequest(ReadRequest):
kind: Literal["request-position", "pulse-output", "set-output", "restart"]
pin: int | None = Field(default=None, ge=4, le=6, strict=True)
seconds: int | None = Field(default=None, ge=1, le=5, strict=True)
enabled: bool | None = Field(default=None, strict=True)
@router.post("/instances/{identifier}/command")
def send_command(
identifier: str, body: CommandRequest, response: Response, fleet: Fleet
) -> Document:
from k1link.fleet.equipment_network import start
from k1link.web.vps_host_api import store
command = body.model_dump(exclude={"expected_revision"}, exclude_none=True)
return action(
response, lambda: start(store(fleet), identifier, body.expected_revision, command=command)
)
@router.post("/instances/{identifier}/inspect")
def read_existing(identifier: str, body: ReadRequest, response: Response, fleet: Fleet) -> Document:
return action(
response,
lambda: equipment_store(fleet).refresh_observation(identifier, body.expected_revision),
)
@router.post("/instances/{identifier}/apply")
def apply_existing(
identifier: str, body: ReadRequest, response: Response, fleet: Fleet
) -> Document:
from k1link.fleet.equipment_bootstrap import apply
from k1link.web.vps_host_api import store
return action(response, lambda: apply(store(fleet), identifier, body.expected_revision))
@router.post("/instances/{identifier}/apply-network")
def apply_network(
identifier: str, body: NetworkApplyRequest, response: Response, fleet: Fleet
) -> Document:
from k1link.fleet.equipment_network import start
from k1link.web.vps_host_api import store
return action(
response,
lambda: start(store(fleet), identifier, body.expected_revision, select_sim=body.select_sim),
)
@router.post("/instances/{identifier}/inspect-network")
def inspect_network(
identifier: str, body: ReadRequest, response: Response, fleet: Fleet
) -> Document:
from k1link.fleet.equipment_network import start
from k1link.web.vps_host_api import store
return action(response, lambda: start(store(fleet), identifier, body.expected_revision, True))
class QueuedCommandRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
request_id: str = Field(pattern=r"^[a-f0-9]{32}$")
preset_id: str = Field(min_length=1, max_length=40)
@router.get("/instances/{identifier}/commands")
def command_runtime(
identifier: str,
response: Response,
fleet: Fleet,
before: int | None = Query(default=None, ge=1),
tracked: Annotated[list[str] | None, Query(max_length=32)] = None,
) -> Document:
from k1link.fleet.equipment_command_catalog import catalog
from k1link.fleet.equipment_command_journal import listing
from k1link.fleet.equipment_command_runtime import source
from k1link.fleet.equipment_operations import KINDS, supported
from k1link.web.vps_host_api import store
def run() -> Document:
equipment = equipment_store(fleet)
with equipment.db() as db:
row = equipment._find(db, "instances", identifier)
host = source(store(fleet), row)
return {
**listing(equipment, identifier, before, tracked=tracked or ()),
"device": equipment.public(row),
"catalog": catalog(equipment, row),
"capacity": 32,
"durable_kinds": sorted(k for k in KINDS if supported(host or {}, k)),
}
return action(response, run)
@router.post("/instances/{identifier}/commands")
def enqueue_command(
identifier: str, body: QueuedCommandRequest, response: Response, fleet: Fleet
) -> Document:
from k1link.fleet.equipment_command_runtime import enqueue
from k1link.web.vps_host_api import store
return action(
response, lambda: enqueue(store(fleet), identifier, body.request_id, body.preset_id)
)
@router.post("/instances/{identifier}/commands/{request_id}/cancel")
def cancel_command(identifier: str, request_id: str, response: Response, fleet: Fleet) -> Document:
from k1link.fleet.equipment_command_runtime import cancel
from k1link.web.vps_host_api import store
return action(
response, lambda: cancel(equipment_store(fleet), identifier, request_id, store(fleet))
)
@router.get("/instances/{identifier}/commands/{request_id}/attempts")
def command_attempts(
identifier: str,
request_id: str,
response: Response,
fleet: Fleet,
before: int | None = Query(default=None, ge=1),
) -> Document:
from k1link.fleet.equipment_operations import attempts
from k1link.web.vps_host_api import store
return action(response, lambda: attempts(store(fleet), identifier, request_id, before))
@@ -0,0 +1,19 @@
"""Reviewed operator-host enrollment adapters; no onboard plugin dependency."""
from k1link.device_plugins.arnavi_b2.enrollment import B2Enrollment
from k1link.device_plugins.arnavi_b2.firmware import KNOWN_IMAGES
from k1link.fleet.equipment_firmware import FirmwareArchive
from k1link.fleet.independent_equipment import EquipmentStore
from k1link.fleet.registry import FleetRegistry
def equipment_store(fleet: FleetRegistry) -> EquipmentStore:
with fleet.lock:
if fleet.independent_equipment is None:
adapter = B2Enrollment()
fleet.independent_equipment = EquipmentStore(fleet.root, {adapter.model_id: adapter})
return fleet.independent_equipment
def firmware_archive(fleet: FleetRegistry) -> FirmwareArchive:
return FirmwareArchive(fleet.root, {B2Enrollment.model_id: KNOWN_IMAGES})
+69
View File
@@ -0,0 +1,69 @@
"""Verified, locally published installers. Never expose arbitrary filesystem paths."""
import hashlib
import json
import re
from pathlib import Path
from typing import Annotated, Any
from fastapi import APIRouter, Depends, HTTPException, Response
from fastapi.responses import FileResponse
from k1link.fleet.registry import FleetRegistry
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"}
DOWNLOAD_NAMES = {
"node": "mission-core-node-install.pyz",
"vps-arnavi": "mission-core-vps-install.pyz",
}
def verified(root: Path, kind: str) -> tuple[dict[str, Any], Path]:
if kind not in KINDS:
raise ValueError("unknown installer")
directory = root / "installers"
item = json.loads((directory / (kind + ".json")).read_text())
if item["id"] != kind or not re.fullmatch(r"[a-zA-Z0-9_.-]+\.pyz", item["filename"]):
raise ValueError("invalid installer manifest")
file = directory / item["filename"]
if file.is_symlink() or file.stat().st_size != item["bytes"]:
raise ValueError("installer changed")
with file.open("rb") as stream:
digest = hashlib.file_digest(stream, "sha256").hexdigest()
if digest != item["sha256"]:
raise ValueError("installer changed")
return {
**item,
"filename": DOWNLOAD_NAMES[kind],
"download_url": f"/api/v1/fleet/installers/{kind}/download",
}, file
@router.get("")
def catalog(response: Response, fleet: Fleet) -> dict[str, Any]:
response.headers["Cache-Control"] = "no-store"
items = []
for kind in sorted(KINDS):
try:
item, _ = verified(fleet.root, kind)
items.append(item)
except (OSError, ValueError, KeyError, TypeError):
continue
return {"items": items}
@router.get("/{kind}/download")
def download(kind: str, fleet: Fleet) -> FileResponse:
try:
item, path = verified(fleet.root, kind)
except (OSError, ValueError, KeyError, TypeError):
raise HTTPException(404, "Проверенный установщик недоступен.") from None
return FileResponse(
path,
filename=item["filename"],
media_type="application/octet-stream",
headers={"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"},
)
+108
View File
@@ -0,0 +1,108 @@
"""Local-operator VPS enrollment and shared vehicle assignment."""
import logging
import sqlite3
from collections.abc import Callable
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Response
from pydantic import BaseModel, ConfigDict, Field
from k1link.fleet.independent_equipment import Document
from k1link.fleet.registry import FleetRegistry
from k1link.fleet.trust import PairingError
from k1link.fleet.vps_hosts import VPSHosts
from k1link.fleet.vps_transport import interfaces
from k1link.web.fleet_api import local_operator
from k1link.web.independent_equipment_composition import equipment_store
router = APIRouter(prefix="/api/v1/fleet/vps-hosts", tags=["vps-hosts"])
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
def start(fleet: FleetRegistry) -> None:
try:
fleet.vps_hosts = VPSHosts(fleet.root, fleet.trust.core_id, equipment_store(fleet))
fleet.vps_hosts.start()
except (OSError, ValueError, sqlite3.Error):
fleet.vps_hosts = None
logging.getLogger(__name__).error("VPS storage unavailable; independent host API disabled")
def store(fleet: FleetRegistry) -> VPSHosts:
if fleet.vps_hosts is None:
raise HTTPException(503, "Хранилище VPS недоступно.")
return fleet.vps_hosts
class Details(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str = Field(min_length=1, max_length=80)
vehicle_ids: list[str] = Field(max_length=10000)
network_interface: str | None = Field(default=None, max_length=20)
class PairRequest(Details):
code: str = Field(min_length=1, max_length=4096)
replaces_id: str | None = Field(default=None, max_length=80)
class UpdateRequest(Details):
expected_revision: int = Field(ge=1)
def operation(fleet: FleetRegistry, body: Details, callback: Callable[[], Document]) -> Document:
try:
if not body.name.strip():
raise PairingError("Укажите название VPS.")
with fleet.lock:
for vehicle in body.vehicle_ids:
fleet.find(vehicle) # type: ignore[no-untyped-call] # legacy fleet boundary
return callback()
except PairingError as error:
raise HTTPException(409, str(error)) from None
except (OSError, ValueError):
raise HTTPException(
503, "Не удалось связаться с VPS. Проверьте адрес и доступность сервера."
) from None
@router.get("")
def listing(response: Response, fleet: Fleet) -> Document:
response.headers["Cache-Control"] = "no-store"
return {"items": store(fleet).listing()}
@router.get("/interfaces")
def network_interfaces(fleet: Fleet) -> Document:
return {"items": interfaces()}
@router.get("/telemetry")
def telemetry(response: Response, fleet: Fleet, vehicle_id: str | None = None) -> Document:
response.headers["Cache-Control"] = "no-store"
return {"items": store(fleet).telemetry(vehicle_id)}
@router.post("")
def pair(body: PairRequest, response: Response, fleet: Fleet) -> Document:
response.headers["Cache-Control"] = "no-store"
return operation(
fleet,
body,
lambda: store(fleet).pair(
body.code, body.name, body.vehicle_ids, body.network_interface, body.replaces_id
),
)
@router.put("/{identifier}")
def update(identifier: str, body: UpdateRequest, response: Response, fleet: Fleet) -> Document:
response.headers["Cache-Control"] = "no-store"
return operation(
fleet,
body,
lambda: store(fleet).update(
identifier, body.expected_revision, body.name, body.vehicle_ids, body.network_interface
),
)