feat(node): add confirmed board shutdown with expiring commands

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 15:52:46 +03:00
parent f76928b606
commit ab8e977f11
21 changed files with 967 additions and 4 deletions
+126
View File
@@ -0,0 +1,126 @@
"""Ephemeral, owner-bound power-off handshake. Never replay a persisted command."""
import time
SCHEMA = "missioncore.node-power/v1"
class BoardPower:
# All access is under FleetRegistry.lock; no disk queue or background retry.
def __init__(self):
self.nodes = {}
self.operations = {}
def heartbeat(self, row, value):
now = time.time()
key = row["id"]
binding = row["binding"]["binding_id"]
power = value.get("power")
if not isinstance(power, dict) or power.get("schema") != SCHEMA:
self.nodes.pop(key, None)
return {}
epoch = power.get("epoch")
if not isinstance(epoch, str) or len(epoch) != 43:
self.nodes.pop(key, None)
return {}
self.nodes[key] = dict(
at=now, binding=binding, epoch=epoch, available=power.get("available") is True
)
op = self.operations.get(key)
if not op:
return {}
if op["binding"] != binding or op["epoch"] != epoch:
op.update(state="expired", message="Борт переподключился. Команда отменена.")
return {}
result = power.get("result")
if isinstance(result, dict) and result.get("id") == op["id"]:
state = result.get("state")
if state in ("accepted", "executing", "submitted", "failed", "expired"):
op["state"] = state
op["message"] = {
"accepted": "Борт принял команду выключения.",
"executing": "Борт выполняет выключение.",
"submitted": "Выключение запрошено. Связь с бортом будет потеряна.",
"failed": "Борт не смог выполнить выключение. Проверьте состояние системы.",
"expired": "Срок действия команды истёк. Выключение не выполнено.",
}[state]
self._expire(op, now)
if op["state"] == "queued":
return {
"power_command": {
"schema": SCHEMA,
"id": op["id"],
"binding_id": binding,
"epoch": epoch,
"action": "poweroff",
"expires_at": op["expires_at"],
}
}
if op["state"] == "accepted":
return {"power_ack": op["id"]}
return {}
@staticmethod
def _expire(op, now):
if now >= op["expires_at"] and op["state"] in ("queued", "accepted", "executing"):
uncertain = op["state"] != "queued"
op.update(
state="unknown" if uncertain else "expired",
message=(
"Связь прервалась после приёма команды. Проверьте, выключился ли борт."
if uncertain
else "Борт не принял команду вовремя. Выключение отменено."
),
)
def view(self, row):
now = time.time()
node = self.nodes.get(row["id"], {})
op = self.operations.get(row["id"])
if op:
self._expire(op, now)
bound = row.get("enrollment") == "paired" and node.get("binding") == (
row.get("binding") or {}
).get("binding_id")
fresh = bound and now - node.get("at", 0) < 12
available = fresh and node.get("available", False)
pending = (
op
and op["state"] in ("queued", "accepted", "executing", "submitted", "unknown")
and op["epoch"] == node.get("epoch")
)
return {
"available": bool(available and not pending),
"epoch": node.get("epoch"),
"reason": ""
if available
else (
"Выключение недоступно в текущей версии или окружении борта."
if not node
and row.get("enrollment") == "paired"
and now - (row.get("last_seen") or 0) < 12
else (
"Нет связи с бортом."
if not fresh
else "Выключение недоступно в текущем окружении борта."
)
),
"operation": {k: op[k] for k in ("id", "state", "message")} if op else None,
}
def start(self, row, epoch, request_id):
current = self.operations.get(row["id"])
if current and current["id"] == request_id:
return self.view(row)
view = self.view(row)
if not view["available"] or view["epoch"] != epoch:
raise ValueError(view["reason"] or "Состояние борта изменилось. Обновите окно.")
self.operations[row["id"]] = dict(
id=request_id,
epoch=epoch,
binding=row["binding"]["binding_id"],
expires_at=time.time() + 20,
state="queued",
message="Передаём команду выключения…",
)
return self.view(row)
+3
View File
@@ -38,6 +38,8 @@ class FleetRegistry:
self.vps_hosts: VPSHosts | None = None
self.lock = threading.RLock()
self.presence: dict[str, dict] = {}
from .power import BoardPower
self.power = BoardPower()
from .events import FleetEvents
self.events = FleetEvents()
@@ -574,6 +576,7 @@ class FleetRegistry:
**sensor_response,
**enrollment_response,
**router_response,
**self.power.heartbeat(row, value),
}
def receive_liveness(self, row, value, address):