Files
NODEDC_MISSION_CORE/src/k1link/fleet/rover_channel.py
T

144 lines
6.8 KiB
Python

"""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"),
"network_paths": row.get("network_paths", {}),
})
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):
"""Retire superseded endpoints; each send still fully authenticates a candidate.
A higher revision is an in-flight route change. Its feedback must work
before the first paced heartbeat can commit that revision.
"""
with self.lock:
row = self.nodes.get(value.get("node_id"))
revision = value.get("endpoint_revision", 0)
return bool(row and row["enrollment"] == "paired"
and row["binding"]["binding_id"] == value.get("binding_id")
and type(revision) is int
and row["binding"].get("endpoint_revision", 0) <= revision <= 1000000000)
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