feat(events): deliver state changes to the configurable operator event center
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
"""Transitions from confirmed arrivals and Core-owned control decisions. No network I/O."""
|
||||
|
||||
import time
|
||||
from collections import deque
|
||||
from uuid import uuid4
|
||||
|
||||
LINK_TIMEOUT = 20
|
||||
STOP_CAUSES = {
|
||||
"input_deadline_expired": "Истёк срок действия команды управления.",
|
||||
"operator_socket_closed": "Закрылось соединение оператора.",
|
||||
"driver_unavailable": "Драйвер контроллеров недоступен.",
|
||||
"driver_terminal": "Борт сообщил о завершении управления контроллерами.",
|
||||
"driver_restarted": "Драйвер контроллеров перезапустился.",
|
||||
"relay_changed": "Сменился сеанс бортового канала.",
|
||||
}
|
||||
|
||||
|
||||
class BoardPresence:
|
||||
"""Only a binding seen since Core startup can go missing. All calls under registry lock."""
|
||||
|
||||
def __init__(self, history, clock=time.monotonic, wall=time.time):
|
||||
self.history, self.clock, self.wall = history, clock, wall
|
||||
self.links = {}
|
||||
|
||||
def received(self, row):
|
||||
key = row["binding"]["binding_id"]
|
||||
now = self.clock()
|
||||
previous = self.links.get(key)
|
||||
if previous and now >= previous["until"]:
|
||||
self.expire(row)
|
||||
self.history.publish(
|
||||
"board.restored",
|
||||
previous["episode"] + ":up",
|
||||
"success",
|
||||
"Связь с бортом · " + row["name"],
|
||||
"Связь восстановлена.",
|
||||
at=self.wall(),
|
||||
)
|
||||
if not previous or now >= previous["until"]:
|
||||
previous = self.links[key] = {"episode": uuid4().hex, "lost": False}
|
||||
previous.update(until=now + LINK_TIMEOUT, at=self.wall() + LINK_TIMEOUT)
|
||||
|
||||
def expire(self, row):
|
||||
link = self.links.get(row["binding"]["binding_id"])
|
||||
if link and not link["lost"] and self.clock() >= link["until"]:
|
||||
self.history.publish(
|
||||
"board.lost",
|
||||
link["episode"] + ":down",
|
||||
"warning",
|
||||
"Связь с бортом · " + row["name"],
|
||||
"Борт перестал выходить на связь.",
|
||||
at=link["at"],
|
||||
)
|
||||
link["lost"] = True
|
||||
|
||||
|
||||
class ControlTransitions:
|
||||
"""Access under the control lock. Publishing/SQLite runs on the registry worker."""
|
||||
|
||||
def __init__(self):
|
||||
self.pending = deque(maxlen=128)
|
||||
self.stopped = False
|
||||
|
||||
def stop(self, reason, session, age_ms):
|
||||
if reason == "operator_stop":
|
||||
return
|
||||
if reason == "telemetry_stale":
|
||||
message = (
|
||||
f"Возраст телеметрии {round(age_ms)} мс. "
|
||||
f"Порог остановки {session['telemetry_stop_ms']} мс."
|
||||
)
|
||||
else:
|
||||
message = STOP_CAUSES.get(reason, "Управление отозвано защитой.")
|
||||
self.pending.append(("control.stop", session["id"], time.time(), message))
|
||||
self.stopped = True
|
||||
|
||||
def ready(self, session):
|
||||
if self.stopped:
|
||||
self.pending.append(
|
||||
(
|
||||
"control.ready",
|
||||
session,
|
||||
time.time(),
|
||||
"Борт подтвердил готовность управления в новом сеансе.",
|
||||
)
|
||||
)
|
||||
self.stopped = False
|
||||
|
||||
|
||||
def publish_control(history, row, stream):
|
||||
node = row["node_id"]
|
||||
with stream.lock:
|
||||
board = stream.boards.get(node)
|
||||
transitions = board.get("operator_transitions") if board else None
|
||||
batch = list(transitions.pending) if transitions else []
|
||||
for item in batch:
|
||||
kind, session, at, message = item
|
||||
history.publish(
|
||||
kind,
|
||||
f"{row['binding']['binding_id']}:{kind}:{session}",
|
||||
"warning" if kind == "control.stop" else "success",
|
||||
"Управление · " + row["name"],
|
||||
message,
|
||||
at=at,
|
||||
)
|
||||
with stream.lock:
|
||||
if transitions.pending and transitions.pending[0] == item:
|
||||
transitions.pending.popleft()
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Accept bounded transition receipts from the paired Node's authenticated heartbeat."""
|
||||
|
||||
import re
|
||||
|
||||
MESSAGES = {
|
||||
"delivery.loss": (
|
||||
"warning",
|
||||
"Телеметрия",
|
||||
"Борт перестал получать подтверждения доставки телеметрии от Core.",
|
||||
),
|
||||
"delivery.recovery": (
|
||||
"success",
|
||||
"Телеметрия",
|
||||
"Core снова подтверждает борту доставку телеметрии.",
|
||||
),
|
||||
"telemetry.loss": ("warning", "Телеметрия", "Борт зафиксировал потерю телеметрии VESC."),
|
||||
"telemetry.recovery": (
|
||||
"success",
|
||||
"Телеметрия",
|
||||
"Борт подтвердил восстановление телеметрии VESC.",
|
||||
),
|
||||
"board.shutdown": ("info", "Питание", "Ubuntu начала штатное завершение работы."),
|
||||
"board.boot": ("info", "Питание", "Борт сообщил о новой загрузке Linux."),
|
||||
"camera.loss": ("warning", "Камера", "Камера отключилась от USB."),
|
||||
"camera.recovery": ("success", "Камера", "Камера обнаружена по USB."),
|
||||
"frames.loss": ("warning", "Видео", "При включённом просмотре перестали поступать кадры."),
|
||||
"frames.recovery": ("success", "Видео", "Кадры камеры снова поступают."),
|
||||
"thermal.loss": ("warning", "Температура", "Ядро включило тепловое ограничение процессора."),
|
||||
"thermal.recovery": ("success", "Температура", "Ядро сняло тепловое ограничение процессора."),
|
||||
"control.stop": (
|
||||
"warning",
|
||||
"Управление",
|
||||
"Бортовой драйвер зарегистрировал аварийное завершение сеанса управления.",
|
||||
),
|
||||
"control.ready": (
|
||||
"success",
|
||||
"Управление",
|
||||
"Борт подтвердил готовность управления в новом сеансе.",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def valid(item):
|
||||
if (
|
||||
not isinstance(item, dict)
|
||||
or not isinstance(kind := item.get("kind"), str)
|
||||
or kind not in MESSAGES
|
||||
):
|
||||
return False
|
||||
fields = {"id", "kind", "at"}
|
||||
source = kind.partition(".")[0]
|
||||
if source in ("camera", "frames"):
|
||||
fields.add("device")
|
||||
if not isinstance(device := item.get("device"), str) or not re.fullmatch(
|
||||
r"(instax4|rsd455)_[0-9a-f]{32}", device
|
||||
):
|
||||
return False
|
||||
if source == "control":
|
||||
fields.add("session")
|
||||
if not isinstance(session := item.get("session"), str) or not re.fullmatch(
|
||||
r"[0-9a-f]{32}", session
|
||||
):
|
||||
return False
|
||||
return (
|
||||
fields == item.keys()
|
||||
and isinstance(item["id"], str)
|
||||
and bool(re.fullmatch(r"[A-Za-z0-9_-]{43}", item["id"]))
|
||||
and type(item["at"]) is int
|
||||
and 0 < item["at"] < 253402300800
|
||||
)
|
||||
|
||||
|
||||
def accept_operator_events(history, row, batch):
|
||||
if not isinstance(batch, list) or not 1 <= len(batch) <= 8 or not all(map(valid, batch)):
|
||||
return {}
|
||||
binding = row["binding"]["binding_id"]
|
||||
for item in batch:
|
||||
kind = item["kind"]
|
||||
tone, title, message = MESSAGES[kind]
|
||||
identity = f"node:{binding}:{item['id']}"
|
||||
if session := item.get("session"):
|
||||
# The driver and Core can independently observe the same stop.
|
||||
identity = f"{binding}:{kind}:{session}"
|
||||
if device := item.get("device"):
|
||||
sensor = next(
|
||||
(
|
||||
d
|
||||
for d in (row.get("sensor_state") or {}).get("items", [])
|
||||
if d.get("id") == device
|
||||
),
|
||||
{},
|
||||
)
|
||||
model = "Insta360 X4" if device.startswith("instax4_") else "RealSense D455"
|
||||
message += f" {sensor.get('name') or model} · {device[-6:]}"
|
||||
history.publish(kind, identity, tone, f"{title} · {row['name']}", message, at=item["at"])
|
||||
return {"operator_events_ack": batch[-1]["id"]}
|
||||
@@ -1,6 +1,8 @@
|
||||
"""Ephemeral, owner-bound power-off handshake. Never replay a persisted command."""
|
||||
|
||||
import sqlite3
|
||||
import time
|
||||
from contextlib import suppress
|
||||
|
||||
SCHEMA = "missioncore.node-power/v1"
|
||||
|
||||
@@ -8,6 +10,7 @@ SCHEMA = "missioncore.node-power/v1"
|
||||
class BoardPower:
|
||||
# All access is under FleetRegistry.lock; no disk queue or background retry.
|
||||
def __init__(self):
|
||||
self.notifications = None
|
||||
self.nodes = {}
|
||||
self.operations = {}
|
||||
|
||||
@@ -44,6 +47,13 @@ class BoardPower:
|
||||
"failed": "Борт не смог выполнить выключение. Проверьте состояние системы.",
|
||||
"expired": "Срок действия команды истёк. Выключение не выполнено.",
|
||||
}[state]
|
||||
if (op["state"] in ("accepted", "executing", "submitted") and self.notifications
|
||||
and not op.get("notified")):
|
||||
with suppress(OSError, sqlite3.Error):
|
||||
self.notifications.publish("board.shutdown", f"power:{binding}:{op['id']}",
|
||||
"info", "Питание · " + row["name"],
|
||||
"Борт принял команду штатного выключения.")
|
||||
op["notified"] = True
|
||||
self._expire(op, now)
|
||||
if op["state"] == "queued":
|
||||
return {
|
||||
|
||||
@@ -25,6 +25,11 @@ from .recovery import listener_addresses
|
||||
from .sensor_transient import cache as sensor_transient
|
||||
from .trust import SCHEMA, CoreTrust, PairingError, node_request, parse_invitation, pem, public_id
|
||||
|
||||
from .board_event_transitions import BoardPresence, LINK_TIMEOUT, publish_control
|
||||
from .node_operator_events import accept_operator_events
|
||||
from .uplink_notifications import publish_uplink_applied
|
||||
|
||||
|
||||
class FleetRegistry:
|
||||
"""One writer lock and durable transactions; transport never owns vehicles."""
|
||||
|
||||
@@ -57,6 +62,10 @@ class FleetRegistry:
|
||||
self.rover_telemetry_preferences = RoverTelemetryPreferences(root)
|
||||
from .uplinks import Uplinks
|
||||
self.uplinks = Uplinks(guard=self.rover_control.network_change)
|
||||
from k1link.notifications import NotificationHistory
|
||||
self.notifications = NotificationHistory(root.parent / 'notifications')
|
||||
self.board_presence = BoardPresence(self.notifications)
|
||||
self.power.notifications = self.notifications
|
||||
from .rover_channel import RoverChannel
|
||||
self.rover_channel = RoverChannel(self.rover_control)
|
||||
from .rover_configuration import RoverConfigurations
|
||||
@@ -118,7 +127,10 @@ class FleetRegistry:
|
||||
# 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 previous and previous["binding"]["binding_id"] != row["binding"]["binding_id"]:
|
||||
self.board_presence.links.pop(previous["binding"]["binding_id"], None)
|
||||
if row["enrollment"] == "revoked":
|
||||
self.board_presence.links.pop(row["binding"]["binding_id"], None)
|
||||
self.network_profiles.revoke_node(row["node_id"])
|
||||
self.events.notify()
|
||||
|
||||
@@ -301,7 +313,7 @@ class FleetRegistry:
|
||||
row["enrollment"] == "paired"
|
||||
and last_seen is not None
|
||||
and last_seen >= self.started_at
|
||||
and time.time() - last_seen < 20
|
||||
and time.time() - last_seen < LINK_TIMEOUT
|
||||
)
|
||||
return {
|
||||
"id": row["id"],
|
||||
@@ -438,6 +450,11 @@ class FleetRegistry:
|
||||
self.routers.prune()
|
||||
self.uplinks.prune()
|
||||
active = [row for row in self.rows() if row["enrollment"] in ("pending", "paired")]
|
||||
for row in active:
|
||||
if row["enrollment"] == "paired":
|
||||
with suppress(OSError, sqlite3.Error):
|
||||
self.board_presence.expire(row)
|
||||
publish_control(self.notifications, row, self.rover_control)
|
||||
for address in {address for row in active for address in listener_addresses(row)}:
|
||||
try:
|
||||
self.listen(address)
|
||||
@@ -524,6 +541,11 @@ class FleetRegistry:
|
||||
configuration_response = self.rover_configurations.heartbeat(node_id, value)
|
||||
network_response = self.network_profiles.heartbeat(row, value)
|
||||
uplink_response = self.uplinks.heartbeat(row, value)
|
||||
try:
|
||||
self.notifications.uplink(row, self.uplinks.events(row))
|
||||
publish_uplink_applied(self.notifications, row, self.uplinks)
|
||||
except (OSError, sqlite3.Error):
|
||||
logging.getLogger(__name__).warning('Notification history unavailable')
|
||||
archive_ack = None
|
||||
archive_started = time.monotonic()
|
||||
try:
|
||||
@@ -539,6 +561,12 @@ class FleetRegistry:
|
||||
archive_elapsed = time.monotonic() - archive_started
|
||||
enrollment_response = self.device_enrollment.heartbeat(row, value)
|
||||
router_response = self.routers.heartbeat(row, value)
|
||||
try:
|
||||
from .router_notifications import publish_router_results, publish_router_incidents
|
||||
publish_router_results(self.notifications, row, self.routers.pending)
|
||||
publish_router_incidents(self.notifications, row, self.routers.latest.get(node_id))
|
||||
except (OSError, sqlite3.Error):
|
||||
logging.getLogger(__name__).warning('Router notification history unavailable')
|
||||
host = value.get("host")
|
||||
if (
|
||||
not isinstance(host, dict)
|
||||
@@ -569,13 +597,22 @@ class FleetRegistry:
|
||||
if archive_elapsed > .025 or save_elapsed > .025:
|
||||
logging.getLogger(__name__).warning(
|
||||
"fleet heartbeat timing archive_ms=%.1f save_ms=%.1f", archive_elapsed*1000, save_elapsed*1000)
|
||||
with suppress(OSError, sqlite3.Error):
|
||||
self.board_presence.received(row)
|
||||
monitor_ack = None
|
||||
try:
|
||||
monitor_ack = self.monitor.submit(node_id, value.get("monitor"))
|
||||
except (ValueError, TypeError, KeyError, sqlite3.Error):
|
||||
# Telemetry persistence failure must not block device control.
|
||||
pass
|
||||
event_ack = {}
|
||||
if value.get('operator_events_v1'):
|
||||
try:
|
||||
event_ack = accept_operator_events(self.notifications, row, value['operator_events_v1'])
|
||||
except (OSError, sqlite3.Error):
|
||||
logging.getLogger(__name__).warning('Operator events awaiting storage')
|
||||
return 200, {
|
||||
**event_ack,
|
||||
"vesc_configurations_ack": archive_ack,
|
||||
"monitor_ack": monitor_ack,
|
||||
"ok": True,
|
||||
@@ -611,4 +648,6 @@ class FleetRegistry:
|
||||
"at": now, "binding_id": row["binding"]["binding_id"],
|
||||
"agent_instance_id": binding.agent_instance_id,
|
||||
}
|
||||
with suppress(OSError, sqlite3.Error):
|
||||
self.board_presence.received(row)
|
||||
return 200, {"ok": True, "heartbeat_encoding": "gzip"}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Publish outcomes of operator commands independently of the settings window."""
|
||||
|
||||
import hashlib
|
||||
|
||||
|
||||
def publish_router_results(history, row, pending):
|
||||
for (vehicle, operation), entry in pending.items():
|
||||
if vehicle != row["id"] or entry["binding"] != row["binding"]["binding_id"]:
|
||||
continue
|
||||
receipt = entry["public"]
|
||||
state = receipt["state"]
|
||||
if receipt.get("action") != "policy" or state not in {"complete", "error", "unknown"}:
|
||||
continue
|
||||
# A late definitive result may follow an unconfirmed timeout.
|
||||
if entry.get("notified_state") == state:
|
||||
continue
|
||||
if state == "complete":
|
||||
tone = "success"
|
||||
message = (
|
||||
"Роутер подтвердил сохранение и применение настроек. "
|
||||
"Фактический канал показан в обзоре роутера."
|
||||
)
|
||||
elif state == "unknown":
|
||||
tone = "warning"
|
||||
message = (
|
||||
"Результат применения не подтверждён. "
|
||||
"Проверьте текущее состояние роутера перед повторной командой."
|
||||
)
|
||||
else:
|
||||
tone = "error"
|
||||
message = {
|
||||
"router_busy": (
|
||||
"Настройки не применены: роутер занят другой операцией. "
|
||||
"Дождитесь её завершения и повторите применение."
|
||||
),
|
||||
"router_conflict": (
|
||||
"Настройки не применены: состояние роутера изменилось. "
|
||||
"Обновите форму перед новой командой."
|
||||
),
|
||||
"router_unavailable": "Настройки не применены: роутер недоступен.",
|
||||
"access_rejected": "Роутер отклонил доступ. Проверьте настройки доступа.",
|
||||
"expired": "Команда не выполнена: срок запроса истёк.",
|
||||
}.get(
|
||||
receipt.get("error"),
|
||||
"Роутер не подтвердил применение настроек. "
|
||||
"Подробности доступны в разделе «Управление».",
|
||||
)
|
||||
identity = (
|
||||
"router:"
|
||||
+ hashlib.sha256(
|
||||
f"{row['node_id']}:{entry['binding']}:{operation}:{state}".encode()
|
||||
).hexdigest()
|
||||
)
|
||||
kind = "router.applied" if state == "complete" else "router.error"
|
||||
history.publish(kind, identity, tone, "Режим роутера · " + row["name"], message)
|
||||
entry["notified_state"] = state
|
||||
|
||||
|
||||
def publish_router_incidents(history, row, cached):
|
||||
if not cached or cached.get("invalid") or cached["binding"] != row["binding"]["binding_id"]:
|
||||
return
|
||||
snapshot = cached["state"]
|
||||
last = snapshot["journal"]["last_sequence"]
|
||||
scope = row["node_id"] + ":" + cached["binding"]
|
||||
previous = history.journal_position(scope)
|
||||
if previous == last:
|
||||
return
|
||||
if previous is not None and previous < last:
|
||||
names = {
|
||||
"aggregation": "Агрегация",
|
||||
"direct": "Одна SIM-карта",
|
||||
"ready": "Доступен",
|
||||
"unreachable": "Недоступен",
|
||||
"access_required": "Требуется доступ",
|
||||
"access_rejected": "Доступ отклонён",
|
||||
"incompatible": "Несовместим",
|
||||
}
|
||||
for event in snapshot["events"]:
|
||||
key = {
|
||||
"mode_changed": "router.mode",
|
||||
"operator_changed": "router.operator",
|
||||
"availability": "router.availability",
|
||||
}.get(event["code"])
|
||||
if not key or event["sequence"] <= previous:
|
||||
continue
|
||||
label = {
|
||||
"router.mode": "Режим роутера",
|
||||
"router.operator": f"Оператор SIM{event['slot']}",
|
||||
"router.availability": "Связь с роутером",
|
||||
}[key]
|
||||
before, after = (
|
||||
names.get(event[k], event[k]) or "Нет данных" for k in ("before", "after")
|
||||
)
|
||||
identity = f"router:{scope}:{event['boot_id']}:{event['sequence']}"
|
||||
tone = (
|
||||
("warning" if event["after"] != "ready" else "success")
|
||||
if key == "router.availability"
|
||||
else "info"
|
||||
)
|
||||
history.publish(
|
||||
key,
|
||||
identity,
|
||||
tone,
|
||||
label + " · " + row["name"],
|
||||
f"{before} → {after}",
|
||||
at=event["at"],
|
||||
)
|
||||
history.advance_journal(scope, last)
|
||||
@@ -8,6 +8,7 @@ import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
from .board_event_transitions import ControlTransitions
|
||||
from .rover_diagnostics import RoverDiagnostics
|
||||
from .rover_observation_evidence import ObservationEvidence
|
||||
from .rover_telemetry_policy import DEFAULT_MS, telemetry_stop_ms
|
||||
@@ -25,7 +26,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, self.diagnostic_root / hashlib.sha256(node.encode()).hexdigest()[:24] if self.diagnostic_root is not None else None),"observation":ObservationEvidence(self.clock)}
|
||||
self.boards[node]={"operator_transitions":ControlTransitions(),"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):
|
||||
@@ -78,6 +79,7 @@ class RoverControl:
|
||||
if session is None:
|
||||
return
|
||||
b["session"] = None
|
||||
b["operator_transitions"].stop(reason, session, max(0., self.clock() - b["seen"]) * 1000)
|
||||
observed = b["snapshot"] if snapshot is None else snapshot
|
||||
b["diagnostics"].control_stop.record(
|
||||
reason, session, core_instance=self.clock_id,
|
||||
@@ -291,6 +293,8 @@ class RoverControl:
|
||||
s = None
|
||||
command = None
|
||||
if s:
|
||||
if publish and snapshot.get("session_id") == s["id"] and snapshot.get("state") in ("ready", "driving"):
|
||||
b["operator_transitions"].ready(s["id"])
|
||||
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"].watch_required(), "command": command,
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Only a confirmed operator switch to the verified target is an applied event."""
|
||||
|
||||
|
||||
def publish_uplink_applied(history, row, uplinks):
|
||||
node = row["node_id"]
|
||||
operation = uplinks.operations.get(node)
|
||||
if (
|
||||
not operation
|
||||
or operation["phase"] != "applied"
|
||||
or operation.get("notified")
|
||||
or operation.get("reported_only")
|
||||
or operation["binding"] != row["binding"]["binding_id"]
|
||||
):
|
||||
return
|
||||
view = uplinks.view(row)
|
||||
if not view["path_verified"] or view["current_id"] != operation["target"]:
|
||||
return
|
||||
candidate = next((c for c in view["candidates"] if c["id"] == view["current_id"]), None)
|
||||
if candidate:
|
||||
channel = "Wi-Fi" if candidate["kind"] == "wifi" else "Ethernet"
|
||||
history.publish(
|
||||
"uplink.applied",
|
||||
f"uplink:{node}:{operation['id']}",
|
||||
"success",
|
||||
"Связь с бортом · " + row["name"],
|
||||
f"Борт подтвердил связь с Core через {channel}.",
|
||||
)
|
||||
operation["notified"] = True
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Bounded operator notification history, separate from live telemetry."""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from .operator_events import CATALOG, DEFAULT_OFF, KEYS
|
||||
|
||||
MAX_ITEMS = 5000
|
||||
|
||||
|
||||
class NotificationHistory:
|
||||
def __init__(self, root: Path):
|
||||
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
self.subscribers = {}
|
||||
self.subscriber_lock = threading.Lock()
|
||||
self.path = root / "history.sqlite3"
|
||||
with self.connect() as db:
|
||||
db.execute("""CREATE TABLE IF NOT EXISTS notifications (
|
||||
sequence INTEGER PRIMARY KEY AUTOINCREMENT, identity TEXT UNIQUE NOT NULL,
|
||||
at REAL NOT NULL, tone TEXT NOT NULL, title TEXT NOT NULL,
|
||||
description TEXT NOT NULL, source TEXT NOT NULL, read INTEGER NOT NULL DEFAULT 0
|
||||
)""")
|
||||
db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS network_receipts "
|
||||
"(node TEXT PRIMARY KEY, ids TEXT NOT NULL)"
|
||||
)
|
||||
db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS event_preferences "
|
||||
"(kind TEXT PRIMARY KEY, enabled INTEGER NOT NULL)"
|
||||
)
|
||||
db.execute(
|
||||
"CREATE TABLE IF NOT EXISTS router_journals "
|
||||
"(scope TEXT PRIMARY KEY, sequence INTEGER NOT NULL)"
|
||||
)
|
||||
columns = {column["name"] for column in db.execute("PRAGMA table_info(notifications)")}
|
||||
if "visible" not in columns:
|
||||
db.execute(
|
||||
"ALTER TABLE notifications ADD COLUMN visible INTEGER NOT NULL DEFAULT 1"
|
||||
)
|
||||
self.path.chmod(0o600)
|
||||
self.journal_position = lru_cache(maxsize=128)(self._journal_position)
|
||||
|
||||
def _journal_position(self, scope):
|
||||
with self.connect() as db:
|
||||
row = db.execute(
|
||||
"SELECT sequence FROM router_journals WHERE scope=?", (scope,)
|
||||
).fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
def advance_journal(self, scope, sequence):
|
||||
with self.connect() as db:
|
||||
db.execute("INSERT OR REPLACE INTO router_journals VALUES (?,?)", (scope, sequence))
|
||||
self.journal_position.cache_clear()
|
||||
|
||||
@contextmanager
|
||||
def connect(self):
|
||||
db = sqlite3.connect(self.path, timeout=3)
|
||||
db.row_factory = sqlite3.Row
|
||||
try:
|
||||
with db:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@contextmanager
|
||||
def subscribe(self):
|
||||
signal = asyncio.Event()
|
||||
with self.subscriber_lock:
|
||||
self.subscribers[signal] = asyncio.get_running_loop()
|
||||
try:
|
||||
yield signal
|
||||
finally:
|
||||
with self.subscriber_lock:
|
||||
self.subscribers.pop(signal, None)
|
||||
|
||||
def changed(self):
|
||||
with self.subscriber_lock:
|
||||
for signal, loop in self.subscribers.items():
|
||||
if not loop.is_closed():
|
||||
loop.call_soon_threadsafe(signal.set)
|
||||
|
||||
def preferences(self):
|
||||
with self.connect() as db:
|
||||
stored = dict(db.execute("SELECT kind,enabled FROM event_preferences"))
|
||||
return [
|
||||
dict(
|
||||
key=key,
|
||||
section=section,
|
||||
group=group,
|
||||
label=label,
|
||||
enabled=bool(stored.get(key, key not in DEFAULT_OFF)),
|
||||
)
|
||||
for key, section, group, label in CATALOG
|
||||
]
|
||||
|
||||
def configure(self, kind, enabled):
|
||||
if kind not in KEYS or type(enabled) is not bool:
|
||||
raise ValueError("Неизвестная настройка событий.")
|
||||
with self.connect() as db:
|
||||
db.execute("INSERT OR REPLACE INTO event_preferences VALUES (?,?)", (kind, enabled))
|
||||
return self.preferences()
|
||||
|
||||
def publish(self, kind, identity, tone, title, description, *, at=None):
|
||||
if kind not in KEYS:
|
||||
raise ValueError("Unknown event kind")
|
||||
return self.add(identity, tone, title, description, kind.split(".")[0], kind=kind, at=at)
|
||||
|
||||
def add(self, identity, tone, title, description="", source="interface", *, kind=None, at=None):
|
||||
with self.connect() as db:
|
||||
inserted = db.execute(
|
||||
"INSERT OR IGNORE INTO notifications "
|
||||
"(identity,at,tone,title,description,source,visible) VALUES (?,?,?,?,?,?,"
|
||||
"COALESCE((SELECT enabled FROM event_preferences WHERE kind=?),?))",
|
||||
(
|
||||
identity,
|
||||
time.time() if at is None else at,
|
||||
tone,
|
||||
title[:160],
|
||||
description[:1200],
|
||||
source[:160],
|
||||
kind,
|
||||
kind not in DEFAULT_OFF,
|
||||
),
|
||||
)
|
||||
if inserted.rowcount:
|
||||
db.execute(
|
||||
"DELETE FROM notifications WHERE sequence <= "
|
||||
"(SELECT sequence FROM notifications "
|
||||
"ORDER BY sequence DESC LIMIT 1 OFFSET ?)",
|
||||
(MAX_ITEMS,),
|
||||
)
|
||||
record = dict(
|
||||
db.execute("SELECT * FROM notifications WHERE identity=?", (identity,)).fetchone()
|
||||
)
|
||||
if inserted.rowcount and record["visible"]:
|
||||
self.changed()
|
||||
return record
|
||||
|
||||
def listing(self, after=0, before=0, *, ascending=False):
|
||||
with self.connect() as db:
|
||||
db.execute("BEGIN")
|
||||
if after or ascending:
|
||||
rows = db.execute(
|
||||
"SELECT * FROM notifications WHERE visible=1 AND sequence>? "
|
||||
"ORDER BY sequence LIMIT 100",
|
||||
(after,),
|
||||
)
|
||||
elif before:
|
||||
rows = db.execute(
|
||||
"SELECT * FROM notifications WHERE visible=1 AND sequence<? "
|
||||
"ORDER BY sequence DESC LIMIT 100",
|
||||
(before,),
|
||||
)
|
||||
else:
|
||||
rows = db.execute(
|
||||
"SELECT * FROM notifications WHERE visible=1 ORDER BY sequence DESC LIMIT 100"
|
||||
)
|
||||
items = [dict(row) for row in rows]
|
||||
unread = db.execute(
|
||||
"SELECT count(*) FROM notifications WHERE visible=1 AND read=0"
|
||||
).fetchone()[0]
|
||||
maximum = db.execute(
|
||||
"SELECT COALESCE(max(sequence),0) FROM notifications WHERE visible=1"
|
||||
).fetchone()[0]
|
||||
return dict(items=items, unread=unread, latest=maximum, retention_limit=MAX_ITEMS)
|
||||
|
||||
def read(self, through):
|
||||
with self.connect() as db:
|
||||
changed = db.execute(
|
||||
"UPDATE notifications SET read=1 WHERE visible=1 AND read=0 AND sequence<=?",
|
||||
(through,),
|
||||
).rowcount
|
||||
if changed:
|
||||
self.changed()
|
||||
|
||||
def uplink(self, row, events):
|
||||
names = {"wifi": "Wi-Fi", "ethernet": "Ethernet"}
|
||||
with self.connect() as db:
|
||||
previous = db.execute(
|
||||
"SELECT ids FROM network_receipts WHERE node=?", (row["node_id"],)
|
||||
).fetchone()
|
||||
seen = json.loads(previous["ids"]) if previous else []
|
||||
fresh = [event for event in events if event["id"] not in seen]
|
||||
for event in fresh:
|
||||
identity = (
|
||||
"uplink:"
|
||||
+ hashlib.sha256((row["node_id"] + ":" + event["id"]).encode()).hexdigest()
|
||||
)
|
||||
source, target = names[event["source"]], names[event["target"]]
|
||||
if event["kind"] == "manual_rollback":
|
||||
message = (
|
||||
f"Не удалось установить связь с Core через {source}. "
|
||||
f"Восстановлено подключение по {target}."
|
||||
)
|
||||
else:
|
||||
message = f"{source} недоступен. Связь восстановлена через {target}."
|
||||
kind = "uplink.rollback" if event["kind"] == "manual_rollback" else "uplink.fallback"
|
||||
self.publish(
|
||||
kind,
|
||||
identity,
|
||||
"warning",
|
||||
"Связь с бортом · " + row["name"],
|
||||
message,
|
||||
at=event["at"],
|
||||
)
|
||||
if fresh:
|
||||
with self.connect() as db:
|
||||
db.execute(
|
||||
"INSERT OR REPLACE INTO network_receipts (node,ids) VALUES (?,?)",
|
||||
(row["node_id"], json.dumps([e["id"] for e in events][-8:])),
|
||||
)
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Operator-selectable events. Keys are stable across UI translations and releases."""
|
||||
|
||||
# key, section, group, operator-facing label
|
||||
CATALOG = (
|
||||
("uplink.applied", "Сеть", "Бортовой компьютер", "Ручное переключение подключения"),
|
||||
("uplink.fallback", "Сеть", "Бортовой компьютер", "Переход на резервный канал"),
|
||||
("uplink.rollback", "Сеть", "Бортовой компьютер", "Откат переключения"),
|
||||
("router.applied", "Сеть", "Роутер", "Подтверждение настроек"),
|
||||
("router.error", "Сеть", "Роутер", "Ошибки и неподтверждённые команды"),
|
||||
("router.availability", "Сеть", "Роутер", "Изменение доступности роутера"),
|
||||
("router.mode", "Сеть", "Роутер", "Смена режима подключения"),
|
||||
("router.operator", "Сеть", "Роутер", "Смена оператора SIM-карты"),
|
||||
("delivery.loss", "Сеть", "Бортовой компьютер", "Потеря подтверждения доставки телеметрии"),
|
||||
("delivery.recovery", "Сеть", "Бортовой компьютер", "Восстановление доставки телеметрии"),
|
||||
("telemetry.loss", "Управление", "VESC", "Потеря телеметрии контроллеров"),
|
||||
("telemetry.recovery", "Управление", "VESC", "Восстановление телеметрии"),
|
||||
("board.lost", "Сеть", "Бортовой компьютер", "Потеря связи с бортом"),
|
||||
("board.restored", "Сеть", "Бортовой компьютер", "Восстановление связи с бортом"),
|
||||
("board.shutdown", "Борт", "Питание", "Начало штатного выключения"),
|
||||
("board.boot", "Борт", "Питание", "Новая загрузка бортового компьютера"),
|
||||
("camera.loss", "Камера", "USB", "Отключение камеры"),
|
||||
("camera.recovery", "Камера", "USB", "Возврат камеры"),
|
||||
("frames.loss", "Камера", "Видеопоток", "Камера перестала выдавать кадры"),
|
||||
("frames.recovery", "Камера", "Видеопоток", "Поступление кадров восстановлено"),
|
||||
("control.stop", "Управление", "Защита", "Защитная остановка управления"),
|
||||
("control.ready", "Управление", "Защита", "Управление снова готово"),
|
||||
("thermal.loss", "Борт", "Процессор", "Включение теплового ограничения CPU"),
|
||||
("thermal.recovery", "Борт", "Процессор", "Снятие теплового ограничения CPU"),
|
||||
)
|
||||
KEYS = {entry[0] for entry in CATALOG}
|
||||
|
||||
DEFAULT_OFF = {"uplink.applied", "router.applied", "router.mode", "router.operator"}
|
||||
@@ -115,6 +115,7 @@ from k1link.web.fleet_api import router as fleet_router
|
||||
from k1link.web.frontend_assets import ControlStationStaticFiles, frontend_build_id
|
||||
from k1link.web.independent_equipment_api import router as equipment_router
|
||||
from k1link.web.installer_api import router as installer_router
|
||||
from k1link.web.notifications_api import router as notifications_router
|
||||
from k1link.web.local_storage_api import build_local_storage_router
|
||||
from k1link.web.map_api import (
|
||||
MapGatewayConfiguration,
|
||||
@@ -882,6 +883,7 @@ app.state.system_connections_root = REPOSITORY_ROOT / ".runtime" / "system"
|
||||
app.include_router(server_catalog_router)
|
||||
app.include_router(network_speedtest_router)
|
||||
app.include_router(installer_router)
|
||||
app.include_router(notifications_router)
|
||||
app.include_router(rover_router)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Local operator history: independently dismissible toasts and durable messages."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel, ConfigDict, Field, StrictBool
|
||||
|
||||
from k1link.fleet.registry import FleetRegistry
|
||||
from k1link.web.fleet_api import local_operator
|
||||
|
||||
router = APIRouter(prefix="/api/v1/notifications", tags=["notifications"])
|
||||
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
|
||||
|
||||
|
||||
class Publish(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
identity: str = Field(pattern=r"^ui:[a-f0-9-]{36}$")
|
||||
tone: Literal["success", "error", "warning", "info"]
|
||||
title: str = Field(min_length=1, max_length=160)
|
||||
description: str = Field(default="", max_length=1200)
|
||||
|
||||
|
||||
class Read(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
through: int = Field(ge=0, le=9223372036854775807)
|
||||
|
||||
|
||||
@router.get("")
|
||||
def listing(
|
||||
response: Response,
|
||||
fleet: Fleet,
|
||||
after: int = Query(0, ge=0, le=9223372036854775807),
|
||||
before: int = Query(0, ge=0, le=9223372036854775807),
|
||||
):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return fleet.notifications.listing(after=after, before=before)
|
||||
|
||||
|
||||
@router.post("")
|
||||
def publish(body: Publish, fleet: Fleet):
|
||||
return fleet.notifications.add(**body.model_dump())
|
||||
|
||||
|
||||
@router.post("/read")
|
||||
def read(body: Read, fleet: Fleet):
|
||||
fleet.notifications.read(body.through)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
class Preference(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
key: str = Field(max_length=64)
|
||||
enabled: StrictBool
|
||||
|
||||
|
||||
@router.get("/preferences")
|
||||
def preferences(response: Response, fleet: Fleet):
|
||||
response.headers["Cache-Control"] = "no-store"
|
||||
return fleet.notifications.preferences()
|
||||
|
||||
|
||||
@router.patch("/preferences")
|
||||
def configure(body: Preference, fleet: Fleet):
|
||||
try:
|
||||
return fleet.notifications.configure(body.key, body.enabled)
|
||||
except ValueError as error:
|
||||
raise HTTPException(422, str(error)) from error
|
||||
|
||||
|
||||
@router.get("/events")
|
||||
async def events(
|
||||
request: Request, fleet: Fleet, after: int = Query(0, ge=0, le=9223372036854775807)
|
||||
):
|
||||
history = fleet.notifications
|
||||
resumed = request.headers.get("last-event-id", "")
|
||||
cursor = max(after, int(resumed)) if re.fullmatch("[0-9]{1,18}", resumed) else after
|
||||
|
||||
async def stream():
|
||||
nonlocal cursor
|
||||
with history.subscribe() as changed:
|
||||
yield "retry: 3000\n\n"
|
||||
while True:
|
||||
changed.clear()
|
||||
page = await asyncio.to_thread(history.listing, after=cursor, ascending=True)
|
||||
if page["items"]:
|
||||
cursor = page["items"][-1]["sequence"]
|
||||
yield f"id: {cursor}\ndata: {json.dumps(page, ensure_ascii=False)}\n\n"
|
||||
if cursor >= page["latest"]:
|
||||
await changed.wait()
|
||||
|
||||
return StreamingResponse(
|
||||
stream(),
|
||||
media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},
|
||||
)
|
||||
Reference in New Issue
Block a user