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:
@@ -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()}
|
||||
|
||||
Reference in New Issue
Block a user