feat(fleet): add shared WireGuard profiles and bounded rover transport
Add portable shared WireGuard profiles while retaining Tailscale and Worker boundaries. Bound rover command/telemetry delivery, recovery and diagnostic capture across Core and Node.
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
"""Shared authorization checks for durable and real-time Node channels."""
|
||||
import time
|
||||
|
||||
from cryptography import x509
|
||||
|
||||
from .trust import SCHEMA
|
||||
|
||||
|
||||
def authenticate(row, node_id, serial, value):
|
||||
if (row is None or row["enrollment"] not in ("pending", "paired")
|
||||
or value.get("node_id") != node_id
|
||||
or value.get("binding_id") != row["binding"]["binding_id"]):
|
||||
return 410, {"error": "Binding revoked"}
|
||||
allowed = [row["binding"]["client_pem"]]
|
||||
previous = row.get("certificate_previous")
|
||||
if previous and previous["until"] > time.time():
|
||||
allowed.append(previous["pem"])
|
||||
if serial not in [x509.load_pem_x509_certificate(item.encode()).serial_number
|
||||
for item in allowed]:
|
||||
return 403, {"error": "Certificate superseded"}
|
||||
if value.get("schema") != SCHEMA:
|
||||
return 400, {"error": "Incompatible protocol"}
|
||||
return None
|
||||
|
||||
|
||||
def endpoint_error(row, value, address):
|
||||
from .recovery import tailnet_address
|
||||
|
||||
revision = value.get("endpoint_revision", 0)
|
||||
if type(revision) is not int or not 0 <= revision <= 1000000000:
|
||||
return 400, {"error": "Invalid endpoint revision"}
|
||||
previous = row["binding"].get("endpoint_revision", 0)
|
||||
if revision < previous:
|
||||
return 409, {"error": "Endpoint superseded"}
|
||||
if revision > previous and (
|
||||
not (tailnet_address(address) or any(path.get("core") == address for path in row.get("network_paths", {}).values()))
|
||||
or value.get("core_endpoint") != f"https://{address}:8782"
|
||||
):
|
||||
return 400, {"error": "Endpoint does not match authenticated channel"}
|
||||
return None
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Bounded, negotiated compression for the existing full Node heartbeat."""
|
||||
|
||||
import zlib
|
||||
|
||||
MAX_HEARTBEAT_BYTES = 8 * 1024 * 1024
|
||||
|
||||
|
||||
def decode_heartbeat(body: bytes, encoding: str, path: str) -> bytes:
|
||||
if not encoding:
|
||||
return body
|
||||
if encoding != "gzip" or path != "/v1/node/heartbeat":
|
||||
raise ValueError("Unsupported encoding")
|
||||
try:
|
||||
stream = zlib.decompressobj(16 + zlib.MAX_WBITS)
|
||||
decoded = stream.decompress(body, MAX_HEARTBEAT_BYTES + 1)
|
||||
if (len(decoded) > MAX_HEARTBEAT_BYTES or not stream.eof
|
||||
or stream.unused_data or stream.unconsumed_tail):
|
||||
raise ValueError("Invalid compressed heartbeat")
|
||||
return decoded
|
||||
except zlib.error as error:
|
||||
raise ValueError("Invalid compressed heartbeat") from error
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Bounded access to the installed WireGuard system helper."""
|
||||
import json
|
||||
import hashlib
|
||||
import os
|
||||
import platform
|
||||
import shlex
|
||||
import socket
|
||||
import subprocess
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
SOCKET = "/var/run/ndc-mission-wireguard.sock"
|
||||
|
||||
|
||||
def request(action, server_id, **values):
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
|
||||
connection.settimeout(25)
|
||||
connection.connect(SOCKET)
|
||||
connection.sendall(json.dumps({"action": action, "server_id": server_id, **values}).encode() + b"\n")
|
||||
with connection.makefile("rb") as stream:
|
||||
data = stream.readline(16385)
|
||||
if len(data) > 16384 or not data.endswith(b"\n"):
|
||||
raise ValueError("Некорректный ответ сетевой службы.")
|
||||
result = json.loads(data)
|
||||
if not result.get("ok"):
|
||||
raise ValueError("Не удалось применить сетевой профиль: " + result.get("error", "ошибка службы"))
|
||||
return result["result"]
|
||||
|
||||
|
||||
def ensure():
|
||||
source = Path(__file__).resolve().parents[3] / "apps/wireguard-client"
|
||||
if Path(SOCKET).is_socket():
|
||||
try:
|
||||
status = request("health", "")
|
||||
if status.get("sha256") == hashlib.sha256((source / "helper.py").read_bytes()).hexdigest():
|
||||
return
|
||||
except (ValueError, OSError):
|
||||
pass
|
||||
if platform.system() != "Darwin" or platform.machine() != "arm64":
|
||||
raise ValueError("Подготовка компьютера поддерживает macOS Apple Silicon.")
|
||||
source = Path(__file__).resolve().parents[3] / "apps/wireguard-client"
|
||||
# Administrator processes cannot read macOS protected Downloads. The app
|
||||
# stages only its reviewed installer payload before asking for OS authorization.
|
||||
with tempfile.TemporaryDirectory(prefix="ndc-wireguard-install-", dir="/private/tmp") as folder:
|
||||
staging = Path(folder)
|
||||
for name in ("install_macos.py", "helper.py"):
|
||||
shutil.copyfile(source / name, staging / name)
|
||||
shutil.copytree(source / "build/macos-arm64", staging / "build/macos-arm64")
|
||||
command = shlex.join(["/usr/bin/python3", str(staging / "install_macos.py"), "--uid", str(os.getuid())])
|
||||
script = "do shell script " + json.dumps(command) + " with administrator privileges"
|
||||
result = subprocess.run(["/usr/bin/osascript", "-e", script], capture_output=True, timeout=180)
|
||||
if result.returncode:
|
||||
raise ValueError("Системная установка WireGuard не завершена. Подтвердите запрос администратора macOS и повторите импорт.")
|
||||
for _ in range(40):
|
||||
if Path(SOCKET).is_socket():
|
||||
try:
|
||||
if request("health", "").get("sha256") == hashlib.sha256((source / "helper.py").read_bytes()).hexdigest():
|
||||
return
|
||||
except (ValueError, OSError):
|
||||
pass
|
||||
time.sleep(0.25)
|
||||
raise ValueError("Системная служба WireGuard пока не запущена.")
|
||||
|
||||
|
||||
def verify_tunnel(config):
|
||||
"""Probe only the isolated gateway, explicitly using the fleet source address."""
|
||||
import ipaddress
|
||||
gateway = str(ipaddress.ip_network(config["subnet"])[1])
|
||||
for _ in range(3):
|
||||
result = subprocess.run(["/sbin/ping", "-n", "-c", "1", "-W", "1500", "-S", config["address"], gateway],
|
||||
capture_output=True, timeout=4)
|
||||
status = request("status", config["server_id"])
|
||||
if result.returncode == 0 and time.time() - status.get("last_handshake", 0) < 180:
|
||||
return
|
||||
raise ValueError("Сервер отвечает, но туннель WireGuard не установлен. Проверьте доступность UDP 51830 на VPS. Прежнее подключение сохранено.")
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Constrain board media signalling to its acknowledged private network path."""
|
||||
import copy
|
||||
import re
|
||||
from urllib.parse import urlsplit
|
||||
from .trust import PairingError
|
||||
|
||||
|
||||
def filter_sdp(sdp, address, *, browser_offer=False):
|
||||
if not isinstance(sdp, str) or not 1 <= len(sdp) <= 32768:
|
||||
raise PairingError("Некорректное подключение просмотра.")
|
||||
lines, admitted, hidden_hosts = [], 0, False
|
||||
for line in sdp.splitlines():
|
||||
if line.startswith("a=candidate:"):
|
||||
fields = line.split()
|
||||
if (len(fields) >= 8 and fields[7] == "host" and fields[2].lower() == "udp"
|
||||
and re.fullmatch(r"[A-Za-z0-9-]{1,63}\.local", fields[4])):
|
||||
hidden_hosts = True
|
||||
if len(fields) < 8 or fields[4] != address or fields[7] != "host" or fields[2].lower() != "udp":
|
||||
continue
|
||||
admitted += 1
|
||||
if line.startswith("a=remote-candidates:"):
|
||||
continue
|
||||
if line.startswith("c=IN IP4 "):
|
||||
line = "c=IN IP4 " + address
|
||||
lines.append(line)
|
||||
if not admitted and browser_offer and hidden_hosts:
|
||||
# Browsers mask local addresses with mDNS. Never resolve or relabel an
|
||||
# unrelated interface. Only the Node's exact WG candidate is returned;
|
||||
# its authenticated ICE checks learn the Core's WG peer-reflexive address.
|
||||
# Keep gathering open so the receiver can wait for that incoming check.
|
||||
lines = [line for line in lines if line != "a=end-of-candidates"]
|
||||
elif not admitted:
|
||||
raise PairingError("Просмотр не получил адрес выбранной сети. Проверьте WireGuard и откройте просмотр заново.")
|
||||
return "\r\n".join(lines) + "\r\n"
|
||||
|
||||
|
||||
def selected_path(row):
|
||||
address = urlsplit(row.get("binding", {}).get("endpoint", "")).hostname
|
||||
return next((p for p in row.get("network_paths", {}).values() if p.get("core") == address), None)
|
||||
|
||||
|
||||
def offer(row, value):
|
||||
path = selected_path(row)
|
||||
if path and value.get("action_id") == "offer":
|
||||
value = copy.deepcopy(value)
|
||||
value["parameters"]["sdp"] = filter_sdp(value["parameters"].get("sdp"), path["core"], browser_offer=True)
|
||||
return value
|
||||
|
||||
|
||||
def answer(row, value):
|
||||
path = selected_path(row)
|
||||
if path and value.get("command", {}).get("action_id") == "offer" and value.get("state") == "complete":
|
||||
value = copy.deepcopy(value)
|
||||
value["result"]["sdp"] = filter_sdp(value["result"].get("sdp"), path["node"])
|
||||
return value
|
||||
@@ -0,0 +1,358 @@
|
||||
"""Shared VPS profiles and bounded board network transactions. Worker is not a consumer."""
|
||||
import base64
|
||||
import copy
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from . import network_client
|
||||
from .trust import atomic_private
|
||||
from .vps_transport import request, interfaces
|
||||
|
||||
SCHEMA = "missioncore.wireguard-connect/v1"
|
||||
|
||||
|
||||
def parse_file(raw):
|
||||
if not isinstance(raw, str) or len(raw.encode()) > 16384:
|
||||
raise ValueError("Файл подключения слишком большой.")
|
||||
value = json.loads(raw)
|
||||
required = {"schema", "server_id", "endpoint", "vpn_endpoint", "fingerprint", "server_public_key", "subnet", "bootstrap", "expires_at"}
|
||||
if not isinstance(value, dict) or not required <= set(value) or set(value) - required - {"capacity"} or value["schema"] != SCHEMA:
|
||||
raise ValueError("Выберите файл подключения WireGuard, созданный установщиком VPS.")
|
||||
if any(not isinstance(value[k], str) for k in required - {"expires_at"}):
|
||||
raise ValueError("Некорректный формат файла подключения.")
|
||||
if not re.fullmatch(r"wg_[a-f0-9]{32}", value["server_id"]) or not re.fullmatch(r"[a-f0-9]{64}", value["fingerprint"]):
|
||||
raise ValueError("Некорректная идентичность сервера.")
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{43}", value["bootstrap"]):
|
||||
raise ValueError("Некорректный ключ подключения.")
|
||||
if type(value["expires_at"]) is not int or ("capacity" in value and (type(value["capacity"]) is not int or value["capacity"] < 1)):
|
||||
raise ValueError("Несовместимый файл подключения.")
|
||||
if len(base64.b64decode(value["server_public_key"], validate=True)) != 32:
|
||||
raise ValueError("Некорректный ключ WireGuard.")
|
||||
network = ipaddress.ip_network(value["subnet"])
|
||||
if network.version != 4 or network.prefixlen != 24 or not network.subnet_of(ipaddress.ip_network("10.203.0.0/16")):
|
||||
raise ValueError("Неподдерживаемая адресация парка.")
|
||||
endpoint = urlsplit(value["endpoint"])
|
||||
if endpoint.scheme != "https" or endpoint.port != 19444 or not endpoint.hostname or endpoint.username or endpoint.password or endpoint.path or endpoint.query or endpoint.fragment:
|
||||
raise ValueError("Некорректный адрес сервера.")
|
||||
if value["vpn_endpoint"] != endpoint.hostname + ":51830":
|
||||
raise ValueError("Адреса сервера не согласованы.")
|
||||
# Old connection files carried an illustrative quota; it is not a fleet policy.
|
||||
value.pop("capacity", None)
|
||||
return value
|
||||
|
||||
|
||||
class NetworkProfiles:
|
||||
def __init__(self, fleet):
|
||||
self.fleet = fleet
|
||||
self.root = fleet.root / "networks"
|
||||
self.root.mkdir(mode=0o700, exist_ok=True)
|
||||
self.path = self.root / "profiles.json"
|
||||
self.lock = threading.RLock()
|
||||
self.changed = threading.Condition(self.lock)
|
||||
self.profiles = json.loads(self.path.read_text()) if self.path.exists() else {}
|
||||
self.latest = {}
|
||||
self.commands = {}
|
||||
self.operations = {}
|
||||
self.workers = {}
|
||||
self.import_lock = threading.Lock()
|
||||
self.sync_lock = threading.RLock()
|
||||
self.revoke_retry = {}
|
||||
|
||||
def save(self):
|
||||
atomic_private(self.path, json.dumps(self.profiles).encode())
|
||||
|
||||
def revoke_node(self, node_id):
|
||||
with self.lock:
|
||||
changed = False
|
||||
for row in self.profiles.values():
|
||||
if any(p["id"] == node_id for p in row.get("status", {}).get("peers", [])):
|
||||
pending = row.setdefault("revocations", [])
|
||||
if node_id not in pending:
|
||||
pending.append(node_id)
|
||||
changed = True
|
||||
if changed:
|
||||
self.save()
|
||||
|
||||
def reconcile(self):
|
||||
# Durable revocation retries run outside registry/control locks.
|
||||
now = time.monotonic()
|
||||
with self.lock:
|
||||
candidates = [copy.deepcopy(row) for row in self.profiles.values()
|
||||
if row.get("revocations") and now >= self.revoke_retry.get(row["server_id"], 0)]
|
||||
for row in candidates:
|
||||
if self.fleet.stop.is_set():
|
||||
return
|
||||
node_id = row["revocations"][0]
|
||||
with self.lock:
|
||||
self.revoke_retry[row["server_id"]] = now + 30
|
||||
try:
|
||||
status = self.call(row, "DELETE", "/v1/peers/" + node_id)
|
||||
self.sync_operator(row, status)
|
||||
with self.lock:
|
||||
current = self.profiles[row["server_id"]]
|
||||
if node_id in current.get("revocations", []):
|
||||
current["revocations"].remove(node_id)
|
||||
self.save()
|
||||
except (ValueError, OSError):
|
||||
continue
|
||||
|
||||
def public(self, row):
|
||||
status = row.get("status") or {}
|
||||
return {"id": row["server_id"], "name": row["name"], "endpoint": row["endpoint"],
|
||||
"state": row["state"],
|
||||
"boards": len([p for p in status.get("peers", []) if p["kind"] == "node"]),
|
||||
"network_interface": row.get("network_interface"), "last_verified": row.get("last_verified")}
|
||||
|
||||
def listing(self):
|
||||
with self.lock:
|
||||
return [self.public(row) for row in self.profiles.values()]
|
||||
|
||||
def verify_status(self, row, value):
|
||||
if not isinstance(value, dict) or value.get("schema") != "missioncore.wireguard-status/v1" or value.get("server_id") != row["server_id"] or value.get("server_public_key") != row["server_public_key"] or value.get("subnet") != row["subnet"]:
|
||||
raise ValueError("Сервер вернул другую идентичность профиля.")
|
||||
peers = value.get("peers")
|
||||
if not isinstance(peers, list) or len(peers) > ipaddress.ip_network(row["subnet"]).num_addresses - 4:
|
||||
raise ValueError("Некорректный список участников.")
|
||||
network = ipaddress.ip_network(row["subnet"])
|
||||
seen_ids, seen_keys, seen_addresses = set(), set(), set()
|
||||
if value.get("server_address") != str(network[1]):
|
||||
raise ValueError("Некорректный адрес шлюза.")
|
||||
for peer in peers:
|
||||
address = ipaddress.ip_address(peer["address"])
|
||||
if (address not in network or peer["kind"] not in ("core", "node")
|
||||
or (peer["kind"] == "core" and (peer["id"] != self.fleet.trust.core_id or address != network[2]))
|
||||
or (peer["kind"] == "node" and not network[3] <= address <= network[253])
|
||||
or peer["id"] in seen_ids or peer["public_key"] in seen_keys or str(address) in seen_addresses
|
||||
or len(base64.b64decode(peer["public_key"], validate=True)) != 32):
|
||||
raise ValueError("Некорректная адресация участника.")
|
||||
seen_ids.add(peer["id"]); seen_keys.add(peer["public_key"]); seen_addresses.add(str(address))
|
||||
return value
|
||||
|
||||
def call(self, row, method, path, body=None):
|
||||
return self.verify_status(row, request(row, method, path, body))
|
||||
|
||||
def operator_config(self, row, status):
|
||||
core = next((p for p in status["peers"] if p["id"] == self.fleet.trust.core_id and p["kind"] == "core"), None)
|
||||
if core is None:
|
||||
raise ValueError("Сервер не подтвердил этот Mission Core.")
|
||||
local = network_client.request("status", row["server_id"])
|
||||
if core["public_key"] != local["public_key"]:
|
||||
raise ValueError("Сервер не подтвердил ключ этого Core.")
|
||||
addresses = [status["server_address"] + "/32"] + [p["address"] + "/32" for p in status["peers"] if p["kind"] == "node"]
|
||||
return {"server_id": row["server_id"], "address": core["address"], "subnet": row["subnet"],
|
||||
"server_public_key": row["server_public_key"], "endpoint": row["vpn_endpoint"],
|
||||
"allowed_ips": addresses, "role": "core", "interface": row.get("network_interface")}
|
||||
|
||||
def sync_operator(self, row, status):
|
||||
with self.sync_lock:
|
||||
config = self.operator_config(row, status)
|
||||
operation = secrets.token_hex(16)
|
||||
network_client.request("stage", row["server_id"], config=config, operation_id=operation)
|
||||
try:
|
||||
network_client.verify_tunnel(config)
|
||||
with self.fleet.lock:
|
||||
self.fleet.listen(config["address"])
|
||||
with self.lock:
|
||||
current = self.profiles[row["server_id"]]
|
||||
previous = copy.deepcopy(current)
|
||||
current.update(status=status, state="ready", last_verified=time.time())
|
||||
try:
|
||||
self.save()
|
||||
network_client.request("confirm", row["server_id"], operation_id=operation)
|
||||
except Exception:
|
||||
self.profiles[row["server_id"]] = previous
|
||||
self.save()
|
||||
raise
|
||||
except Exception:
|
||||
network_client.request("rollback", row["server_id"], operation_id=operation)
|
||||
raise
|
||||
return config
|
||||
|
||||
def import_file(self, raw, name="", interface=None):
|
||||
if not self.import_lock.acquire(blocking=False):
|
||||
raise ValueError("Дождитесь завершения импорта профиля.")
|
||||
previous = copy.deepcopy(self.profiles)
|
||||
try:
|
||||
return self._import_file(raw, name, interface)
|
||||
except Exception:
|
||||
# A failed new claim keeps its retry token; an existing active profile
|
||||
# retains its last verified endpoint and peer set.
|
||||
with self.lock:
|
||||
for identity, row in previous.items():
|
||||
if row.get("state") == "ready":
|
||||
self.profiles[identity] = row
|
||||
self.save()
|
||||
raise
|
||||
finally:
|
||||
self.import_lock.release()
|
||||
|
||||
def _import_file(self, raw, name="", interface=None):
|
||||
value = parse_file(raw)
|
||||
with self.lock:
|
||||
old = self.profiles.get(value["server_id"])
|
||||
if old and (old["fingerprint"] != value["fingerprint"] or old["server_public_key"] != value["server_public_key"]):
|
||||
raise ValueError("Ключи существующего сервера изменились. Профиль сохранён без изменений.")
|
||||
if not old and value["expires_at"] <= time.time():
|
||||
raise ValueError("Файл подключения просрочен. Получите новый файл на VPS.")
|
||||
if any(p["server_id"] != value["server_id"] and p["subnet"] == value["subnet"] for p in self.profiles.values()):
|
||||
raise ValueError("Адресация совпадает с другим подключённым VPS.")
|
||||
row = {**value, "name": name.strip()[:80] or (old or {}).get("name") or "WireGuard · " + urlsplit(value["endpoint"]).hostname,
|
||||
"token": (old or {}).get("token") or secrets.token_urlsafe(32),
|
||||
"state": (old or {}).get("state", "pending"), "network_interface": interface or (old or {}).get("network_interface")}
|
||||
# Persist the retry credential before either administrator interaction or claim.
|
||||
self.profiles[value["server_id"]] = row
|
||||
self.save()
|
||||
network_client.ensure()
|
||||
local = network_client.request("prepare", row["server_id"])
|
||||
claim = {"core_id": self.fleet.trust.core_id, "public_key": local["public_key"],
|
||||
"credential": row["token"], "bootstrap": row["bootstrap"]}
|
||||
candidates = [row.get("network_interface")]
|
||||
if not candidates[0]:
|
||||
candidates += [item["id"] for item in interfaces() if re.fullmatch(r"en[0-9]+", item["id"])]
|
||||
failure = None
|
||||
for selected in candidates:
|
||||
try:
|
||||
row["network_interface"] = selected
|
||||
status = self.call(row, "POST", "/v1/claim", claim)
|
||||
break
|
||||
except (OSError, ValueError) as error:
|
||||
failure = error
|
||||
else:
|
||||
raise ValueError("Не удалось подключиться к VPS. Проверьте доступность сервера.") from failure
|
||||
self.sync_operator(row, status)
|
||||
with self.lock:
|
||||
self.profiles[row["server_id"]].pop("bootstrap", None)
|
||||
self.save()
|
||||
return self.public(self.profiles[row["server_id"]])
|
||||
|
||||
def heartbeat(self, row, value):
|
||||
snapshot = value.get("network_profile")
|
||||
if isinstance(snapshot, dict) and snapshot.get("phase") in ("applied", "rolled_back"):
|
||||
selected = snapshot.get("server_id") if snapshot.get("provider") == "wireguard" else "tailscale"
|
||||
if selected == "tailscale" or selected in row.get("network_paths", {}):
|
||||
row["network_active"] = selected
|
||||
with self.changed:
|
||||
if isinstance(snapshot, dict) and len(json.dumps(snapshot)) < 16384:
|
||||
self.latest[row["node_id"]] = {"value": copy.deepcopy(snapshot), "received": time.monotonic(), "endpoint": value.get("core_endpoint")}
|
||||
self.changed.notify_all()
|
||||
command = self.commands.get(row["node_id"])
|
||||
if command and command["expires_at"] > time.time():
|
||||
return {"network_profile_change": copy.deepcopy(command)}
|
||||
return {}
|
||||
|
||||
def view(self, node_id):
|
||||
with self.lock:
|
||||
latest = self.latest.get(node_id)
|
||||
return {"profiles": self.listing(), "available": bool(latest and time.monotonic() - latest["received"] < 20),
|
||||
"node": copy.deepcopy(latest["value"]) if latest else None,
|
||||
"operation": copy.deepcopy(self.operations.get(node_id))}
|
||||
|
||||
def wait(self, node_id, operation, phase, timeout=45):
|
||||
end = time.monotonic() + timeout
|
||||
with self.changed:
|
||||
while time.monotonic() < end and not self.fleet.stop.is_set():
|
||||
latest = self.latest.get(node_id)
|
||||
value = latest["value"] if latest else {}
|
||||
if value.get("operation_id") == operation:
|
||||
if value.get("phase") in ("failed", "rolled_back"):
|
||||
raise ValueError(value.get("error") or "Борт вернул прежнее подключение.")
|
||||
if value.get("phase") == phase:
|
||||
return copy.deepcopy(latest)
|
||||
self.changed.wait(timeout=min(2, max(0, end - time.monotonic())))
|
||||
raise ValueError("Борт не подтвердил применение подключения.")
|
||||
|
||||
def command(self, node_id, value):
|
||||
with self.changed:
|
||||
self.commands[node_id] = {**value, "expires_at": int(time.time()) + 110}
|
||||
|
||||
def start(self, vehicle_id, provider, profile_id, expected_revision):
|
||||
if provider not in ("tailscale", "wireguard"):
|
||||
raise ValueError("Неизвестный способ подключения.")
|
||||
with self.fleet.lock:
|
||||
vehicle = copy.deepcopy(self.fleet.find(vehicle_id))
|
||||
if vehicle["enrollment"] != "paired":
|
||||
raise ValueError("Сначала привяжите бортовой компьютер.")
|
||||
node_id = vehicle["node_id"]
|
||||
with self.lock:
|
||||
if self.workers.get(node_id) and self.workers[node_id].is_alive():
|
||||
raise ValueError("Дождитесь завершения текущего переключения.")
|
||||
current = self.view(node_id)
|
||||
if not current["available"]:
|
||||
raise ValueError("Борт недоступен или требует обновления Node.")
|
||||
if current["node"].get("revision", 0) != expected_revision:
|
||||
raise ValueError("Настройки борта изменились. Обновите окно.")
|
||||
if provider == "wireguard" and profile_id in self.profiles and node_id in self.profiles[profile_id].get("revocations", []):
|
||||
raise ValueError("Дождитесь подтверждения предыдущего отзыва доступа к VPS.")
|
||||
if provider == "wireguard" and (profile_id not in self.profiles or self.profiles[profile_id]["state"] != "ready"):
|
||||
raise ValueError("Сначала подключите профиль VPS.")
|
||||
self.fleet.rover_control.network_change(node_id, True)
|
||||
op = secrets.token_hex(16)
|
||||
self.operations[node_id] = {"id": op, "state": "applying", "provider": provider, "profile_id": profile_id}
|
||||
worker = threading.Thread(target=self.apply, args=(vehicle, provider, profile_id, expected_revision, op), daemon=True)
|
||||
self.workers[node_id] = worker
|
||||
worker.start()
|
||||
return self.operations[node_id].copy()
|
||||
|
||||
def apply(self, vehicle, provider, profile_id, revision, op):
|
||||
node_id = vehicle["node_id"]
|
||||
command = {"id": op, "provider": provider, "server_id": profile_id or "", "expected_revision": revision, "expires_at": int(time.time()) + 110}
|
||||
try:
|
||||
if provider == "wireguard":
|
||||
with self.lock:
|
||||
row = copy.deepcopy(self.profiles[profile_id])
|
||||
self.command(node_id, {**command, "action": "prepare"})
|
||||
prepared = self.wait(node_id, op, "prepared")
|
||||
status = self.call(row, "POST", "/v1/peers", {"node_id": node_id, "public_key": prepared["value"]["public_key"]})
|
||||
operator = self.sync_operator(row, status)
|
||||
peer = next(p for p in status["peers"] if p["id"] == node_id)
|
||||
config = {"server_id": profile_id, "address": peer["address"], "subnet": row["subnet"],
|
||||
"server_public_key": row["server_public_key"], "endpoint": row["vpn_endpoint"],
|
||||
"allowed_ips": [status["server_address"] + "/32", operator["address"] + "/32"], "role": "node"}
|
||||
endpoint = "https://" + operator["address"] + ":8782"
|
||||
with self.fleet.lock:
|
||||
latest = self.fleet.find(vehicle["id"])
|
||||
if latest["enrollment"] != "paired" or latest["binding"]["binding_id"] != vehicle["binding"]["binding_id"]:
|
||||
self.revoke_node(node_id)
|
||||
raise ValueError("Привязка БК изменилась во время подключения.")
|
||||
paths = latest.setdefault("network_paths", {})
|
||||
paths[profile_id] = {"core": operator["address"], "node": peer["address"]}
|
||||
self.fleet.save(latest)
|
||||
self.command(node_id, {**command, "action": "apply", "config": config, "core_endpoint": endpoint})
|
||||
else:
|
||||
with self.lock:
|
||||
snapshot = copy.deepcopy(self.latest[node_id]["value"])
|
||||
endpoint = snapshot.get("tailscale_endpoint")
|
||||
from .recovery import tailnet_address
|
||||
if not isinstance(endpoint, str) or not tailnet_address(urlsplit(endpoint).hostname):
|
||||
raise ValueError("Нет сохранённого подключения Tailscale к этому Core.")
|
||||
with self.fleet.lock:
|
||||
self.fleet.listen(urlsplit(endpoint).hostname)
|
||||
self.command(node_id, {**command, "action": "apply", "core_endpoint": endpoint})
|
||||
applied = self.wait(node_id, op, "verifying", timeout=55)
|
||||
if applied["endpoint"] != endpoint:
|
||||
raise ValueError("Борт ответил через другое подключение.")
|
||||
self.command(node_id, {**command, "action": "commit"})
|
||||
self.wait(node_id, op, "applied", timeout=30)
|
||||
with self.lock:
|
||||
self.operations[node_id]["state"] = "applied"
|
||||
except Exception as error:
|
||||
self.command(node_id, {**command, "action": "abort"})
|
||||
with self.lock:
|
||||
self.operations[node_id].update(state="rolling_back", error=str(error) if isinstance(error, ValueError) else "Не удалось применить подключение.")
|
||||
end = time.monotonic() + 105
|
||||
with self.changed:
|
||||
while time.monotonic() < end and not self.fleet.stop.is_set():
|
||||
latest = self.latest.get(node_id, {}).get("value", {})
|
||||
if latest.get("operation_id") != op or latest.get("phase") in ("rolled_back", "failed", "prepared"):
|
||||
break
|
||||
self.changed.wait(timeout=1)
|
||||
self.operations[node_id]["state"] = "failed"
|
||||
finally:
|
||||
self.fleet.rover_control.network_change(node_id, False)
|
||||
with self.lock:
|
||||
self.commands.pop(node_id, None)
|
||||
@@ -29,6 +29,10 @@ def tailnet_address(value):
|
||||
|
||||
|
||||
def node_addresses(row):
|
||||
selected = row.get("network_active")
|
||||
if selected and selected != "tailscale":
|
||||
path = row.get("network_paths", {}).get(selected)
|
||||
return [path["node"]] if path else []
|
||||
addresses = set()
|
||||
for network in (row.get("inventory") or {}).get("networks", [])[:64]:
|
||||
if not isinstance(network, dict) or not network.get("up"):
|
||||
@@ -83,14 +87,14 @@ def request(connection, path, body):
|
||||
|
||||
|
||||
def recover(registry, row, address, context):
|
||||
if not tailnet_address(address) or address not in node_addresses(row):
|
||||
if address not in node_addresses(row):
|
||||
raise PairingError("Нет подтверждённого адреса БК.")
|
||||
connection = http.client.HTTPSConnection(address, 8781, timeout=4, context=context)
|
||||
try:
|
||||
connection.connect()
|
||||
verify_node_certificate(connection.sock.getpeercert(binary_form=True), row["node_id"])
|
||||
local = connection.sock.getsockname()[0]
|
||||
if not tailnet_address(local):
|
||||
if not (tailnet_address(local) or any(path.get("core") == local and path.get("node") == address for path in row.get("network_paths", {}).values())):
|
||||
raise PairingError("Обратный адрес Core не относится к частному каналу.")
|
||||
body = {"schema": SCHEMA, "binding_id": row["binding"]["binding_id"]}
|
||||
value = request(connection, "/v1/channel/inspect", body)
|
||||
@@ -145,7 +149,7 @@ def reconcile(registry):
|
||||
if now < attempts.get(row["id"], 0):
|
||||
continue
|
||||
attempts[row["id"]] = now + 30
|
||||
if tailnet_address(row["core_address"]) and (row.get("last_seen") or 0) >= max(
|
||||
if (row.get("last_seen") or 0) >= max(
|
||||
registry.started_at, time.time() - 20
|
||||
):
|
||||
continue
|
||||
|
||||
@@ -20,9 +20,10 @@ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
||||
from missioncore_plugin_sdk.v0alpha2.identity import ExecutionBinding
|
||||
|
||||
from . import sensors
|
||||
from .channel_binding import authenticate, endpoint_error
|
||||
from .sensor_transient import cache as sensor_transient
|
||||
from .trust import SCHEMA, CoreTrust, PairingError, node_request, parse_invitation, pem, public_id
|
||||
|
||||
|
||||
class FleetRegistry:
|
||||
"""One writer lock and durable transactions; transport never owns vehicles."""
|
||||
|
||||
@@ -35,20 +36,27 @@ class FleetRegistry:
|
||||
self.independent_equipment: EquipmentStore | None = None
|
||||
self.vps_hosts: VPSHosts | None = None
|
||||
self.lock = threading.RLock()
|
||||
self.presence: dict[str, dict] = {}
|
||||
from .events import FleetEvents
|
||||
|
||||
self.events = FleetEvents()
|
||||
from .device_enrollment import DeviceEnrollment
|
||||
|
||||
self.device_enrollment = DeviceEnrollment()
|
||||
from .routers import Routers
|
||||
self.routers = Routers()
|
||||
from .monitor import MonitorReceiver
|
||||
|
||||
self.monitor = MonitorReceiver(root)
|
||||
from .rover_control import RoverControl
|
||||
self.rover_control = RoverControl()
|
||||
from .rover_channel import RoverChannel
|
||||
self.rover_channel = RoverChannel(self.rover_control)
|
||||
from .rover_configuration import RoverConfigurations
|
||||
self.rover_configurations = RoverConfigurations(root)
|
||||
self.trust = CoreTrust(root)
|
||||
from .network_profiles import NetworkProfiles
|
||||
self.network_profiles = NetworkProfiles(self)
|
||||
path = root / "fleet.sqlite3"
|
||||
if path.is_symlink():
|
||||
raise PairingError("Конфликт файла реестра.")
|
||||
@@ -72,6 +80,7 @@ class FleetRegistry:
|
||||
# Preserve pre-archive releases' completed backups before the ordinary
|
||||
# short-lived operation receipts are pruned.
|
||||
for row in self.rows():
|
||||
self.rover_channel.publish(row)
|
||||
for receipt in row.get("sensor_commands", {}).values():
|
||||
if receipt.get("state") == "complete" and receipt.get("command", {}).get("action_id") == "vesc.config.backup":
|
||||
with suppress(ValueError, KeyError, TypeError):
|
||||
@@ -84,26 +93,31 @@ class FleetRegistry:
|
||||
|
||||
def rows(self):
|
||||
return [
|
||||
json.loads(row[0]) for row in self.db.execute("SELECT body FROM vehicles ORDER BY id")
|
||||
sensor_transient(self).hydrate(json.loads(row[0])) for row in self.db.execute("SELECT body FROM vehicles ORDER BY id")
|
||||
]
|
||||
|
||||
def save(self, row, *, previous=None):
|
||||
with self.db:
|
||||
if previous is not None:
|
||||
self.db.execute("INSERT INTO board_history VALUES(?,?,?)",
|
||||
(previous["id"], previous["revision"], json.dumps(previous)))
|
||||
(previous["id"], previous["revision"], json.dumps(sensor_transient(self).persist(previous))))
|
||||
self.db.execute(
|
||||
"INSERT INTO vehicles VALUES(?,?,?) "
|
||||
"ON CONFLICT(id) DO UPDATE SET node_id=excluded.node_id, body=excluded.body",
|
||||
(row["id"], row["node_id"], json.dumps(row)),
|
||||
(row["id"], row["node_id"], json.dumps(sensor_transient(self).persist(row))),
|
||||
)
|
||||
# Publish only after commit. Inventory fsync never holds the control
|
||||
# channel lock; a failed transaction cannot change its authority.
|
||||
self.rover_channel.publish(row)
|
||||
if row["enrollment"] == "revoked":
|
||||
self.network_profiles.revoke_node(row["node_id"])
|
||||
self.events.notify()
|
||||
|
||||
def find(self, identifier):
|
||||
result = self.db.execute("SELECT body FROM vehicles WHERE id=?", (identifier,)).fetchone()
|
||||
if not result:
|
||||
raise PairingError("Аппарат не найден.")
|
||||
return json.loads(result[0])
|
||||
return sensor_transient(self).hydrate(json.loads(result[0]))
|
||||
|
||||
def start(self):
|
||||
with self.lock:
|
||||
@@ -112,6 +126,11 @@ class FleetRegistry:
|
||||
# Address absent: keep the binding and show offline.
|
||||
with suppress(OSError):
|
||||
self.listen(row["core_address"])
|
||||
for profile in self.network_profiles.profiles.values():
|
||||
if profile.get("state") == "ready":
|
||||
import ipaddress
|
||||
with suppress(OSError):
|
||||
self.listen(str(ipaddress.ip_network(profile["subnet"])[2]))
|
||||
self.worker = threading.Thread(
|
||||
target=self.reconcile, name="mission-core-fleet", daemon=True
|
||||
)
|
||||
@@ -134,6 +153,8 @@ class FleetRegistry:
|
||||
self.worker.join(timeout=20)
|
||||
if self.recovery_worker:
|
||||
self.recovery_worker.join(timeout=30)
|
||||
for worker in self.network_profiles.workers.values():
|
||||
worker.join(timeout=30)
|
||||
for server in self.listeners.values():
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
@@ -184,7 +205,9 @@ class FleetRegistry:
|
||||
|
||||
def add(self, preview_id: str, name: str, platform: str, *,
|
||||
vehicle_id: str | None = None, expected_revision: int | None = None) -> dict:
|
||||
with self.lock:
|
||||
# Replacement admission and publication exclude a concurrent arm.
|
||||
# This exceptional identity operation is not the heartbeat writer path.
|
||||
with self.lock, self.rover_channel.lock:
|
||||
preview = self.previews.get(preview_id)
|
||||
if preview is None or preview["expires"] <= time.time():
|
||||
raise PairingError("Проверка приглашения истекла. Вставьте код снова.")
|
||||
@@ -259,11 +282,15 @@ class FleetRegistry:
|
||||
return self.public(row)
|
||||
|
||||
def public(self, row):
|
||||
presence = self.presence.get(row["id"], {})
|
||||
if presence.get("binding_id") != row["binding"]["binding_id"]:
|
||||
presence = {}
|
||||
last_seen = max(row["last_seen"] or 0, presence.get("at", 0)) or None
|
||||
online = (
|
||||
row["enrollment"] == "paired"
|
||||
and row["last_seen"] is not None
|
||||
and row["last_seen"] >= self.started_at
|
||||
and time.time() - row["last_seen"] < 20
|
||||
and last_seen is not None
|
||||
and last_seen >= self.started_at
|
||||
and time.time() - last_seen < 20
|
||||
)
|
||||
return {
|
||||
"id": row["id"],
|
||||
@@ -274,6 +301,13 @@ class FleetRegistry:
|
||||
"revision": row["revision"],
|
||||
"connectivity": "online" if online else "offline",
|
||||
"last_seen": row["last_seen"],
|
||||
"link_last_seen": last_seen,
|
||||
"inventory_fresh": bool(
|
||||
row["last_seen"] and row["last_seen"] >= self.started_at
|
||||
and time.time() - row["last_seen"] < 20
|
||||
and (not presence or presence.get("agent_instance_id")
|
||||
== (row.get("runtime") or {}).get("agent_instance_id"))
|
||||
),
|
||||
"host": row["inventory"],
|
||||
"execution_binding": row["runtime"],
|
||||
"devices": row.get("sensor_state", {}).get("items", []),
|
||||
@@ -308,7 +342,7 @@ class FleetRegistry:
|
||||
}
|
||||
|
||||
def revoke(self, identifier: str):
|
||||
with self.lock:
|
||||
with self.lock, self.rover_channel.lock:
|
||||
row = self.find(identifier)
|
||||
if row["enrollment"] == "revoked":
|
||||
return self.public(row)
|
||||
@@ -385,7 +419,9 @@ class FleetRegistry:
|
||||
|
||||
def reconcile(self):
|
||||
while not self.stop.is_set():
|
||||
self.network_profiles.reconcile()
|
||||
with self.lock:
|
||||
self.routers.prune()
|
||||
active = [row for row in self.rows() if row["enrollment"] in ("pending", "paired")]
|
||||
for address in {row["core_address"] for row in active}:
|
||||
try:
|
||||
@@ -421,31 +457,24 @@ class FleetRegistry:
|
||||
if not isinstance(key, Ed25519PublicKey):
|
||||
return 403, {"error": "Unauthorized Node"}
|
||||
node_id = public_id("node_", key)
|
||||
if path in ("/v1/node/rover", "/v1/node/rover-stream", "/v1/node/rover-link", "/v1/node/rover-diagnostics"):
|
||||
started = time.monotonic()
|
||||
result = self.rover_channel.receive(node_id, cert.serial_number, path, value, address)
|
||||
if path == "/v1/node/rover" and result[0] == 200:
|
||||
self.rover_control.record_telemetry_timing(
|
||||
node_id, (time.monotonic() - started) * 1000,
|
||||
result[1]["control_clock"]["monotonic_ms"],
|
||||
)
|
||||
return result
|
||||
entered = time.monotonic()
|
||||
with self.lock:
|
||||
waited = time.monotonic() - entered
|
||||
if waited > .025:
|
||||
logging.getLogger(__name__).warning("fleet timing path=%s lock_ms=%.1f", path, waited*1000)
|
||||
row = next((item for item in self.rows() if item["node_id"] == node_id), None)
|
||||
if (
|
||||
row is None
|
||||
or row["enrollment"] not in ("pending", "paired")
|
||||
or value.get("node_id") != node_id
|
||||
or value.get("binding_id") != row["binding"]["binding_id"]
|
||||
):
|
||||
return 410, {"error": "Binding revoked"}
|
||||
allowed = [row["binding"]["client_pem"]]
|
||||
if (
|
||||
row.get("certificate_previous")
|
||||
and row["certificate_previous"]["until"] > time.time()
|
||||
):
|
||||
allowed.append(row["certificate_previous"]["pem"])
|
||||
if cert.serial_number not in [
|
||||
x509.load_pem_x509_certificate(item.encode()).serial_number for item in allowed
|
||||
]:
|
||||
return 403, {"error": "Certificate superseded"}
|
||||
if value.get("schema") != SCHEMA:
|
||||
return 400, {"error": "Incompatible protocol"}
|
||||
error = authenticate(row, node_id, cert.serial_number, value)
|
||||
if error:
|
||||
return error
|
||||
if path == "/v1/node/unpair":
|
||||
row.update(
|
||||
enrollment="revoked",
|
||||
@@ -456,42 +485,28 @@ class FleetRegistry:
|
||||
)
|
||||
self.save(row)
|
||||
return 200, {"ok": True}
|
||||
if path not in ("/v1/node/heartbeat", "/v1/node/rover", "/v1/node/rover-stream"):
|
||||
if path == "/v1/node/liveness":
|
||||
return self.receive_liveness(row, value, address)
|
||||
if path != "/v1/node/heartbeat":
|
||||
return 404, {"error": "Unknown operation"}
|
||||
# Endpoint revisions prevent an old in-flight heartbeat or lost ack
|
||||
# from reversing a migration. Use the actual listener, not a claimed IP.
|
||||
from .recovery import tailnet_address
|
||||
|
||||
error = endpoint_error(row, value, address)
|
||||
if error:
|
||||
return error
|
||||
revision = value.get("endpoint_revision", 0)
|
||||
if type(revision) is not int or not 0 <= revision <= 1000000000:
|
||||
return 400, {"error": "Invalid endpoint revision"}
|
||||
previous_revision = row["binding"].get("endpoint_revision", 0)
|
||||
if revision < previous_revision:
|
||||
return 409, {"error": "Endpoint superseded"}
|
||||
if revision > previous_revision:
|
||||
if (
|
||||
not tailnet_address(address)
|
||||
or value.get("core_endpoint") != f"https://{address}:8782"
|
||||
):
|
||||
return 400, {"error": "Endpoint does not match authenticated channel"}
|
||||
row["core_address"] = address
|
||||
row["binding"]["endpoint"] = value["core_endpoint"]
|
||||
row["binding"]["endpoint_revision"] = revision
|
||||
if path in ("/v1/node/rover", "/v1/node/rover-stream"):
|
||||
if row["enrollment"] != "paired":
|
||||
return 410, {"error": "Pairing incomplete"}
|
||||
if path.endswith("-stream"):
|
||||
relay = value.get("relay_id")
|
||||
if not isinstance(relay, str) or len(relay) != 32:
|
||||
return 400, {"error": "Invalid relay"}
|
||||
return 200, self.rover_control.stream(node_id, relay)
|
||||
return 200, self.rover_control.exchange(node_id, value)
|
||||
binding = ExecutionBinding.model_validate(value["execution_binding"])
|
||||
if binding.node_id != node_id or binding.platform.value != "linux":
|
||||
return 400, {"error": "Invalid Node inventory"}
|
||||
sensor_state = sensors.validate_inventory(value, node_id)
|
||||
sensor_response = sensors.heartbeat(row, value)
|
||||
configuration_response = self.rover_configurations.heartbeat(node_id, value)
|
||||
network_response = self.network_profiles.heartbeat(row, value)
|
||||
archive_ack = None
|
||||
archive_started = time.monotonic()
|
||||
try:
|
||||
@@ -506,6 +521,7 @@ class FleetRegistry:
|
||||
archive_ack = None
|
||||
archive_elapsed = time.monotonic() - archive_started
|
||||
enrollment_response = self.device_enrollment.heartbeat(row, value)
|
||||
router_response = self.routers.heartbeat(row, value)
|
||||
host = value.get("host")
|
||||
if (
|
||||
not isinstance(host, dict)
|
||||
@@ -548,6 +564,32 @@ class FleetRegistry:
|
||||
"ok": True,
|
||||
"client_pem": row["binding"]["client_pem"],
|
||||
**configuration_response,
|
||||
**network_response,
|
||||
**sensor_response,
|
||||
**enrollment_response,
|
||||
**router_response,
|
||||
}
|
||||
|
||||
def receive_liveness(self, row, value, address):
|
||||
# Called after the same certificate/binding authentication, under lock.
|
||||
# RAM-only presence does not refresh equipment, monitor, configuration,
|
||||
# command acknowledgements, persisted inventory or motor authority.
|
||||
allowed = {"schema", "node_id", "binding_id", "execution_binding",
|
||||
"core_endpoint", "endpoint_revision"}
|
||||
if set(value) - allowed or len(json.dumps(value).encode()) > 2048:
|
||||
return 400, {"error": "Invalid liveness envelope"}
|
||||
error = endpoint_error(row, value, address)
|
||||
if error:
|
||||
return error
|
||||
binding = ExecutionBinding.model_validate(value["execution_binding"])
|
||||
if binding.node_id != row["node_id"] or binding.platform.value != "linux":
|
||||
return 400, {"error": "Invalid Node identity"}
|
||||
now = time.time()
|
||||
self.presence = {key: item for key, item in self.presence.items() if now-item["at"] < 20}
|
||||
if row["id"] not in self.presence and len(self.presence) >= 256:
|
||||
return 503, {"error": "Presence capacity"}
|
||||
self.presence[row["id"]] = {
|
||||
"at": now, "binding_id": row["binding"]["binding_id"],
|
||||
"agent_instance_id": binding.agent_instance_id,
|
||||
}
|
||||
return 200, {"ok": True, "heartbeat_encoding": "gzip"}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Committed binding projection for control, independent of inventory disk I/O.
|
||||
|
||||
Lock order: registry writer -> channel -> RoverControl. Channel operations never
|
||||
take the writer lock or access SQLite. Each frame still checks current authority.
|
||||
"""
|
||||
import copy
|
||||
import threading
|
||||
import time
|
||||
|
||||
from .channel_binding import authenticate, endpoint_error
|
||||
from .trust import PairingError
|
||||
|
||||
|
||||
class RoverChannel:
|
||||
def __init__(self, control):
|
||||
self.control = control
|
||||
self.lock = threading.RLock()
|
||||
self.vehicles = {}
|
||||
self.nodes = {}
|
||||
|
||||
def publish(self, row):
|
||||
# Only committed identity metadata is projected, never inventory, action
|
||||
# receipts, camera payloads or durable motion state.
|
||||
binding = row["binding"]
|
||||
projection = copy.deepcopy({
|
||||
"name": row.get("name",row["id"]), "id": row["id"], "node_id": row["node_id"], "enrollment": row["enrollment"],
|
||||
"binding": {key: binding[key] for key in
|
||||
("binding_id", "client_pem", "endpoint_revision") if key in binding},
|
||||
"certificate_previous": row.get("certificate_previous"),
|
||||
})
|
||||
with self.lock:
|
||||
old = self.vehicles.get(row["id"])
|
||||
if old and (old["node_id"] != row["node_id"]
|
||||
or old["binding"]["binding_id"] != binding["binding_id"]
|
||||
or old["binding"].get("endpoint_revision", 0) != binding.get("endpoint_revision", 0)
|
||||
or (old["enrollment"] == "paired" and row["enrollment"] != "paired")):
|
||||
self.nodes.pop(old["node_id"], None)
|
||||
self.control.forget(old["node_id"])
|
||||
self.vehicles[row["id"]] = projection
|
||||
self.nodes[row["node_id"]] = projection
|
||||
|
||||
def same_generation(self, value):
|
||||
"""Cheap retirement check only; a send still performs full authentication."""
|
||||
with self.lock:
|
||||
row = self.nodes.get(value.get("node_id"))
|
||||
return bool(row and row["enrollment"] == "paired"
|
||||
and row["binding"]["binding_id"] == value.get("binding_id")
|
||||
and row["binding"].get("endpoint_revision", 0) == value.get("endpoint_revision", 0))
|
||||
|
||||
def operator(self, vehicle, operation, body=None, *, expires_at=None):
|
||||
with self.lock:
|
||||
row = self.vehicles.get(vehicle)
|
||||
if row is None:
|
||||
raise PairingError("Аппарат не найден.")
|
||||
if row["enrollment"] != "paired":
|
||||
raise ValueError("Борт не привязан.")
|
||||
node = row["node_id"]
|
||||
if operation == "diagnostics":
|
||||
return self.control.diagnostics(node,row.get("name",vehicle))
|
||||
if operation == "view":
|
||||
return self.control.view(node)
|
||||
if operation == "observation_evidence":
|
||||
return self.control.observation(node, body)
|
||||
if operation == "arm":
|
||||
return self.control.arm(node, body, expires_at=expires_at)
|
||||
if operation == "command":
|
||||
return self.control.command(node, body, expires_at=expires_at)
|
||||
if operation == "hold":
|
||||
return self.control.hold(node, body, expires_at=expires_at)
|
||||
if operation == "maintain_neutral":
|
||||
return self.control.maintain_neutral(node, body["session_id"])
|
||||
if operation == "disconnect":
|
||||
return self.control.disconnect(node, body["session_id"])
|
||||
raise ValueError("Unknown control operation")
|
||||
|
||||
def receive(self, node, serial, path, value, address):
|
||||
started = time.monotonic()
|
||||
with self.lock:
|
||||
row = self.nodes.get(node)
|
||||
error = self._receive_error(row, node, serial, value, address)
|
||||
if error:
|
||||
return error
|
||||
if path == "/v1/node/rover-link":
|
||||
# Authenticate/establish the connection only. This must never
|
||||
# publish a snapshot, renew a lease or make stale data fresh.
|
||||
relay = value.get("relay_id")
|
||||
if (set(value) - {"schema", "node_id", "binding_id", "core_endpoint",
|
||||
"endpoint_revision", "relay_id"}
|
||||
or not isinstance(relay, str) or len(relay) != 32
|
||||
or any(c not in "0123456789abcdef" for c in relay)):
|
||||
return 400, {"error": "Invalid rover link probe"}
|
||||
return 200, {"connected": True, "sample_clock_v1": True, "diagnostic_lane_v1": True, "budget_interval_v1": True, "rover_details_v1": True,
|
||||
"control_clock": self.control._clock()}
|
||||
if path == "/v1/node/rover-diagnostics":
|
||||
# Capture this binding's diagnostics object while authority is
|
||||
# locked, but never serialize control behind optional ingest or
|
||||
# export. A forgotten binding's object cannot recreate a board.
|
||||
diagnostics = self.control.diagnostics(node, row.get("name", row["id"]))
|
||||
elif path == "/v1/node/rover-stream":
|
||||
relay = value.get("relay_id")
|
||||
if not isinstance(relay, str) or len(relay) != 32:
|
||||
return 400, {"error": "Invalid relay"}
|
||||
return 200, self.control.stream(node, relay)
|
||||
else:
|
||||
result = self.control.exchange(node, value)
|
||||
result["core_processing_ms"] = (time.monotonic() - started) * 1000
|
||||
return 200, result
|
||||
|
||||
reply = diagnostics.exchange(value)
|
||||
with self.lock:
|
||||
# Revocation/rotation/rebinding may finish during optional work.
|
||||
# Recheck current authority before releasing any diagnostic reply.
|
||||
error = self._receive_error(self.nodes.get(node), node, serial, value, address)
|
||||
if error:
|
||||
return error
|
||||
with self.control.lock:
|
||||
board = self.control.boards.get(node)
|
||||
if board is None or board["diagnostics"] is not diagnostics:
|
||||
return 409, {"error": "Diagnostic binding superseded"}
|
||||
return 200, reply
|
||||
|
||||
@staticmethod
|
||||
def _receive_error(row, node, serial, value, address):
|
||||
error = authenticate(row, node, serial, value)
|
||||
if error:
|
||||
return error
|
||||
error = endpoint_error(row, value, address)
|
||||
if error:
|
||||
return error
|
||||
if row["enrollment"] != "paired":
|
||||
return 410, {"error": "Pairing incomplete"}
|
||||
return None
|
||||
@@ -7,6 +7,9 @@ import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
from .rover_diagnostics import RoverDiagnostics
|
||||
from .rover_observation_evidence import ObservationEvidence
|
||||
|
||||
|
||||
class RoverControl:
|
||||
def __init__(self, clock=time.monotonic):
|
||||
@@ -14,50 +17,126 @@ class RoverControl:
|
||||
self.lock = threading.RLock()
|
||||
self.changed = threading.Condition(self.lock)
|
||||
self.boards = {}
|
||||
self.network_changes = set()
|
||||
self.clock_id = secrets.token_hex(16)
|
||||
|
||||
def _board(self, node):
|
||||
return self.boards.setdefault(node, {"seen": -1e9, "watch": 0, "snapshot": {},
|
||||
"session": None, "relay": None})
|
||||
if node not in self.boards:
|
||||
self.boards[node]={"seen":-1e9,"watch":0,"snapshot":{},"session":None,"relay":None,"diagnostics":RoverDiagnostics(self.clock),"observation":ObservationEvidence(self.clock)}
|
||||
return self.boards[node]
|
||||
|
||||
def diagnostics(self,node,vehicle):
|
||||
with self.lock:
|
||||
board=self._board(node);value=board["diagnostics"];value.vehicle=vehicle
|
||||
session=board["session"] or {}
|
||||
value.context={"vehicle":vehicle,"core_clock_instance":self.clock_id,"driver_state":board["snapshot"].get("state"),
|
||||
"session_id":session.get("id"),"settings":copy.deepcopy(session.get("settings"))}
|
||||
return value
|
||||
|
||||
def forget(self, node):
|
||||
"""A revoked/replaced binding cannot retain a lease or a fresh snapshot."""
|
||||
with self.changed:
|
||||
self.boards.pop(node, None)
|
||||
self.changed.notify_all()
|
||||
|
||||
def observation(self, node, event=None):
|
||||
with self.lock:
|
||||
evidence = self._board(node)["observation"]
|
||||
if event in ("operator_socket_opened", "operator_socket_closed"):
|
||||
evidence.event(event)
|
||||
return evidence.snapshot()
|
||||
|
||||
def view(self, node):
|
||||
with self.lock:
|
||||
b = self._board(node)
|
||||
b["watch"] = self.clock() + 2
|
||||
fresh = self.clock() - b["seen"] < 1
|
||||
elapsed = max(0., self.clock() - b["seen"])
|
||||
fresh = elapsed < 1
|
||||
b["observation"].view(fresh)
|
||||
self._expire(b)
|
||||
return {"fresh": fresh, "snapshot": copy.deepcopy(b["snapshot"]) if fresh else {},
|
||||
"controlling": b["session"] is not None}
|
||||
snapshot = copy.deepcopy(b["snapshot"]) if fresh else {}
|
||||
for reading in snapshot.get("devices", []):
|
||||
age = reading.get("age_ms")
|
||||
if type(age) in (int, float) and math.isfinite(age):
|
||||
reading["age_ms"] = max(0, age) + int(elapsed * 1000)
|
||||
result = {"fresh": fresh, "snapshot": snapshot,
|
||||
"controlling": b["session"] is not None}
|
||||
if fresh and self.clock()-b.get("budget_seen", -1e9) < 2 and isinstance(b.get("link_budget"), dict):
|
||||
result["link_budget"] = copy.deepcopy(b["link_budget"])
|
||||
result["link_budget"]["snapshot_age_ms"] = max(0, int((self.clock()-b["budget_seen"])*1000))
|
||||
return result
|
||||
|
||||
def _withdraw(self, b, reason, *, snapshot=None):
|
||||
session = b["session"]
|
||||
if session is None:
|
||||
return
|
||||
b["session"] = None
|
||||
observed = b["snapshot"] if snapshot is None else snapshot
|
||||
b["diagnostics"].control_stop.record(
|
||||
reason, session, core_instance=self.clock_id,
|
||||
telemetry_age_ms=(self.clock() - b["seen"]) * 1000,
|
||||
driver_state=observed.get("state"),
|
||||
)
|
||||
|
||||
def _expire(self, b):
|
||||
if b["session"] and self.clock() >= b["session"]["until"]:
|
||||
b["session"] = None
|
||||
b["diagnostics"].trace.add("lease_expired", session_id=b["session"]["id"], sequence=b["session"]["sequence"])
|
||||
self._withdraw(b, "input_deadline_expired")
|
||||
|
||||
def arm(self, node, body):
|
||||
if (set(body) != {"standstill_confirmed", "current_a", "max_erpm"}
|
||||
def disconnect(self, node, session):
|
||||
"""A closed operator socket can retire only the lease it created."""
|
||||
with self.changed:
|
||||
b = self._board(node)
|
||||
if b["session"] and b["session"]["id"] == session:
|
||||
b["diagnostics"].trace.add("operator_disconnect", session_id=session)
|
||||
self._withdraw(b, "operator_socket_closed")
|
||||
self.changed.notify_all()
|
||||
|
||||
def network_change(self, node, active):
|
||||
with self.lock:
|
||||
if active:
|
||||
board = self._board(node)
|
||||
self._expire(board)
|
||||
if board["session"] is not None:
|
||||
raise ValueError("Отключите управление перед изменением сети борта.")
|
||||
self.network_changes.add(node)
|
||||
else:
|
||||
self.network_changes.discard(node)
|
||||
|
||||
def arm(self, node, body, *, expires_at=None):
|
||||
duty = "max_duty_percent" in body
|
||||
speed_key, low, high = ("max_duty_percent", 1, 100) if duty else ("max_erpm", 300, 3000)
|
||||
if (set(body) != {"standstill_confirmed", "current_a", speed_key}
|
||||
or body["standstill_confirmed"] is not True
|
||||
or type(body["current_a"]) not in (int, float)
|
||||
or not .5 <= body["current_a"] <= 30
|
||||
or type(body["max_erpm"]) not in (int, float)
|
||||
or not 300 <= body["max_erpm"] <= 3000):
|
||||
or not math.isfinite(body["current_a"]) or body["current_a"] < .5
|
||||
or type(body[speed_key]) not in (int, float)
|
||||
or not low <= body[speed_key] <= high):
|
||||
raise ValueError("Подтвердите остановку и выберите допустимые пределы.")
|
||||
with self.lock:
|
||||
if node in self.network_changes:
|
||||
raise ValueError("Дождитесь завершения переключения сети борта.")
|
||||
b = self._board(node)
|
||||
if expires_at is not None and self.clock() >= expires_at:
|
||||
raise ValueError("Команда устарела до передачи на борт.")
|
||||
self._expire(b)
|
||||
if b["session"]:
|
||||
raise ValueError("Аппаратом уже управляют. Сначала остановите управление.")
|
||||
snapshot = b["snapshot"]
|
||||
if self.clock() - b["seen"] >= 1 or snapshot.get("supported") is not True:
|
||||
raise ValueError("Канал управления бортом недоступен.")
|
||||
if duty and "duty" not in (snapshot.get("control_modes") or []):
|
||||
raise ValueError("Обновите драйвер борта для управления газом.")
|
||||
if snapshot.get("state") in ("preparing", "ready", "driving", "stopping"):
|
||||
raise ValueError("Дождитесь завершения предыдущего управления.")
|
||||
identifier = secrets.token_hex(16)
|
||||
b["session"] = {"id": identifier, "sequence": 0, "until": self.clock()+.4,
|
||||
b["session"] = {"id": identifier, "sequence": 0, "operator_sequence": 0, "neutral_hold": False, "until": min(self.clock()+.4, expires_at) if expires_at is not None else self.clock()+.4,
|
||||
"left": 0, "right": 0, "settings": copy.deepcopy(body)}
|
||||
self.changed.notify_all()
|
||||
b["diagnostics"].trace.add("armed", session_id=identifier, settings=body)
|
||||
return {"session_id": identifier}
|
||||
|
||||
def command(self, node, body):
|
||||
def command(self, node, body, *, expires_at=None):
|
||||
if set(body) != {"session_id", "sequence", "left", "right", "stop"}:
|
||||
raise ValueError("Некорректная команда управления.")
|
||||
if (type(body["sequence"]) is not int or not 1 <= body["sequence"] < 2**53
|
||||
@@ -67,20 +146,66 @@ class RoverControl:
|
||||
raise ValueError("Некорректные значения команды.")
|
||||
with self.lock:
|
||||
b = self._board(node)
|
||||
if expires_at is not None and self.clock() >= expires_at:
|
||||
raise ValueError("Команда устарела до передачи на борт.")
|
||||
self._expire(b)
|
||||
s = b["session"]
|
||||
if not s or not secrets.compare_digest(str(body["session_id"]), s["id"]):
|
||||
raise ValueError("Управление завершено. Включите его заново.")
|
||||
if body["sequence"] <= s["sequence"]:
|
||||
if body["sequence"] <= s["operator_sequence"]:
|
||||
raise ValueError("Устаревшая команда отклонена.")
|
||||
if body["stop"]:
|
||||
b["session"] = None
|
||||
self._withdraw(b, "operator_stop")
|
||||
else:
|
||||
s.update(sequence=body["sequence"], left=body["left"], right=body["right"],
|
||||
until=self.clock()+.4)
|
||||
s.update(sequence=max(s["sequence"]+1, body["sequence"]), operator_sequence=body["sequence"],
|
||||
neutral_hold=False, left=body["left"], right=body["right"],
|
||||
until=min(self.clock()+.4, expires_at) if expires_at is not None else self.clock()+.4)
|
||||
self.changed.notify_all()
|
||||
b["diagnostics"].trace.add("operator_command", **body)
|
||||
return {"accepted_sequence": body["sequence"]}
|
||||
|
||||
def hold(self, node, body, *, expires_at=None):
|
||||
"""Explicit socket-owner handoff to neutral; no remembered motion."""
|
||||
if not isinstance(body, dict) or set(body) != {"session_id", "sequence"}:
|
||||
raise ValueError("Некорректная команда удержания готовности.")
|
||||
with self.lock:
|
||||
result = self.command(node, {**body, "left": 0, "right": 0, "stop": False},
|
||||
expires_at=expires_at)
|
||||
self._board(node)["session"]["neutral_hold"] = True
|
||||
return result
|
||||
|
||||
def maintain_neutral(self, node, session):
|
||||
"""Called only by the live owner socket, never by observation/Node pull.
|
||||
|
||||
This creates fresh ZERO frames, not fresh timestamps on remembered
|
||||
operator input. Missing a deadline is terminal even in neutral hold.
|
||||
"""
|
||||
with self.changed:
|
||||
b = self._board(node)
|
||||
self._expire(b)
|
||||
s = b["session"]
|
||||
if not s or s["id"] != session or not s["neutral_hold"]:
|
||||
return False
|
||||
snapshot = b["snapshot"]
|
||||
if (self.clock()-b["seen"] >= 1 or snapshot.get("supported") is not True
|
||||
or (snapshot.get("session_id") == session and snapshot.get("state")
|
||||
in ("stopping", "stopped", "fault", "receiver"))):
|
||||
reason = ("telemetry_stale" if self.clock()-b["seen"] >= 1 else
|
||||
"driver_unavailable" if snapshot.get("supported") is not True else
|
||||
"driver_terminal")
|
||||
self._withdraw(b, reason)
|
||||
self.changed.notify_all()
|
||||
return False
|
||||
s.update(left=0, right=0, sequence=s["sequence"]+1, until=self.clock()+.4)
|
||||
self.changed.notify_all()
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _intent(session):
|
||||
# Browser sequence and neutral ownership never cross the Node boundary.
|
||||
return {key: copy.deepcopy(session[key]) for key in
|
||||
("id", "sequence", "left", "right", "settings")}
|
||||
|
||||
def exchange(self, node, body):
|
||||
"""Called only after normal paired-certificate/binding authentication."""
|
||||
snapshot = body.get("rover")
|
||||
@@ -88,27 +213,112 @@ class RoverControl:
|
||||
if not isinstance(snapshot, dict) or not isinstance(relay, str) or len(relay) != 32:
|
||||
raise ValueError("Invalid rover exchange")
|
||||
with self.lock:
|
||||
observed = self.clock()
|
||||
timing = body.get("sample_clock")
|
||||
if timing is not None:
|
||||
if (not isinstance(timing, dict) or set(timing) != {"instance", "monotonic_ms"}
|
||||
or timing["instance"] != self.clock_id
|
||||
or type(timing["monotonic_ms"]) not in (int, float)
|
||||
or not math.isfinite(timing["monotonic_ms"])
|
||||
or not 0 <= timing["monotonic_ms"] <= observed * 1000):
|
||||
raise ValueError("Invalid rover sample clock")
|
||||
observed = timing["monotonic_ms"] / 1000
|
||||
b = self._board(node)
|
||||
if b["relay"] != relay:
|
||||
b["session"] = None # No resume after relay restart/rebind.
|
||||
if b["snapshot"].get("instance") != snapshot.get("instance"):
|
||||
b["session"] = None # Driver restarts also revoke the browser lease.
|
||||
b.update(relay=relay, snapshot=copy.deepcopy(snapshot), seen=self.clock())
|
||||
# A delayed/cancelled request may arrive after its replacement.
|
||||
# It cannot replace a newer sample or change its relay/session.
|
||||
publish = observed >= b["seen"]
|
||||
metadata = None
|
||||
if publish and "rover_details_v1" in body:
|
||||
from .rover_metadata import expand
|
||||
snapshot, metadata = expand(snapshot, body["rover_details_v1"], b.get("rover_metadata"),
|
||||
relay=relay, observed=observed, now=self.clock())
|
||||
readings = snapshot.get("devices")
|
||||
b["observation"].receive(observed, publish, len(readings) if isinstance(readings, list) else 0)
|
||||
if publish and b["relay"] != relay:
|
||||
self._withdraw(b, "relay_changed", snapshot=snapshot)
|
||||
if publish and b["snapshot"].get("instance") != snapshot.get("instance"):
|
||||
self._withdraw(b, "driver_restarted", snapshot=snapshot)
|
||||
b["diagnostics"].ingest(body.get("diagnostics"))
|
||||
if publish:
|
||||
b["diagnostics"].supports_options=body.get("diagnostic_options_v1") is True
|
||||
b.update(relay=relay, snapshot=copy.deepcopy(snapshot), seen=observed, rover_metadata=metadata)
|
||||
if "link_budget" in body:
|
||||
b["link_budget"] = copy.deepcopy(body["link_budget"])
|
||||
b["budget_seen"] = observed
|
||||
snapshot = b["snapshot"]
|
||||
self._expire(b)
|
||||
s = b["session"]
|
||||
if s and snapshot.get("session_id") == s["id"] and snapshot.get("state") in (
|
||||
"stopped", "fault", "receiver"):
|
||||
b["session"] = s = None
|
||||
"stopping", "stopped", "fault", "receiver"):
|
||||
self._withdraw(b, "driver_terminal")
|
||||
s = None
|
||||
command = None
|
||||
if s:
|
||||
command = {k: copy.deepcopy(v) for k,v in s.items() if k != "until"}
|
||||
command = self._intent(s)
|
||||
command["ttl_ms"] = max(0, min(400, int((s["until"]-self.clock())*1000)))
|
||||
return {"watch": self.clock() < b["watch"] or s is not None, "command": command,
|
||||
"control_clock": self._clock()}
|
||||
return {"watch": self.clock() < b["watch"] or s is not None or b["diagnostics"].enabled or b["diagnostics"].closing, "command": command,
|
||||
"control_active": s is not None,
|
||||
# Atomic hints only: never take the optional recorder/export
|
||||
# locks in the command/telemetry path.
|
||||
"diagnostics_pending": bool(b["diagnostics"].enabled or b["diagnostics"].closing or b["diagnostics"].export.busy),
|
||||
"control_clock": self._clock(), "diagnostics": None if body.get("diagnostic_lane_v1") is True else b["diagnostics"].desired(relay_ack=body.get("diagnostic_relay_ack_v1") is True)}
|
||||
|
||||
def exchange_diagnostics(self, node, body):
|
||||
with self.lock:
|
||||
diagnostics = self._board(node)["diagnostics"]
|
||||
# No control lock while ingesting optional records or waiting for files.
|
||||
return diagnostics.exchange(body)
|
||||
|
||||
def record_telemetry_timing(self, node, dispatch_ms, reply_mono_ms):
|
||||
"""DEV-only Core dispatch timing; no publication or lease renewal.
|
||||
|
||||
Excludes body transfer and reply transmission. Compare with Node's
|
||||
HTTP trace to distinguish channel processing from end-to-end delay.
|
||||
Aggregate at most once/second to avoid amplifying optional traffic.
|
||||
Never retain the control lock while writing the diagnostic ring.
|
||||
"""
|
||||
with self.lock:
|
||||
board = self.boards.get(node)
|
||||
if board is None:
|
||||
return
|
||||
diagnostics = board["diagnostics"]
|
||||
if not diagnostics.trace.recording():
|
||||
board.pop("telemetry_timing", None)
|
||||
return
|
||||
trace = diagnostics.trace
|
||||
now = self.clock()
|
||||
timing = board.get("telemetry_timing")
|
||||
if timing is None or timing["capture_id"] != trace.capture_identity():
|
||||
timing = {"capture_id": trace.capture_identity(), "next": now, "count": 0, "max_ms": 0.}
|
||||
board["telemetry_timing"] = timing
|
||||
timing["count"] += 1
|
||||
timing["max_ms"] = max(timing["max_ms"], dispatch_ms)
|
||||
if now < timing["next"]:
|
||||
return
|
||||
details = {"exchanges": timing["count"],
|
||||
"dispatch_max_ms": round(timing["max_ms"], 3),
|
||||
"reply_mono_ms": reply_mono_ms}
|
||||
timing.update(next=now + 1, count=0, max_ms=0.)
|
||||
trace.add("node_telemetry_handled", **details)
|
||||
|
||||
def _clock(self):
|
||||
return {"instance": self.clock_id, "monotonic_ms": self.clock()*1000}
|
||||
|
||||
def stream_trace(self, node):
|
||||
"""Capture a recorder reference; never hold the authority lock on I/O."""
|
||||
with self.lock:
|
||||
board = self.boards.get(node)
|
||||
return board["diagnostics"].trace if board else None
|
||||
|
||||
def intent_changed(self, node, relay, previous):
|
||||
"""Read-only wake hint; never create a board or grant send authority."""
|
||||
with self.lock:
|
||||
board = self.boards.get(node)
|
||||
current = (board["session"] if board and board["relay"] == relay else None) or {}
|
||||
previous = previous or {}
|
||||
return (current.get("id"), current.get("sequence")) != (
|
||||
previous.get("id"), previous.get("sequence"))
|
||||
|
||||
def wait_for_intent(self, node, relay, previous, timeout=.05):
|
||||
"""Wake on a new intent, including updates between write and wait."""
|
||||
previous = previous or {}
|
||||
@@ -125,11 +335,11 @@ class RoverControl:
|
||||
b = self._board(node)
|
||||
self._expire(b)
|
||||
if self.clock() - b["seen"] >= 1:
|
||||
b["session"] = None
|
||||
self._withdraw(b, "telemetry_stale")
|
||||
s = b["session"] if b["relay"] == relay else None
|
||||
command = None
|
||||
if s:
|
||||
command = {k: copy.deepcopy(v) for k,v in s.items() if k != "until"}
|
||||
command = self._intent(s)
|
||||
command["expires_mono_ms"] = s["until"]*1000
|
||||
return {"watch": self.clock() < b["watch"] or s is not None,
|
||||
return {"watch": self.clock() < b["watch"] or s is not None or b["diagnostics"].enabled or b["diagnostics"].closing,
|
||||
"command": command, "control_clock": self._clock()}
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Latest-state datagrams, with keys delivered only through the paired mTLS lane.
|
||||
|
||||
No command queue, retransmission, authority or lease lives here. Every send asks
|
||||
RoverChannel for the currently authorized intent. Unknown/forged/replayed input
|
||||
gets no response. Keys and packet contents are never logged or persisted.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import secrets
|
||||
import socket
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
|
||||
from cryptography.exceptions import InvalidTag
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
|
||||
# Qualified on 2026-10-27: isolated impairment tests and paired Python/Go mTLS.
|
||||
# Deployment/field acceptance is recorded separately in the network runtime audit.
|
||||
QUALIFIED = True
|
||||
|
||||
MAGIC = b"MCR1"
|
||||
MAX_PACKET = 1200
|
||||
MAX_COUNTER = 2**32 - 1
|
||||
MAX_CHANNELS = 16
|
||||
HEADER = 28 # magic + random channel id + uint64 counter
|
||||
KEEPALIVE_INTERVAL = .05
|
||||
MIN_SEND_INTERVAL = .01
|
||||
|
||||
|
||||
class DatagramCipher:
|
||||
"""One direction, one random key; a counter is never reused under that key."""
|
||||
|
||||
def __init__(self, channel: bytes, key: bytes):
|
||||
if len(channel) != 16 or len(key) != 32:
|
||||
raise ValueError("Invalid datagram key")
|
||||
self.channel, self.aead = channel, AESGCM(key)
|
||||
self.sent = self.received = 0
|
||||
|
||||
def seal(self, value: dict) -> bytes:
|
||||
raw = json.dumps(value, separators=(",", ":"), allow_nan=False).encode()
|
||||
if len(raw) + HEADER + 16 > MAX_PACKET or self.sent >= MAX_COUNTER:
|
||||
raise ValueError("Datagram bound exceeded")
|
||||
self.sent += 1
|
||||
counter = struct.pack("!Q", self.sent)
|
||||
header = MAGIC + self.channel + counter
|
||||
return header + self.aead.encrypt(b"\0" * 4 + counter, raw, header)
|
||||
|
||||
def open(self, packet: bytes):
|
||||
if (not HEADER + 16 < len(packet) <= MAX_PACKET
|
||||
or packet[:20] != MAGIC + self.channel):
|
||||
return None
|
||||
counter = struct.unpack("!Q", packet[20:28])[0]
|
||||
if not self.received < counter <= MAX_COUNTER:
|
||||
return None
|
||||
try:
|
||||
raw = self.aead.decrypt(b"\0" * 4 + packet[20:28], packet[28:], packet[:28])
|
||||
value = json.loads(raw)
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
except (InvalidTag, ValueError, UnicodeError):
|
||||
return None
|
||||
self.received = counter
|
||||
return counter, value
|
||||
|
||||
|
||||
class RoverDatagramServer:
|
||||
"""Bounded socket/thread owned by one existing NodeChannelServer listener."""
|
||||
|
||||
def __init__(self, address, registry, *, port=8782):
|
||||
self.address, self.registry = address, registry
|
||||
self.lock = threading.Lock()
|
||||
self.channels = {}
|
||||
self.stop = threading.Event()
|
||||
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
self.socket.bind((address, port))
|
||||
self.socket.settimeout(.01)
|
||||
except BaseException:
|
||||
self.socket.close()
|
||||
raise
|
||||
self.thread = threading.Thread(
|
||||
target=self.run, name="mission-core-rover-datagram", daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
def open(self, certificate, value):
|
||||
# Caller already authenticated /rover-link, and every frame rechecks
|
||||
# the original certificate/binding. A replacement destroys old keys.
|
||||
channel = secrets.token_bytes(16)
|
||||
send, receive = secrets.token_bytes(32), secrets.token_bytes(32)
|
||||
now = time.monotonic()
|
||||
with self.lock:
|
||||
self.channels = {k: c for k, c in self.channels.items()
|
||||
if c["value"]["node_id"] != value["node_id"] and now < c["expires"]}
|
||||
if len(self.channels) >= MAX_CHANNELS:
|
||||
return 503, {"error": "Datagram capacity reached"}
|
||||
self.channels[channel] = {
|
||||
"value": dict(value), "certificate": certificate,
|
||||
"send": DatagramCipher(channel, send), "receive": DatagramCipher(channel, receive),
|
||||
"peer": None, "probe": 0, "probe_clock": None, "last_probe": now,
|
||||
"next": now, "last_sent": -1e9, "last_command": None, "expires": now + 86400,
|
||||
}
|
||||
return 200, {"channel": channel.hex(), "send_key": receive.hex(),
|
||||
"receive_key": send.hex(), "port": self.socket.getsockname()[1],
|
||||
"max_packet": MAX_PACKET, "lifetime_s": 86400}
|
||||
|
||||
def close(self):
|
||||
self.stop.set()
|
||||
self.socket.close()
|
||||
self.thread.join(timeout=2)
|
||||
with self.lock:
|
||||
self.channels.clear()
|
||||
|
||||
def run(self):
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
packet, peer = self.socket.recvfrom(MAX_PACKET + 1)
|
||||
except (TimeoutError, BlockingIOError):
|
||||
packet = None
|
||||
except OSError:
|
||||
break
|
||||
now = time.monotonic()
|
||||
with self.lock:
|
||||
if packet is not None and len(packet) <= MAX_PACKET:
|
||||
c = self.channels.get(packet[4:20])
|
||||
if c is not None:
|
||||
opened = c["receive"].open(packet)
|
||||
if opened is not None and opened[1] == {}:
|
||||
# This clock is sampled AFTER the exact echoed probe,
|
||||
# never at a later periodic send for that same probe.
|
||||
c.update(peer=peer, probe=opened[0],
|
||||
probe_clock=self.registry.rover_control._clock(),
|
||||
last_probe=now)
|
||||
for key, c in list(self.channels.items()):
|
||||
if (now >= c["expires"] or now - c["last_probe"] >= 2
|
||||
or not self.registry.rover_channel.same_generation(c["value"])):
|
||||
self.channels.pop(key, None)
|
||||
continue
|
||||
if c["peer"] is None or now - c["last_sent"] < MIN_SEND_INTERVAL:
|
||||
continue
|
||||
# Fresh input and withdrawal must not wait for a keepalive
|
||||
# tick. This hint does not authorize a send: the original
|
||||
# certificate/binding/endpoint is checked again below.
|
||||
if now < c["next"] and not self.registry.rover_control.intent_changed(
|
||||
c["value"]["node_id"], c["value"]["relay_id"], c["last_command"]):
|
||||
continue
|
||||
periodic_lag_ms = max(0., (now - c["next"]) * 1000)
|
||||
dispatched = time.monotonic()
|
||||
try:
|
||||
status, reply = self.registry.receive(
|
||||
c["certificate"], "/v1/node/rover-stream",
|
||||
c["value"], address=self.address)
|
||||
if status != 200:
|
||||
self.channels.pop(key, None)
|
||||
continue
|
||||
received = time.monotonic()
|
||||
packet = c["send"].seal({"probe": c["probe"],
|
||||
"probe_clock": c["probe_clock"], "reply": reply})
|
||||
sealed = time.monotonic()
|
||||
self.socket.sendto(packet, c["peer"])
|
||||
sent = time.monotonic()
|
||||
c.update(last_sent=sent, next=sent + KEEPALIVE_INTERVAL,
|
||||
last_command=reply.get("command"))
|
||||
trace = self.registry.rover_control.stream_trace(c["value"]["node_id"])
|
||||
if trace is not None:
|
||||
command = reply.get("command") or {}
|
||||
trace.add("datagram_sent", packet_sequence=c["send"].sent,
|
||||
channel=key.hex(), bytes=len(packet),
|
||||
session_id=command.get("id"),
|
||||
sequence=command.get("sequence"),
|
||||
expires_mono_ms=command.get("expires_mono_ms"),
|
||||
dispatch_ms=(sent - dispatched) * 1000,
|
||||
registry_ms=(received - dispatched) * 1000,
|
||||
encrypt_ms=(sealed - received) * 1000,
|
||||
socket_ms=(sent - sealed) * 1000,
|
||||
periodic_lag_ms=periodic_lag_ms)
|
||||
if not reply.get("watch"):
|
||||
self.channels.pop(key, None)
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
# Drop this generation; receiver's unchanged guard stops.
|
||||
self.channels.pop(key, None)
|
||||
@@ -0,0 +1,189 @@
|
||||
"""DEV evidence transport; independent from every motion lease and output."""
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
|
||||
from missioncore_plugin_sdk.bounded_diagnostics import BoundedDiagnostics
|
||||
from missioncore_plugin_sdk.diagnostic_options import LEGACY_OPTIONS, diagnostic_options
|
||||
|
||||
from .rover_diagnostics_export import DiagnosticExport
|
||||
from .rover_local_trace import LocalRoverTrace
|
||||
from .rover_preview_evidence import preview_sample
|
||||
from .rover_stop_evidence import CoreStopEvidence
|
||||
|
||||
KEYS={'KeyW','KeyA','KeyS','KeyD','KeyQ','KeyE','Space','Escape'}
|
||||
INPUT_EVENTS={'key_down','key_up','pause','stop','pointer_down','pointer_up','pointer_cancel',
|
||||
'settings','demand','heartbeat','request','transport','lifecycle'}
|
||||
INPUT_FIELDS={'code','repeat','reason','held','mode','current_a','speed','control_mode','left','right',
|
||||
'sequence','session_id','foreground','input_valid','pending','action','outcome','elapsed_ms',
|
||||
'browser_ms','ready_state','buffered_bytes','close_code','visibility','dropped',
|
||||
'request_id','socket_id','expires_ms','clock_ms','state_age_ms','gap_ms'}
|
||||
|
||||
class CoreTrace(BoundedDiagnostics):
|
||||
def __init__(self,clock,live):
|
||||
super().__init__('core',clock);self.live=live;self.local=LocalRoverTrace(clock)
|
||||
def recording(self):return self.active() or self.local.active()
|
||||
def capture_identity(self):return (self.id if self.active() else None, self.local.id if self.local.active() else None)
|
||||
def add(self,event,**data):
|
||||
self.local.add(event,**data)
|
||||
self.add_remote(event,**data)
|
||||
def add_remote(self,event,**data):
|
||||
row=super().add(event,**data)
|
||||
if row:self.live.add('record',record=row)
|
||||
|
||||
class RoverDiagnostics:
|
||||
def __init__(self,clock):
|
||||
self.lock=threading.RLock();self.live=BoundedDiagnostics('core',clock)
|
||||
self.trace=CoreTrace(clock,self.live);self.node_ack=0;self.relay_ack=0;self.node_status={}
|
||||
self.clock=clock;self.options=dict(LEGACY_OPTIONS);self.supports_options=False
|
||||
self.control_stop=CoreStopEvidence(clock)
|
||||
self.trace_tokens=4096.0;self.trace_at=clock()
|
||||
self.enabled=False;self.closing=False;self.vehicle='Rover';self.context={};self.export=DiagnosticExport()
|
||||
self.local_owner = None
|
||||
|
||||
def exchange(self, body):
|
||||
self.ingest(body.get('diagnostics'))
|
||||
return {'diagnostics': self.desired(relay_ack=True, export_v2=body.get('diagnostic_export_v2') is True)}
|
||||
|
||||
def set_enabled(self, enabled, options=None, local_options=None):
|
||||
if type(enabled) is not bool:raise ValueError('Invalid DEV mode')
|
||||
selected=diagnostic_options(options)
|
||||
if local_options is not None and (not isinstance(local_options, dict)
|
||||
or set(local_options) - {"enabled", "preview", "previous_id"}
|
||||
or type(local_options.get("enabled")) is not bool
|
||||
or type(local_options.get("preview")) is not bool):
|
||||
raise ValueError("Invalid operator capture options")
|
||||
if enabled and options is not None and not self.supports_options:
|
||||
raise ValueError('Борт ещё не подтвердил поддержку настроек записи.')
|
||||
with self.lock:
|
||||
if enabled and not self.enabled:
|
||||
if self.closing or self.export.busy:raise ValueError('Дождитесь завершения записи или сохранения файла.')
|
||||
if local_options and local_options["enabled"]:
|
||||
local = self.trace.local.start(
|
||||
previous_id=local_options.get("previous_id"), preview=local_options["preview"])
|
||||
self.local_owner = local["id"]
|
||||
identifier=secrets.token_hex(16)
|
||||
self.options=selected;self.trace_tokens=4096.0;self.trace_at=self.clock()
|
||||
self.live.configure(identifier,True);self.trace.configure(identifier,selected['core_trace'])
|
||||
self.node_ack=self.relay_ack=0;self.node_status={};self.enabled=True
|
||||
self.trace.add('capture_started',context=self.context)
|
||||
if self.local_owner == self.trace.local.id and self.local_owner is not None:
|
||||
self.trace.local.add('local_capture_context', context=self.context,
|
||||
board_capture_id=identifier)
|
||||
elif not enabled and self.enabled:
|
||||
self.trace.add('capture_stop_requested');self.trace.configure(self.trace.id,False)
|
||||
self.enabled=False;self.closing=True
|
||||
if self.local_owner is not None and self.trace.local.id == self.local_owner:
|
||||
self.trace.local.stop(self.local_owner)
|
||||
self.local_owner = None
|
||||
return self.view()
|
||||
|
||||
def desired(self, *, relay_ack=False, export_v2=False):
|
||||
with self.lock:
|
||||
if not self.trace.id:return None
|
||||
stored=self.node_status.get('storage') or {}
|
||||
ack=(stored.get('external_ack') or {}).get('core',0)
|
||||
# Acquisition and tail delivery are distinct on capable boards.
|
||||
# Keep legacy draining semantics only until the board advertises it.
|
||||
stop_tail=self.node_status.get('stop_tail_v1') is True
|
||||
recording=self.enabled or (self.closing and not stop_tail and ack<self.trace.sequence and not stored.get('error'))
|
||||
now=self.clock();self.trace_tokens=min(4096.0,self.trace_tokens+max(0,now-self.trace_at)*self.options['core_kbps']*125);self.trace_at=now
|
||||
allowance=int(self.trace_tokens) if self.options['core_trace'] else 0
|
||||
events=[];size=0
|
||||
for row in self.trace.snapshot(ack,64)['frames']:
|
||||
row_size=len(json.dumps(row).encode())+2
|
||||
if row_size>4096:
|
||||
row={'source':'core','event':'core_record_omitted','record_sequence':row['record_sequence'],
|
||||
'reason':'trace_rate_bound','original_bytes':row_size}
|
||||
row_size=len(json.dumps(row).encode())+2
|
||||
if size+row_size>allowance:break
|
||||
events.append(row);size+=row_size
|
||||
self.trace_tokens=max(0,self.trace_tokens-size)
|
||||
result = {'id':self.trace.id,'enabled':recording,'after':self.node_ack,'vehicle':self.vehicle,
|
||||
'core_events':events,'export':self.export.desired(export_v2)}
|
||||
if self.supports_options:result['options']=dict(self.options)
|
||||
if self.closing and stop_tail:result['stop_after']=self.trace.sequence
|
||||
if relay_ack:result['relay_after']=self.relay_ack
|
||||
return result
|
||||
|
||||
def ingest(self,packet):
|
||||
if not isinstance(packet,dict):return
|
||||
with self.lock:
|
||||
identifier=packet.get('id')
|
||||
stored=packet.get('storage') or {}
|
||||
stop_after=packet.get('stop_after')
|
||||
draining=packet.get('stop_tail_v1') is True and type(stop_after) is int and 0<=stop_after<=2**53-1 and stored.get('closed') is False
|
||||
recoverable=draining or packet.get('active') is True or (stored.get('closed') is True and isinstance(stored.get('file'),str))
|
||||
if self.trace.id is None and isinstance(identifier,str) and re.fullmatch(r'[a-f0-9]{32}',identifier) and recoverable:
|
||||
# Recover the last paired-board file after Core restart, including
|
||||
# a completed capture. Recovery never reopens its writer.
|
||||
active=packet.get('active') is True and stored.get('closed') is not True
|
||||
try:self.options=diagnostic_options(packet.get('options'))
|
||||
except ValueError:return
|
||||
self.live.configure(identifier,active);self.trace.configure(identifier,active and self.options['core_trace']);self.enabled=active
|
||||
self.trace.sequence=((packet.get('storage') or {}).get('external_ack') or {}).get('core',0)
|
||||
self.vehicle=packet.get('vehicle','Rover')
|
||||
self.trace.add('core_reconnected')
|
||||
if draining:
|
||||
self.enabled=False;self.closing=True
|
||||
ack=self.trace.sequence
|
||||
if ack<stop_after:
|
||||
# RAM tail cannot survive Core restart. Close honestly with
|
||||
# an explicit gap instead of reopening acquisition or hanging.
|
||||
self.trace.configure(identifier,True);self.trace.sequence=stop_after-1
|
||||
self.trace.add('core_tail_interrupted',after=ack,before=stop_after)
|
||||
self.trace.configure(identifier,False)
|
||||
if identifier!=self.trace.id:return
|
||||
rows=packet.get('frames',[]);relay=packet.get('relay_events',[])
|
||||
if not isinstance(rows,list) or len(rows)>32 or not isinstance(relay,list) or len(relay)>64:return
|
||||
self.node_status={k:packet.get(k) for k in ('id','active','dropped','rejected','sequence','first_sequence','storage','transport_error','stop_tail_v1','options')}
|
||||
for row in relay:
|
||||
if isinstance(row,dict) and type(row.get('record_sequence')) is int and row['record_sequence']>self.relay_ack:
|
||||
self.live.add('record',record=row);self.relay_ack=row['record_sequence']
|
||||
for row in rows:
|
||||
if not isinstance(row,dict) or type(row.get('record_sequence')) is not int:continue
|
||||
if row['record_sequence']<=self.node_ack:continue
|
||||
if row['record_sequence']>self.node_ack+1:self.live.add('live_view_gap',after=self.node_ack,before=row['record_sequence'])
|
||||
self.live.add('record',record=row);self.node_ack=row['record_sequence']
|
||||
stored=packet.get('storage') or {}
|
||||
if stored.get('closed'):
|
||||
if self.local_owner is not None and self.trace.local.id == self.local_owner:
|
||||
self.trace.local.stop(self.local_owner)
|
||||
self.local_owner = None
|
||||
self.closing=False;self.enabled=False
|
||||
self.trace.configure(identifier,False)
|
||||
self.export.ingest(packet.get('export'))
|
||||
|
||||
def browser(self,body,*,local=False):
|
||||
with self.lock:
|
||||
target=self.trace.local if local else self.trace
|
||||
admitted=target.active() if local else self.enabled and self.options['core_trace']
|
||||
if not isinstance(body,dict) or body.get('id')!=target.id or not admitted:return False
|
||||
rows=body.get('events')
|
||||
if not isinstance(rows,list) or len(rows)>32:raise ValueError('Invalid diagnostic events')
|
||||
for row in rows:
|
||||
if not isinstance(row,dict):raise ValueError('Invalid diagnostic event')
|
||||
if row.get('event')=='preview' and local:
|
||||
if not self.trace.local.preview:
|
||||
continue
|
||||
fields={'sample':preview_sample(row.get('sample'))}
|
||||
stamp=row.get('browser_ms')
|
||||
if type(stamp) in (int,float):fields['browser_ms']=stamp
|
||||
else:
|
||||
if row.get('event') not in INPUT_EVENTS:raise ValueError('Invalid diagnostic event')
|
||||
fields={k:v for k,v in row.items() if k in INPUT_FIELDS}
|
||||
if len(json.dumps(fields,allow_nan=False))>2048:raise ValueError('Diagnostic event too large')
|
||||
if 'code' in fields and fields['code'] not in KEYS:fields.pop('code')
|
||||
if 'held' in fields:fields['held']=[k for k in fields['held'] if k in KEYS][:8] if isinstance(fields['held'],list) else []
|
||||
# Local-only ingress must never be fanned out to the Node recorder.
|
||||
(target.add if local else self.trace.add_remote)('browser_'+row['event'],**fields)
|
||||
return True
|
||||
|
||||
def view(self,after=0,limit=200):
|
||||
with self.lock:
|
||||
after=max(after,self.live.sequence-limit,0)
|
||||
return {**self.live.snapshot(after,limit),'active':self.enabled,'closing':self.closing,
|
||||
'local_capture':self.trace.local.snapshot(limit=0),
|
||||
'core_stop_v1':self.control_stop.snapshot(),
|
||||
'node':self.node_status,'options':dict(self.options),'options_supported':self.supports_options,'schema':'missioncore.rover-dev/v1'}
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Bounded prefetch from the paired board; no whole-file cache on Core."""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
import threading
|
||||
|
||||
|
||||
class DiagnosticExport:
|
||||
WAIT_SECONDS = 120 # Includes pacing at the minimum optional bandwidth.
|
||||
|
||||
def __init__(self):
|
||||
self.changed = threading.Condition()
|
||||
self.request = self.chunk = self.capture = None
|
||||
self.busy = False
|
||||
|
||||
def start(self, capture, *, offset=0, total=None, snapshot=None):
|
||||
with self.changed:
|
||||
if self.busy:
|
||||
raise ValueError("Сохранение этого лога уже выполняется.")
|
||||
if not capture:
|
||||
raise ValueError("Сначала включите DEV.")
|
||||
if type(offset) is not int or offset < 0 or (offset and total is None):
|
||||
raise ValueError("Invalid export offset")
|
||||
if total is not None and (type(total) is not int or total < offset or not snapshot):
|
||||
raise ValueError("Invalid export snapshot")
|
||||
self.busy = True
|
||||
self.capture, self.chunk = capture, None
|
||||
token = secrets.token_hex(16)
|
||||
self.request = {"offset": offset, "token": token}
|
||||
if total is not None:
|
||||
self.request.update(total_bytes=total, snapshot=snapshot)
|
||||
return token
|
||||
|
||||
def begin(self, capture, **kwargs):
|
||||
token = self.start(capture, **kwargs)
|
||||
try:
|
||||
return self.take(token)
|
||||
except Exception:
|
||||
self.finish(token)
|
||||
raise
|
||||
|
||||
def desired(self, large=False):
|
||||
with self.changed:
|
||||
if self.request is None:
|
||||
return None
|
||||
result = dict(self.request)
|
||||
if large:
|
||||
result["chunk_bytes"] = 65536
|
||||
return result
|
||||
|
||||
def ingest(self, value):
|
||||
with self.changed:
|
||||
request = self.request
|
||||
if not isinstance(value, dict) or not request or self.chunk is not None:
|
||||
return
|
||||
if (
|
||||
value.get("capture_id") != self.capture
|
||||
or value.get("offset") != request["offset"]
|
||||
or value.get("token") != request["token"]
|
||||
):
|
||||
return
|
||||
if any(type(value.get(k)) is not int for k in ("offset", "next", "total_bytes")):
|
||||
return
|
||||
if not value["offset"] <= value["next"] <= value["total_bytes"]:
|
||||
return
|
||||
encoded = value.get("data")
|
||||
if not isinstance(encoded, str) or len(encoded) > 87384:
|
||||
return
|
||||
try:
|
||||
data = base64.b64decode(encoded, validate=True)
|
||||
except ValueError:
|
||||
return
|
||||
if len(data) > 65536 or len(data) != value["next"] - value["offset"]:
|
||||
return
|
||||
if not data and value["next"] != value["total_bytes"]:
|
||||
return
|
||||
if "total_bytes" in request and value["total_bytes"] != request["total_bytes"]:
|
||||
return
|
||||
if "snapshot" in request and value.get("snapshot") != request["snapshot"]:
|
||||
return
|
||||
# Legacy boards remain readable. Once a snapshot is advertised every
|
||||
# block must carry its board checksum, including resumed transfers.
|
||||
digest = value.get("sha256")
|
||||
if (
|
||||
digest is not None or value.get("snapshot") is not None
|
||||
) and digest != hashlib.sha256(data).hexdigest():
|
||||
return
|
||||
self.chunk = {**value, "data": data}
|
||||
self.changed.notify_all()
|
||||
|
||||
def take(self, token=None):
|
||||
with self.changed:
|
||||
token = token or (self.request or {}).get("token")
|
||||
|
||||
def ready():
|
||||
return (
|
||||
self.chunk is not None
|
||||
or not self.busy
|
||||
or (self.request or {}).get("token") != token
|
||||
)
|
||||
|
||||
if not self.changed.wait_for(ready, self.WAIT_SECONDS):
|
||||
raise TimeoutError("Борт не передал файл. Проверьте связь и повторите сохранение.")
|
||||
if not self.busy or (self.request or {}).get("token") != token:
|
||||
raise TimeoutError("Сохранение завершено или отменено.")
|
||||
chunk, self.chunk = self.chunk, None
|
||||
# Admit at most one further block while the caller writes this one.
|
||||
# Repeated delivery of the old offset is ignored, never queued.
|
||||
if chunk["next"] < chunk["total_bytes"]:
|
||||
self.request = {
|
||||
"offset": chunk["next"],
|
||||
"total_bytes": chunk["total_bytes"],
|
||||
"token": token,
|
||||
}
|
||||
if chunk.get("snapshot"):
|
||||
self.request["snapshot"] = chunk["snapshot"]
|
||||
return chunk
|
||||
|
||||
def stream(self, first):
|
||||
token = first["token"]
|
||||
try:
|
||||
chunk = first
|
||||
while True:
|
||||
yield chunk["data"]
|
||||
if chunk["next"] == chunk["total_bytes"]:
|
||||
return
|
||||
chunk = self.take(token)
|
||||
finally:
|
||||
self.finish(token)
|
||||
|
||||
async def stream_async(self, first, *, framed=False):
|
||||
token = first["token"]
|
||||
try:
|
||||
chunk = first
|
||||
while True:
|
||||
if framed:
|
||||
row = {k: v for k, v in chunk.items() if k != "token"}
|
||||
row["data"] = base64.b64encode(chunk["data"]).decode()
|
||||
yield (json.dumps(row, separators=(",", ":")) + "\n").encode()
|
||||
else:
|
||||
yield chunk["data"]
|
||||
if chunk["next"] == chunk["total_bytes"]:
|
||||
return
|
||||
chunk = await asyncio.to_thread(self.take, token)
|
||||
finally:
|
||||
# Cancels a blocked worker immediately on HTTP client disconnect.
|
||||
self.finish(token)
|
||||
|
||||
def finish(self, token=None):
|
||||
with self.changed:
|
||||
if token is not None and (self.request or {}).get("token") != token:
|
||||
return
|
||||
self.request = self.chunk = None
|
||||
self.busy = False
|
||||
self.changed.notify_all()
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Explicit operator-host evidence; no Node traffic, disk I/O or motor authority."""
|
||||
|
||||
import secrets
|
||||
|
||||
from missioncore_plugin_sdk.bounded_diagnostics import BoundedDiagnostics
|
||||
|
||||
|
||||
class LocalRoverTrace(BoundedDiagnostics):
|
||||
MAX_BYTES = 2 * 1024 * 1024
|
||||
MAX_ROWS = 6000
|
||||
|
||||
def __init__(self, clock):
|
||||
super().__init__("core", clock)
|
||||
self.until = 0.0
|
||||
self.preview = True
|
||||
|
||||
def active(self):
|
||||
return super().active() and self.clock() < self.until
|
||||
|
||||
def snapshot(self, after=0, limit=200):
|
||||
return {
|
||||
**super().snapshot(after, limit),
|
||||
"expires_mono_ms": self.until * 1000,
|
||||
"max_rows": self.MAX_ROWS,
|
||||
"scope": "operator_host_only",
|
||||
"preview": self.preview,
|
||||
}
|
||||
|
||||
def start(self, *, duration=900, previous_id=None, preview=True):
|
||||
if type(preview) is not bool:
|
||||
raise ValueError("Invalid preview capture option")
|
||||
if type(duration) is not int or not 10 <= duration <= 3600:
|
||||
raise ValueError("Invalid local capture duration")
|
||||
if self.active():
|
||||
raise ValueError("Local capture is already active")
|
||||
if self.id is not None and previous_id != self.id:
|
||||
raise ValueError("Export the previous local capture and supply its identity")
|
||||
self.preview = preview
|
||||
self.until = self.clock() + duration
|
||||
self.configure(secrets.token_hex(16), True)
|
||||
self.add("local_capture_started", duration_s=duration)
|
||||
return self.snapshot(limit=0)
|
||||
|
||||
def stop(self, identifier):
|
||||
if self.id is None or identifier != self.id:
|
||||
raise ValueError("Local capture identity changed")
|
||||
self.add("local_capture_stopped")
|
||||
self.configure(identifier, False)
|
||||
return self.snapshot(limit=0)
|
||||
|
||||
def page(self, identifier, after=0, limit=200):
|
||||
if self.id is None or identifier != self.id:
|
||||
raise ValueError("Local capture identity changed")
|
||||
return self.snapshot(after, limit)
|
||||
@@ -0,0 +1,81 @@
|
||||
"""One immutable metadata revision per relay/driver; no live values or authority."""
|
||||
|
||||
import copy
|
||||
|
||||
TOP = {"supported", "control_modes", "profile"}
|
||||
DEVICE = {"uuid", "slot", "label"}
|
||||
|
||||
|
||||
def expand(snapshot, envelope, previous, *, relay, observed, now):
|
||||
if (
|
||||
not isinstance(envelope, dict)
|
||||
or set(envelope) - {"revision", "details"}
|
||||
or type(envelope.get("revision")) is not int
|
||||
or not 0 < envelope["revision"] < 2**53
|
||||
or not isinstance(snapshot.get("instance"), str)
|
||||
or not snapshot["instance"]
|
||||
or any(k in snapshot for k in TOP)
|
||||
):
|
||||
raise ValueError("Invalid rover metadata envelope")
|
||||
identity = (relay, snapshot["instance"])
|
||||
same = previous is not None and previous["identity"] == identity
|
||||
revision = envelope["revision"]
|
||||
if "details" in envelope:
|
||||
details = envelope["details"]
|
||||
if (
|
||||
not isinstance(details, dict)
|
||||
or set(details) - TOP - {"devices"}
|
||||
or not isinstance(details.get("devices"), dict)
|
||||
or len(details["devices"]) > 500
|
||||
):
|
||||
raise ValueError("Invalid rover metadata")
|
||||
for key, value in details["devices"].items():
|
||||
if (
|
||||
not isinstance(key, str)
|
||||
or not key
|
||||
or not isinstance(value, dict)
|
||||
or set(value) - DEVICE
|
||||
):
|
||||
raise ValueError("Invalid rover device metadata")
|
||||
if same and (
|
||||
revision < previous["revision"]
|
||||
or (revision == previous["revision"] and details != previous["details"])
|
||||
):
|
||||
raise ValueError("Rover metadata revision changed")
|
||||
cache = {
|
||||
"identity": identity,
|
||||
"revision": revision,
|
||||
"details": copy.deepcopy(details),
|
||||
"observed": observed,
|
||||
}
|
||||
else:
|
||||
if not same or revision != previous["revision"]:
|
||||
raise ValueError("Rover metadata refresh required")
|
||||
cache = previous
|
||||
# A reference explicitly asserts the same immutable revision. Expiring
|
||||
# these labels/profile by a network-age TTL rejects otherwise fresh samples
|
||||
# and forces another handshake precisely when the transport is recovering.
|
||||
# The caller still publishes the ORIGINAL sample clock, expires live values
|
||||
# after one second, and never renews a control lease from this cache.
|
||||
# Relay/driver/revision changes and roster conflicts remain fail-closed.
|
||||
readings = snapshot.get("devices")
|
||||
details = cache["details"]
|
||||
if not isinstance(readings, list) or len(readings) != len(details["devices"]):
|
||||
raise ValueError("Rover metadata roster changed")
|
||||
seen = set()
|
||||
result = copy.deepcopy(snapshot)
|
||||
for row in result["devices"]:
|
||||
if (
|
||||
not isinstance(row, dict)
|
||||
or not isinstance(row.get("id"), str)
|
||||
or row["id"] in seen
|
||||
or row["id"] not in details["devices"]
|
||||
or not isinstance(row.get("session_id"), str)
|
||||
or not row["session_id"]
|
||||
or any(k in row for k in DEVICE)
|
||||
):
|
||||
raise ValueError("Invalid compact rover sample")
|
||||
seen.add(row["id"])
|
||||
row.update(copy.deepcopy(details["devices"][row["id"]]))
|
||||
result.update({k: copy.deepcopy(v) for k, v in details.items() if k != "devices"})
|
||||
return result, cache
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Bounded lifecycle evidence, independent of DEV, values and motor authority.
|
||||
|
||||
Only the latest receipt summary and 64 transitions live in RAM. Daily reset;
|
||||
no raw samples, inventory, disk writes or network traffic.
|
||||
"""
|
||||
from collections import deque
|
||||
from datetime import UTC, datetime
|
||||
|
||||
|
||||
class ObservationEvidence:
|
||||
def __init__(self, clock, utc_now=lambda: datetime.now(UTC)):
|
||||
self.clock, self.utc_now = clock, utc_now
|
||||
self.day = None
|
||||
self._reset()
|
||||
|
||||
def _reset(self):
|
||||
self.day = self.utc_now().date()
|
||||
self.events = deque(maxlen=64)
|
||||
self.latest = None
|
||||
self.receipts = self.ignored = 0
|
||||
self.max_gap_ms = 0.
|
||||
self.phase = None
|
||||
|
||||
def _daily(self):
|
||||
if self.day != self.utc_now().date():
|
||||
self._reset()
|
||||
|
||||
def event(self, kind):
|
||||
self._daily()
|
||||
self.events.append({"event": kind, "at_utc": self.utc_now().isoformat(),
|
||||
"monotonic_ms": self.clock()*1000})
|
||||
|
||||
def receive(self, sampled, published, devices):
|
||||
self._daily()
|
||||
now = self.clock()
|
||||
gap = 0. if self.latest is None else max(0., now-self.latest["received_mono_ms"]/1000)*1000
|
||||
self.max_gap_ms = max(self.max_gap_ms, gap)
|
||||
self.receipts += 1
|
||||
self.ignored += int(not published)
|
||||
self.latest = {"received_mono_ms": now*1000, "received_utc": self.utc_now().isoformat(),
|
||||
"sample_age_at_receipt_ms": max(0., now-sampled)*1000,
|
||||
"published": published, "sampled_devices": min(128, devices)}
|
||||
if self.receipts == 1 or gap >= 1000:
|
||||
self.event("first_receipt" if self.receipts == 1 else "receipt_after_gap")
|
||||
|
||||
def view(self, fresh):
|
||||
self._daily()
|
||||
phase = "fresh" if fresh else "stale" if self.receipts else "awaiting_first_receipt"
|
||||
if phase != self.phase:
|
||||
self.phase = phase
|
||||
self.event(phase)
|
||||
|
||||
def snapshot(self):
|
||||
self._daily()
|
||||
return {"schema": "missioncore.observation-evidence/v1", "scope": "core_memory_daily",
|
||||
"receipts": self.receipts, "ignored_older_receipts": self.ignored,
|
||||
"max_receipt_gap_ms": self.max_gap_ms, "phase": self.phase,
|
||||
"latest": dict(self.latest) if self.latest else None,
|
||||
"events": list(self.events)}
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Local-only numeric video evidence; never a signaling or control payload."""
|
||||
|
||||
import math
|
||||
import re
|
||||
|
||||
NUMBERS = frozenset(
|
||||
[
|
||||
'width',
|
||||
'height',
|
||||
'source_age_ms',
|
||||
'sender_mono_ms',
|
||||
'allocation_bps',
|
||||
'target_bps',
|
||||
'encoder_bps',
|
||||
'receiver_bps',
|
||||
'max_width',
|
||||
'max_fps',
|
||||
'encoder_frames',
|
||||
'encoder_reinitializations',
|
||||
'encode_ms',
|
||||
'sent_bytes',
|
||||
'queue_dropped',
|
||||
'expired_frames',
|
||||
'expired_datagrams',
|
||||
'stale_rtp_packets',
|
||||
'max_permit_wait_ms',
|
||||
'decoder_errors',
|
||||
'decoder_frames',
|
||||
'decoder_gaps',
|
||||
'receiver_sampled_at_ms',
|
||||
'interval_ms',
|
||||
'fps',
|
||||
'mbps',
|
||||
'round_trip_ms',
|
||||
'jitter_buffer_ms',
|
||||
'requested_jitter_ms',
|
||||
'jitter_target_ms',
|
||||
'jitter_minimum_ms',
|
||||
'decode_ms',
|
||||
'processing_ms',
|
||||
'assembly_ms',
|
||||
'frames_dropped',
|
||||
'packets_lost',
|
||||
'freezes',
|
||||
'reset_frame',
|
||||
'reset_mono_ms',
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def preview_sample(value):
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("Invalid preview evidence")
|
||||
result = {}
|
||||
for key in ("peer_id", "device_session"):
|
||||
item = value.get(key)
|
||||
if not isinstance(item, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", item):
|
||||
raise ValueError("Invalid preview identity")
|
||||
result[key] = item
|
||||
for key in NUMBERS & value.keys():
|
||||
item = value[key]
|
||||
if type(item) not in (int, float) or not 0 <= item <= 2**53 - 1 or not math.isfinite(item):
|
||||
raise ValueError("Invalid preview metric")
|
||||
result[key] = item
|
||||
if value.get("mode") in ("observing", "control_reserved"):
|
||||
result["mode"] = value["mode"]
|
||||
return result
|
||||
@@ -0,0 +1,48 @@
|
||||
"""One latest Core withdrawal in RAM; independent of DEV and motion authority."""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from threading import Lock
|
||||
|
||||
|
||||
class CoreStopEvidence:
|
||||
def __init__(self, clock, utc_now=lambda: datetime.now(UTC)):
|
||||
self.clock, self.utc_now = clock, utc_now
|
||||
self._latest = None
|
||||
self._lock = Lock()
|
||||
|
||||
def record(self, reason, session, *, core_instance, telemetry_age_ms, driver_state):
|
||||
now, wall = self.clock(), self.utc_now()
|
||||
# Board state is untrusted; never retain an arbitrary object or string.
|
||||
state = driver_state if driver_state in (
|
||||
"observing", "preparing", "ready", "driving", "stopping",
|
||||
"stopped", "fault", "receiver",
|
||||
) else None
|
||||
value = (wall.date(), now, {
|
||||
"schema": "missioncore.core-control-stop/v1",
|
||||
"reason": reason,
|
||||
"at_utc": wall.isoformat(),
|
||||
"monotonic_ms": now * 1000,
|
||||
"core_clock_instance": core_instance,
|
||||
"session_id": session["id"],
|
||||
"sequence": session["sequence"],
|
||||
"operator_sequence": session["operator_sequence"],
|
||||
"neutral_hold": session["neutral_hold"],
|
||||
"remaining_ms": (session["until"] - now) * 1000,
|
||||
"telemetry_age_ms": max(0, telemetry_age_ms),
|
||||
"driver_state": state,
|
||||
})
|
||||
|
||||
# No optional-recorder/export lock, file I/O or transport in this path.
|
||||
with self._lock:
|
||||
self._latest = value
|
||||
|
||||
def snapshot(self):
|
||||
now, day = self.clock(), self.utc_now().date()
|
||||
with self._lock:
|
||||
if self._latest is None:
|
||||
return None
|
||||
recorded_day, at, value = self._latest
|
||||
if recorded_day != day or now - at >= 86400:
|
||||
self._latest = None
|
||||
return None
|
||||
return dict(value)
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Opt-in per-frame evidence for the existing command stream."""
|
||||
import secrets
|
||||
import time
|
||||
|
||||
|
||||
class RoverStreamTiming:
|
||||
def __init__(self, trace, clock=time.monotonic):
|
||||
self.trace, self.clock = trace, clock
|
||||
self.stream_id = secrets.token_hex(8)
|
||||
self.capture_id = None
|
||||
self.previous = None
|
||||
self.index = 0
|
||||
|
||||
def write(self, writer, raw, data, *, dispatch_ms, wait_ms):
|
||||
# No additional socket write, authority, queue, or retry. Without either capture,
|
||||
# no frame evidence is serialized/stored and no previous sample is retained.
|
||||
trace = self.trace
|
||||
if trace is None or not getattr(trace, "recording", trace.active)():
|
||||
self.capture_id = self.previous = None
|
||||
writer.write(raw)
|
||||
return
|
||||
started = self.clock()
|
||||
outcome = "ok"
|
||||
try:
|
||||
writer.write(raw)
|
||||
except OSError:
|
||||
outcome = "write_error"
|
||||
raise
|
||||
finally:
|
||||
finished = self.clock()
|
||||
try:
|
||||
identity = getattr(trace, "capture_identity", lambda: trace.id)()
|
||||
if self.capture_id != identity:
|
||||
self.capture_id, self.previous, self.index = identity, None, 0
|
||||
self.index += 1
|
||||
command = data.get("command") or {}
|
||||
trace.add("command_stream_frame", stream_id=self.stream_id,
|
||||
frame_index=self.index, session_id=command.get("id"),
|
||||
sequence=command.get("sequence"),
|
||||
frame_clock_ms=(data.get("control_clock") or {}).get("monotonic_ms"),
|
||||
write_started_ms=started * 1000,
|
||||
write_finished_ms=finished * 1000,
|
||||
gap_ms=None if self.previous is None else (started-self.previous)*1000,
|
||||
dispatch_ms=dispatch_ms, wait_ms=wait_ms,
|
||||
write_ms=(finished-started)*1000, bytes=len(raw), outcome=outcome)
|
||||
self.previous = started
|
||||
except Exception:
|
||||
# Evidence must not alter stream cleanup, including when the
|
||||
# original socket write raised. Never log private socket errors.
|
||||
pass
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Bounded RAM receipts for Sample Data and QML; durable records are tombstones.
|
||||
|
||||
After a Core restart an ephemeral request is never re-enqueued. A missing frame
|
||||
or capture must be requested explicitly again with a new operation identity.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from datetime import UTC, datetime
|
||||
from functools import wraps
|
||||
|
||||
|
||||
def ephemeral(action):
|
||||
return action.startswith(("vesc.samples.", "vesc.qml.", "can."))
|
||||
|
||||
|
||||
def synchronized(method):
|
||||
@wraps(method)
|
||||
def run(self, *args, **kwargs):
|
||||
with self.lock:
|
||||
return method(self, *args, **kwargs)
|
||||
|
||||
return run
|
||||
|
||||
|
||||
class SensorTransient:
|
||||
def __init__(self, clock=time.monotonic, day=lambda: datetime.now(UTC).date()):
|
||||
self.clock, self.day = clock, day
|
||||
self.date = day()
|
||||
self.entries = OrderedDict()
|
||||
self.lock = threading.RLock()
|
||||
|
||||
@synchronized
|
||||
def prune(self):
|
||||
if self.day() != self.date:
|
||||
self.entries.clear()
|
||||
self.date = self.day()
|
||||
now = self.clock()
|
||||
for key, (at, _, _) in list(self.entries.items()):
|
||||
if now - at >= 300:
|
||||
del self.entries[key]
|
||||
|
||||
@synchronized
|
||||
def persist(self, row):
|
||||
self.prune()
|
||||
result = dict(row)
|
||||
operations = dict(row.get("sensor_commands", {}))
|
||||
for key, value in operations.items():
|
||||
command = value.get("command", {})
|
||||
if not ephemeral(command.get("action_id", "")) or value.get("ephemeral_expired"):
|
||||
continue
|
||||
cache_key = (row["id"], key)
|
||||
raw = json.dumps(value, allow_nan=False).encode()
|
||||
fingerprint = hashlib.sha256(
|
||||
json.dumps(command, sort_keys=True, separators=(",", ":")).encode()
|
||||
).hexdigest()
|
||||
at = self.entries.get(cache_key, (self.clock(), None, None))[0]
|
||||
self.entries[cache_key] = (at, fingerprint, raw)
|
||||
operations[key] = {
|
||||
"command": {**command, "parameters": {}},
|
||||
"state": "unknown",
|
||||
"error": "Временный результат истёк. Повторите просмотр.",
|
||||
"updated_at": value["updated_at"],
|
||||
"ephemeral_expired": True,
|
||||
"command_sha256": fingerprint,
|
||||
}
|
||||
while len(self.entries) > 64 or sum(len(v[2]) for v in self.entries.values()) > 8 * 1024**2:
|
||||
self.entries.popitem(last=False)
|
||||
if "sensor_commands" in row:
|
||||
result["sensor_commands"] = operations
|
||||
return result
|
||||
|
||||
@synchronized
|
||||
def hydrate(self, row):
|
||||
self.prune()
|
||||
for key, value in list(row.get("sensor_commands", {}).items()):
|
||||
if not value.get("ephemeral_expired"):
|
||||
continue
|
||||
cached = self.entries.get((row["id"], key))
|
||||
if cached and cached[1] == value["command_sha256"]:
|
||||
row["sensor_commands"][key] = json.loads(cached[2])
|
||||
return row
|
||||
|
||||
|
||||
def cache(fleet):
|
||||
if not hasattr(fleet, "_sensor_transient"):
|
||||
fleet._sensor_transient = SensorTransient()
|
||||
return fleet._sensor_transient
|
||||
@@ -10,6 +10,7 @@ from missioncore_plugin_sdk.v0alpha2.session import DeviceSessionSnapshot
|
||||
from .trust import PairingError
|
||||
|
||||
ACTIONS = {
|
||||
"can.status", "can.configure", "can.start", "can.stop", "can.clear", "can.transmit.preview", "can.transmit.apply", "can.transmit.stop",
|
||||
"prepare",
|
||||
"details",
|
||||
"rename",
|
||||
@@ -30,8 +31,8 @@ ACTIONS = {
|
||||
"files.list",
|
||||
"recovery.configure",
|
||||
"power.wake",
|
||||
"vesc.link.check", "vesc.telemetry.read", "vesc.limits.read",
|
||||
"vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.drive.assign", "vesc.drive.layout", "vesc.drive.unassign", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release",
|
||||
"vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.configuration.read", "vesc.configuration.preview", "vesc.configuration.apply", "vesc.bms.configuration.read", "vesc.bms.configuration.preview", "vesc.bms.configuration.apply", "vesc.bms.configuration.reconcile", "vesc.bms.configuration.restore", "vesc.packages.catalog", "vesc.packages.inspect", "vesc.packages.download", "vesc.packages.begin", "vesc.packages.chunk", "vesc.packages.load", "vesc.packages.forget", "vesc.packages.status", "vesc.packages.prepare", "vesc.packages.remove_prepare", "vesc.packages.restore", "vesc.packages.apply", "vesc.packages.reconcile", "vesc.packages.refresh", "vesc.samples.start", "vesc.samples.status", "vesc.samples.fetch", "vesc.samples.stop", "vesc.samples.read", "vesc.qml.begin", "vesc.qml.chunk", "vesc.qml.render", "vesc.qml.open", "vesc.qml.frame", "vesc.qml.close", "vesc.code.read", "vesc.code.begin", "vesc.code.chunk", "vesc.code.prepare", "vesc.code.erase_prepare", "vesc.code.apply", "vesc.code.reconcile", "vesc.code.control_prepare", "vesc.code.control_apply", "vesc.code.stats", "vesc.code.restore", "vesc.bms.read", "vesc.bms.prepare", "vesc.bms.apply", "vesc.tools.read", "vesc.terminal.read", "vesc.configuration.reconcile", "vesc.firmware.backup", "vesc.firmware.target", "vesc.firmware.catalog", "vesc.firmware.catalog_prepare", "vesc.firmware.begin", "vesc.firmware.chunk", "vesc.firmware.seal", "vesc.firmware.discard", "vesc.firmware.apply", "vesc.firmware.status", "vesc.firmware.cancel", "vesc.firmware.reconcile", "vesc.diagnostics.read",
|
||||
"vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.transport.configure", "vesc.drive.assign", "vesc.drive.layout", "vesc.drive.unassign", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release",
|
||||
}
|
||||
MAX_INVENTORY_ITEMS = 500
|
||||
MAX_SENSOR_STATE_BYTES = 3 * 1024 * 1024
|
||||
@@ -73,6 +74,8 @@ def submit(fleet, vehicle_id, value):
|
||||
raise PairingError("Неподдерживаемая команда устройства.")
|
||||
with fleet.lock:
|
||||
row = fleet.find(vehicle_id)
|
||||
from .network_media import offer
|
||||
value = offer(row, value)
|
||||
if fleet.public(row)["connectivity"] != "online":
|
||||
raise PairingError("БК недоступен. Дождитесь связи перед настройкой устройства.")
|
||||
existing = row.setdefault("sensor_commands", {}).get(command.operation_id)
|
||||
@@ -140,7 +143,8 @@ def operation(fleet, vehicle_id, identifier):
|
||||
"state": "unknown",
|
||||
"error": "Подтверждение не получено. Обновите фактическое состояние устройства.",
|
||||
}
|
||||
return value
|
||||
from .network_media import answer
|
||||
return answer(fleet.find(vehicle_id), value)
|
||||
|
||||
|
||||
def heartbeat(row, value):
|
||||
|
||||
@@ -6,6 +6,9 @@ import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
from .heartbeat_encoding import decode_heartbeat
|
||||
from .rover_datagram import QUALIFIED, RoverDatagramServer
|
||||
from .rover_stream_timing import RoverStreamTiming
|
||||
from .trust import private_address
|
||||
|
||||
|
||||
@@ -18,7 +21,18 @@ class NodeChannelServer(ThreadingHTTPServer):
|
||||
self.address = address
|
||||
self.refresh_context()
|
||||
self.capacity = threading.BoundedSemaphore(16)
|
||||
self.datagrams = None
|
||||
super().__init__((address, 8782), NodeChannelHandler)
|
||||
try:
|
||||
self.datagrams = RoverDatagramServer(address, registry) if QUALIFIED else None
|
||||
except OSError:
|
||||
super().server_close()
|
||||
raise
|
||||
|
||||
def server_close(self):
|
||||
if self.datagrams is not None:
|
||||
self.datagrams.close()
|
||||
super().server_close()
|
||||
|
||||
def refresh_context(self):
|
||||
self.context = self.registry.trust.server_context(self.address)
|
||||
@@ -62,18 +76,34 @@ class NodeChannelHandler(BaseHTTPRequestHandler):
|
||||
or self.headers.get("Origin")
|
||||
# A bounded 500-camera summary is carried both in devices and
|
||||
# sensor_state for the existing paired heartbeat contract.
|
||||
or not 0 < size <= 8 * 1024 * 1024
|
||||
or not 0 < size <= (
|
||||
2048 if self.path in ("/v1/node/liveness", "/v1/node/rover-datagram") else
|
||||
112 * 1024 if self.path == "/v1/node/rover-diagnostics" else 8 * 1024 * 1024
|
||||
)
|
||||
):
|
||||
raise ValueError
|
||||
value = json.loads(self.rfile.read(size))
|
||||
body = self.rfile.read(size)
|
||||
if len(body) != size:
|
||||
raise ValueError
|
||||
value = json.loads(decode_heartbeat(body, self.headers.get("Content-Encoding", ""), self.path))
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError
|
||||
dispatched = time.monotonic()
|
||||
path = "/v1/node/rover-link" if self.path == "/v1/node/rover-datagram" else self.path
|
||||
status, data = self.server.registry.receive(
|
||||
self.connection.getpeercert(binary_form=True),
|
||||
self.path,
|
||||
path,
|
||||
value,
|
||||
address=self.server.address,
|
||||
)
|
||||
if status == 200 and self.path == "/v1/node/rover-link":
|
||||
data["latest_datagram_v1"] = getattr(self.server, "datagrams", None) is not None
|
||||
if status == 200 and self.path == "/v1/node/rover-datagram":
|
||||
status, data = (self.server.datagrams.open(
|
||||
self.connection.getpeercert(binary_form=True), value)
|
||||
if getattr(self.server, "datagrams", None) is not None
|
||||
else (404, {"error": "Datagram transport unavailable"}))
|
||||
dispatch_ms = (time.monotonic() - dispatched) * 1000
|
||||
except (ValueError, KeyError, TypeError):
|
||||
self.close_connection = True
|
||||
status, data = 400, {"error": "Invalid request"}
|
||||
@@ -84,19 +114,26 @@ class NodeChannelHandler(BaseHTTPRequestHandler):
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
timing = RoverStreamTiming(self.server.registry.rover_control.stream_trace(value["node_id"]))
|
||||
wait_ms = 0.
|
||||
try:
|
||||
while not self.server.registry.stop.is_set():
|
||||
self.wfile.write(json.dumps(data, allow_nan=False).encode()+b"\n")
|
||||
timing.write(self.wfile, json.dumps(data, allow_nan=False).encode()+b"\n",
|
||||
data, dispatch_ms=dispatch_ms, wait_ms=wait_ms)
|
||||
if not data.get("watch"):
|
||||
break
|
||||
# Every frame rechecks the same certificate and binding.
|
||||
# No queued intent and no lease renewal from a keepalive.
|
||||
waited = time.monotonic()
|
||||
self.server.registry.rover_control.wait_for_intent(
|
||||
value["node_id"], value["relay_id"], data.get("command"))
|
||||
wait_ms = (time.monotonic() - waited) * 1000
|
||||
dispatched = time.monotonic()
|
||||
status, data = self.server.registry.receive(
|
||||
self.connection.getpeercert(binary_form=True), self.path,
|
||||
value, address=self.server.address,
|
||||
)
|
||||
dispatch_ms = (time.monotonic() - dispatched) * 1000
|
||||
if status != 200:
|
||||
break
|
||||
except (OSError, ValueError):
|
||||
|
||||
@@ -151,6 +151,7 @@ from k1link.web.e47_semantic_slam_api import build_e47_semantic_slam_router
|
||||
from k1link.web.environment_api import build_environment_router
|
||||
from k1link.web.frontend_assets import ControlStationStaticFiles, frontend_build_id
|
||||
from k1link.web.response_compression import ResponseCompressionMiddleware
|
||||
from k1link.web.runtime_http_timing import RuntimeHttpTimingMiddleware
|
||||
from k1link.web.l3_pointpillars_visual_api import (
|
||||
build_l3_pointpillars_visual_router,
|
||||
)
|
||||
@@ -1008,6 +1009,8 @@ app = FastAPI(
|
||||
)
|
||||
app.add_middleware(ResponseCompressionMiddleware, minimum_size=1_024, compresslevel=5)
|
||||
|
||||
app.add_middleware(RuntimeHttpTimingMiddleware)
|
||||
|
||||
|
||||
app.include_router(fleet_router)
|
||||
app.include_router(equipment_router)
|
||||
|
||||
@@ -62,6 +62,11 @@ class RenameRequest(BaseModel):
|
||||
|
||||
router = APIRouter(prefix="/api/v1/fleet", tags=["fleet"])
|
||||
|
||||
from .fleet_router_api import register as register_router_equipment
|
||||
register_router_equipment(router, local_operator)
|
||||
from .fleet_network_api import register as register_network_profiles
|
||||
register_network_profiles(router, local_operator)
|
||||
|
||||
|
||||
class BoardLayoutChange(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
@@ -154,16 +159,19 @@ def observation_configuration_write(vehicle_id: str, body: ObservationConfigurat
|
||||
@router.get("/{vehicle_id}/monitor")
|
||||
def board_monitor(vehicle_id: str, response: Response,
|
||||
fleet: Annotated[FleetRegistry, Depends(local_operator)],
|
||||
metric: str = "cpu.usage", window: int = 900, end: float | None = None):
|
||||
metric: str | None = None, window: int | None = None,
|
||||
end: float | None = None):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
try:
|
||||
if metric is not None or window is not None or end is not None:
|
||||
raise ValueError("Historical operator queries are unavailable")
|
||||
with fleet.lock:
|
||||
node_id = fleet.find(vehicle_id)["node_id"]
|
||||
return fleet.monitor.query(node_id, metric, window, end)
|
||||
return fleet.monitor.query(node_id)
|
||||
except PairingError as error:
|
||||
raise HTTPException(404, str(error)) from None
|
||||
except ValueError:
|
||||
raise HTTPException(400, "Выберите доступный период и показатель.") from None
|
||||
raise HTTPException(400, "Доступны только текущие показатели БК.") from None
|
||||
|
||||
|
||||
@router.get("")
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Operator-only network profile actions, separate from compute contours."""
|
||||
from typing import Annotated, Literal
|
||||
from fastapi import Depends, HTTPException, Response
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from k1link.fleet.registry import FleetRegistry
|
||||
|
||||
class ImportProfile(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
document: str = Field(min_length=1, max_length=16384)
|
||||
name: str = Field(default="", max_length=80)
|
||||
network_interface: str | None = Field(default=None, max_length=20)
|
||||
|
||||
class SelectProfile(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
provider: Literal["tailscale", "wireguard"]
|
||||
profile_id: str | None = Field(default=None, max_length=80)
|
||||
expected_revision: int = Field(ge=0, lt=2**53, strict=True)
|
||||
|
||||
|
||||
def register(router, local_operator):
|
||||
@router.get("/network-profiles")
|
||||
def listing(fleet: Annotated[FleetRegistry, Depends(local_operator)]):
|
||||
return {"items": fleet.network_profiles.listing()}
|
||||
|
||||
@router.post("/network-profiles/import")
|
||||
def import_profile(body: ImportProfile, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
|
||||
try:
|
||||
return fleet.network_profiles.import_file(body.document, body.name, body.network_interface)
|
||||
except (ValueError, OSError) as error:
|
||||
raise HTTPException(409, str(error) if isinstance(error, ValueError) else "Не удалось подготовить подключение.") from None
|
||||
|
||||
@router.get("/{vehicle_id}/network-profile")
|
||||
def view(vehicle_id: str, response: Response, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
with fleet.lock:
|
||||
try:
|
||||
node_id = fleet.find(vehicle_id)["node_id"]
|
||||
except ValueError as error:
|
||||
raise HTTPException(404, str(error)) from None
|
||||
return fleet.network_profiles.view(node_id)
|
||||
|
||||
@router.put("/{vehicle_id}/network-profile")
|
||||
def apply(vehicle_id: str, body: SelectProfile, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
|
||||
try:
|
||||
return fleet.network_profiles.start(vehicle_id, body.provider, body.profile_id, body.expected_revision)
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
@@ -6,20 +6,17 @@ from k1link.fleet.trust import PairingError
|
||||
from .fleet_api import local_operator
|
||||
|
||||
router = APIRouter(prefix="/api/v1/fleet", tags=["fleet"])
|
||||
|
||||
def node(fleet, vehicle):
|
||||
with fleet.lock:
|
||||
row = fleet.find(vehicle)
|
||||
if row["enrollment"] != "paired":
|
||||
raise ValueError("Борт не привязан.")
|
||||
return row["node_id"]
|
||||
from .rover_socket import register
|
||||
register(router)
|
||||
from .rover_diagnostics_api import register as register_diagnostics
|
||||
register_diagnostics(router)
|
||||
|
||||
@router.get("/{vehicle_id}/rover")
|
||||
def rover_state(vehicle_id: str, response: Response,
|
||||
fleet: Annotated[FleetRegistry, Depends(local_operator)]):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
try:
|
||||
return fleet.rover_control.view(node(fleet, vehicle_id))
|
||||
return fleet.rover_channel.operator(vehicle_id, "view")
|
||||
except (ValueError, PairingError) as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@@ -27,9 +24,7 @@ def rover_state(vehicle_id: str, response: Response,
|
||||
def rover_arm(vehicle_id: str, body: dict,
|
||||
fleet: Annotated[FleetRegistry, Depends(local_operator)]):
|
||||
try:
|
||||
# Admission and node resolution must not race a computer replacement.
|
||||
with fleet.lock:
|
||||
return fleet.rover_control.arm(node(fleet, vehicle_id), body)
|
||||
return fleet.rover_channel.operator(vehicle_id, "arm", body)
|
||||
except (ValueError, PairingError) as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@@ -37,7 +32,6 @@ def rover_arm(vehicle_id: str, body: dict,
|
||||
def rover_command(vehicle_id: str, body: dict,
|
||||
fleet: Annotated[FleetRegistry, Depends(local_operator)]):
|
||||
try:
|
||||
with fleet.lock:
|
||||
return fleet.rover_control.command(node(fleet, vehicle_id), body)
|
||||
return fleet.rover_channel.operator(vehicle_id, "command", body)
|
||||
except (ValueError, PairingError) as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""Local operator DEV controls and full onboard-file streaming."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import Depends, HTTPException, Query
|
||||
from fastapi.responses import Response, StreamingResponse
|
||||
|
||||
from ..fleet.trust import PairingError
|
||||
from .fleet_api import local_operator
|
||||
|
||||
|
||||
def register(router):
|
||||
def recorder(fleet, vehicle):
|
||||
try:
|
||||
return fleet.rover_channel.operator(vehicle, "diagnostics")
|
||||
except (ValueError, PairingError) as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@router.get("/{vehicle_id}/rover/diagnostics")
|
||||
def view(vehicle_id: str, after: int = Query(0, ge=0), fleet=Depends(local_operator)):
|
||||
return recorder(fleet, vehicle_id).view(after)
|
||||
|
||||
@router.get("/{vehicle_id}/rover/diagnostics/runtime")
|
||||
def runtime(vehicle_id: str, fleet=Depends(local_operator)):
|
||||
from .rover_runtime_diagnostics import snapshot
|
||||
|
||||
recorder(fleet, vehicle_id)
|
||||
result = snapshot()
|
||||
result["observation"] = fleet.rover_channel.operator(vehicle_id, "observation_evidence")
|
||||
return Response(json.dumps(result), media_type="application/json",
|
||||
headers={"Cache-Control": "no-store"})
|
||||
|
||||
@router.post("/{vehicle_id}/rover/diagnostics")
|
||||
def configure(vehicle_id: str, body: dict, fleet=Depends(local_operator)):
|
||||
if set(body)-{"enabled", "options", "local_options"} or type(body.get("enabled")) is not bool:
|
||||
raise HTTPException(400, "Invalid DEV mode")
|
||||
try:
|
||||
return recorder(fleet, vehicle_id).set_enabled(
|
||||
body["enabled"], body.get("options"), body.get("local_options"))
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@router.post("/{vehicle_id}/rover/diagnostics/events")
|
||||
def events(vehicle_id: str, body: dict, fleet=Depends(local_operator)):
|
||||
try:
|
||||
recorder(fleet, vehicle_id).browser(body)
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(400, "Invalid diagnostic events") from None
|
||||
return {"accepted": True}
|
||||
|
||||
@router.post("/{vehicle_id}/rover/diagnostics/local")
|
||||
def local_configure(vehicle_id: str, body: dict, fleet=Depends(local_operator)):
|
||||
if set(body)-{"enabled", "duration_s", "capture_id"} or type(body.get("enabled")) is not bool:
|
||||
raise HTTPException(400, "Invalid local diagnostic mode")
|
||||
capture = recorder(fleet, vehicle_id)
|
||||
try:
|
||||
with capture.lock:
|
||||
if body["enabled"]:
|
||||
capture.trace.local.start(duration=body.get("duration_s", 900), previous_id=body.get("capture_id"))
|
||||
capture.trace.local.add("local_capture_context", context=capture.context, board_capture_id=capture.trace.id)
|
||||
return capture.trace.local.snapshot(limit=0)
|
||||
return capture.trace.local.stop(body.get("capture_id"))
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@router.get("/{vehicle_id}/rover/diagnostics/local")
|
||||
def local_view(vehicle_id: str, capture_id: str = Query(..., pattern=r"^[a-f0-9]{32}$"),
|
||||
after: int = Query(0, ge=0), limit: int = Query(200, ge=0, le=500), fleet=Depends(local_operator)):
|
||||
capture = recorder(fleet, vehicle_id)
|
||||
try:
|
||||
with capture.lock:
|
||||
return capture.trace.local.page(capture_id, after, limit)
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@router.get("/{vehicle_id}/rover/diagnostics/local/export")
|
||||
def local_export(vehicle_id: str,
|
||||
capture_id: str = Query(..., pattern=r"^[a-f0-9]{32}$"),
|
||||
fleet=Depends(local_operator)):
|
||||
capture = recorder(fleet, vehicle_id)
|
||||
try:
|
||||
with capture.lock:
|
||||
page = capture.trace.local.page(capture_id, limit=capture.trace.local.MAX_ROWS)
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
rows = page.pop("frames")
|
||||
metadata = {"schema": "missioncore.operator-capture/v1", **page}
|
||||
text = "\n".join(json.dumps(row, ensure_ascii=False, allow_nan=False)
|
||||
for row in [metadata, *rows]) + "\n"
|
||||
return Response(text, media_type="application/x-ndjson", headers={
|
||||
"Cache-Control": "no-store",
|
||||
"Content-Disposition": f'attachment; filename="rover-operator-{capture_id}.jsonl"',
|
||||
})
|
||||
|
||||
@router.post("/{vehicle_id}/rover/diagnostics/local/events")
|
||||
def local_events(vehicle_id: str, body: dict, fleet=Depends(local_operator)):
|
||||
try:
|
||||
accepted = recorder(fleet, vehicle_id).browser(body, local=True)
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(400, "Invalid local diagnostic events") from None
|
||||
return {"accepted": bool(accepted)}
|
||||
|
||||
@router.get("/{vehicle_id}/rover/diagnostics/export")
|
||||
async def export(
|
||||
vehicle_id: str,
|
||||
format: Literal["raw", "chunks"] = "raw",
|
||||
capture_id: str | None = Query(None, pattern=r"^[a-f0-9]{32}$"),
|
||||
offset: int = Query(0, ge=0),
|
||||
total_bytes: int | None = Query(None, ge=0),
|
||||
snapshot: str | None = Query(None, pattern=r"^[a-f0-9]{64}$"),
|
||||
fleet=Depends(local_operator),
|
||||
):
|
||||
capture = recorder(fleet, vehicle_id)
|
||||
if capture_id is not None and capture_id != capture.trace.id:
|
||||
raise HTTPException(409, "Запись изменилась. Повторите сохранение нужной сессии.")
|
||||
if offset and capture_id is None:
|
||||
raise HTTPException(400, "Missing capture identity")
|
||||
try:
|
||||
token = capture.export.start(
|
||||
capture.trace.id, offset=offset, total=total_bytes, snapshot=snapshot
|
||||
)
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
try:
|
||||
first = await asyncio.to_thread(capture.export.take, token)
|
||||
if format == "chunks" and (not first.get("sha256") or not first.get("snapshot")):
|
||||
raise HTTPException(409, "Для продолжения выгрузки обновите бортовой модуль VESC.")
|
||||
except BaseException as error:
|
||||
capture.export.finish(token)
|
||||
if isinstance(error, TimeoutError):
|
||||
raise HTTPException(503, str(error)) from None
|
||||
raise
|
||||
filename = first.get("file", "")
|
||||
if not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", filename):
|
||||
filename = f"rover-{capture.trace.id}.jsonl"
|
||||
headers = {
|
||||
"Cache-Control": "no-store",
|
||||
"Content-Disposition": f'attachment; filename="{filename}"',
|
||||
}
|
||||
if format == "raw":
|
||||
headers["Content-Length"] = str(first["total_bytes"] - offset)
|
||||
return StreamingResponse(
|
||||
capture.export.stream_async(first, framed=format == "chunks"),
|
||||
media_type="application/x-ndjson",
|
||||
headers=headers,
|
||||
)
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Bounded read-only thread locations for local operator runtime diagnosis.
|
||||
|
||||
No frame locals, source lines, request bodies, keys or persistent profiler are
|
||||
exposed. A native sampler can correlate native_id with these Python locations.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import PurePath
|
||||
|
||||
from .runtime_http_timing import http_timings
|
||||
|
||||
|
||||
def snapshot() -> dict:
|
||||
started = time.monotonic()
|
||||
threads = {thread.ident: thread for thread in threading.enumerate()}
|
||||
frames = sys._current_frames()
|
||||
rows = []
|
||||
try:
|
||||
for ident, frame in sorted(frames.items())[:128]:
|
||||
thread = threads.get(ident)
|
||||
stack = []
|
||||
while frame is not None and len(stack) < 24:
|
||||
code = frame.f_code
|
||||
stack.append({"file": PurePath(code.co_filename).name[:128],
|
||||
"function": code.co_name[:128], "line": frame.f_lineno})
|
||||
frame = frame.f_back
|
||||
rows.append({"native_id": thread.native_id if thread else None,
|
||||
"name": thread.name[:128] if thread else "unregistered",
|
||||
"stack": stack, "truncated": frame is not None})
|
||||
finally:
|
||||
# Do not retain application frames (and their locals) beyond this call.
|
||||
frames.clear()
|
||||
del frame
|
||||
return {"schema": "missioncore.runtime-threads/v1", "pid": os.getpid(),
|
||||
"monotonic_ms": started * 1000, "duration_ms": (time.monotonic()-started)*1000,
|
||||
"thread_count": len(threads), "truncated": len(threads) > 128,
|
||||
"threads": rows, "http": http_timings.snapshot()}
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Independent local operator transport; the existing control authority is unchanged."""
|
||||
import asyncio
|
||||
import json
|
||||
import math
|
||||
import secrets
|
||||
import time
|
||||
from contextlib import suppress
|
||||
|
||||
from fastapi import HTTPException, WebSocket, WebSocketDisconnect
|
||||
|
||||
from k1link.fleet.trust import PairingError
|
||||
|
||||
from .fleet_api import local_operator
|
||||
|
||||
|
||||
def register(router):
|
||||
@router.websocket("/{vehicle_id}/rover-channel")
|
||||
async def channel(socket: WebSocket, vehicle_id: str):
|
||||
try:
|
||||
fleet = local_operator(socket)
|
||||
# WebSocket browser handshakes must have the exact local origin.
|
||||
if socket.headers.get("origin") != f"http://{socket.headers.get('host', '')}":
|
||||
raise HTTPException(403)
|
||||
fleet.rover_channel.operator(vehicle_id, "view")
|
||||
except (HTTPException, ValueError, PairingError):
|
||||
await socket.close(code=1008)
|
||||
return
|
||||
trace=fleet.rover_channel.operator(vehicle_id,"diagnostics").trace
|
||||
await socket.accept()
|
||||
socket_id = secrets.token_hex(8)
|
||||
trace.add("operator_socket_opened", socket_id=socket_id)
|
||||
fleet.rover_channel.operator(vehicle_id, "observation_evidence", "operator_socket_opened")
|
||||
owned = None
|
||||
sending = asyncio.Lock()
|
||||
|
||||
async def send(value):
|
||||
async with sending:
|
||||
await socket.send_json({**value, "socket_id": socket_id})
|
||||
|
||||
async def receive():
|
||||
nonlocal owned
|
||||
window, count = time.monotonic(), 0
|
||||
while True:
|
||||
raw = await socket.receive_text()
|
||||
now = time.monotonic()
|
||||
if now - window >= 1:
|
||||
window, count = now, 0
|
||||
count += 1
|
||||
if len(raw) > 4096 or count > 64:
|
||||
await socket.close(code=1008)
|
||||
return
|
||||
try:
|
||||
message = json.loads(raw)
|
||||
if (not isinstance(message, dict)
|
||||
or set(message) != {"id", "action", "body", "expires_ms"}
|
||||
or type(message["id"]) is not int
|
||||
or not 0 < message["id"] < 2**53
|
||||
or message["action"] not in ("arm", "command", "hold")
|
||||
or not isinstance(message["body"], dict)
|
||||
or type(message["expires_ms"]) not in (int, float)
|
||||
or not math.isfinite(message["expires_ms"])):
|
||||
raise ValueError
|
||||
except (ValueError, TypeError):
|
||||
await socket.close(code=1008)
|
||||
return
|
||||
# A delayed local/browser send cannot become fresh motion on
|
||||
# arrival. Clock samples are sent below; receipt never extends it.
|
||||
remaining = message["expires_ms"] - time.monotonic() * 1000
|
||||
trace.add("operator_socket_received", socket_id=socket_id, request_id=message["id"],
|
||||
action=message["action"], session_id=message["body"].get("session_id"),
|
||||
sequence=message["body"].get("sequence"), received_ms=now*1000,
|
||||
expires_ms=message["expires_ms"], remaining_ms=remaining, bytes=len(raw))
|
||||
if not 0 < remaining <= 400:
|
||||
trace.add("operator_socket_rejected",reason="expired",action=message["action"],remaining_ms=remaining,session_id=owned,socket_id=socket_id)
|
||||
await send({"type": "reply", "id": message["id"], "status": 408,
|
||||
"error": "Команда устарела до передачи на борт."})
|
||||
continue
|
||||
try:
|
||||
if message["action"] in ("command", "hold") and message["body"].get("session_id") != owned:
|
||||
raise ValueError("Управление не принадлежит этому окну.")
|
||||
dispatch_started = time.monotonic()
|
||||
result = fleet.rover_channel.operator(vehicle_id, message["action"], message["body"], expires_at=message["expires_ms"]/1000)
|
||||
if message["action"] == "arm":
|
||||
owned = result["session_id"]
|
||||
trace.add("operator_socket_applied", socket_id=socket_id, request_id=message["id"],
|
||||
session_id=owned, sequence=message["body"].get("sequence"),
|
||||
action=message["action"], dispatch_ms=(time.monotonic()-dispatch_started)*1000)
|
||||
# The ack carries a post-operation view. The browser must
|
||||
# not apply its cached pre-arm controlling=false snapshot
|
||||
# to the newly acknowledged session before the next push.
|
||||
await send({"type": "reply", "id": message["id"], "value": result,
|
||||
"state": fleet.rover_channel.operator(vehicle_id, "view"),
|
||||
"clock_ms": time.monotonic()*1000})
|
||||
except (ValueError, PairingError) as error:
|
||||
trace.add("operator_socket_rejected",reason=str(error)[:512],action=message["action"],session_id=owned,socket_id=socket_id)
|
||||
await send({"type": "reply", "id": message["id"], "status": 409, "error": str(error)})
|
||||
|
||||
reader = asyncio.create_task(receive())
|
||||
next_state = 0.
|
||||
try:
|
||||
while not reader.done():
|
||||
if owned:
|
||||
# Native process timer, independent of hidden browser JS.
|
||||
# Only an explicit hold can produce fresh neutral frames.
|
||||
fleet.rover_channel.operator(vehicle_id, "maintain_neutral", {"session_id": owned})
|
||||
if time.monotonic() < next_state:
|
||||
await asyncio.wait({reader}, timeout=.1)
|
||||
continue
|
||||
next_state = time.monotonic()+.2
|
||||
value = fleet.rover_channel.operator(vehicle_id, "view")
|
||||
await send({"type": "state", "value": value, "clock_ms": time.monotonic() * 1000})
|
||||
await asyncio.wait({reader}, timeout=.1)
|
||||
await reader
|
||||
except (WebSocketDisconnect, OSError, RuntimeError, ValueError, PairingError) as error:
|
||||
trace.add("operator_socket_closed",error_type=type(error).__name__,close_code=getattr(error,"code",None),session_id=owned,socket_id=socket_id)
|
||||
finally:
|
||||
with suppress(ValueError, PairingError):
|
||||
fleet.rover_channel.operator(vehicle_id, "observation_evidence", "operator_socket_closed")
|
||||
reader.cancel()
|
||||
with suppress(asyncio.CancelledError, WebSocketDisconnect, OSError, RuntimeError):
|
||||
await reader
|
||||
if owned:
|
||||
with suppress(ValueError, PairingError):
|
||||
fleet.rover_channel.operator(vehicle_id, "disconnect", {"session_id": owned})
|
||||
with suppress(WebSocketDisconnect, OSError, RuntimeError):
|
||||
await socket.close()
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Bounded, expiring HTTP timing metadata; no bodies, query strings or client IDs."""
|
||||
import threading
|
||||
import time
|
||||
from collections import deque
|
||||
|
||||
from starlette.types import ASGIApp, Receive, Scope, Send
|
||||
|
||||
|
||||
class HttpTimingWindow:
|
||||
def __init__(self, clock=time.monotonic):
|
||||
self.clock = clock
|
||||
self.lock = threading.Lock()
|
||||
self.rows = deque(maxlen=256)
|
||||
|
||||
def add(self, row):
|
||||
with self.lock:
|
||||
self.rows.append(row)
|
||||
self._expire(self.clock() * 1000)
|
||||
|
||||
def _expire(self, now_ms):
|
||||
while self.rows and now_ms - self.rows[0]["ended_mono_ms"] >= 30_000:
|
||||
self.rows.popleft()
|
||||
|
||||
def snapshot(self):
|
||||
with self.lock:
|
||||
self._expire(self.clock() * 1000)
|
||||
return [dict(row) for row in self.rows]
|
||||
|
||||
|
||||
http_timings = HttpTimingWindow()
|
||||
|
||||
|
||||
class RuntimeHttpTimingMiddleware:
|
||||
def __init__(self, app: ASGIApp, window=http_timings):
|
||||
self.app, self.window = app, window
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send):
|
||||
if scope["type"] != "http":
|
||||
return await self.app(scope, receive, send)
|
||||
started = self.window.clock() * 1000
|
||||
status, size, first, complete = 500, 0, None, False
|
||||
|
||||
async def measured_send(message):
|
||||
nonlocal status, size, first, complete
|
||||
if message["type"] == "http.response.start":
|
||||
status = message["status"]
|
||||
first = self.window.clock() * 1000 - started
|
||||
elif message["type"] == "http.response.body":
|
||||
size += len(message.get("body", b""))
|
||||
await send(message)
|
||||
if message["type"] == "http.response.body" and not message.get("more_body", False):
|
||||
complete = True
|
||||
|
||||
try:
|
||||
await self.app(scope, receive, measured_send)
|
||||
finally:
|
||||
ended = self.window.clock() * 1000
|
||||
# Only the registered route template is retained. The raw path can
|
||||
# contain filenames, tokens or other user data even without a query.
|
||||
route = getattr(scope.get("route"), "path", None)
|
||||
route = (route[:240] if isinstance(route, str) and route.startswith("/api/")
|
||||
else "<other>")
|
||||
method = scope.get("method")
|
||||
if method not in {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}:
|
||||
method = "<other>"
|
||||
self.window.add({"route": route, "method": method, "status": status,
|
||||
"duration_ms": ended - started, "response_start_ms": first,
|
||||
"ended_mono_ms": ended, "bytes": size, "complete": complete})
|
||||
Reference in New Issue
Block a user