feat(events): deliver state changes to the configurable operator event center

This commit is contained in:
DCCONSTRUCTIONS
2026-11-21 20:58:27 +03:00
parent d4ed96f3cd
commit 1b67d5f7df
35 changed files with 2058 additions and 8 deletions
+6
View File
@@ -50,6 +50,8 @@ import type {
import { useRecordedSessionAdmission } from "./core/observation/useRecordedSessionAdmission";
import { useWorkspaceLayoutProfile } from "./core/observation/useWorkspaceLayoutProfile";
import { useSessionDisplayProfile } from "./core/observation/useSessionDisplayProfile";
import { EventPanel } from './components/notifications/NotificationHost';
import { useNotifications } from './core/notifications/useNotificationHistory';
import { viewerSettingsTargetIdentity } from "./core/observation/viewerSettingsTarget";
import { resolvePolygonRunRoute } from "./core/polygon/runArchive";
import {
@@ -233,6 +235,7 @@ export default function App() {
);
runtimeUpdateViewerSettingsRef.current = runtime.updateViewerSettings;
replayActiveRef.current = replayPresented;
const notifications = useNotifications();
const sessionDisplayProfile = useSessionDisplayProfile(replayPresented ? recordedReplay?.sessionId ?? null : null, (settings) => {
sceneSettingsRef.current = settings;
displayDraftRef.current = settings;
@@ -691,6 +694,7 @@ export default function App() {
displayName="DC"
subtitle="Mission Core"
triggerLabel={null}
headerAction={{label: notifications.unread ? `Центр событий · непрочитанных: ${notifications.unread}` : 'Центр событий', pressed: notifications.open, controls: 'operator-events', onSelect: () => notifications.setOpen(open => !open)}}
actions={[
{
id: "refresh",
@@ -721,6 +725,8 @@ export default function App() {
}
contentOpen={workspace.contentOpen && activeDefinition !== null}
contentExpanded
endPanel={<EventPanel/>}
endPanelOpen={notifications.open}
header={header}
stage={activeDefinition ? null :
<LandingStage
@@ -0,0 +1,54 @@
import {useEffect, useState} from 'react';
import {Button, Checker, Description, FeatureSettingsWindow, SettingsCard} from '@nodedc/ui-react';
import {notificationRequest} from '../../core/notifications/history';
interface Preference {
key: string;
section: string;
group: string;
label: string;
enabled: boolean;
}
export function EventSettings({onClose}: {onClose: () => void}) {
const [items, setItems] = useState<Preference[]>([]);
const [section, setSection] = useState('Сеть');
const [error, setError] = useState('');
const [saving, setSaving] = useState(false);
const [attempt, setAttempt] = useState(0);
useEffect(() => {
let active = true;
setError('');
notificationRequest<Preference[]>('/preferences').then(result => {
if (active) setItems(result);
}).catch(() => { if (active) setError('Не удалось загрузить настройки событий.'); });
return () => { active = false; };
}, [attempt]);
async function configure(key: string, enabled: boolean) {
setSaving(true);
setError('');
try {
setItems(await notificationRequest<Preference[]>('/preferences', 'PATCH', {key, enabled}));
} catch {
setError('Не удалось подтвердить изменение. Обновите настройки и повторите попытку.');
} finally {
setSaving(false);
}
}
const sections = [...new Set(items.map(item => item.section))];
const current = items.filter(item => item.section === section);
const groups = [...new Set(current.map(item => item.group))];
return <FeatureSettingsWindow open title="Настройки центра событий"
identity={{title: 'Центр событий', avatarLabel: 'ЦС'}}
sections={sections.map(label => ({id: label, label, icon: label === 'Сеть' ? 'network' : 'activity'}))}
activeSection={section} onSectionChange={setSection} onClose={onClose}>
{error && <><Description role="alert">{error}</Description><Button onClick={() => setAttempt(n => n + 1)}>Обновить настройки</Button></>}
{!error && !items.length && <Description role="status">Загружаем настройки…</Description>}
{groups.map(group => <SettingsCard key={group} title={group}>
{current.filter(item => item.group === group).map(item => <Checker key={item.key}
label={item.label} checked={item.enabled} disabled={saving}
onChange={enabled => void configure(item.key, enabled)}/>)}
</SettingsCard>)}
</FeatureSettingsWindow>;
}
@@ -0,0 +1,47 @@
import {useEffect, useRef, useState, type ReactNode} from 'react';
import {ApplicationSidePanel, Button, Description, Icon, IconButton, ResourceList, ResourceRow, StatusBadge, ToastStack} from '@nodedc/ui-react';
import {NotificationContext, useNotificationHistory, useNotifications} from '../../core/notifications/useNotificationHistory';
import type {NotificationTone} from '../../core/notifications/history';
import {EventSettings} from './EventSettings';
const tones = {success: 'success', warning: 'warning', error: 'danger', info: 'neutral'} as const;
const labels: Record<NotificationTone, string> = {success: 'Успешно', warning: 'Внимание', error: 'Ошибка', info: 'Информация'};
export function NotificationHost({children}: {children: ReactNode}) {
const state = useNotificationHistory();
return <NotificationContext.Provider value={state}>
{children}
<ToastStack items={state.toasts} onDismiss={state.dismiss} observe={false}/>
</NotificationContext.Provider>;
}
export function EventPanel() {
const state = useNotifications();
const [settings, setSettings] = useState(false);
const gear = useRef<HTMLButtonElement>(null);
const close = () => {
state.setOpen(false);
document.querySelector<HTMLButtonElement>('[aria-controls="operator-events"]')?.focus();
};
useEffect(() => {
if (!state.open) return;
gear.current?.focus({preventScroll: true});
}, [state.open]);
return <ApplicationSidePanel id="operator-events" eyebrow="Mission Core" title="Центр событий"
inert={!state.open} aria-label="Центр событий" closeLabel="Закрыть центр событий" onClose={close}
onKeyDown={event => {
if (event.key === 'Escape' && !settings) { event.stopPropagation(); close(); }
}}
headerActions={<IconButton ref={gear} label="Настройки центра событий" onClick={() => setSettings(true)}><Icon name="settings"/></IconButton>}>
{state.error && <Description role="status">{state.error}</Description>}
{!state.items.length && <Description>{state.loading ? 'Получаем события…' : 'Событий пока нет.'}</Description>}
<ResourceList aria-label="История событий">{state.items.map(item => <li key={item.identity}>
<ResourceRow title={item.title} description={item.description}
metadata={new Date(item.at * 1000).toLocaleString('ru-RU')}
statusPlacement="leading" status={<StatusBadge variant="indicator" tone={tones[item.tone]}
aria-label={labels[item.tone]} title={labels[item.tone]}/>}/>
</li>)}</ResourceList>
{state.more && <Button loading={state.loading} onClick={() => void state.loadMore()}>Показать ещё</Button>}
{settings && state.open && <EventSettings onClose={() => setSettings(false)}/>}
</ApplicationSidePanel>;
}
@@ -0,0 +1,22 @@
export type NotificationTone='success'|'error'|'warning'|'info';
export interface NotificationMessage {id:string;tone:NotificationTone|'loading';title:string;description?:string;durationMs?:number|null}
export interface NotificationRecord {sequence:number;identity:string;at:number;tone:NotificationTone;title:string;description:string;source:string;read:number}
export interface NotificationPage {items:NotificationRecord[];unread:number;latest:number;retention_limit:number}
export async function notificationRequest<T>(path='',method='GET',body?:unknown):Promise<T>{
const response=await fetch('/api/v1/notifications'+path,{method,credentials:'same-origin',cache:'no-store',signal:AbortSignal.timeout(10000),headers:body===undefined?{}:{'Content-Type':'application/json'},body:body===undefined?undefined:JSON.stringify(body)});
if(!response.ok)throw new Error('История уведомлений временно недоступна.');
return response.json();
}
export function mergeNotifications(current:NotificationRecord[],incoming:NotificationRecord[]){
return [...new Map([...current,...incoming].map(item=>[item.sequence,item])).values()].sort((a,b)=>b.sequence-a.sequence).slice(0,5000);
}
export function networkToasts(items:NotificationRecord[],seen:Set<string>,now:number){
const result:NotificationMessage[]=[];
for(const item of items){
if(seen.has(item.identity))continue;
seen.add(item.identity);
if(item.source!=='interface'&&now-item.at<=120&&now>=item.at-10)result.push({id:item.identity,tone:item.tone,title:item.title,description:item.description});
}
while(seen.size>5000)seen.delete(seen.values().next().value!);
return result;
}
@@ -0,0 +1,56 @@
import {createContext,useContext,useEffect,useRef,useState} from 'react';
import {mergeNotifications,networkToasts,notificationRequest,type NotificationMessage,type NotificationPage,type NotificationRecord} from './history';
export function useNotificationHistory(){
const [items,setItems]=useState<NotificationRecord[]>([]),[unread,setUnread]=useState(0),[open,setOpen]=useState(false),[error,setError]=useState(''),[loading,setLoading]=useState(true),[more,setMore]=useState(false),[toasts,setToasts]=useState<NotificationMessage[]>([]);
const seen=useRef(new Set<string>()),readThrough=useRef(0);
useEffect(()=>{
let live=true, stream:EventSource|undefined, retry:ReturnType<typeof setTimeout>|undefined;
async function connect(){
try{
const initial=await notificationRequest<NotificationPage>();
if(!live)return;
setItems(initial.items);setUnread(initial.unread);setMore(initial.items.length===100);
setLoading(false);setError('');
stream=new EventSource('/api/v1/notifications/events?after='+initial.latest);
stream.onopen=()=>{if(live)setError('');};
stream.onerror=()=>{if(live)setError('Восстанавливаем связь с центром событий…');};
stream.onmessage=event=>{
if(!live)return;
const page:NotificationPage=JSON.parse(event.data);
setUnread(page.unread);setError('');
if(page.items.length){
setItems(old=>mergeNotifications(old,page.items));
const incoming=networkToasts(page.items,seen.current,Date.now()/1000);
if(incoming.length)setToasts(old=>[...old,...incoming].slice(-5));
}
};
}catch{
if(live){setLoading(false);setError('Восстанавливаем связь с центром событий…');retry=setTimeout(connect,5000);}
}
}
void connect();
return()=>{live=false;stream?.close();clearTimeout(retry);};
},[]);
const maximum=items[0]?.sequence??0;
useEffect(()=>{
if(!open||!unread||maximum<=readThrough.current)return;
let active=true,timer:ReturnType<typeof setTimeout>|undefined;
async function markRead(){
try{
await notificationRequest('/read','POST',{through:maximum});
if(active){readThrough.current=maximum;setItems(old=>old.map(item=>item.sequence<=maximum?{...item,read:1}:item));}
}catch{if(active)timer=setTimeout(markRead,5000);}
}
void markRead();
return()=>{active=false;clearTimeout(timer);};
},[open,maximum,unread]);
const loadMore=async()=>{
if(loading||!items.length)return;setLoading(true);
try{const page=await notificationRequest<NotificationPage>('?before='+items[items.length-1].sequence);setItems(old=>mergeNotifications(old,page.items));setMore(page.items.length===100);setError('');}
catch(e){setError(e instanceof Error?e.message:'История недоступна.');}finally{setLoading(false);}
};
return {items,unread,open,setOpen,error,loading,more,loadMore,toasts,dismiss:(id:string)=>setToasts(old=>old.filter(item=>item.id!==id))};
}
export const NotificationContext=createContext<ReturnType<typeof useNotificationHistory>|null>(null);
export function useNotifications(){const context=useContext(NotificationContext);if(!context)throw new Error('Notification host missing');return context;}
+2 -1
View File
@@ -7,6 +7,7 @@ import "@nodedc/tokens/themes.css";
import "@nodedc/ui-core/styles.css";
import App from "./App";
import { NotificationHost } from './components/notifications/NotificationHost';
import { installedDevicePlugins, installedNodeSensorContributions } from "./composition/devicePlugins";
import { PlanningTestProvider } from "./core/missions/PlanningTestContext";
import { DevicePluginHostProvider } from "./core/device-plugins/DevicePluginHost";
@@ -27,7 +28,7 @@ createRoot(rootElement).render(
<StrictMode><TooltipProvider>
<DevicePluginHostProvider plugins={installedDevicePlugins} nodeSensorContributions={installedNodeSensorContributions}>
<ComputeContourProvider>
<PlanningTestProvider><App /></PlanningTestProvider>
<PlanningTestProvider><NotificationHost><App /></NotificationHost></PlanningTestProvider>
</ComputeContourProvider>
</DevicePluginHostProvider>
</TooltipProvider></StrictMode>,
@@ -0,0 +1,28 @@
import assert from 'node:assert/strict';
import {after,before,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,merge,network,canSet,pending,canSelect;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
({mergeNotifications:merge,networkToasts:network}=await server.ssrLoadModule('/src/core/notifications/history.ts'));
({canSetFallback:canSet,fallbackPending:pending,canSelectUplink:canSelect}=await server.ssrLoadModule('/src/core/fleet/boardUplink.ts'));});
after(async()=>{await server?.close();});
test('history merges pages without losing dates or read status',()=>{
assert.deepEqual(merge([{sequence:1,read:0},{sequence:3,read:0}],[{sequence:1,read:1},{sequence:2,read:0}]),[{sequence:3,read:0},{sequence:2,read:0},{sequence:1,read:1}]);
});
test('confirmed network transitions toast once; history and UI errors are not replayed',()=>{
const seen=new Set(),message={identity:'transition',source:'uplink',at:1000,tone:'warning',title:'Связь',description:'Ethernet → Wi-Fi'};
assert.equal(network([message],seen,1010).length,1);
assert.equal(network([message],seen,1011).length,0);
assert.equal(network([{...message,identity:'old',at:500},{...message,identity:'ui',source:'interface'}],seen,1011).length,0);
});
test('router outcomes toast globally once even outside the router window',()=>{
const seen=new Set(),message={identity:'router:operation',source:'router',at:1000,tone:'error',title:'Режим роутера',description:'Роутер занят'};
assert.equal(network([message],seen,1010).length,1);
assert.equal(network([message],seen,1011).length,0);
assert.equal(network([{...message,identity:'old',at:500}],seen,1011).length,0);
});
test('fallback control requires live support and does not turn a queued write into saved state',()=>{
const v={available:true,path_verified:true,fallback:{enabled:true,revision:0},current_id:'a',candidates:[{id:'b',verified:true}],operation:null};
assert.ok(canSet(v));assert.ok(!canSet({...v,fallback:null}));assert.ok(!canSet({...v,path_verified:false}));
const queued={...v,fallback_operation:{phase:'queued'}};assert.ok(pending(queued));assert.ok(!canSet(queued));assert.ok(!canSelect(queued,'b'));assert.equal(queued.fallback.enabled,true);
});
@@ -0,0 +1,258 @@
package node
import (
"context"
"encoding/json"
"log"
"os"
"regexp"
"sync"
"time"
)
// Transitions share the existing authenticated heartbeat. This queue never opens a transport.
type operatorEvent struct {
ID string `json:"id"`
At int64 `json:"at"`
Kind string `json:"kind"`
Device string `json:"device,omitempty"`
Session string `json:"session,omitempty"`
}
type operatorJournal struct {
States map[string]string `json:"states,omitempty"`
Binding string `json:"binding"`
Last string `json:"last"`
Delivery string `json:"delivery"`
Pending []operatorEvent `json:"pending,omitempty"`
}
type operatorOutbox struct {
mu sync.Mutex
path string
data operatorJournal
owner string
bound bool
}
func openOperatorOutbox(path string) *operatorOutbox {
s := &operatorOutbox{path: path}
raw, err := os.ReadFile(path)
if err == nil && len(raw) <= 131072 {
var data operatorJournal
if json.Unmarshal(raw, &data) == nil && len(data.Pending) <= 128 && len(data.States) <= 256 {
s.data = data
}
} else if err != nil && !os.IsNotExist(err) {
log.Printf("operator event journal: %v", err)
}
return s
}
// Ignore observations still arriving from a retired binding after a re-pair.
func (s *operatorOutbox) setOwner(binding string) {
if s == nil {
return
}
s.mu.Lock()
defer s.mu.Unlock()
s.owner, s.bound = binding, true
}
func (s *operatorOutbox) commit(data operatorJournal) bool {
if err := savePrivateJSON(s.path, data); err != nil {
log.Printf("operator event journal: %v", err)
return false
}
s.data = data
return true
}
func (s *operatorOutbox) transition(binding, source, status string, at time.Time) {
s.mu.Lock()
defer s.mu.Unlock()
if s.bound && s.owner != binding {
return
}
data := s.data
if data.Binding != binding {
data = operatorJournal{Binding: binding}
}
previous := &data.Last
if source == "delivery" {
previous = &data.Delivery
}
if status == *previous || (*previous == "" && status != "online") {
return
}
if *previous != "" {
kind := source + ".loss"
if status == "online" {
kind = source + ".recovery"
}
data.enqueue(operatorEvent{ID: token(), At: at.Unix(), Kind: kind})
}
*previous = status
s.commit(data)
}
func (s *operatorOutbox) batch(binding string) []operatorEvent {
if s == nil {
return nil
}
s.mu.Lock()
defer s.mu.Unlock()
if s.data.Binding != binding {
return nil
}
rows := s.data.Pending
return append([]operatorEvent(nil), rows[:min(len(rows), 8)]...)
}
func (s *operatorOutbox) acknowledge(binding string, sent []operatorEvent, raw json.RawMessage) {
if s == nil || len(sent) == 0 {
return
}
var id string
if json.Unmarshal(raw, &id) != nil || id != sent[len(sent)-1].ID {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if s.data.Binding != binding {
return
}
for i, e := range s.data.Pending {
if e.ID == id {
data := s.data
data.Pending = append([]operatorEvent(nil), data.Pending[i+1:]...)
s.commit(data)
return
}
}
}
type operatorSample struct {
snapshot map[string]any
at time.Time
watch bool
}
// The driver intentionally stops refreshing sample ages without a viewer. Do not
// classify that as a fault. Device disappearance is still observable while idle.
func vescEventStatus(sample operatorSample) string {
devices, _ := sample.snapshot["devices"].([]any)
profile, _ := sample.snapshot["profile"].(map[string]any)
bindings, _ := profile["bindings"].(map[string]any)
if sample.snapshot["supported"] != true || len(devices) == 0 {
return "lost"
}
for _, raw := range bindings {
b, _ := raw.(map[string]any)
found := false
for _, r := range devices {
d, _ := r.(map[string]any)
id, _ := b["device_id"].(string)
uuid, _ := b["uuid"].(string)
if id != "" && uuid != "" && d["id"] == id && d["uuid"] == uuid {
found = true
break
}
}
if !found {
return "lost"
}
}
for _, raw := range devices {
d, _ := raw.(map[string]any)
age, ok := finiteNumber(d["age_ms"])
if !ok || age < 0 || age >= 1000 {
if !sample.watch {
return ""
}
return "lost"
}
}
return "online"
}
type operatorDebounce struct {
candidate string
since, last time.Time
}
func (d *operatorDebounce) sample(sample operatorSample) (string, time.Time) {
return d.update(vescEventStatus(sample), sample.at, time.Second)
}
func (d *operatorDebounce) update(status string, at time.Time, maxGap time.Duration) (string, time.Time) {
if status != d.candidate || (maxGap > 0 && at.Sub(d.last) > maxGap) {
d.candidate, d.since = status, at
}
d.last = at
if status != "" && at.Sub(d.since) >= 2*time.Second {
return status, d.since
}
return "", time.Time{}
}
func (s *operatorOutbox) observe(ctx context.Context, binding string, samples <-chan operatorSample, delivery <-chan deliveryOutcome) {
var debounce, transport operatorDebounce
observerStarted := time.Now()
for {
select {
case <-ctx.Done():
return
case result := <-delivery:
if status, at := transport.update(result.status, result.at, 0); status != "" {
s.transition(binding, "delivery", status, at)
}
case sample := <-samples:
s.driverSafety(binding, sample, observerStarted)
if status, at := debounce.sample(sample); status != "" {
s.transition(binding, "telemetry", status, at)
}
}
}
}
type deliveryOutcome struct {
status string
at time.Time
}
func (s *roverStreamState) noteTelemetryDelivery(success bool) {
if s.operatorDelivery == nil {
return
}
status := "lost"
if success {
status = "online"
}
select {
case s.operatorDelivery <- deliveryOutcome{status, time.Now()}:
default:
}
}
// A driver fault can occur after Core has already lost contact. Record the
// driver's receipt, including its original time, without executing any action.
var controlSessionID = regexp.MustCompile("^[0-9a-f]{32}$")
func (s *operatorOutbox) driverSafety(binding string, sample operatorSample, started time.Time) {
stop, _ := sample.snapshot["last_stop"].(map[string]any)
id, _ := stop["session_id"].(string)
if stop["state"] == "fault" && controlSessionID.MatchString(id) {
stamp, _ := stop["at"].(string)
at, err := time.Parse(time.RFC3339Nano, stamp)
if err == nil && !at.Before(started) && !at.After(sample.at.Add(time.Second)) {
s.recordState(binding, "driver-fault", id, operatorEvent{Kind: "control.stop", At: at.Unix(), Session: id}, true)
}
}
if sample.snapshot["state"] != "ready" && sample.snapshot["state"] != "driving" {
return
}
session, _ := sample.snapshot["session_id"].(string)
s.mu.Lock()
fault := s.data.States["driver-fault"]
recovered := s.data.States["driver-recovery"]
eligible := s.data.Binding == binding && fault != "" && fault != recovered && session != fault
s.mu.Unlock()
if eligible && controlSessionID.MatchString(session) {
s.recordState(binding, "driver-recovery", fault, operatorEvent{Kind: "control.ready", At: sample.at.Unix(), Session: session}, true)
}
}
@@ -0,0 +1,179 @@
package node
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestOperatorEventsQuietDebounceAndOfflineReplay(t *testing.T) {
path := filepath.Join(t.TempDir(), "events.json")
out := openOperatorOutbox(path)
var filter operatorDebounce
now := time.Unix(1000, 0)
sample := func(count int, age float64, watch bool) {
snap := map[string]any{"supported": true, "devices": []any{map[string]any{"id": "a", "uuid": "b", "age_ms": age}}}
for i := 0; i < count; i++ {
now = now.Add(250 * time.Millisecond)
if status, at := filter.sample(operatorSample{snap, now, watch}); status != "" {
out.transition("bound", "telemetry", status, at)
}
}
}
sample(100, 14, true)
sample(6, 1200, true)
sample(100, 12, true)
sample(80, 9000, false)
if len(out.batch("bound")) != 0 {
t.Fatal("healthy, idle or transient produced network data")
}
sample(40, 2000, true)
sample(40, 13, true)
batch := out.batch("bound")
if len(batch) != 2 || batch[0].Kind != "telemetry.loss" || batch[1].Kind != "telemetry.recovery" {
t.Fatal(batch)
}
out = openOperatorOutbox(path)
if len(out.batch("other")) != 0 || out.batch("bound")[0].ID != batch[0].ID {
t.Fatal("binding/restart")
}
out.acknowledge("bound", batch, json.RawMessage(`"wrong"`))
if len(out.batch("bound")) != 2 {
t.Fatal("unconfirmed batch erased")
}
raw, _ := json.Marshal(batch[1].ID)
out.acknowledge("bound", batch, raw)
if len(openOperatorOutbox(path).batch("bound")) != 0 {
t.Fatal("confirmed data replayed")
}
}
func TestDeliveryFailureIsIndependentOfLocalVESC(t *testing.T) {
out := openOperatorOutbox(filepath.Join(t.TempDir(), "events.json"))
var filter operatorDebounce
start := time.Unix(1000, 0)
out.transition("board", "telemetry", "online", start)
for i, state := range []string{"online", "online", "online", "lost", "online", "lost", "lost", "lost", "online", "online", "online"} {
if confirmed, at := filter.update(state, start.Add(time.Duration(i)*time.Second), 0); confirmed != "" {
out.transition("board", "delivery", confirmed, at)
}
}
batch := out.batch("board")
if len(batch) != 2 || batch[0].Kind != "delivery.loss" || batch[0].At != 1005 || batch[1].Kind != "delivery.recovery" {
t.Fatal(batch)
}
}
func TestBoardEventTransitionsAcrossBootAndOffline(t *testing.T) {
path := filepath.Join(t.TempDir(), "events.json")
out := openOperatorOutbox(path)
at := time.Unix(1450, 0)
id, second := modelDeviceID(&sensorModels[2], "camera A"), modelDeviceID(&sensorModels[2], "camera B")
a := usbSensor{model: &sensorModels[2], id: id}
b := usbSensor{model: &sensorModels[2], id: second}
for range 30 {
out.observeCameras("owner", []usbSensor{a, b}, map[string]string{id: "online", second: "idle"}, at)
out.observeState("owner", "boot", "boot-1", "board.boot", "", at, false)
out.observeState("owner", "thermal", "online", "thermal.recovery", "", at, false)
}
if got := out.batch("owner"); len(got) != 0 {
t.Fatal("initial inventory generated traffic", got)
}
for range 20 {
out.observeCameras("owner", []usbSensor{a}, map[string]string{id: "lost"}, at)
out.observeState("owner", "thermal", "lost", "thermal.loss", "", at, true)
}
out = openOperatorOutbox(path)
for range 20 {
out.observeCameras("owner", []usbSensor{a, b}, map[string]string{id: "online", second: "idle"}, at)
out.observeState("owner", "thermal", "online", "thermal.recovery", "", at, false)
out.observeState("owner", "shutdown", "boot-1", "board.shutdown", "", at, true)
out.observeState("owner", "boot", "boot-2", "board.boot", "", at, false)
}
seen := map[string]int{}
batch := out.batch("owner")
for _, e := range batch {
seen[e.Kind]++
if e.Kind == "camera.loss" && e.Device != second {
t.Fatal(e)
}
if e.Kind == "frames.loss" && e.Device != id {
t.Fatal(e)
}
}
for _, kind := range []string{"frames.loss", "frames.recovery", "camera.loss", "camera.recovery", "thermal.loss", "thermal.recovery", "board.shutdown", "board.boot"} {
if seen[kind] != 1 {
t.Fatalf("%s: %v", kind, batch)
}
}
ack, _ := json.Marshal(batch[len(batch)-1].ID)
out.acknowledge("owner", batch, ack)
out.observeCameras("owner", []usbSensor{a, b}, map[string]string{id: "idle"}, at)
out.observeCameras("owner", []usbSensor{a, b}, map[string]string{id: "online"}, at)
if len(out.batch("owner")) != 0 || len(out.batch("other")) != 0 {
t.Fatal("idle viewer generated a recovery")
}
}
func TestCPUCoolingScopeAndUnreadableState(t *testing.T) {
root := t.TempDir()
create := func(n, typ, val string) {
p := filepath.Join(root, "sys/class/thermal", n)
if err := os.MkdirAll(p, 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(p, "type"), []byte(typ), 0644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(p, "cur_state"), []byte(val), 0644); err != nil {
t.Fatal(err)
}
}
create("cooling_device0", "Fan", "3")
if cpuCoolingState(root) != "" {
t.Fatal("fan does not prove processor throttling")
}
create("cooling_device1", "Processor", "2")
if cpuCoolingState(root) != "lost" {
t.Fatal("missed thermal limit")
}
create("cooling_device2", "Processor", "unknown")
create("cooling_device1", "Processor", "0")
if cpuCoolingState(root) != "" {
t.Fatal("unknown read reported as recovery")
}
create("cooling_device2", "Processor", "0")
if cpuCoolingState(root) != "online" {
t.Fatal("missed recovery")
}
}
func TestDriverFaultRecoveryAndRetiredBinding(t *testing.T) {
out := openOperatorOutbox(filepath.Join(t.TempDir(), "events.json"))
out.setOwner("board")
now := time.Unix(1000, 0)
ended, next := strings.Repeat("a", 32), strings.Repeat("b", 32)
receipt := map[string]any{"state": "fault", "session_id": ended, "at": now.Format(time.RFC3339Nano)}
snap := map[string]any{"state": "fault", "last_stop": receipt}
sample := operatorSample{snapshot: snap, at: now}
out.driverSafety("board", sample, now.Add(time.Minute))
if len(out.batch("board")) != 0 {
t.Fatal("old receipt replayed")
}
for range 50 {
out.driverSafety("board", sample, now)
}
snap["state"], snap["session_id"] = "ready", next
for range 50 {
out.driverSafety("board", sample, now)
}
out.observeState("retired", "thermal", "lost", "thermal.loss", "", now, true)
out.transition("retired", "telemetry", "online", now)
got := out.batch("board")
if len(got) != 2 || got[0].Kind != "control.stop" || got[0].Session != ended || got[1].Kind != "control.ready" || got[1].Session != next {
t.Fatal(got)
}
}
@@ -0,0 +1,189 @@
package node
import (
"bufio"
"context"
_ "embed"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
// The saved state changes only on an edge. Neither a disk write nor an event
// packet is needed for another identical observation.
func (s *operatorOutbox) observeState(binding, key, value, kind, device string, at time.Time, reportFirst bool) {
s.recordState(binding, key, value, operatorEvent{At: at.Unix(), Kind: kind, Device: device}, reportFirst)
}
func (s *operatorOutbox) recordState(binding, key, value string, event operatorEvent, reportFirst bool) {
if s == nil || binding == "" || value == "" {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if s.bound && s.owner != binding {
return
}
data := s.data
if data.Binding != binding {
data = operatorJournal{Binding: binding}
}
last := data.States[key]
if last == value {
return
}
states := make(map[string]string, len(data.States)+1)
for k, v := range data.States {
states[k] = v
}
// Retire inactive attachments first. Never let a changing USB identity grow the journal forever.
if last == "" && len(states) >= 256 {
for k, v := range states {
if (strings.HasPrefix(k, "camera:") && v == "lost") || (strings.HasPrefix(k, "frames:") && v == "idle") {
delete(states, k)
break
}
}
if len(states) >= 256 {
return
}
}
states[key] = value
data.States = states
if event.Kind != "" && (last != "" || reportFirst) && !(last == "idle" && event.Kind == "frames.recovery") {
event.ID = token()
data.enqueue(event)
}
s.commit(data)
}
func (data *operatorJournal) enqueue(event operatorEvent) {
pending := data.Pending
if len(pending) >= 128 {
pending = pending[1:]
}
data.Pending = append(append([]operatorEvent(nil), pending...), event)
}
func (s *operatorOutbox) observeCameras(binding string, usb []usbSensor, frames map[string]string, at time.Time) {
if s == nil {
return
}
present := map[string]bool{}
for _, u := range usb {
if u.model.ID == "insta360.x4" || u.model.ID == "realsense.d455" {
present[u.id] = true
}
}
s.mu.Lock()
primed := s.data.Binding == binding && s.data.States["usb"] == "known"
var absent []string
if primed {
for k, state := range s.data.States {
if id, ok := strings.CutPrefix(k, "camera:"); ok && state == "online" && !present[id] {
absent = append(absent, id)
}
}
}
s.mu.Unlock()
for _, id := range absent {
s.observeState(binding, "camera:"+id, "lost", "camera.loss", id, at, false)
s.observeState(binding, "frames:"+id, "idle", "", id, at, false)
}
for id := range present {
s.observeState(binding, "camera:"+id, "online", "camera.recovery", id, at, primed)
status := frames[id]
switch status {
case "idle":
s.observeState(binding, "frames:"+id, status, "", id, at, false)
case "online":
s.observeState(binding, "frames:"+id, status, "frames.recovery", id, at, false)
case "lost":
s.observeState(binding, "frames:"+id, status, "frames.loss", id, at, true)
}
}
s.observeState(binding, "usb", "known", "", "", at, false)
}
func cpuCoolingState(root string) string {
paths, _ := filepath.Glob(filepath.Join(root, "sys/class/thermal/cooling_device*"))
known, unknown := false, false
for _, p := range paths {
raw, _ := os.ReadFile(filepath.Join(p, "type"))
typ := strings.ToLower(strings.TrimSpace(string(raw)))
if typ != "processor" && typ != "intel_powerclamp" && !strings.HasPrefix(typ, "thermal-cpufreq") && !strings.HasPrefix(typ, "cpufreq-") {
continue
}
raw, err := os.ReadFile(filepath.Join(p, "cur_state"))
level, e := strconv.Atoi(strings.TrimSpace(string(raw)))
if err != nil || e != nil || level < 0 {
unknown = true
continue
}
known = true
if level > 0 {
return "lost"
}
}
if known && !unknown {
return "online"
}
return ""
}
var linuxBootID = regexp.MustCompile("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$")
func bootIdentity() string {
b, _ := os.ReadFile("/proc/sys/kernel/random/boot_id")
id := strings.TrimSpace(string(b))
if linuxBootID.MatchString(id) {
return id
}
return ""
}
//go:embed operator_shutdown.py
var shutdownSubscriber string
func (p *Pairing) watchShutdown(ctx context.Context) {
if runtime.GOOS != "linux" || p.operatorEvents == nil {
return
}
boot := bootIdentity()
if boot == "" {
return
}
for ctx.Err() == nil {
cmd := exec.CommandContext(ctx, "/usr/bin/python3", "-I", "-c", shutdownSubscriber)
output, err := cmd.StdoutPipe()
if err == nil && cmd.Start() == nil {
scanner := bufio.NewScanner(output)
for scanner.Scan() {
if scanner.Text() != "prepare" {
continue
}
if b := p.roverBinding(); b != nil {
// A Core-initiated shutdown already has an authenticated command receipt.
if p.Power != nil && p.Power.shuttingDown(b.BindingID) {
continue
}
p.operatorEvents.observeState(b.BindingID, "shutdown", boot, "board.shutdown", "", time.Now(), true)
}
}
_ = cmd.Wait()
}
if !roverWait(ctx, 30*time.Second) {
return
}
}
}
func (p *NodePower) shuttingDown(binding string) bool {
p.mu.Lock()
defer p.mu.Unlock()
return p.command.BindingID == binding && (p.result.State == "executing" || p.result.State == "submitted")
}
@@ -0,0 +1,23 @@
"""Subscribe locally to logind. A power cut cannot produce this signal."""
import dbus
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib
DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
def prepare(active):
if active:
print("prepare", flush=True)
bus.add_signal_receiver(
prepare,
"PrepareForShutdown",
"org.freedesktop.login1.Manager",
bus_name="org.freedesktop.login1",
path="/org/freedesktop/login1",
)
GLib.MainLoop().run()
+2
View File
@@ -44,6 +44,7 @@ type PairState struct {
Revocations []CoreBinding `json:"revocations,omitempty"`
}
type Pairing struct {
operatorEvents *operatorOutbox
Power *NodePower
Budget *LinkBudget
Routers *routers.Collector
@@ -74,6 +75,7 @@ func OpenPairing(store *Store, dir, version string, inventory func() Inventory)
p := &Pairing{store: store, path: filepath.Join(dir, "core-binding.json"), now: time.Now, inventory: inventory, version: version, connection: "offline", clients: make(map[string]*http.Client), state: PairState{Schema: PairSchema, Phase: "unpaired"}}
id, name := store.Public()
p.RoverConfiguration = OpenRoverConfiguration(dir, id, name)
p.operatorEvents = openOperatorOutbox(filepath.Join(dir, "operator-events.json"))
data, e := os.ReadFile(p.path)
if os.IsNotExist(e) {
return p, nil
@@ -155,6 +155,7 @@ func (p *Pairing) Run(ctx context.Context) {
p.uplink = newUplink(ctx)
go monitorNetBird(ctx)
go p.networkWatch(ctx)
go p.watchShutdown(ctx)
go p.channel(ctx)
go p.roverChannel(ctx)
var server *http.Server
@@ -307,6 +308,7 @@ func (p *Pairing) sendEncoded(ctx context.Context, b CoreBinding, path string, p
}
func (p *Pairing) channel(ctx context.Context) {
instance := "agent_" + token()
boot := bootIdentity()
var changed <-chan struct{}
var speedChanged <-chan struct{}
if p.Routers != nil {
@@ -348,7 +350,17 @@ func (p *Pairing) channel(ctx context.Context) {
}
if binding != nil {
id, name := p.store.Public()
payload := map[string]any{"schema": PairSchema, "binding_id": binding.BindingID, "node_id": id, "name": name, "version": p.version, "execution_binding": map[string]string{"node_id": id, "agent_instance_id": instance, "platform": "linux"}, "host": p.inventory(), "devices": []any{}}
host := p.inventory()
at := p.now()
p.operatorEvents.observeState(binding.BindingID, "boot", boot, "board.boot", "", at, false)
if status := cpuCoolingState("/"); status != "" {
kind := "thermal.recovery"
if status == "lost" {
kind = "thermal.loss"
}
p.operatorEvents.observeState(binding.BindingID, "thermal", status, kind, "", at, status == "lost")
}
payload := map[string]any{"schema": PairSchema, "binding_id": binding.BindingID, "node_id": id, "name": name, "version": p.version, "execution_binding": map[string]string{"node_id": id, "agent_instance_id": instance, "platform": "linux"}, "host": host, "devices": []any{}}
if p.RoverConfiguration != nil {
payload["rover_configuration"] = p.RoverConfiguration.Snapshot()
}
@@ -366,7 +378,10 @@ func (p *Pairing) channel(ctx context.Context) {
payload["core_endpoint"] = binding.Endpoint
payload["endpoint_revision"] = binding.EndpointRevision
if p.Sensors != nil {
inv := p.Sensors.Inventory()
inv, usb, frames := p.Sensors.inventoryWithCameraState()
if host.USBReadable && usb != nil {
p.operatorEvents.observeCameras(binding.BindingID, usb, frames, p.now())
}
payload["devices"] = inv["items"]
payload["sensor_state"] = inv
payload["sensor_results"] = p.Sensors.RemoteResults()
@@ -384,6 +399,10 @@ func (p *Pairing) channel(ctx context.Context) {
if p.Routers != nil {
payload["routers"] = p.Routers.Snapshot()
}
sentEvents := p.operatorEvents.batch(binding.BindingID)
if len(sentEvents) > 0 {
payload["operator_events_v1"] = sentEvents
}
result, status, e := p.sendHeartbeat(ctx, *binding, payload)
received := time.Now()
var networkRequestResult json.RawMessage
@@ -457,6 +476,7 @@ func (p *Pairing) channel(ctx context.Context) {
}
p.mu.Unlock()
if e == nil && status == http.StatusOK {
p.operatorEvents.acknowledge(binding.BindingID, sentEvents, result["operator_events_ack"])
p.networkLocalAcknowledged(*binding)
}
p.acceptNetworkRequestResult(networkRequestResult)
@@ -20,10 +20,12 @@ import (
// The control loop reads an immutable value, never the background-work mutex.
func (p *Pairing) publishRoverBinding() {
if p.state.Phase != "paired" || p.state.Binding == nil {
p.operatorEvents.setOwner("")
p.roverAuthority.Store(nil)
return
}
b := *p.state.Binding
p.operatorEvents.setOwner(b.BindingID)
p.roverAuthority.Store(&b)
}
func (p *Pairing) roverBinding() *CoreBinding {
@@ -84,6 +86,15 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
ctx, cancel := context.WithCancel(parent)
var workers sync.WaitGroup
defer func() { cancel(); workers.Wait() }()
if p.operatorEvents != nil {
state.operatorSamples = make(chan operatorSample, 1)
state.operatorDelivery = make(chan deliveryOutcome, 2)
workers.Add(1)
go func() {
defer workers.Done()
p.operatorEvents.observe(ctx, b.BindingID, state.operatorSamples, state.operatorDelivery)
}()
}
workers.Add(4)
optional := &http.Client{Transport: transport(), CheckRedirect: telemetry.CheckRedirect}
defer optional.CloseIdleConnections()
@@ -26,6 +26,9 @@ type roverStreamReply struct {
// clocks. Server time was sampled after that send, so it gives an upper bound
// on server-minus-local monotonic offset even on an asymmetric network.
type roverStreamState struct {
operatorDelivery chan deliveryOutcome
operatorSamples chan operatorSample
lastOperatorSample time.Time
budget *LinkBudget
latestDatagram bool
roverDetails bool
@@ -225,6 +228,13 @@ func (s *roverStreamState) deliveredAt(snapshot map[string]any, stop uint64, sam
defer s.mu.Unlock()
s.snapshotAt = sampled
s.snapshot = snapshot
if s.operatorSamples != nil && sampled.Sub(s.lastOperatorSample) >= 250*time.Millisecond {
select {
case s.operatorSamples <- operatorSample{snapshot, sampled, s.watch}:
s.lastOperatorSample = sampled
default:
}
}
s.snapshotClock = s.observationClockAt(sampled)
if stop != 0 && stop == s.stopRevision {
s.stopPending = false
@@ -51,6 +51,7 @@ func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, b
acknowledgedRevision = 0
budgetAt = time.Time{}
if !connected {
state.noteTelemetryDelivery(false)
if !roverWait(ctx, 250*time.Millisecond) {
return
}
@@ -71,6 +72,9 @@ func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, b
state.stopStream()
}
frame := result.frame
if result.sequence > applied {
state.noteTelemetryDelivery(frame.Stage == "")
}
state.recordDev("telemetry", roverTelemetryEvidence(result, state, epoch))
diagnostic.record(result.started, frame)
if frame.Stage == "" || frame.Stage == "telemetry_transport" {
@@ -119,10 +119,14 @@ type usbSensor struct {
// Read-only OS discovery works before any vendor runtime has been installed.
// An absent or duplicated serial is not enough authority to initialize a unit.
func discoverSensors(root string) []usbSensor {
paths, _ := filepath.Glob(filepath.Join(root, "*"))
entries, err := os.ReadDir(root)
if err != nil {
return nil
}
items := []usbSensor{}
counts := map[string]int{}
for _, path := range paths {
for _, entry := range entries {
path := filepath.Join(root, entry.Name())
read := func(name string) string {
data, _ := os.ReadFile(filepath.Join(path, name))
return strings.TrimSpace(string(data))
+12 -1
View File
@@ -209,6 +209,11 @@ func (s *Sensors) modelDriver(ctx context.Context, model *sensorModel, path stri
return result, nil
}
func (s *Sensors) Inventory() map[string]any {
inventory, _, _ := s.inventoryWithCameraState()
return inventory
}
func (s *Sensors) inventoryWithCameraState() (map[string]any, []usbSensor, map[string]string) {
frameState := map[string]string{}
// Concurrent local/remote refreshes must observe the same hotplug generation.
s.inventoryMu.Lock()
defer s.inventoryMu.Unlock()
@@ -232,6 +237,12 @@ func (s *Sensors) Inventory() map[string]any {
continue
}
id, _ := item["id"].(string)
if model.ID == "insta360.x4" {
if status, ok := item["local_frame_state"].(string); ok {
frameState[id] = status
}
delete(item, "local_frame_state")
}
if modelForDevice(id) != model || seen[id] {
continue
}
@@ -326,7 +337,7 @@ func (s *Sensors) Inventory() map[string]any {
for i, value := range preparations {
preparations[i] = preparationView(value)
}
return map[string]any{"schema": "missioncore.node.devices/v1", "items": items, "preparation": preparation, "preparations": preparations, "operations": operations}
return map[string]any{"schema": "missioncore.node.devices/v1", "items": items, "preparation": preparation, "preparations": preparations, "operations": operations}, usb, frameState
}
func (s *Sensors) discovery(id, speed string, online bool) map[string]any {
now := time.Now().UTC().Format(time.RFC3339Nano)
+9
View File
@@ -0,0 +1,9 @@
# Центр событий
Конверт открывает правую панель. Шестерёнка открывает настройки источников. Фильтры хранятся в Core и действуют на будущие записи и всплывающие уведомления. Старые записи сохраняются. Необязательные подтверждения команд и смена оператора выключены по умолчанию. Временные сообщения интерфейса остаются у инициировавшего их действия.
Node определяет потерю и восстановление телеметрии по уже полученным локальным показаниям VESC. Для события состояние должно сохраняться две секунды. Первое рабочее состояние задаёт точку отсчёта. Когда наблюдение закрыто, возраст намеренно закэшированного значения сам по себе не считается потерей. Индикатор в заголовке показывает свежесть данных, доступных в интерфейсе, независимо от фильтров и доставки журнала.
Борт сохраняет до 128 переходов для текущей привязки. До восьми неподтверждённых переходов передаются в обычном исходящем heartbeat. При пустой очереди поле отсутствует. После обрыва и перезапуска неподтверждённые переходы доставляются повторно с исходными временем и идентификатором. Core возвращает подтверждение после записи. Для потери и восстановления подтверждений доставки Node использует результат уже выполняемой передачи телеметрии. Эти события доступны отдельно от потери показаний самих контроллеров.
Core принимает события переключения и журнал роутера из существующих сообщений Node. Браузер один раз открывает историю, затем получает изменения по SSE от Core. При восстановлении соединения используется номер последней записи. История ограничена 5000 записями, размер страницы — 100.
+108
View File
@@ -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()
+96
View File
@@ -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"]}
+10
View File
@@ -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 {
+40 -1
View File
@@ -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"}
+108
View File
@@ -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)
+5 -1
View File
@@ -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,
+28
View File
@@ -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
+218
View File
@@ -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:])),
)
+32
View File
@@ -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"}
+2
View File
@@ -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)
+99
View File
@@ -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"},
)
+138
View File
@@ -0,0 +1,138 @@
"""Disconnected simulated board, actual history and settings, no socket or hardware."""
from test_pairing import cert, create, heartbeat
from test_pairing import setup as setup
from test_rover_control import arm, cmd, exchange
from test_rover_control import hub as hub
from k1link.fleet.board_event_transitions import BoardPresence, publish_control
from k1link.fleet.node_operator_events import accept_operator_events
from k1link.fleet.power import SCHEMA, BoardPower
from k1link.notifications import NotificationHistory
ROW = {
"id": "board",
"node_id": "node",
"binding": {"binding_id": "owner"},
"name": "Тест",
"enrollment": "paired",
}
def test_silence_and_return_use_local_deadline_only(tmp_path):
h = NotificationHistory(tmp_path)
now = [50]
presence = BoardPresence(h, lambda: now[0], lambda: now[0] + 100)
presence.expire(ROW)
presence.received(ROW)
for now[0] in (58, 65, 80):
presence.received(ROW)
assert not h.listing()["items"]
for now[0] in (100, 102, 119):
presence.expire(ROW)
presence.received(ROW)
presence.received(ROW)
now[0] = 150
presence.received(ROW) # Race: heartbeat before the expiry worker.
assert [i["at"] for i in h.listing(ascending=True)["items"]] == [200, 219, 239, 250]
reopened = BoardPresence(h)
reopened.expire(ROW)
assert len(h.listing()["items"]) == 4
def test_power_ack_only_and_switches_and_bounded_replay(tmp_path):
history = NotificationHistory(tmp_path)
power = BoardPower()
power.notifications = history
epoch, ident = "a" * 43, "00000000-0000-4000-8000-000000000000"
data = dict(schema=SCHEMA, epoch=epoch, available=True)
power.heartbeat(ROW, {"power": data})
power.start(ROW, epoch, ident)
assert not history.listing()["items"]
for _ in range(6):
power.heartbeat(ROW, {"power": {**data, "result": {"id": ident, "state": "accepted"}}})
history.configure("frames.loss", False)
data = [
{
"id": str(n) * 43,
"at": 150,
"kind": kind,
**(
{"device": "instax4_" + "f" * 32} if kind.startswith(("frames.", "camera.")) else {}
),
}
for n, kind in enumerate(
(
"board.boot",
"camera.loss",
"frames.loss",
"frames.recovery",
"camera.recovery",
"thermal.loss",
"thermal.recovery",
)
)
]
for _ in range(3):
assert accept_operator_events(history, ROW, data)["operator_events_ack"] == data[-1]["id"]
assert len(history.listing()["items"]) == 7
assert "frames.loss" in {i["key"] for i in history.preferences() if not i["enabled"]}
assert not accept_operator_events(history, ROW, [{**data[1], "device": "forged"}])
assert not accept_operator_events(history, ROW, [{**data[0], "kind": "board.lost"}])
def test_authority_stop_and_new_ready_without_driver_commands(hub, tmp_path): # noqa: F811
control, clock = hub
history = NotificationHistory(tmp_path)
session = arm(control)
# Keep the operator lease alive past the telemetry deadline.
for n in range(2, 15):
clock[0] += 0.085
control.command("node", cmd(session, n))
control.stream("node", "a" * 32)
for _ in range(3):
publish_control(history, ROW, control)
items = history.listing()["items"]
assert len(items) == 1 and "1000 мс" in items[0]["description"]
driver = {"kind": "control.stop", "session": session, "id": "a" * 43, "at": 150}
for _ in range(3):
assert accept_operator_events(history, ROW, [driver])["operator_events_ack"] == driver["id"]
assert len(history.listing()["items"]) == 1
exchange(control)
second = arm(control)
exchange(control, state="ready", session_id=second)
exchange(control, state="ready", session_id=second)
control.command("node", cmd(second, 3, stop=True))
publish_control(history, ROW, control)
assert len(history.listing()["items"]) == 2
assert "готовность" in history.listing()["items"][0]["description"]
def test_paired_heartbeat_and_liveness_emit_without_core_requests(setup):
fleet, _, _, requests = setup
public, _ = create(setup)
fleet.advance(public["id"])
row = fleet.find(public["id"])
leaf, body = cert(row), heartbeat(row)
requests.clear()
now = [100.0]
fleet.board_presence = BoardPresence(fleet.notifications, lambda: now[0], lambda: now[0])
event = {"id": "h" * 43, "kind": "thermal.loss", "at": 100}
for _ in range(3):
status, reply = fleet.receive(
leaf, "/v1/node/heartbeat", {**body, "operator_events_v1": [event]}
)
assert status == 200 and reply["operator_events_ack"] == event["id"]
now[0] = 122
fleet.board_presence.expire(row)
live = {k: v for k, v in body.items() if k not in ("host", "devices")}
assert fleet.receive(leaf, "/v1/node/liveness", {**live, "binding_id": "invalid"})[0] != 200
for _ in range(3):
assert fleet.receive(leaf, "/v1/node/liveness", live)[0] == 200
items = fleet.notifications.listing(ascending=True)["items"]
assert [r["description"] for r in items] == [
"Ядро включило тепловое ограничение процессора.",
"Борт перестал выходить на связь.",
"Связь восстановлена.",
]
assert requests == []
+23
View File
@@ -364,6 +364,29 @@ def test_client_controls_round_trip_with_exact_sim_and_guards(action):
assert fleet.routers.heartbeat(fleet.row, {})["router_commands"] == [request]
def test_policy_notification_uses_confirmed_heartbeat_and_keeps_timeout_identity(tmp_path):
from k1link.fleet.router_notifications import publish_router_results
from k1link.notifications import NotificationHistory
fleet, state, request = ready_client_control()
fleet.row['name'] = 'Test rover'
history = NotificationHistory(tmp_path)
receipt = fleet.routers.control(fleet, 'vehicle', request)
entry = fleet.routers.pending[('vehicle', request['operation_id'])]
entry['deadline'] = time.time() - 1
fleet.routers.prune()
publish_router_results(history, fleet.row, fleet.routers.pending)
assert history.listing()['items'][0]['tone'] == 'warning'
assert entry['public']['action'] == 'policy'
state['results'] = [{**receipt, 'state': 'complete', 'at': int(time.time())}]
fleet.routers.heartbeat(fleet.row, {'routers': state})
publish_router_results(history, fleet.row, fleet.routers.pending)
assert history.listing()['items'][0]['tone'] == 'success'
fleet.routers.heartbeat(fleet.row, {'routers': state})
publish_router_results(history, fleet.row, fleet.routers.pending)
assert len(history.listing()['items']) == 2
@pytest.mark.parametrize(
"change",
[
+68
View File
@@ -0,0 +1,68 @@
from k1link.notifications import NotificationHistory
def test_manual_rollback_message_names_failed_and_restored_channels(tmp_path):
history = NotificationHistory(tmp_path)
for i, (source, target, name) in enumerate([
('ethernet', 'wifi', 'Wi-Fi'), ('wifi', 'ethernet', 'Ethernet')]):
event = dict(id=f'{i:032x}', kind='manual_rollback', source=source, target=target, at=1000)
history.uplink({'node_id': str(i), 'name': 'Rover'}, [event])
message = history.listing()['items'][0]['description']
assert f'Восстановлено подключение по {name}.' in message
def test_history_read_dismiss_separation_and_repeated_node_event(tmp_path):
history=NotificationHistory(tmp_path)
row={'node_id':'board','name':'Test rover'}
event=dict(id='a'*32,kind='fallback',source='ethernet',target='wifi',at=1000)
history.uplink(row,[event])
history.uplink(row,[event])
page=history.listing()
assert len(page['items'])==1 and page['unread']==1
assert 'Wi-Fi' in page['items'][0]['description']
history.read(page['latest'])
assert history.listing()['unread']==0
# Restart replays the bounded board receipt without another notification.
history=NotificationHistory(tmp_path)
history.uplink(row,[event])
assert len(history.listing()['items'])==1
def test_ui_retries_and_pagination_are_idempotent(tmp_path):
history=NotificationHistory(tmp_path)
for i in range(105):
history.add('ui:'+str(i),'error','Error',str(i))
history.add('ui:104','error','Error','104')
newest=history.listing()
assert len(newest['items'])==100 and newest['latest']==105
older=history.listing(before=newest['items'][-1]['sequence'])
assert len(older['items'])==5
assert len(history.listing(after=103)['items'])==2
def test_history_api_requires_local_origin_and_bounds_cursors(tmp_path):
from types import SimpleNamespace
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.web.notifications_api import router
app = FastAPI()
app.include_router(router)
app.state.fleet = SimpleNamespace(notifications=NotificationHistory(tmp_path))
with TestClient(app, base_url='http://127.0.0.1', client=('127.0.0.1', 12345)) as client:
path = '/api/v1/notifications'
message = dict(identity='ui:'+'a'*36, tone='success', title='Saved')
rejected = client.post(path, json=message,
headers={'Origin':'https://other.invalid'})
assert rejected.status_code == 403
assert client.get(path+'?after=999999999999999999999').status_code == 422
assert client.post(path, json={**message, 'tone':'loading'}).status_code == 422
assert client.post(path, json=message).status_code == 200
page = client.get(path)
assert page.headers['cache-control'] == 'no-store'
assert len(page.json()['items']) == 1
assert client.post(path+'/read', json={'through':page.json()['latest']}).status_code == 200
assert client.get(path).json()['unread'] == 0
+100
View File
@@ -0,0 +1,100 @@
import asyncio
from k1link.fleet.node_operator_events import accept_operator_events
from k1link.notifications import NotificationHistory
def test_only_committed_board_transitions_wake_stream_and_disabled_receipts_stay_muted(tmp_path):
row = dict(name="Rover", binding={"binding_id": "test"})
history = NotificationHistory(tmp_path)
loss = dict(kind="telemetry.loss", id="a" * 43, at=120)
restored = dict(kind="telemetry.recovery", id="b" * 43, at=130)
assert not accept_operator_events(history, row, [loss, {**restored, "at": -1}])
async def simulation():
with history.subscribe() as signal:
assert accept_operator_events(history, row, [loss]) == {
"operator_events_ack": loss["id"]
}
await asyncio.wait_for(signal.wait(), 1)
signal.clear()
accept_operator_events(history, row, [loss])
history.configure("telemetry.recovery", False)
assert accept_operator_events(history, row, [restored]) == {
"operator_events_ack": restored["id"]
}
await asyncio.sleep(0)
assert not signal.is_set()
asyncio.run(simulation())
reopened = NotificationHistory(tmp_path)
assert not next(
i["enabled"] for i in reopened.preferences() if i["key"] == "telemetry.recovery"
)
reopened.configure("telemetry.recovery", True)
accept_operator_events(reopened, row, [restored])
page = reopened.listing(after=0, ascending=True)
assert [item["at"] for item in page["items"]] == [120]
assert page["unread"] == 1
def test_router_journal_baseline_replay_and_confirmed_mode(tmp_path):
from k1link.fleet.router_notifications import publish_router_incidents
history = NotificationHistory(tmp_path)
history.configure("router.mode", True)
row = dict(name="Board", node_id="n", binding={"binding_id": "b"})
def journal(seq):
return dict(
binding="b",
state=dict(
journal={"last_sequence": seq},
events=[
dict(
sequence=seq,
boot_id="1" * 32,
code="mode_changed",
at=240,
slot=0,
before="direct",
after="aggregation",
)
],
),
)
publish_router_incidents(history, row, journal(7))
assert not history.listing()["items"]
publish_router_incidents(history, row, journal(8))
publish_router_incidents(NotificationHistory(tmp_path), row, journal(8))
assert [i["description"] for i in history.listing()["items"]] == ["Одна SIM-карта → Агрегация"]
def test_browser_stream_waits_for_commit_and_resumes_after_cursor(tmp_path):
from types import SimpleNamespace
from starlette.requests import Request
from k1link.web.notifications_api import events
async def run():
history = NotificationHistory(tmp_path)
fleet = SimpleNamespace(notifications=history)
history.publish("telemetry.loss", "first", "warning", "Первое", "")
request = Request({"type": "http", "headers": [(b"last-event-id", b"1")]})
stream = (await events(request, fleet, after=0)).body_iterator
try:
assert (await anext(stream)).startswith("retry:")
assert '"items": []' in await anext(stream)
waiting = asyncio.create_task(anext(stream))
await asyncio.sleep(0.03)
assert not waiting.done()
history.publish("telemetry.recovery", "second", "success", "Второе", "")
frame = await asyncio.wait_for(waiting, 1)
assert "id: 2" in frame and "Второе" in frame and "Первое" not in frame
finally:
await stream.aclose()
assert not history.subscribers
asyncio.run(run())
+43
View File
@@ -0,0 +1,43 @@
from k1link.fleet.router_notifications import publish_router_results
from k1link.notifications import NotificationHistory
def test_outcome_is_durable_once_and_independent_of_open_windows(tmp_path):
history = NotificationHistory(tmp_path)
row = dict(id='rover', node_id='node', name='Test', binding={'binding_id': 'bound'})
entry = dict(binding='bound', public=dict(operation_id='one', action='policy', state='queued'))
pending = {('rover', 'one'): entry}
for state in ['queued', 'applying']:
entry['public']['state'] = state
publish_router_results(history, row, pending)
assert history.listing()['items'] == []
entry['public'].update(state='error', error='router_busy')
publish_router_results(history, row, pending)
publish_router_results(history, row, pending)
messages = history.listing()['items']
assert len(messages) == 1 and messages[0]['tone'] == 'error'
assert 'занят' in messages[0]['description']
del entry['notified_state']
publish_router_results(NotificationHistory(tmp_path), row, pending)
assert len(history.listing()['items']) == 1
def test_scope_is_operator_policy_and_late_confirmation_updates_uncertainty(tmp_path):
history = NotificationHistory(tmp_path)
history.configure('router.applied', True)
row = dict(id='rover', node_id='node', name='Test', binding={'binding_id': 'bound'})
entry = dict(binding='bound', public=dict(operation_id='one', action='policy', state='unknown'))
pending = {
('other', 'one'): entry.copy(),
('rover', 'old'): {**entry, 'binding': 'old'},
('rover', 'inspect'): {**entry, 'public': {'action': 'inspect', 'state': 'complete'}},
('rover', 'one'): entry,
}
publish_router_results(history, row, pending)
assert len(history.listing()['items']) == 1
assert history.listing()['items'][0]['tone'] == 'warning'
entry['public']['state'] = 'complete'
publish_router_results(history, row, pending)
messages = history.listing()['items']
assert len(messages) == 2 and messages[0]['tone'] == 'success'
assert 'Фактический канал' in messages[0]['description']