feat(dev): correlate telemetry recovery, safety stops and passive drive evidence
This commit is contained in:
@@ -52,7 +52,9 @@ class FleetRegistry:
|
||||
|
||||
self.monitor = MonitorReceiver(root)
|
||||
from .rover_control import RoverControl
|
||||
self.rover_control = RoverControl()
|
||||
self.rover_control = RoverControl(diagnostic_root=Path(root) / "rover-diagnostics")
|
||||
from .rover_telemetry_policy import RoverTelemetryPreferences
|
||||
self.rover_telemetry_preferences = RoverTelemetryPreferences(root)
|
||||
from .uplinks import Uplinks
|
||||
self.uplinks = Uplinks(guard=self.rover_control.network_change)
|
||||
from .rover_channel import RoverChannel
|
||||
@@ -344,11 +346,14 @@ class FleetRegistry:
|
||||
|
||||
def listing(self):
|
||||
with self.lock:
|
||||
return {
|
||||
result = {
|
||||
"schema": "missioncore.fleet-registry/v1",
|
||||
"core_id": self.trust.core_id,
|
||||
"items": [self.public(row) for row in self.rows()],
|
||||
}
|
||||
for item in result["items"]:
|
||||
self.rover_control.record_inventory(item["node_id"], item)
|
||||
return result
|
||||
|
||||
def revoke(self, identifier: str):
|
||||
with self.lock, self.rover_channel.lock:
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Bounded explicit DEV archives. The command path only enqueues; a worker owns I/O."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import re
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ID = re.compile(r"^[a-f0-9]{32}$")
|
||||
|
||||
|
||||
class CaptureFiles:
|
||||
MAX_BYTES = 32 * 1024 * 1024
|
||||
MAX_FILES = 4
|
||||
|
||||
def __init__(self, root):
|
||||
self.root = Path(root)
|
||||
self.identifier = None
|
||||
self.queue = queue.Queue(maxsize=512)
|
||||
self.error = None
|
||||
self.dropped = self.written = 0
|
||||
self.closed = True
|
||||
self.thread = None
|
||||
self.stop_event = threading.Event()
|
||||
self.lock = threading.RLock()
|
||||
|
||||
def start(self, identifier, metadata):
|
||||
if not ID.fullmatch(identifier):
|
||||
raise ValueError("Invalid diagnostic capture")
|
||||
if self.thread and self.thread.is_alive():
|
||||
self.finish()
|
||||
self.thread.join(2)
|
||||
if self.thread.is_alive():
|
||||
raise ValueError("Дождитесь сохранения предыдущего замера Core.")
|
||||
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
if self.root.is_symlink() or shutil.disk_usage(self.root).free < 2 * 1024**3:
|
||||
raise ValueError("Недостаточно места для DEV-записи Core.")
|
||||
path = self.root / (identifier + ".jsonl")
|
||||
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
|
||||
fd = os.open(path, flags, 0o600)
|
||||
stream = os.fdopen(fd, "wb")
|
||||
raw = (json.dumps({"schema": "missioncore.operator-capture/v2", **metadata,
|
||||
"id": identifier, "scope": "operator_host_file"},
|
||||
ensure_ascii=False) + "\n").encode()
|
||||
try:
|
||||
stream.write(raw)
|
||||
stream.flush()
|
||||
except Exception:
|
||||
stream.close()
|
||||
raise
|
||||
self.identifier = identifier
|
||||
self.error = None
|
||||
self.dropped = self.written = 0
|
||||
self.closed = False
|
||||
self.queue = queue.Queue(maxsize=512)
|
||||
self.stop_event = threading.Event()
|
||||
self.thread = threading.Thread(target=self._write, args=(stream, len(raw)), daemon=True,
|
||||
name="core-dev-file")
|
||||
self.thread.start()
|
||||
# These are explicit rotating diagnostic archives, never recordings or scans.
|
||||
files = self.files()
|
||||
for old in files[self.MAX_FILES:]:
|
||||
old.unlink()
|
||||
|
||||
def files(self):
|
||||
if not self.root.exists():
|
||||
return []
|
||||
return sorted((p for p in self.root.glob("*.jsonl")
|
||||
if ID.fullmatch(p.stem) and p.is_file() and not p.is_symlink()),
|
||||
key=lambda p: p.stat().st_mtime_ns, reverse=True)
|
||||
|
||||
def append(self, row, *, identifier=None, nonblocking=False):
|
||||
if not self.lock.acquire(blocking=not nonblocking):
|
||||
self.dropped += 1
|
||||
return
|
||||
try:
|
||||
if identifier is not None and identifier != self.identifier:
|
||||
return
|
||||
if self.closed or self.error or self.stop_event.is_set():
|
||||
return
|
||||
raw = (json.dumps(row, ensure_ascii=False, allow_nan=False,
|
||||
separators=(",", ":")) + "\n").encode()
|
||||
if len(raw) > 8192:
|
||||
self.dropped += 1
|
||||
return
|
||||
try:
|
||||
self.queue.put_nowait(raw)
|
||||
except queue.Full:
|
||||
self.dropped += 1
|
||||
finally:
|
||||
self.lock.release()
|
||||
|
||||
def _write(self, stream, size):
|
||||
synced = time.monotonic()
|
||||
try:
|
||||
while not self.stop_event.is_set() or not self.queue.empty():
|
||||
try:
|
||||
item = self.queue.get(timeout=.2)
|
||||
except queue.Empty:
|
||||
item = None
|
||||
if isinstance(item, threading.Event):
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
item.set()
|
||||
elif item is not None:
|
||||
if size + len(item) > self.MAX_BYTES:
|
||||
self.error = "size_limit"
|
||||
self.stop_event.set()
|
||||
self.dropped += 1
|
||||
elif not self.error:
|
||||
stream.write(item)
|
||||
size += len(item)
|
||||
self.written += 1
|
||||
else:
|
||||
self.dropped += 1
|
||||
if time.monotonic() - synced >= 1:
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
synced = time.monotonic()
|
||||
stream.write((json.dumps({"event": "capture_file_closed", "written": self.written,
|
||||
"dropped": self.dropped,
|
||||
"error": self.error}) + "\n").encode())
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
except OSError:
|
||||
self.error = "storage_error"
|
||||
finally:
|
||||
stream.close()
|
||||
self.closed = True
|
||||
|
||||
def finish(self):
|
||||
self.stop_event.set()
|
||||
|
||||
def status(self):
|
||||
return dict(persistent=True, closed=self.closed, written=self.written,
|
||||
dropped=self.dropped, error=self.error, max_bytes=self.MAX_BYTES)
|
||||
|
||||
def export(self, identifier):
|
||||
if not ID.fullmatch(identifier):
|
||||
raise ValueError("Invalid diagnostic capture")
|
||||
path = self.root / (identifier + ".jsonl")
|
||||
if not path.is_file() or path.is_symlink():
|
||||
raise ValueError("Замер Core не найден.")
|
||||
if identifier == self.identifier and not self.closed:
|
||||
if self.stop_event.is_set():
|
||||
self.thread.join(2)
|
||||
if not self.closed:
|
||||
raise ValueError("Дождитесь сохранения замера Core.")
|
||||
else:
|
||||
marker = threading.Event()
|
||||
try:
|
||||
self.queue.put(marker, timeout=.5)
|
||||
except queue.Full:
|
||||
raise ValueError("Запись занята. Повторите сохранение.") from None
|
||||
if not marker.wait(2):
|
||||
raise ValueError("Не удалось подтвердить сохранение замера Core.")
|
||||
return path
|
||||
|
||||
def open_snapshot(self, identifier):
|
||||
path = self.export(identifier)
|
||||
fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
|
||||
stream = os.fdopen(fd, "rb")
|
||||
try:
|
||||
size = os.fstat(fd).st_size
|
||||
# The writer can append during a download. Freeze a complete-line
|
||||
# boundary and retain the descriptor across archive rotation.
|
||||
start = max(0, size - 8192)
|
||||
stream.seek(start)
|
||||
tail = stream.read(size - start)
|
||||
end = tail.rfind(b"\n")
|
||||
size = start + end + 1 if end >= 0 else 0
|
||||
stream.seek(0)
|
||||
return stream, size
|
||||
except BaseException:
|
||||
stream.close()
|
||||
raise
|
||||
|
||||
def history(self):
|
||||
result = []
|
||||
for path in self.files():
|
||||
if path.stem == self.identifier:
|
||||
continue
|
||||
try:
|
||||
with path.open("rb") as stream:
|
||||
metadata = json.loads(stream.readline(8193))
|
||||
with path.open("rb") as stream:
|
||||
stream.seek(max(0, path.stat().st_size - 8192))
|
||||
tail = stream.read(8192).splitlines()
|
||||
try:
|
||||
end = json.loads(tail[-1])
|
||||
except (ValueError, IndexError):
|
||||
end = {}
|
||||
closed = end.get("event") == "capture_file_closed"
|
||||
storage = dict(persistent=True, closed=True, written=end.get("written"),
|
||||
dropped=end.get("dropped"),
|
||||
error=end.get("error") if closed else "interrupted")
|
||||
result.append(dict(id=path.stem, active=False,
|
||||
started_at=metadata.get("started_at"),
|
||||
scope="operator_host_file", recovered=True, storage=storage))
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
return result
|
||||
@@ -100,7 +100,7 @@ class RoverChannel:
|
||||
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,
|
||||
"rover_details_v1": True, "telemetry_overlap_v1": True,
|
||||
"control_clock": self.control._clock()}
|
||||
if path == "/v1/node/rover-diagnostics":
|
||||
# Capture this binding's diagnostics object while authority is
|
||||
@@ -113,7 +113,15 @@ class RoverChannel:
|
||||
return 400, {"error": "Invalid relay"}
|
||||
return 200, self.control.stream(node, relay)
|
||||
else:
|
||||
result = self.control.exchange(node, value)
|
||||
try:
|
||||
result = self.control.exchange(node, value)
|
||||
except ValueError as error:
|
||||
from .rover_rejection_evidence import REASONS
|
||||
code = REASONS.get(str(error), "invalid_observation")
|
||||
result = {"error": "Observation rejected", "error_code": code}
|
||||
if code == "sample_clock":
|
||||
result["control_clock"] = self.control._clock()
|
||||
return 400, result
|
||||
result["core_processing_ms"] = (time.monotonic() - started) * 1000
|
||||
return 200, result
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import math
|
||||
import secrets
|
||||
import threading
|
||||
@@ -9,10 +10,12 @@ import time
|
||||
|
||||
from .rover_diagnostics import RoverDiagnostics
|
||||
from .rover_observation_evidence import ObservationEvidence
|
||||
from .rover_telemetry_policy import DEFAULT_MS, telemetry_stop_ms
|
||||
|
||||
|
||||
class RoverControl:
|
||||
def __init__(self, clock=time.monotonic):
|
||||
def __init__(self, clock=time.monotonic, diagnostic_root=None):
|
||||
self.diagnostic_root = diagnostic_root
|
||||
self.clock = clock
|
||||
self.lock = threading.RLock()
|
||||
self.changed = threading.Condition(self.lock)
|
||||
@@ -22,7 +25,7 @@ class RoverControl:
|
||||
|
||||
def _board(self, node):
|
||||
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)}
|
||||
self.boards[node]={"seen":-1e9,"watch":0,"snapshot":{},"session":None,"relay":None,"diagnostics":RoverDiagnostics(self.clock, self.diagnostic_root / hashlib.sha256(node.encode()).hexdigest()[:24] if self.diagnostic_root is not None else None),"observation":ObservationEvidence(self.clock)}
|
||||
return self.boards[node]
|
||||
|
||||
def diagnostics(self,node,vehicle):
|
||||
@@ -30,7 +33,8 @@ class RoverControl:
|
||||
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"))}
|
||||
"session_id":session.get("id"),"settings":copy.deepcopy(session.get("settings")),
|
||||
"telemetry_stop_ms":session.get("telemetry_stop_ms", DEFAULT_MS)}
|
||||
return value
|
||||
|
||||
def forget(self, node):
|
||||
@@ -54,13 +58,16 @@ class RoverControl:
|
||||
fresh = elapsed < 1
|
||||
b["observation"].view(fresh)
|
||||
self._expire(b)
|
||||
snapshot = copy.deepcopy(b["snapshot"]) if fresh else {}
|
||||
control_fresh = b["session"] is not None and elapsed < self._telemetry_limit(b)
|
||||
snapshot = copy.deepcopy(b["snapshot"]) if fresh or control_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}
|
||||
"controlling": b["session"] is not None,
|
||||
"control_fresh": bool(control_fresh), "telemetry_age_ms": elapsed * 1000 if b["seen"] != -1e9 else None,
|
||||
"telemetry_stop_ms": (b["session"] or {}).get("telemetry_stop_ms", DEFAULT_MS)}
|
||||
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))
|
||||
@@ -83,6 +90,10 @@ class RoverControl:
|
||||
b["diagnostics"].trace.add("lease_expired", session_id=b["session"]["id"], sequence=b["session"]["sequence"])
|
||||
self._withdraw(b, "input_deadline_expired")
|
||||
|
||||
@staticmethod
|
||||
def _telemetry_limit(b):
|
||||
return (b["session"] or {}).get("telemetry_stop_ms", DEFAULT_MS) / 1000
|
||||
|
||||
def disconnect(self, node, session):
|
||||
"""A closed operator socket can retire only the lease it created."""
|
||||
with self.changed:
|
||||
@@ -104,6 +115,8 @@ class RoverControl:
|
||||
self.network_changes.discard(node)
|
||||
|
||||
def arm(self, node, body, *, expires_at=None):
|
||||
threshold = telemetry_stop_ms(body.get("telemetry_stop_ms", DEFAULT_MS))
|
||||
body = {k:v for k,v in body.items() if k != "telemetry_stop_ms"}
|
||||
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}
|
||||
@@ -131,9 +144,9 @@ class RoverControl:
|
||||
raise ValueError("Дождитесь завершения предыдущего управления.")
|
||||
identifier = secrets.token_hex(16)
|
||||
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)}
|
||||
"left": 0, "right": 0, "settings": copy.deepcopy(body), "telemetry_stop_ms": threshold}
|
||||
self.changed.notify_all()
|
||||
b["diagnostics"].trace.add("armed", session_id=identifier, settings=body)
|
||||
b["diagnostics"].trace.add("armed", session_id=identifier, settings=body, telemetry_stop_ms=threshold)
|
||||
return {"session_id": identifier}
|
||||
|
||||
def command(self, node, body, *, expires_at=None):
|
||||
@@ -187,10 +200,10 @@ class RoverControl:
|
||||
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
|
||||
if (self.clock()-b["seen"] >= self._telemetry_limit(b) 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
|
||||
reason = ("telemetry_stale" if self.clock()-b["seen"] >= self._telemetry_limit(b) else
|
||||
"driver_unavailable" if snapshot.get("supported") is not True else
|
||||
"driver_terminal")
|
||||
self._withdraw(b, reason)
|
||||
@@ -207,9 +220,26 @@ class RoverControl:
|
||||
("id", "sequence", "left", "right", "settings")}
|
||||
|
||||
def exchange(self, node, body):
|
||||
"""Keep rejected authenticated observations diagnosable without publishing them."""
|
||||
try:
|
||||
return self._exchange(node, body)
|
||||
except ValueError as error:
|
||||
from .rover_rejection_evidence import rejection_evidence
|
||||
with self.lock:
|
||||
board = self.boards.get(node)
|
||||
if board is not None:
|
||||
evidence = rejection_evidence(error, body, self.clock_id, self.clock() * 1000)
|
||||
board["observation"].reject(evidence)
|
||||
board["diagnostics"].trace.local.add("node_observation_rejected", **evidence)
|
||||
raise
|
||||
|
||||
def _exchange(self, node, body):
|
||||
"""Called only after normal paired-certificate/binding authentication."""
|
||||
snapshot = body.get("rover")
|
||||
relay = body.get("relay_id")
|
||||
observation_id = body.get("observation_id")
|
||||
if observation_id is not None and (type(observation_id) is not int or not 0 < observation_id < 2**53):
|
||||
raise ValueError("Invalid observation identity")
|
||||
if not isinstance(snapshot, dict) or not isinstance(relay, str) or len(relay) != 32:
|
||||
raise ValueError("Invalid rover exchange")
|
||||
with self.lock:
|
||||
@@ -232,6 +262,11 @@ class RoverControl:
|
||||
from .rover_metadata import expand
|
||||
snapshot, metadata = expand(snapshot, body["rover_details_v1"], b.get("rover_metadata"),
|
||||
relay=relay, observed=observed, now=self.clock())
|
||||
if observation_id is not None:
|
||||
b["diagnostics"].trace.local.add("node_observation_received", epoch=relay,
|
||||
observation_id=observation_id, sample_core_mono_ms=observed*1000,
|
||||
received_core_mono_ms=self.clock()*1000,
|
||||
observation_age_ms=max(0, (self.clock()-observed)*1000), published=publish)
|
||||
readings = snapshot.get("devices")
|
||||
b["observation"].receive(observed, publish, len(readings) if isinstance(readings, list) else 0)
|
||||
if publish and b["relay"] != relay:
|
||||
@@ -241,6 +276,8 @@ class RoverControl:
|
||||
b["diagnostics"].ingest(body.get("diagnostics"))
|
||||
if publish:
|
||||
b["diagnostics"].supports_options=body.get("diagnostic_options_v1") is True
|
||||
b["diagnostics"].supports_sources=body.get("diagnostic_sources_v1") is True
|
||||
b["diagnostics"].supports_passive=body.get("diagnostic_passive_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"])
|
||||
@@ -256,11 +293,11 @@ class RoverControl:
|
||||
if s:
|
||||
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 or b["diagnostics"].enabled or b["diagnostics"].closing, "command": command,
|
||||
return {"watch": self.clock() < b["watch"] or s is not None or b["diagnostics"].watch_required(), "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),
|
||||
"diagnostics_pending": b["diagnostics"].traffic_pending(),
|
||||
"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):
|
||||
@@ -269,6 +306,13 @@ class RoverControl:
|
||||
# No control lock while ingesting optional records or waiting for files.
|
||||
return diagnostics.exchange(body)
|
||||
|
||||
def record_inventory(self, node, value):
|
||||
with self.lock:
|
||||
board = self.boards.get(node)
|
||||
diagnostics = board["diagnostics"] if board else None
|
||||
if diagnostics is not None:
|
||||
diagnostics.record_inventory(value)
|
||||
|
||||
def record_telemetry_timing(self, node, dispatch_ms, reply_mono_ms):
|
||||
"""DEV-only Core dispatch timing; no publication or lease renewal.
|
||||
|
||||
@@ -334,12 +378,12 @@ class RoverControl:
|
||||
with self.lock:
|
||||
b = self._board(node)
|
||||
self._expire(b)
|
||||
if self.clock() - b["seen"] >= 1:
|
||||
if self.clock() - b["seen"] >= self._telemetry_limit(b):
|
||||
self._withdraw(b, "telemetry_stale")
|
||||
s = b["session"] if b["relay"] == relay else None
|
||||
command = None
|
||||
if s:
|
||||
command = self._intent(s)
|
||||
command["expires_mono_ms"] = s["until"]*1000
|
||||
return {"watch": self.clock() < b["watch"] or s is not None or b["diagnostics"].enabled or b["diagnostics"].closing,
|
||||
return {"watch": self.clock() < b["watch"] or s is not None or b["diagnostics"].watch_required(),
|
||||
"command": command, "control_clock": self._clock()}
|
||||
|
||||
@@ -5,9 +5,14 @@ import secrets
|
||||
import threading
|
||||
|
||||
from missioncore_plugin_sdk.bounded_diagnostics import BoundedDiagnostics
|
||||
from missioncore_plugin_sdk.diagnostic_options import LEGACY_OPTIONS, diagnostic_options
|
||||
from missioncore_plugin_sdk.diagnostic_options import (
|
||||
LEGACY_OPTIONS,
|
||||
PASSIVE_OPTIONS,
|
||||
diagnostic_options,
|
||||
)
|
||||
|
||||
from .rover_diagnostics_export import DiagnosticExport
|
||||
from .rover_inventory_evidence import InventoryEvidence
|
||||
from .rover_local_trace import LocalRoverTrace
|
||||
from .rover_preview_evidence import preview_sample
|
||||
from .rover_stop_evidence import CoreStopEvidence
|
||||
@@ -15,14 +20,14 @@ 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',
|
||||
INPUT_FIELDS={'code','repeat','reason','held','mode','current_a','speed','control_mode','telemetry_stop_ms','browser_event_id','left','right',
|
||||
'sequence','session_id','foreground','input_valid','pending','action','outcome','elapsed_ms',
|
||||
'browser_ms','ready_state','buffered_bytes','close_code','visibility','dropped',
|
||||
'browser_ms','browser_time_origin_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 __init__(self,clock,live,root=None):
|
||||
super().__init__('core',clock);self.live=live;self.local=LocalRoverTrace(clock,root)
|
||||
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):
|
||||
@@ -33,22 +38,50 @@ class CoreTrace(BoundedDiagnostics):
|
||||
if row:self.live.add('record',record=row)
|
||||
|
||||
class RoverDiagnostics:
|
||||
def __init__(self,clock):
|
||||
def __init__(self,clock,root=None):
|
||||
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=CoreTrace(clock,self.live,root);self.node_ack=0;self.relay_ack=0;self.node_status={}
|
||||
self.clock=clock;self.options=dict(LEGACY_OPTIONS);self.supports_options=False;self.supports_sources=False
|
||||
self.supports_passive=False;self.passive_confirmed=False
|
||||
self.status_pending = True
|
||||
self.control_stop=CoreStopEvidence(clock, sink=self.trace.local.record_stop)
|
||||
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
|
||||
self.inventory_evidence = InventoryEvidence(self.trace.local)
|
||||
|
||||
def record_inventory(self, value):
|
||||
with self.lock:
|
||||
self.inventory_evidence.record(value)
|
||||
|
||||
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)}
|
||||
# One lifecycle handshake after Core startup discovers a recorder that
|
||||
# survived on Node. Afterwards passive recording remains silent, even
|
||||
# if Node reports that no capture exists. No event rows are requested.
|
||||
self.status_pending = False
|
||||
# Local receipt evidence only: no echo, wake hint or extra network request.
|
||||
self.trace.local.add('board_diagnostics_exchange')
|
||||
reply = {'diagnostics': self.desired(relay_ack=True, export_v2=body.get('diagnostic_export_v2') is True)}
|
||||
if body.get('diagnostic_passive_v1') is True:
|
||||
reply['diagnostics_pending'] = self.traffic_pending()
|
||||
return reply
|
||||
|
||||
def traffic_pending(self):
|
||||
# Atomic read-only hint; no recorder/file locks in the motion path.
|
||||
return bool(
|
||||
(self.supports_passive and self.status_pending) or self.export.busy or self.closing
|
||||
or (self.enabled and (not self.options.get('passive') or not self.passive_confirmed))
|
||||
)
|
||||
|
||||
def watch_required(self):
|
||||
return (self.enabled or self.closing) and not self.options.get('passive')
|
||||
|
||||
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)
|
||||
selected=diagnostic_options(PASSIVE_OPTIONS if options is None and self.supports_passive else options)
|
||||
if enabled and selected["passive"] and local_options is None:
|
||||
local_options = {"enabled": True, "preview": True, "previous_id": self.trace.local.id}
|
||||
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
|
||||
@@ -56,6 +89,10 @@ class RoverDiagnostics:
|
||||
raise ValueError("Invalid operator capture options")
|
||||
if enabled and options is not None and not self.supports_options:
|
||||
raise ValueError('Борт ещё не подтвердил поддержку настроек записи.')
|
||||
if enabled and (selected["router"] or selected["system"]) and not self.supports_sources:
|
||||
raise ValueError("Для записи состояния сети и оборудования обновите Node на борту.")
|
||||
if enabled and selected["passive"] and not self.supports_passive:
|
||||
raise ValueError("Для пассивной DEV-записи обновите Node на борту.")
|
||||
with self.lock:
|
||||
if enabled and not self.enabled:
|
||||
if self.closing or self.export.busy:raise ValueError('Дождитесь завершения записи или сохранения файла.')
|
||||
@@ -66,7 +103,7 @@ class RoverDiagnostics:
|
||||
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.node_ack=self.relay_ack=0;self.node_status={};self.enabled=True;self.passive_confirmed=False
|
||||
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,
|
||||
@@ -135,6 +172,9 @@ class RoverDiagnostics:
|
||||
self.trace.add('core_tail_interrupted',after=ack,before=stop_after)
|
||||
self.trace.configure(identifier,False)
|
||||
if identifier!=self.trace.id:return
|
||||
self.status_pending = False
|
||||
if packet.get('active') is True and stored.get('closed') is not True:
|
||||
self.passive_confirmed = True
|
||||
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')}
|
||||
@@ -161,15 +201,19 @@ class RoverDiagnostics:
|
||||
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')
|
||||
if not isinstance(rows,list) or len(rows)>(256 if local else 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'))}
|
||||
if isinstance(row.get('browser_event_id'), str):fields['browser_event_id']=row['browser_event_id'][:64]
|
||||
stamp=row.get('browser_ms')
|
||||
if type(stamp) in (int,float):fields['browser_ms']=stamp
|
||||
origin=row.get('browser_time_origin_ms')
|
||||
if type(origin) in (int,float):
|
||||
fields['browser_time_origin_ms']=origin
|
||||
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}
|
||||
@@ -185,5 +229,6 @@ class RoverDiagnostics:
|
||||
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),
|
||||
'local_history':self.trace.local.history(),
|
||||
'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'}
|
||||
'node':self.node_status,'options':dict(self.options),'options_supported':self.supports_options,'sources_supported':self.supports_sources,'passive_supported':self.supports_passive,'passive_confirmed':self.passive_confirmed,'schema':'missioncore.rover-dev/v1'}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Bounded local DEV evidence of the inventory projection shown to the operator."""
|
||||
import time
|
||||
|
||||
|
||||
class InventoryEvidence:
|
||||
def __init__(self, trace):
|
||||
self.trace = trace
|
||||
self.identity = None
|
||||
self.next_at = 0.0
|
||||
|
||||
def record(self, value):
|
||||
# The diagnostics lifecycle lock covers selection and append. This path
|
||||
# runs after releasing registry/control locks; it sends nothing to Node.
|
||||
if not self.trace.active():
|
||||
self.identity = None
|
||||
return
|
||||
now = self.trace.clock()
|
||||
if self.identity == self.trace.id and now < self.next_at:
|
||||
return
|
||||
self.identity, self.next_at = self.trace.id, now + 1
|
||||
devices = (value.get("sensor_state") or {}).get("items", [])
|
||||
wall = time.time()
|
||||
|
||||
def age(key):
|
||||
observed = value.get(key)
|
||||
return round(max(0., wall - observed), 3) if observed is not None else None
|
||||
|
||||
self.trace.add(
|
||||
"inventory_projection", online=value.get("connectivity") == "online",
|
||||
inventory_fresh=value.get("inventory_fresh") is True,
|
||||
inventory_age_s=age("last_seen"), link_age_s=age("link_last_seen"),
|
||||
device_count=len(devices),
|
||||
online_device_count=sum(d.get("online") is True for d in devices),
|
||||
devices=[{"id": str(d.get("id", ""))[:96], "online": d.get("online") is True}
|
||||
for d in devices[:32]], devices_omitted=max(0, len(devices) - 32),
|
||||
scope="core_inventory_projection", clock_source="core_receipt_wall_clock",
|
||||
)
|
||||
@@ -1,6 +1,9 @@
|
||||
"""Explicit operator-host evidence; no Node traffic, disk I/O or motor authority."""
|
||||
"""Explicit operator evidence; optional bounded disk archive, no Node traffic or motor authority."""
|
||||
|
||||
import json
|
||||
import secrets
|
||||
from collections import OrderedDict
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from missioncore_plugin_sdk.bounded_diagnostics import BoundedDiagnostics
|
||||
|
||||
@@ -8,25 +11,48 @@ from missioncore_plugin_sdk.bounded_diagnostics import BoundedDiagnostics
|
||||
class LocalRoverTrace(BoundedDiagnostics):
|
||||
MAX_BYTES = 2 * 1024 * 1024
|
||||
MAX_ROWS = 6000
|
||||
MAX_ARCHIVES = 3
|
||||
|
||||
def __init__(self, clock):
|
||||
def __init__(self, clock, root=None):
|
||||
super().__init__("core", clock)
|
||||
self.until = 0.0
|
||||
self.preview = True
|
||||
self.started_at = None
|
||||
self.archives = OrderedDict()
|
||||
from .rover_capture_file import CaptureFiles
|
||||
self.files = CaptureFiles(root) if root is not None else None
|
||||
|
||||
def add(self, event, **data):
|
||||
row = super().add(event, **data)
|
||||
if row is not None and self.files is not None:
|
||||
self.files.append(row)
|
||||
return row
|
||||
|
||||
def active(self):
|
||||
return super().active() and self.clock() < self.until
|
||||
|
||||
def record_stop(self, evidence):
|
||||
if self.files is not None and self.active():
|
||||
try:
|
||||
self.files.append({'source': 'core', 'event': 'core_control_stop', **evidence},
|
||||
identifier=self.id, nonblocking=True)
|
||||
except Exception:
|
||||
self.files.dropped += 1 # Optional evidence cannot interrupt withdrawal.
|
||||
|
||||
def snapshot(self, after=0, limit=200):
|
||||
if self.files is not None and not self.active():
|
||||
self.files.finish()
|
||||
return {
|
||||
"storage": self.files.status() if self.files is not None else None,
|
||||
**super().snapshot(after, limit),
|
||||
"expires_mono_ms": self.until * 1000,
|
||||
"max_rows": self.MAX_ROWS,
|
||||
"scope": "operator_host_only",
|
||||
"preview": self.preview,
|
||||
"started_at": self.started_at,
|
||||
}
|
||||
|
||||
def start(self, *, duration=900, previous_id=None, preview=True):
|
||||
def start(self, *, duration=3600, 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:
|
||||
@@ -34,10 +60,22 @@ class LocalRoverTrace(BoundedDiagnostics):
|
||||
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")
|
||||
raise ValueError("Local capture identity changed")
|
||||
if self.id is not None:
|
||||
# Preserve completed evidence without blocking the next acquisition.
|
||||
# Store serialized bounded rows, not a second expanded event history.
|
||||
with self.lock:
|
||||
rows = tuple(self.rows)
|
||||
self.archives[self.id] = (self.snapshot(limit=0), rows)
|
||||
while len(self.archives) > self.MAX_ARCHIVES:
|
||||
self.archives.popitem(last=False)
|
||||
self.started_at = datetime.now(UTC).isoformat()
|
||||
self.preview = preview
|
||||
self.until = self.clock() + duration
|
||||
self.configure(secrets.token_hex(16), True)
|
||||
identifier = secrets.token_hex(16)
|
||||
if self.files is not None:
|
||||
self.files.start(identifier, {"started_at": self.started_at, "duration_s": duration})
|
||||
self.configure(identifier, True)
|
||||
self.add("local_capture_started", duration_s=duration)
|
||||
return self.snapshot(limit=0)
|
||||
|
||||
@@ -46,9 +84,20 @@ class LocalRoverTrace(BoundedDiagnostics):
|
||||
raise ValueError("Local capture identity changed")
|
||||
self.add("local_capture_stopped")
|
||||
self.configure(identifier, False)
|
||||
if self.files is not None:
|
||||
self.files.finish()
|
||||
return self.snapshot(limit=0)
|
||||
|
||||
def history(self):
|
||||
if self.files is not None:
|
||||
return self.files.history()
|
||||
return [dict(meta) for meta, _ in reversed(self.archives.values())]
|
||||
|
||||
def page(self, identifier, after=0, limit=200):
|
||||
if identifier in self.archives:
|
||||
meta, rows = self.archives[identifier]
|
||||
raw = [raw for seq, raw, _ in rows if seq > after][:limit]
|
||||
return {**meta, "frames": [json.loads(row) for row in raw]}
|
||||
if self.id is None or identifier != self.id:
|
||||
raise ValueError("Local capture identity changed")
|
||||
return self.snapshot(after, limit)
|
||||
|
||||
@@ -20,6 +20,9 @@ class ObservationEvidence:
|
||||
self.receipts = self.ignored = 0
|
||||
self.max_gap_ms = 0.
|
||||
self.phase = None
|
||||
self.rejected = 0
|
||||
self.rejection_reasons = {}
|
||||
self.last_rejection = None
|
||||
|
||||
def _daily(self):
|
||||
if self.day != self.utc_now().date():
|
||||
@@ -43,6 +46,14 @@ class ObservationEvidence:
|
||||
if self.receipts == 1 or gap >= 1000:
|
||||
self.event("first_receipt" if self.receipts == 1 else "receipt_after_gap")
|
||||
|
||||
def reject(self, evidence):
|
||||
self._daily()
|
||||
self.rejected += 1
|
||||
reason = evidence["reason"]
|
||||
self.rejection_reasons[reason] = self.rejection_reasons.get(reason, 0) + 1
|
||||
self.last_rejection = {**evidence, "at_utc": self.utc_now().isoformat(),
|
||||
"monotonic_ms": self.clock() * 1000}
|
||||
|
||||
def view(self, fresh):
|
||||
self._daily()
|
||||
phase = "fresh" if fresh else "stale" if self.receipts else "awaiting_first_receipt"
|
||||
@@ -53,6 +64,8 @@ class ObservationEvidence:
|
||||
def snapshot(self):
|
||||
self._daily()
|
||||
return {"schema": "missioncore.observation-evidence/v1", "scope": "core_memory_daily",
|
||||
"rejected": self.rejected, "rejection_reasons": dict(self.rejection_reasons),
|
||||
"last_rejection": dict(self.last_rejection) if self.last_rejection else None,
|
||||
"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,
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Fixed, bounded rejection facts; never retain requests, identities or error text."""
|
||||
|
||||
import math
|
||||
|
||||
REASONS = {
|
||||
"Invalid observation identity": "observation_identity",
|
||||
"Invalid rover exchange": "exchange_shape",
|
||||
"Invalid rover sample clock": "sample_clock",
|
||||
"Invalid rover metadata envelope": "metadata_envelope",
|
||||
"Invalid rover metadata": "metadata_shape",
|
||||
"Invalid rover device metadata": "device_metadata",
|
||||
"Rover metadata revision changed": "metadata_revision",
|
||||
"Rover metadata refresh required": "metadata_refresh",
|
||||
"Rover metadata roster changed": "metadata_roster",
|
||||
"Invalid compact rover sample": "compact_sample",
|
||||
}
|
||||
|
||||
|
||||
def rejection_evidence(error, body, instance, now_ms):
|
||||
result = {"reason": REASONS.get(str(error), "invalid_observation")}
|
||||
stamp = body.get("sample_clock")
|
||||
if isinstance(stamp, dict):
|
||||
result["clock_instance_matches"] = stamp.get("instance") == instance
|
||||
value = stamp.get("monotonic_ms")
|
||||
if type(value) in (int, float) and math.isfinite(value):
|
||||
result["sample_offset_ms"] = round(max(-86400000, min(86400000, value - now_ms)), 3)
|
||||
return result
|
||||
@@ -5,8 +5,9 @@ from threading import Lock
|
||||
|
||||
|
||||
class CoreStopEvidence:
|
||||
def __init__(self, clock, utc_now=lambda: datetime.now(UTC)):
|
||||
def __init__(self, clock, utc_now=lambda: datetime.now(UTC), sink=None):
|
||||
self.clock, self.utc_now = clock, utc_now
|
||||
self.sink = sink
|
||||
self._latest = None
|
||||
self._lock = Lock()
|
||||
|
||||
@@ -29,12 +30,17 @@ class CoreStopEvidence:
|
||||
"neutral_hold": session["neutral_hold"],
|
||||
"remaining_ms": (session["until"] - now) * 1000,
|
||||
"telemetry_age_ms": max(0, telemetry_age_ms),
|
||||
"telemetry_stop_ms": session.get("telemetry_stop_ms", 1000),
|
||||
"driver_state": state,
|
||||
})
|
||||
|
||||
# No optional-recorder/export lock, file I/O or transport in this path.
|
||||
with self._lock:
|
||||
self._latest = value
|
||||
if self.sink is not None:
|
||||
# The sink only enqueues into the active local file, without waiting
|
||||
# for optional recorder locks, disk or network. Motion is already stopped.
|
||||
self.sink(value[2])
|
||||
|
||||
def snapshot(self):
|
||||
now, day = self.clock(), self.utc_now().date()
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Operator preference, separate from motor configuration and command leases."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import TypedDict
|
||||
|
||||
from .trust import atomic_private
|
||||
|
||||
DEFAULT_MS = 1000
|
||||
MIN_MS = 250
|
||||
MAX_MS = 5000
|
||||
|
||||
|
||||
class TelemetryPolicy(TypedDict):
|
||||
revision: int
|
||||
telemetry_stop_ms: int
|
||||
|
||||
|
||||
def telemetry_stop_ms(value: object) -> int:
|
||||
if type(value) is not int or not MIN_MS <= value <= MAX_MS:
|
||||
raise ValueError(f"Максимальный возраст телеметрии: {MIN_MS}–{MAX_MS} мс.")
|
||||
return value
|
||||
|
||||
|
||||
class RoverTelemetryPreferences:
|
||||
def __init__(self, root: Path) -> None:
|
||||
self.root = root / "rover-telemetry-preferences"
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def path(self, vehicle: str) -> Path:
|
||||
return self.root / (hashlib.sha256(vehicle.encode()).hexdigest() + ".json")
|
||||
|
||||
def _read(self, vehicle: str) -> TelemetryPolicy:
|
||||
path = self.path(vehicle)
|
||||
if not path.exists():
|
||||
return {"revision": 0, "telemetry_stop_ms": DEFAULT_MS}
|
||||
if path.is_symlink() or path.stat().st_size > 4096:
|
||||
raise ValueError("Не удалось прочитать настройки телеметрии.")
|
||||
value = json.loads(path.read_bytes())
|
||||
if (
|
||||
not isinstance(value, dict)
|
||||
or set(value) != {"revision", "telemetry_stop_ms"}
|
||||
or type(value["revision"]) is not int
|
||||
or value["revision"] < 0
|
||||
):
|
||||
raise ValueError("Некорректные настройки телеметрии.")
|
||||
return {
|
||||
"revision": value["revision"],
|
||||
"telemetry_stop_ms": telemetry_stop_ms(value["telemetry_stop_ms"]),
|
||||
}
|
||||
|
||||
def view(self, vehicle: str) -> TelemetryPolicy:
|
||||
with self.lock:
|
||||
return self._read(vehicle)
|
||||
|
||||
def update(self, vehicle: str, body: object) -> TelemetryPolicy:
|
||||
if (
|
||||
not isinstance(body, dict)
|
||||
or set(body) != {"revision", "telemetry_stop_ms"}
|
||||
or type(body["revision"]) is not int
|
||||
):
|
||||
raise ValueError("Некорректные настройки телеметрии.")
|
||||
value = telemetry_stop_ms(body["telemetry_stop_ms"])
|
||||
with self.lock:
|
||||
old = self._read(vehicle)
|
||||
if old["revision"] != body["revision"]:
|
||||
raise ValueError("Настройка изменена в другом окне. Откройте настройки заново.")
|
||||
if old["telemetry_stop_ms"] == value:
|
||||
return old
|
||||
result: TelemetryPolicy = {
|
||||
"revision": old["revision"] + 1, "telemetry_stop_ms": value
|
||||
}
|
||||
self.root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
atomic_private(self.path(vehicle), (json.dumps(result) + "\n").encode())
|
||||
return result
|
||||
@@ -10,6 +10,8 @@ from .rover_socket import register
|
||||
register(router)
|
||||
from .rover_diagnostics_api import register as register_diagnostics
|
||||
register_diagnostics(router)
|
||||
from .rover_telemetry_api import register as register_telemetry_policy
|
||||
register_telemetry_policy(router)
|
||||
|
||||
@router.get("/{vehicle_id}/rover")
|
||||
def rover_state(vehicle_id: str, response: Response,
|
||||
|
||||
@@ -59,7 +59,7 @@ def register(router):
|
||||
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.start(duration=body.get("duration_s", 3600), 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"))
|
||||
@@ -83,6 +83,30 @@ def register(router):
|
||||
capture = recorder(fleet, vehicle_id)
|
||||
try:
|
||||
with capture.lock:
|
||||
if capture.trace.local.files is not None:
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
stream, size = capture.trace.local.files.open_snapshot(capture_id)
|
||||
|
||||
def chunks():
|
||||
remaining = size
|
||||
try:
|
||||
while remaining:
|
||||
data = stream.read(min(65536, remaining))
|
||||
if not data:
|
||||
break
|
||||
remaining -= len(data)
|
||||
yield data
|
||||
finally:
|
||||
stream.close()
|
||||
|
||||
return StreamingResponse(
|
||||
chunks(), media_type="application/x-ndjson",
|
||||
background=BackgroundTask(stream.close), headers={
|
||||
"Cache-Control": "no-store", "Content-Length": str(size),
|
||||
"Content-Disposition":
|
||||
f'attachment; filename="rover-operator-{capture_id}.jsonl"',
|
||||
})
|
||||
page = capture.trace.local.page(capture_id, limit=capture.trace.local.MAX_ROWS)
|
||||
except ValueError as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Durable operator preference; never changes an already active session."""
|
||||
|
||||
from typing import Annotated, Any, cast
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from ..fleet.rover_telemetry_policy import TelemetryPolicy
|
||||
from ..fleet.trust import PairingError
|
||||
from .fleet_api import local_operator
|
||||
|
||||
|
||||
def register(router: APIRouter) -> None:
|
||||
@router.get("/{vehicle_id}/rover/telemetry-policy")
|
||||
def read(vehicle_id: str, fleet: Annotated[Any, Depends(local_operator)]) -> TelemetryPolicy:
|
||||
try:
|
||||
fleet.rover_channel.operator(vehicle_id, "view")
|
||||
return cast(TelemetryPolicy, fleet.rover_telemetry_preferences.view(vehicle_id))
|
||||
except (OSError, ValueError, PairingError) as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
|
||||
@router.put("/{vehicle_id}/rover/telemetry-policy")
|
||||
def update(
|
||||
vehicle_id: str, body: dict[str, Any], fleet: Annotated[Any, Depends(local_operator)]
|
||||
) -> TelemetryPolicy:
|
||||
try:
|
||||
fleet.rover_channel.operator(vehicle_id, "view")
|
||||
return cast(TelemetryPolicy, fleet.rover_telemetry_preferences.update(vehicle_id, body))
|
||||
except (OSError, ValueError, PairingError) as error:
|
||||
raise HTTPException(409, str(error)) from None
|
||||
Reference in New Issue
Block a user