feat(routers): add observed router inventory and scoped controls
Separate router discovery, evidence and authorized control from device runtime. Add Node/Core contracts and reusable operator surfaces.
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
"""Allowlisted public router telemetry; never raw vendor responses or secrets."""
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class PublicModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True, allow_inf_nan=False)
|
||||
|
||||
|
||||
class Modem(PublicModel):
|
||||
slot: int = Field(ge=1, le=3)
|
||||
operator: str = Field(max_length=128)
|
||||
connectivity: str = Field(max_length=128)
|
||||
radio: str = Field(max_length=128)
|
||||
ip: str = Field(max_length=45)
|
||||
technology: str = Field(max_length=128)
|
||||
band: str = Field(max_length=128)
|
||||
bandwidth: float | None = Field(ge=0, le=1000)
|
||||
rsrp: float | None = Field(ge=-160, le=-20)
|
||||
rsrq: float | None = Field(ge=-50, le=20)
|
||||
sinr: float | None = Field(ge=-40, le=60)
|
||||
rssi: float | None = Field(ge=-160, le=0)
|
||||
cell_id: str = Field(max_length=128)
|
||||
pci: float | None = Field(ge=0, le=1007)
|
||||
down_kbps: float | None = Field(ge=0, le=1e9)
|
||||
up_kbps: float | None = Field(ge=0, le=1e9)
|
||||
|
||||
|
||||
class Router(PublicModel):
|
||||
id: str = Field(pattern=r"^router_[a-f0-9]{24}$")
|
||||
family: Literal["DexaFlow"]
|
||||
identity: Literal["local_mac"]
|
||||
address: str = Field(max_length=45)
|
||||
interface: str = Field(max_length=64)
|
||||
local_ip: str = Field(max_length=45)
|
||||
state: Literal["ready", "access_required", "access_rejected", "unreachable", "incompatible"]
|
||||
observed_at: int = Field(ge=0)
|
||||
firmware: str = Field(max_length=128)
|
||||
uptime: float | None = Field(ge=0, le=1e12)
|
||||
selected_mode: str = Field(max_length=32)
|
||||
active_mode: str = Field(max_length=32)
|
||||
persisted_mode: str = Field(max_length=32)
|
||||
reboot_resets: bool | None
|
||||
manual_mode: str = Field(default="", max_length=32)
|
||||
active_slots: list[int] = Field(default_factory=list, max_length=3)
|
||||
active_wan: str = Field(max_length=128)
|
||||
internet: Literal["unknown", "verified"]
|
||||
public_ip: str = Field(max_length=45)
|
||||
vps_up: bool | None
|
||||
rtt_ms: float | None = Field(ge=0, le=60000)
|
||||
down_kbps: float | None = Field(ge=0, le=1e9)
|
||||
up_kbps: float | None = Field(ge=0, le=1e9)
|
||||
modems: list[Modem] = Field(max_length=3)
|
||||
|
||||
|
||||
class Incident(PublicModel):
|
||||
sequence: int = Field(ge=1, le=2**53-1)
|
||||
at: int = Field(ge=0)
|
||||
boot_id: str = Field(pattern=r"^[a-f0-9]{32}$")
|
||||
elapsed_ms: int = Field(ge=0)
|
||||
device_id: str = Field(pattern=r"^router_[a-f0-9]{24}$")
|
||||
code: Literal["discovered", "availability", "address_changed", "router_restarted", "mode_changed", "internet_verification", "firmware_changed", "modem_state", "operator_changed", "signal_weak", "signal_recovered", "access_rejected", "access_granted", "command_requested", "command_complete", "command_unconfirmed", "command_failed"]
|
||||
slot: int = Field(default=0, ge=0, le=3)
|
||||
before: str = Field(default="", max_length=128)
|
||||
after: str = Field(default="", max_length=128)
|
||||
|
||||
|
||||
class Journal(PublicModel):
|
||||
first_sequence: int = Field(ge=0, le=2**53-1)
|
||||
last_sequence: int = Field(ge=0, le=2**53-1)
|
||||
dropped: int = Field(ge=0, le=2**53-1)
|
||||
limit: Literal[256]
|
||||
retention_days: Literal[7]
|
||||
error: bool
|
||||
|
||||
|
||||
class Receipt(PublicModel):
|
||||
operation_id: str = Field(pattern=r"^op_[a-f0-9]{32}$")
|
||||
device_id: str = Field(default="", max_length=32)
|
||||
action: Literal["", "mode", "reboot"] = ""
|
||||
state: Literal["queued", "applying", "complete", "error", "unknown"]
|
||||
error: Literal["", "router_unavailable", "expired", "access_rejected", "unsupported_response", "storage_error", "command_rejected", "router_busy", "sim_unavailable", "confirmation_timeout"] = ""
|
||||
|
||||
|
||||
class Snapshot(PublicModel):
|
||||
control_version: Literal[0, 1] = 0
|
||||
schema_version: Literal["missioncore.routers/v1"] = Field(alias="schema")
|
||||
runtime_id: str = Field(pattern=r"^[a-f0-9]{32}$")
|
||||
available: bool
|
||||
observed_at: int = Field(ge=0)
|
||||
items: list[Router] = Field(max_length=4)
|
||||
events: list[Incident] = Field(max_length=256)
|
||||
journal: Journal
|
||||
results: list[Receipt] = Field(max_length=32)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Latest router state in RAM. The bounded incident journal belongs to Node.
|
||||
|
||||
No raw radio time series, access password or command payload enters Fleet DB.
|
||||
All methods run under FleetRegistry.lock; Node sends its immutable cached state.
|
||||
"""
|
||||
import copy
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from .router_contracts import Snapshot
|
||||
from .trust import PairingError
|
||||
|
||||
|
||||
class Routers:
|
||||
def __init__(self):
|
||||
self.latest = {}
|
||||
self.pending = {}
|
||||
self.day = int(time.time() // 86400)
|
||||
|
||||
def prune(self):
|
||||
now = time.time()
|
||||
day = int(now // 86400)
|
||||
if day != self.day:
|
||||
# Only the operator's transient copy is reset. The authoritative
|
||||
# bounded journal stays on Node and returns on its next heartbeat.
|
||||
self.latest.clear()
|
||||
self.day = day
|
||||
for node, entry in list(self.latest.items()):
|
||||
if now - entry["received"] > 86400:
|
||||
del self.latest[node]
|
||||
for key, entry in list(self.pending.items()):
|
||||
if now - entry["created"] > 600:
|
||||
del self.pending[key]
|
||||
elif (entry["deadline"] <= now and entry["public"]["state"] == "queued") or (now - entry["created"] > 300 and entry["public"]["state"] == "applying"):
|
||||
entry["payload"] = None
|
||||
entry["public"] = {"operation_id": key[1], "state": "unknown"}
|
||||
|
||||
def view(self, row):
|
||||
self.prune()
|
||||
cached = self.latest.get(row["node_id"])
|
||||
if not cached or cached["binding"] != (row.get("binding") or {}).get("binding_id"):
|
||||
return {"available": False, "fresh": False, "items": [], "events": [], "results": []}
|
||||
value = copy.deepcopy(cached["state"])
|
||||
value["fresh"] = not cached.get("invalid", False) and row["enrollment"] == "paired" and time.time() - cached["received"] < 30
|
||||
value["received_at"] = cached["received"]
|
||||
return value
|
||||
|
||||
def heartbeat(self, row, payload):
|
||||
self.prune()
|
||||
raw = payload.get("routers")
|
||||
if raw is not None:
|
||||
try:
|
||||
if not isinstance(raw, dict) or len(json.dumps(raw)) > 196608:
|
||||
raise ValueError("router payload limit")
|
||||
value = Snapshot.model_validate(raw).model_dump(by_alias=True)
|
||||
if len({item["id"] for item in value["items"]}) != len(value["items"]):
|
||||
raise ValueError("duplicate router")
|
||||
sequences = [e["sequence"] for e in value["events"]]
|
||||
if sequences != sorted(set(sequences)):
|
||||
raise ValueError("invalid journal sequence")
|
||||
if len(self.latest) >= 128 and row["node_id"] not in self.latest:
|
||||
raise ValueError("router cache limit")
|
||||
self.latest[row["node_id"]] = {"binding": row["binding"]["binding_id"], "received": time.time(), "state": value}
|
||||
for result in value["results"]:
|
||||
entry = self.pending.get((row["id"], result["operation_id"]))
|
||||
if entry and entry["binding"] == row["binding"]["binding_id"]:
|
||||
entry["payload"] = None
|
||||
entry["public"] = result
|
||||
except (ValidationError, ValueError, TypeError):
|
||||
# A broken optional vendor adapter cannot fail camera/control
|
||||
# heartbeat. Its previous observation expires instead.
|
||||
if row["node_id"] in self.latest:
|
||||
self.latest[row["node_id"]]["invalid"] = True
|
||||
commands = []
|
||||
for (vehicle, _), entry in self.pending.items():
|
||||
if vehicle != row["id"]:
|
||||
continue
|
||||
if entry["binding"] != row["binding"]["binding_id"]:
|
||||
entry["payload"] = None
|
||||
entry["public"]["state"] = "unknown"
|
||||
elif entry["payload"] is not None:
|
||||
commands.append(copy.deepcopy(entry["payload"]))
|
||||
return {"router_commands": commands[:2]}
|
||||
|
||||
def authorize(self, fleet, vehicle_id, value):
|
||||
# Manual validation intentionally does not echo a rejected password in
|
||||
# Pydantic/FastAPI validation responses or exception strings.
|
||||
expected = {"operation_id", "runtime_id", "device_id", "deadline", "username", "password"}
|
||||
if not isinstance(value, dict) or set(value) != expected:
|
||||
raise PairingError("Неверный запрос доступа к роутеру.")
|
||||
if any(not isinstance(value[k], str) or not 1 <= len(value[k]) <= limit for k, limit in (("username", 64), ("password", 256), ("device_id", 32), ("runtime_id", 32), ("operation_id", 35))):
|
||||
raise PairingError("Проверьте данные доступа.")
|
||||
if not re.fullmatch(r"op_[a-f0-9]{32}", value["operation_id"]) or type(value["deadline"]) is not int or not 0 < value["deadline"] - time.time() <= 90:
|
||||
raise PairingError("Запрос устарел. Обновите карточку роутера.")
|
||||
with fleet.lock:
|
||||
row = fleet.find(vehicle_id)
|
||||
state = self.view(row)
|
||||
if not state.get("available") or not state.get("fresh") or state.get("runtime_id") != value["runtime_id"] or not any(d["id"] == value["device_id"] and d["state"] in {"ready", "access_required", "access_rejected"} for d in state["items"]):
|
||||
raise PairingError("Роутер недоступен. Обновите его состояние.")
|
||||
key = (vehicle_id, value["operation_id"])
|
||||
if key in self.pending:
|
||||
return copy.deepcopy(self.pending[key]["public"])
|
||||
if len(self.pending) >= 16:
|
||||
raise PairingError("Дождитесь завершения текущих запросов.")
|
||||
receipt = {"operation_id": value["operation_id"], "state": "queued"}
|
||||
self.pending[key] = {"payload": copy.deepcopy(value), "public": receipt, "binding": row["binding"]["binding_id"], "created": time.time(), "deadline": value["deadline"]}
|
||||
return dict(receipt)
|
||||
|
||||
def operation(self, row, identifier):
|
||||
self.prune()
|
||||
entry = self.pending.get((row["id"], identifier))
|
||||
if not entry or entry["binding"] != row["binding"]["binding_id"]:
|
||||
return {"operation_id": identifier, "state": "unknown"}
|
||||
return copy.deepcopy(entry["public"])
|
||||
|
||||
def control(self, fleet, vehicle_id, value):
|
||||
expected = {"operation_id", "runtime_id", "device_id", "deadline", "action", "mode", "slots"}
|
||||
if not isinstance(value, dict) or set(value) != expected:
|
||||
raise PairingError("Неверная команда роутеру.")
|
||||
if any(not isinstance(value[k], str) or not re.fullmatch(pattern, value[k]) for k, pattern in (
|
||||
("operation_id", r"op_[a-f0-9]{32}"), ("runtime_id", r"[a-f0-9]{32}"), ("device_id", r"router_[a-f0-9]{24}"))):
|
||||
raise PairingError("Неверная команда роутеру.")
|
||||
if type(value["deadline"]) is not int or not 0 < value["deadline"] - time.time() <= 90:
|
||||
raise PairingError("Запрос устарел. Обновите карточку роутера.")
|
||||
slots = value["slots"]
|
||||
if not isinstance(slots, list) or len(slots) > 3 or any(type(s) is not int or s not in (1, 2, 3) for s in slots) or len(set(slots)) != len(slots):
|
||||
raise PairingError("Проверьте выбранные SIM-карты.")
|
||||
if value["action"] == "reboot":
|
||||
valid = value["mode"] == "" and not slots
|
||||
else:
|
||||
valid = value["action"] == "mode" and ((value["mode"] == "direct" and len(slots) == 1) or (value["mode"] == "aggregation" and bool(slots)))
|
||||
if not valid:
|
||||
raise PairingError("Неподдерживаемая команда роутеру.")
|
||||
with fleet.lock:
|
||||
row = fleet.find(vehicle_id)
|
||||
state = self.view(row)
|
||||
key = (vehicle_id, value["operation_id"])
|
||||
if key in self.pending and self.pending[key]["binding"] == row["binding"]["binding_id"]:
|
||||
return copy.deepcopy(self.pending[key]["public"])
|
||||
if not state.get("available") or not state.get("fresh") or state.get("control_version") != 1 or state.get("runtime_id") != value["runtime_id"]:
|
||||
raise PairingError("Обновите состояние и версию Mission Core на борту.")
|
||||
device = next((d for d in state["items"] if d["id"] == value["device_id"]), None)
|
||||
if not device or device["state"] != "ready" or not -30 <= time.time() - device["observed_at"] < 40:
|
||||
raise PairingError("Нет свежего состояния роутера.")
|
||||
busy = any(e["public"]["state"] in {"queued", "applying"} for (v, _), e in self.pending.items() if v == vehicle_id)
|
||||
busy = busy or any(r["state"] in {"queued", "applying"} for r in state["results"])
|
||||
if busy or len(self.pending) >= 16:
|
||||
raise PairingError("Дождитесь завершения текущей команды.")
|
||||
receipt = {"operation_id": value["operation_id"], "device_id": value["device_id"], "action": value["action"], "state": "queued"}
|
||||
self.pending[key] = {"payload": copy.deepcopy(value), "public": receipt, "binding": row["binding"]["binding_id"], "created": time.time(), "deadline": value["deadline"]}
|
||||
return dict(receipt)
|
||||
Reference in New Issue
Block a user