feat(events): deliver state changes to the configurable operator event center
This commit is contained in:
@@ -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;}
|
||||
@@ -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()
|
||||
@@ -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))
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user