feat(fleet): add shared WireGuard profiles and bounded rover transport
Add portable shared WireGuard profiles while retaining Tailscale and Worker boundaries. Bound rover command/telemetry delivery, recovery and diagnostic capture across Core and Node.
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
import {useState} from 'react';
|
||||
import {Button,Description,Select,SettingsCard,Switch,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {localDevOptions,type DevOptions,type RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics';
|
||||
import './roverLogs.css';
|
||||
|
||||
export function RoverDevWindow({capture,close,started}:{capture:RoverDiagnostics;close:()=>void;started:()=>void}){
|
||||
const [options,setOptions]=useState<DevOptions>({...localDevOptions});
|
||||
const [local,setLocal]=useState({enabled:true,preview:true});
|
||||
const set=(key:keyof DevOptions,value:boolean|number)=>setOptions(current=>({...current,[key]:value}));
|
||||
const rates=[8,16,32,64].map(value=>({value:String(value),label:`${value} кбит/с`}));
|
||||
const begin=async()=>{if(await capture.toggle(options,local)){started();close();}};
|
||||
return <Window open onClose={close} title="Настройки DEV-записи" size="md" footer={<WindowFooterActions><Button onClick={close}>Отмена</Button><Button variant="primary" loading={capture.pending} disabled={!capture.state.options_supported} onClick={()=>void begin()}>Начать запись</Button></WindowFooterActions>}>
|
||||
<div className="rover-dev-options">
|
||||
<Description>Запись сохраняется на борту. После завершения её можно скачать в окне логов. Закрытие окна не останавливает запись.</Description>
|
||||
<SettingsCard title="Что записывать" description="Переходы управления, остановки и ошибки записываются всегда.">
|
||||
<Switch label="Подробные замеры моторов" checked={options.motor_samples} onChange={value=>set('motor_samples',value)}/>
|
||||
<Switch label="Сетевые события и распределение полосы" checked={options.network} onChange={value=>set('network',value)}/>
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Замеры на компьютере" description="Задержки команд и события браузера сохраняются отдельно от записи борта. Эти замеры не передаются на борт.">
|
||||
<Switch label="Записать замеры Core и браузера" checked={local.enabled} onChange={enabled=>setLocal(current=>({...current,enabled}))}/>
|
||||
{local.enabled&&<><Switch label="Добавить статистику видео" checked={local.preview} onChange={preview=>setLocal(current=>({...current,preview}))}/><Description>Без записи изображения. Замер хранится в памяти до перезапуска Core: не более 15 минут и последних 6000 событий. После остановки сохраните его отдельной кнопкой в окне логов.</Description></>}
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Передача во время записи" description={!options.live&&!options.core_trace?'Диагностические события остаются на борту. По сети передаётся только короткое состояние записи.':'Эти потоки используют сеть. На слабом канале их можно отключить и скачать файл позже.'}>
|
||||
<Switch label="Показывать события онлайн" checked={options.live} onChange={value=>set('live',value)}/>
|
||||
{options.live&&<Select label="Лимит live-событий" value={String(options.live_kbps)} options={rates} onChange={value=>set('live_kbps',Number(value))}/>}
|
||||
<Switch label="Добавлять события Core и браузера" checked={options.core_trace} onChange={value=>set('core_trace',value)}/>
|
||||
{options.core_trace&&<><Description>Эти события передаются с компьютера оператора на борт. При нехватке полосы пропуски отмечаются в записи.</Description><Select label="Лимит событий на борт" value={String(options.core_kbps)} options={rates} onChange={value=>set('core_kbps',Number(value))}/></>}
|
||||
</SettingsCard>
|
||||
{!capture.state.options_supported&&<Description>Борт ещё не подтвердил доступность настроек записи. Запуск станет доступен после подключения совместимого борта.</Description>}
|
||||
</div>
|
||||
</Window>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import {createPortal} from 'react-dom';
|
||||
import {Button,StatusBadge} from '@nodedc/ui-react';
|
||||
import type {RoverDiagnostics} from '../../core/fleet/useRoverDiagnostics';
|
||||
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
||||
import './roverLogs.css';
|
||||
export function RoverLogs({capture,header}:{capture:RoverDiagnostics;header:ObservationHeaderTargets}){
|
||||
const storage=capture.state.node?.storage,failed=storage?.error||capture.state.node?.transport_error;
|
||||
const status=failed?'Ошибка записи':capture.state.closing?'Завершение записи':storage?.closed?'Запись завершена':capture.state.node?.active?'Запись на борт':'Ожидание борта';
|
||||
return <>
|
||||
{createPortal(<StatusBadge variant="indicator" tone={failed?'danger':capture.state.node?.active?'success':'warning'} aria-label={status} title={status}/>,header.statusTarget)}
|
||||
|
||||
<div className="rover-logs">
|
||||
<div className="rover-logs__actions"><Button disabled={!storage?.file} loading={capture.saving} onClick={()=>void capture.save()}>Сохранить с борта</Button>{capture.state.local_capture?.id&&<Button loading={capture.saving} onClick={()=>void capture.saveLocal()}>Сохранить с компьютера</Button>}</div>
|
||||
<p>{status} · {storage?.written??0} записей{storage?.dropped?` · Потеряно при записи: ${storage.dropped}`:''}</p>
|
||||
{storage?.file&&<p title={storage.file}>{storage.file}</p>}
|
||||
{failed&&<p role="alert">Файл может быть неполным: {failed}</p>}
|
||||
<p>{capture.state.options?.live===false?'События записываются локально; live-передача отключена.':'Последние события онлайн.'} «Сохранить с борта» выгружает полный бортовой файл. Закрытие окна не завершает запись.</p>
|
||||
{capture.state.local_capture?.id&&<p>Замер компьютера: {capture.state.local_capture.active?'идёт запись':'завершён'} · {capture.state.local_capture.sequence??0} событий{capture.state.local_capture.dropped?` · Пропущено: ${capture.state.local_capture.dropped}`:''}. Сохраните до перезапуска Core.</p>}
|
||||
<div className="rover-logs__entries" role="log" aria-live="off" aria-label="События DEV-сессии">
|
||||
{[...capture.rows].reverse().map(item=>{const row=item.record??item;return <pre key={item.record_sequence}>{JSON.stringify(row,null,2)}</pre>;})}
|
||||
</div>
|
||||
</div>
|
||||
</>;
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import {ComparisonTable,Description,StatusBadge} from '@nodedc/ui-react';
|
||||
import type {RoverState} from '../../core/fleet/useRoverControl';
|
||||
import type {RoverObservationStatus} from '../../core/fleet/roverObservation';
|
||||
import {drivePositions} from '../../../../../plugins/vesc/frontend/src/model';
|
||||
const number=(v:number|undefined,digits=1)=>typeof v==='number'&&Number.isFinite(v)?v.toLocaleString('ru-RU',{maximumFractionDigits:digits}):'—';
|
||||
export function RoverTelemetry({state}:{state:RoverState}){
|
||||
export function roverTelemetryTable(state:RoverState){
|
||||
const devices=state.snapshot.devices??[],profile=state.snapshot.profile;
|
||||
const positions=drivePositions(profile?.layout??null);
|
||||
const assigned=Object.entries(profile?.bindings??{}).map(([slot,binding])=>({
|
||||
@@ -9,17 +11,19 @@ export function RoverTelemetry({state}:{state:RoverState}){
|
||||
reading:devices.find(d=>d.id===binding.device_id&&d.uuid===binding.uuid),
|
||||
}));
|
||||
const readings=[...assigned,...devices.filter(d=>!assigned.some(a=>a.id===d.id&&a.uuid===d.uuid)).map(d=>({...d,reading:d}))];
|
||||
return <div className="rover-telemetry">
|
||||
{!state.fresh?<p>Нет свежих показаний VESC.</p>:!readings.length?<p>Получение показаний VESC…</p>:readings.map(d=>{
|
||||
const fresh=!!d.reading&&d.reading.age_ms<1000,v=fresh?d.reading?.values:undefined;
|
||||
return <section key={d.uuid}><strong>{d.label}</strong><span>VESC {d.uuid.slice(0,6).toUpperCase()}{!d.reading?' · Нет связи':!fresh?' · Нет свежих данных':''}</span>
|
||||
<dl><div><dt>Ток мотора</dt><dd>{number(v?.motor_current_a)} А</dd></div>
|
||||
<div><dt>Ток батареи</dt><dd>{number(v?.input_current_a)} А</dd></div>
|
||||
<div><dt>Напряжение</dt><dd>{number(v?.input_voltage_v)} В</dd></div>
|
||||
<div><dt>Обороты, ERPM</dt><dd>{number(v?.erpm,0)}</dd></div>
|
||||
<div><dt>Контроллер</dt><dd>{number(v?.mos_temperature_c)} °C</dd></div>
|
||||
<div><dt>Ошибка VESC</dt><dd>{v?v.fault_code===0?'Нет':String(v.fault_code):'—'}</dd></div></dl>
|
||||
</section>;
|
||||
})}
|
||||
</div>;
|
||||
const fresh=(d:typeof readings[number])=>state.fresh&&!!d.reading&&Number.isFinite(d.reading.age_ms)&&d.reading.age_ms>=0&&d.reading.age_ms<1000;
|
||||
const metrics=[['motor_current_a','Ток мотора','А',1],['input_current_a','Ток батареи','А',1],['input_voltage_v','Напряжение','В',1],['erpm','Обороты, ERPM','',0],['mos_temperature_c','Контроллер','°C',1]] as const;
|
||||
return {
|
||||
columns:readings.map(d=>({id:d.id+':'+d.uuid,label:d.uuid.slice(0,6).toUpperCase()})),
|
||||
rows:[{id:'position',label:'Расположение',cells:readings.map(d=>d.label||'Не назначено')},
|
||||
{id:'status',label:'Связь',cells:readings.map(d=>!state.fresh?'Нет данных':!d.reading?'Нет связи':fresh(d)?'В сети':'Нет данных')},
|
||||
...metrics.map(([key,label,unit,digits])=>({id:key,label,cells:readings.map(d=>{const value=fresh(d)?d.reading?.values?.[key]:undefined;return typeof value==='number'&&Number.isFinite(value)?`${number(value,digits)}${unit?' '+unit:''}`:'—';})})),
|
||||
{id:'fault',label:'Ошибка VESC',cells:readings.map(d=>{const code=fresh(d)?d.reading?.values?.fault_code:undefined;return typeof code==='number'?code===0?'Нет':String(code):'—';})}],
|
||||
};
|
||||
}
|
||||
export function RoverTelemetry({state,observation}:{state:RoverState;observation?:RoverObservationStatus}){
|
||||
const table=roverTelemetryTable(state);
|
||||
return <div className="rover-telemetry">{observation?.label&&<StatusBadge tone="warning" pulse={observation.pulse}>{observation.label}</StatusBadge>}{table.columns.length?<ComparisonTable density="compact" label="Телеметрия VESC" heading="VESC" {...table}/>:!observation?.label&&<Description>{state.fresh?'Получение показаний VESC…':'Нет свежих показаний VESC.'}</Description>}</div>;
|
||||
}
|
||||
|
||||
export function roverTelemetryMinimum(state:RoverState){return {width:Math.max(288,144+88*roverTelemetryTable(state).columns.length),height:280};}
|
||||
|
||||
@@ -1,45 +1,63 @@
|
||||
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {createPortal} from 'react-dom';
|
||||
import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,Switch,TextField,ToastStack,Window} from '@nodedc/ui-react';
|
||||
import {keysFor,roverSettings,type RoverMode} from '../../core/fleet/roverInput';
|
||||
import {Button,Icon,IconButton,KeyButton,LoadingRegion,Select,StatusBadge,TextField,ToastStack,Window} from '@nodedc/ui-react';
|
||||
import {keysFor,roverSettings,roverNumberInput,persistableRoverSettings,type RoverMode} from '../../core/fleet/roverInput';
|
||||
import {roverDevEvent} from '../../core/fleet/roverDevEvents';
|
||||
import {bindRoverHoldInput} from '../../core/fleet/roverHoldInput';
|
||||
import type {RoverController} from '../../core/fleet/useRoverControl';
|
||||
import {roverObservationStatus,type RoverObservationStatus} from '../../core/fleet/roverObservation';
|
||||
import type {ObservationHeaderTargets} from '../../../../../packages/sensor-ui/src/observation';
|
||||
import './rover.css';
|
||||
const Scene=lazy(()=>import('./editor/RoverScene'));
|
||||
const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление включено',driving:'Команда движения',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выключено',fault:'Управление остановлено'};
|
||||
const labels:Record<string,string>={observing:'Наблюдение',preparing:'Подготовка управления',ready:'Управление вкл',driving:'Управление вкл',receiver:'Управление с пульта',stopping:'Остановка',stopped:'Управление выкл',fault:'Управление остановлено'};
|
||||
|
||||
export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean}){
|
||||
export function RoverView({vehicleID,controller:c,header,active,observation}:{vehicleID:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){
|
||||
const storage=`missioncore.rover-view.v1:${vehicleID}`;
|
||||
const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}});
|
||||
const [open,setOpen]=useState(false),[confirmed,setConfirmed]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
|
||||
const [open,setOpen]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
|
||||
const [editing,setEditing]=useState(false);
|
||||
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
|
||||
const stage=useRef<HTMLDivElement>(null),input=useRef<ReturnType<typeof bindRoverHoldInput>|null>(null);
|
||||
const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();setConfirmed(false);},[c.stop,c.setInputGuard]);
|
||||
useEffect(()=>{try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]);
|
||||
const focusAfterArm=useRef(false);
|
||||
useEffect(()=>{
|
||||
if(open||!focusAfterArm.current)return;
|
||||
focusAfterArm.current=false;
|
||||
// Window restores its opener on close. Transfer input after that cleanup,
|
||||
// once only, without taking focus back from another window or dialog.
|
||||
const frame=requestAnimationFrame(()=>{if(active&&!document.hidden&&document.hasFocus()&&!document.querySelector('[role=dialog],[role=listbox]'))stage.current?.focus({preventScroll:true});});
|
||||
return()=>cancelAnimationFrame(frame);
|
||||
},[open,active]);
|
||||
const stop=useCallback(()=>{input.current?.dispose();input.current=null;c.setInputGuard(null);setHeld(new Set());c.stop();},[c.stop,c.setInputGuard]);
|
||||
useEffect(()=>{if(persistableRoverSettings(settings))try{localStorage.setItem(storage,JSON.stringify(settings));}catch{}},[storage,settings]);
|
||||
useEffect(()=>{if(!active)stop();},[active,stop]);
|
||||
useEffect(()=>{
|
||||
if(!c.ready||!active||open||editing||!stage.current)return;
|
||||
const binding=bindRoverHoldInput(stage.current,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop});
|
||||
const scope=stage.current.closest<HTMLElement>('.observation-center')??stage.current;
|
||||
const binding=bindRoverHoldInput(scope,settings.mode,{held:setHeld,demand:c.setDemand,pause:c.pauseInput,stop,trace:(event,data)=>roverDevEvent(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,event,data)});
|
||||
input.current=binding;c.setInputGuard(binding.valid);
|
||||
return()=>{c.setInputGuard(null);binding.dispose();if(input.current===binding)input.current=null;};
|
||||
},[c.ready,active,open,editing,settings.mode,c.setDemand,c.setInputGuard,c.pauseInput,stop]);
|
||||
const showSettings=()=>{setEditing(false);stop();setOpen(true);};
|
||||
const preparing=c.pending||(c.armed&&!c.ready);
|
||||
const availability=c.connecting?'Синхронизация с бортом':!c.state.fresh?'Нет свежих данных с борта':!c.state.snapshot.supported?'Управление на борту недоступно':c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null;
|
||||
const tone=preparing||availability?'warning':c.ready?'success':c.state.snapshot.state==='fault'?'warning':'neutral';
|
||||
const status=preparing?'Подготовка управления':availability??(labels[c.state.snapshot.state??'']??'Наблюдение');
|
||||
const preparing=c.recovering||c.pending||(c.armed&&!c.ready);
|
||||
const duty=c.controlMode!=='rpm';
|
||||
const limits=(c.state.snapshot.devices??[]).filter(d=>d.slot&&d.current_limits);
|
||||
const currentDescription=limits.length?limits.map(d=>`${d.label}: до ${d.current_limits!.motor_a.toLocaleString('ru-RU',{maximumFractionDigits:2})} А`).join('; ')+'. Выбранный предел ограничивает тягу; настройки VESC сохраняются.':'Предел тяги. Каждый мотор также ограничен своей конфигурацией VESC.';
|
||||
const speedValid=duty?settings.throttlePercent>=1&&settings.throttlePercent<=100:settings.maxErpm>=300&&settings.maxErpm<=3000;
|
||||
const observing=observation??roverObservationStatus(c.state,c.connection);
|
||||
const availability=observing.label??(c.state.controlling&&!c.armed?'Управление уже включено':!c.canArm&&!c.armed?'Завершение предыдущего управления':null);
|
||||
const tone=preparing||availability?'warning':c.ready?'success':c.error||c.state.snapshot.state==='fault'?'warning':'neutral';
|
||||
const status=c.recovering?'Восстанавливаем связь':preparing?'Подготовка управления':availability??c.error??(labels[c.state.snapshot.state??'']??'Наблюдение');
|
||||
const running=c.armed||c.pending||c.recovering;
|
||||
return <>
|
||||
{createPortal(<><IconButton label={editing?"Завершить редактирование сцены":"Редактировать сцену"} aria-pressed={editing} onClick={()=>{c.pauseInput();setHeld(new Set());setEditing(v=>!v);}}><Icon name="edit"/></IconButton><IconButton label="Настройки управления ровером" onClick={showSettings}><Icon name="settings"/></IconButton></>,header.actionsTarget)}
|
||||
{createPortal(<StatusBadge variant="indicator" tone={tone} aria-label={status} title={status}/>,header.statusTarget)}
|
||||
{createPortal(<><IconButton label={running?"Остановить управление":"Включить управление"} aria-pressed={running||open} onClick={running?stop:showSettings}><Icon name={running?'stop':'play'}/></IconButton><IconButton label={editing?"Завершить редактирование сцены":"Редактировать сцену"} aria-pressed={editing} onClick={()=>{c.pauseInput();setHeld(new Set());setEditing(v=>!v);}}><Icon name="edit"/></IconButton><IconButton label="Настройки управления ровером" onClick={showSettings}><Icon name="settings"/></IconButton></>,header.actionsTarget)}
|
||||
{createPortal(<><StatusBadge variant="indicator" tone={editing?'neutral':tone} pulse={!editing&&(preparing||observing.pulse)} aria-label={editing?'Редактирование сцены':status}/><h3 className="rover-view__title" title={status}>{editing?'Редактирование сцены':status}</h3></>,header.statusTarget)}
|
||||
<div className="rover-view" ref={stage} tabIndex={0} aria-label="3D-вид и управление ровером"
|
||||
onKeyDown={e=>{if(!c.ready&&(c.armed||c.pending||c.recovering)&&e.isTrusted&&['Space','Escape'].includes(e.code)){e.preventDefault();stop();}}}
|
||||
onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
|
||||
{settings.model==='dcd006-v020'?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'} label="Загрузка модели ровера">
|
||||
{settings.model==='dcd006-v020'?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
|
||||
<Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
|
||||
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
|
||||
</LoadingRegion>:<div className="rover-view__empty"><p>Выберите модель аппарата.</p><Button onClick={showSettings}>Настройки вида</Button></div>}
|
||||
<div className="rover-view__status"><StatusBadge tone={editing?'neutral':tone}>{editing?'Редактирование сцены':status}</StatusBadge></div>
|
||||
{c.ready&&!editing&&<div className="rover-view__controls">
|
||||
<div className={`rover-keys rover-keys--${settings.mode}`} aria-label={settings.mode==='arcade'?'Аркадное управление':'Танковое управление'}>
|
||||
{keysFor(settings.mode).map(code=><KeyButton key={code} className={`rover-key-${code}`} label={settings.mode==='arcade'?({KeyW:'Вперёд · W',KeyS:'Назад · S',KeyA:'Налево · A',KeyD:'Направо · D'}[code]??code):({KeyQ:'Левая сторона вперёд · Q',KeyA:'Левая сторона назад · A',KeyE:'Правая сторона вперёд · E',KeyD:'Правая сторона назад · D'}[code]??code)}
|
||||
@@ -51,20 +69,17 @@ export function RoverView({vehicleID,controller:c,header,active}:{vehicleID:stri
|
||||
</div>
|
||||
<span>{settings.mode==='arcade'?'Аркадный':'Танковый'} · пробел — стоп</span>
|
||||
</div>}
|
||||
{!editing&&<div className="rover-view__authority">
|
||||
{c.armed||c.pending?<Button onClick={stop}>Остановить управление</Button>:<Button onClick={showSettings}>Управлять</Button>}
|
||||
</div>}
|
||||
</div>
|
||||
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
|
||||
<Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/>
|
||||
<Select label="3D-модель" value={settings.model} options={[{value:'',label:'Не выбрана'},{value:'dcd006-v020',label:'DCD-006 · полный ровер v020'}]} onChange={model=>setSettings(v=>({...v,model}))}/>
|
||||
<TextField label="Предел тока каждого мотора, А" type="number" min={.5} max={30} step={.5} value={settings.currentA} onChange={e=>setSettings(v=>({...v,currentA:Number(e.target.value)}))}/>
|
||||
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={settings.maxErpm} onChange={e=>setSettings(v=>({...v,maxErpm:Number(e.target.value)}))}/>
|
||||
<Switch label="Моторы остановлены, движение можно начинать" checked={confirmed} onChange={setConfirmed}/>
|
||||
{availability&&<StatusBadge tone="warning">{availability}</StatusBadge>}
|
||||
<p>Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. Команда с пульта прекращает удалённое управление.</p>
|
||||
<Button variant="primary" tone="neutral" disabled={!confirmed||!c.canArm||!(settings.currentA>=.5&&settings.currentA<=30&&settings.maxErpm>=300&&settings.maxErpm<=3000)} loading={c.pending}
|
||||
onClick={async()=>{const acquired=await c.arm(settings.currentA,settings.maxErpm);if(acquired){setOpen(false);if(document.hasFocus())stage.current?.focus();}}}>Включить управление</Button>
|
||||
{duty?<TextField label="Газ, %" hint="1–100" description="Доля полного газа пульта. Фактическая скорость зависит от нагрузки." type="number" min={1} max={100} step={1} value={Number.isFinite(settings.throttlePercent)?settings.throttlePercent:''} onChange={e=>setSettings(v=>({...v,throttlePercent:roverNumberInput(e.target.value)}))}/>:
|
||||
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={Number.isFinite(settings.maxErpm)?settings.maxErpm:''} onChange={e=>setSettings(v=>({...v,maxErpm:roverNumberInput(e.target.value)}))}/>}
|
||||
<TextField label="Предел тока каждого мотора, А" description={currentDescription} type="number" min={.5} step={.5} value={Number.isFinite(settings.currentA)?settings.currentA:''} onChange={e=>setSettings(v=>({...v,currentA:roverNumberInput(e.target.value)}))}/>
|
||||
{(availability||c.error)&&<StatusBadge tone="warning">{availability||c.error}</StatusBadge>}
|
||||
<p>Включайте управление на остановленном аппарате. Движение — только при удержании клавиш или кнопок. При уходе из окна команда снимается. После восстановления связи для движения нажмите клавишу заново. Команда с пульта прекращает удалённое управление.</p>
|
||||
<Button variant="primary" tone="neutral" disabled={!c.canArm||!!observing.label||!(Number.isFinite(settings.currentA)&&settings.currentA>=.5&&speedValid)} loading={c.pending}
|
||||
onClick={async()=>{roverDevEvent(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,'settings',{mode:settings.mode,current_a:settings.currentA,speed:duty?settings.throttlePercent:settings.maxErpm,control_mode:duty?'duty':'rpm'});const acquired=await c.arm(settings.currentA,duty?settings.throttlePercent:settings.maxErpm,duty?'duty':'rpm');if(acquired){focusAfterArm.current=true;setOpen(false);}}}>Включить управление</Button>
|
||||
</div></Window>
|
||||
<ToastStack onDismiss={c.clearError} items={c.error?[{id:'rover-control-error',tone:'error',title:'Управление остановлено',description:c.error}]:[]}/>
|
||||
</>;
|
||||
|
||||
@@ -20,7 +20,7 @@ export default function RoverScene({vehicleID,editing,onModelState}:{vehicleID:s
|
||||
{scene.ready&&<PlayCanvasViewer modelUrl="/rover-scene/dcd006-v020.glb?materials-v2" postFx={scene.document.postFx} cameraAutoRotate={scene.document.cameraAutoRotate} cameraZoomStrength={scene.document.cameraZoomStrength} cameraResetToken={cameraReset} materials={scene.document.materials} assignments={scene.document.assignments} editing={editing} onMaterialPick={pick} onModelState={onModelState} onTextureState={setTextureState}/>}
|
||||
</LoadingRegion>
|
||||
{editing&&<>
|
||||
<div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface"><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>setPalette(v=>!v)}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton></GlassSurface></div>
|
||||
<div className="rover-scene-tools"><GlassSurface className="rover-scene-tools__surface nodedc-viewport-controls"><IconButton label="Материалы сцены" aria-pressed={palette} onClick={()=>setPalette(v=>!v)}><Icon name="layers"/></IconButton><IconButton label="Окружение сцены" aria-pressed={environment} onClick={()=>setEnvironment(v=>!v)}><Icon name="globe"/></IconButton></GlassSurface></div>
|
||||
<div className="rover-scene-save"><StatusBadge tone={saved&&textureState!=='loading'?'neutral':'warning'}>{status}</StatusBadge></div>
|
||||
{palette&&<GlassSurface className="rover-material-palette"><div className="rover-material-palette__header"><span>Материалы · выберите в палитре или на модели</span><IconButton label="Скрыть палитру материалов" onClick={()=>setPalette(false)}><Icon name="close"/></IconButton></div><div className="rover-material-palette__items">{Object.entries(scene.document.materials).map(([id,m])=><Button key={id} variant={selected===id?'primary':'secondary'} tone="neutral" aria-pressed={selected===id} title={m.name} onClick={()=>pick(id)}><span className="rover-material-tile"><span aria-hidden="true" className="rover-material-swatch" style={{'--material-color':m.color,'--material-gloss':1-m.roughness} as CSSProperties}/><span>{m.name}</span></span></Button>)}<Button aria-label="Добавить материал" title="Добавить материал" onClick={addMaterial}><span className="rover-material-tile"><Icon name="plus"/><span>Новый материал</span></span></Button></div></GlassSurface>}
|
||||
</>}
|
||||
|
||||
@@ -2,19 +2,11 @@
|
||||
.rover-view:focus-visible { outline:2px solid var(--nodedc-text-secondary); outline-offset:-2px; }
|
||||
.rover-view .rover-view__scene { position:absolute; inset:0; }
|
||||
.rover-view__empty { display:grid; place-content:center; height:100%; text-align:center; font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-muted); }
|
||||
.rover-view__status { position:absolute; top:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)); left:var(--nodedc-space-3); }
|
||||
.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; }
|
||||
.rover-view__controls { position:absolute; right:var(--nodedc-space-3); bottom:var(--nodedc-space-3); display:flex; flex-direction:column; gap:var(--nodedc-space-2); align-items:center; transform:scale(.8); transform-origin:bottom right; }
|
||||
.rover-view__controls > span { font-size:var(--nodedc-font-size-xs); color:var(--nodedc-text-secondary); }
|
||||
.rover-keys { display:grid; gap:var(--nodedc-space-1); grid-template-columns:repeat(3,46px); }
|
||||
.rover-key-KeyW { grid-column:2; }.rover-key-KeyA { grid-column:1; grid-row:2; }.rover-key-KeyS { grid-column:2; grid-row:2; }.rover-key-KeyD { grid-column:3; grid-row:2; }
|
||||
.rover-key-KeyQ { grid-column:1; }.rover-key-KeyE { grid-column:3; }
|
||||
.rover-view__authority { position:absolute; left:var(--nodedc-space-3); bottom:var(--nodedc-space-3); }
|
||||
@container (max-width: 380px) {
|
||||
.rover-view:has(.rover-view__controls) .rover-view__authority { top:calc(var(--observation-overlay-header-space, 0px) + 48px); bottom:auto; }
|
||||
}
|
||||
.rover-settings { display:flex; flex-direction:column; gap:var(--nodedc-space-3); }
|
||||
.rover-settings p { font-size:var(--nodedc-font-size-sm); color:var(--nodedc-text-secondary); }
|
||||
.rover-telemetry { height:100%; overflow:auto; padding:var(--nodedc-space-3); display:flex; flex-wrap:wrap; align-content:start; gap:var(--nodedc-space-4); font-size:var(--nodedc-font-size-sm); }
|
||||
.rover-telemetry section { flex:1; min-width:170px; }.rover-telemetry section > span { display:block; color:var(--nodedc-text-muted); font-size:var(--nodedc-font-size-xs); margin-top:var(--nodedc-space-1); }
|
||||
.rover-telemetry dl { display:grid; gap:var(--nodedc-space-1); margin-bottom:0; }.rover-telemetry dl > div { display:flex; justify-content:space-between; gap:var(--nodedc-space-3); }
|
||||
.rover-telemetry dt { color:var(--nodedc-text-secondary); }.rover-telemetry dd { margin:0; font-variant-numeric:tabular-nums; }
|
||||
.rover-telemetry {height:100%; min-height:0; min-width:0; overflow:hidden; padding:var(--nodedc-space-3);}.rover-telemetry > .nodedc-comparison-table {max-height:100%;}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
.nodedc-icon-button > .rover-dev-label {color:inherit;font-size:var(--nodedc-font-size-xs);font-weight:var(--nodedc-font-weight-medium);}
|
||||
.rover-logs {height:100%;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:var(--nodedc-space-2);padding:calc(var(--observation-overlay-header-space, 0px) + var(--nodedc-space-3)) var(--nodedc-space-3) var(--nodedc-space-3);}
|
||||
.rover-logs > p {margin:0;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-secondary);overflow-wrap:anywhere;}
|
||||
.rover-logs__entries {flex:1;min-height:0;overflow:auto;}
|
||||
.rover-logs__entries pre {white-space:pre-wrap;overflow-wrap:anywhere;font-size:var(--nodedc-font-size-xs);color:var(--nodedc-text-primary);}
|
||||
|
||||
.rover-dev-options {display:flex;flex-direction:column;gap:var(--nodedc-space-3);}
|
||||
.rover-dev-options .nodedc-settings-card__body {display:flex;flex-direction:column;gap:var(--nodedc-space-3);}
|
||||
|
||||
.rover-logs__actions {display:flex;flex-wrap:wrap;gap:var(--nodedc-space-2);}
|
||||
@@ -38,6 +38,10 @@ export function observationTree(layout:ObservationLayout,ids:string[]):DockTree|
|
||||
const axis=layout.arrangement==='rows'?'y':layout.arrangement==='columns'?'x':depth%2?'y':'x';
|
||||
return {axis,ratio:layout.splits[JSON.stringify(keys)]??50,first:build(keys.slice(0,mid),depth+1)!,second:build(keys.slice(mid),depth+1)!};
|
||||
};
|
||||
if(layout.arrangement==='auto' && !Object.keys(layout.splits).length && ids.includes('telemetry') && ids.length>=3){
|
||||
const other=ids.filter(id=>id!=='telemetry');
|
||||
return {axis:'x',ratio:65,first:build(other.slice(0,-1))!,second:{axis:'y',ratio:40,first:{id:'telemetry'},second:{id:other.at(-1)!}}};
|
||||
}
|
||||
return build(ids);
|
||||
}
|
||||
export function dockObservation(layout:ObservationLayout,ids:string[],move:DockMove):ObservationLayout {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import {sameConfiguration} from './configurationEquality';
|
||||
|
||||
const queues=new Map<string,Promise<unknown>>();
|
||||
/** A pending save survives unmount. The next mount reads only after its ACK. */
|
||||
export function observationSerial<T>(key:string,work:()=>Promise<T>):Promise<T>{
|
||||
const previous=queues.get(key)??Promise.resolve();
|
||||
const next=previous.catch(()=>{}).then(work);queues.set(key,next);
|
||||
void next.finally(()=>{if(queues.get(key)===next)queues.delete(key);}).catch(()=>{});
|
||||
return next;
|
||||
}
|
||||
const object=(v:unknown):v is Record<string,unknown>=>v!==null&&typeof v==='object'&&!Array.isArray(v);
|
||||
/** Three-way merge: unrelated fields survive; arrays and conflicting leaves are atomic. */
|
||||
export function mergeObservation<T>(base:T,local:T,remote:T):{value:T;conflicts:string[]}{
|
||||
const conflicts:string[]=[];
|
||||
function merge(b:unknown,l:unknown,r:unknown,path:string):unknown{
|
||||
if(sameConfiguration(l,b))return r;
|
||||
if(sameConfiguration(r,b)||sameConfiguration(l,r))return l;
|
||||
if(object(b)&&object(l)&&object(r)){
|
||||
const result:Record<string,unknown>={};
|
||||
for(const key of new Set([...Object.keys(b),...Object.keys(l),...Object.keys(r)])){
|
||||
const value=merge(b[key],l[key],r[key],path?path+'.'+key:key);
|
||||
if(value!==undefined)result[key]=value;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
conflicts.push(path);return l;
|
||||
}
|
||||
return {value:merge(base,local,remote,'') as T,conflicts};
|
||||
}
|
||||
export interface ObservationReceipt<T>{revision:number;document:T|null;writable:boolean}
|
||||
export async function saveObservation<T>(revision:number,base:T,local:T,read:()=>Promise<ObservationReceipt<T>>,write:(revision:number,value:T)=>Promise<ObservationReceipt<T>>,normalize:(value:T|null)=>T){
|
||||
let payload=local;
|
||||
for(let attempt=0;attempt<2;attempt++){
|
||||
try{return {receipt:await write(revision,payload),document:payload};}
|
||||
catch(error){
|
||||
// Read after any failed ACK, including timeout. Identity/equality can prove
|
||||
// an already committed write without retrying it or incrementing revision.
|
||||
const latest=await read();if(!latest.writable)throw error;
|
||||
const remote=normalize(latest.document);
|
||||
if(sameConfiguration(remote,payload))return {receipt:latest,document:remote};
|
||||
const merged=mergeObservation(base,payload,remote);
|
||||
if(merged.conflicts.length)throw Error('Раскладка изменена в другом окне. Черновик сохранён: можно загрузить бортовую версию или применить свой черновик.');
|
||||
if(attempt===1)throw error;
|
||||
revision=latest.revision;base=remote;payload=merged.value;
|
||||
}
|
||||
}
|
||||
throw Error('Подтверждение сохранения не получено.');
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/** Opt-in bounded queues on the operator host. Never awaited by motor transport. */
|
||||
type Row=Record<string,unknown>;
|
||||
export class BrowserEvidence {
|
||||
id:string|null=null;rows:Row[]=[];busy=false;dropped=0;
|
||||
constructor(readonly url:string,readonly local=false){}
|
||||
set(id:string|null){if(this.id!==id){this.rows=[];this.dropped=0;this.id=id;}}
|
||||
record(event:string,data:Row={}){
|
||||
if(!this.id)return;
|
||||
const row={event,browser_ms:performance.now(),...data};
|
||||
if(JSON.stringify(row).length>2048){this.dropped++;return;}
|
||||
if(this.rows.length>=256){this.rows.shift();this.dropped++;}
|
||||
this.rows.push(row);
|
||||
}
|
||||
async flush(){
|
||||
if(this.busy||!this.id||!this.rows.length)return;
|
||||
const id=this.id,rows=this.rows.splice(0,32);this.busy=true;
|
||||
try{const r=await fetch(this.url+(this.local?'/diagnostics/local/events':'/diagnostics/events'),{method:'POST',headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({id,events:rows}),signal:AbortSignal.timeout(2000),keepalive:true});
|
||||
if(!r.ok)throw Error('trace');
|
||||
if(this.local&&(await r.json()).accepted!==true&&id===this.id)this.set(null);
|
||||
}
|
||||
catch{if(id===this.id){const pending=[...rows,...this.rows];this.dropped+=Math.max(0,pending.length-256);this.rows=pending.slice(-256);}}
|
||||
finally{this.busy=false;}
|
||||
}
|
||||
}
|
||||
const sessions=new Map<string,{remote:BrowserEvidence;local:BrowserEvidence;preview:boolean}>();
|
||||
export function roverDevEvent(url:string,event:string,data:Row={}){try{const pair=sessions.get(url);pair?.remote.record(event,data);pair?.local.record(event,data);}catch{/* No change to input authority. */}}
|
||||
/** Camera metrics never enter the optional WAN recorder. */
|
||||
export function roverPreviewEvidence(url:string,sample:Row){try{const pair=sessions.get(url);if(pair?.preview)pair.local.record('preview',{sample});}catch{/* No preview/control side effect. */}}
|
||||
export function connectRoverEvidence(url:string){
|
||||
const pair={remote:new BrowserEvidence(url),local:new BrowserEvidence(url,true),preview:true};sessions.set(url,pair);
|
||||
const timer=setInterval(()=>{for(const e of [pair.remote,pair.local]){if(e.dropped){const dropped=e.dropped;e.dropped=0;e.record('lifecycle',{reason:'browser_queue_gap',dropped});}void e.flush();}},250);
|
||||
return {set(id:string|null,localID:string|null=null,preview=true){pair.preview=preview;pair.remote.set(id);const changed=pair.local.id!==localID;pair.local.set(localID);if(changed&&localID)pair.local.record('lifecycle',{reason:'local_capture_attached',foreground:roverEvidenceForeground()});},
|
||||
async flush(){for(const e of [pair.remote,pair.local])for(let n=0;n<9&&e.rows.length;n++){if(e.busy)await new Promise(r=>setTimeout(r,25));else await e.flush();}},
|
||||
close(){clearInterval(timer);for(const e of [pair.remote,pair.local])void e.flush();if(sessions.get(url)===pair)sessions.delete(url);}};
|
||||
}
|
||||
|
||||
export function roverEvidenceForeground(){try{return typeof document!=='undefined'&&!document.hidden&&document.hasFocus();}catch{return false;}}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type {RoverState} from './useRoverControl';
|
||||
|
||||
/** Opening a view reads state; only a new failure produces an event toast. */
|
||||
export class RoverFaultNotice {
|
||||
private baseline=false;
|
||||
private key='';
|
||||
private message='';
|
||||
update(value:RoverState,ownedSession:string|null):{show?:string;clear?:string}{
|
||||
if(!value.fresh)return {};
|
||||
const s=value.snapshot,message=s.state==='fault'?s.message??'':'';
|
||||
const key=message?JSON.stringify([s.instance,s.session_id,message]):'';
|
||||
const changed=key!==this.key;
|
||||
const show=changed&&message&&(this.baseline||!!ownedSession)?message:undefined;
|
||||
const clear=changed&&this.message?this.message:undefined;
|
||||
this.baseline=true;this.key=key;this.message=message;
|
||||
return {show,clear};
|
||||
}
|
||||
}
|
||||
@@ -1,44 +1,53 @@
|
||||
import {keyDemand,keysFor,type Demand,type RoverMode} from './roverInput';
|
||||
|
||||
// The network heartbeat is not evidence that a physical key is still held.
|
||||
// Allow the initial OS repeat delay, then require continuing keyboard evidence.
|
||||
export const firstKeyLeaseMs=1000,repeatKeyLeaseMs=300;
|
||||
// Key state is keydown/keyup, independent of OS autorepeat (which may
|
||||
// stop for the remaining key after releasing the last key in a chord).
|
||||
// Focus/visibility revoke input; Core and Node independently expire heartbeat.
|
||||
export function bindRoverHoldInput(scope:HTMLElement,mode:RoverMode,callbacks:{
|
||||
trace?:(event:string,data:Record<string,unknown>)=>void;
|
||||
held:(keys:Set<string>)=>void;demand:(value:Demand)=>void;pause:()=>void;stop:()=>void;
|
||||
},now:()=>number=()=>performance.now()){
|
||||
}){
|
||||
const doc=scope.ownerDocument,win=doc.defaultView!;
|
||||
const keyboard=new Set<string>(),pointers=new Map<number,string>();
|
||||
let deadline=0,closed=false,suspended=false;
|
||||
const clear=()=>{keyboard.clear();pointers.clear();deadline=0;callbacks.held(new Set());};
|
||||
const pause=()=>{if(closed||suspended)return;suspended=true;clear();callbacks.pause();};
|
||||
const stop=()=>{if(closed)return;closed=true;clear();callbacks.stop();};
|
||||
const focused=()=>!doc.hidden&&doc.hasFocus()&&scope.contains(doc.activeElement);
|
||||
let closed=false,suspended=false;
|
||||
const trace=(event:string,data:Record<string,unknown>={})=>{try{callbacks.trace?.(event,{mode,held:[...keyboard,...pointers.values()],...data});}catch{}};
|
||||
const clear=()=>{keyboard.clear();pointers.clear();callbacks.held(new Set());};
|
||||
const pause=(reason:unknown="contextmenu")=>{if(closed||suspended)return;trace("pause",{reason:typeof reason==="string"?reason:"contextmenu"});suspended=true;clear();callbacks.pause();};
|
||||
const stop=()=>{if(closed)return;trace("stop",{reason:"operator_or_pagehide"});closed=true;clear();callbacks.stop();};
|
||||
// Armed authority belongs to the visible observation center, not one canvas.
|
||||
// Modal focus returns to its header Play button; browser chrome can return it
|
||||
// to body. Neither should require a canvas click before a NEW physical press.
|
||||
const editable='input,textarea,select,[contenteditable]:not([contenteditable="false"]),[role=dialog],[role=listbox],[role=menu]';
|
||||
const focused=()=>!doc.hidden&&doc.hasFocus()
|
||||
&&(scope.contains(doc.activeElement)||doc.activeElement===doc.body)
|
||||
&&!doc.activeElement?.closest(editable)&&!doc.querySelector('[role=dialog],[role=listbox],[role=menu]');
|
||||
const valid=()=>{
|
||||
if(closed)return false;
|
||||
if(!focused()||(keyboard.size>0&&now()>=deadline)){pause();return false;}
|
||||
if(!focused()){pause("focus_lost");return false;}
|
||||
return true;
|
||||
};
|
||||
const publish=()=>{const held=new Set([...keyboard,...pointers.values()]);callbacks.held(held);callbacks.demand(keyDemand(mode,held));};
|
||||
const down=(e:KeyboardEvent)=>{
|
||||
if(!e.isTrusted||closed)return;
|
||||
if(keysFor(mode).includes(e.code)||e.code==='Space'||e.code==='Escape')trace('key_down',{code:e.code,repeat:e.repeat});
|
||||
if(e.code==='Space'||e.code==='Escape'){e.preventDefault();stop();return;}
|
||||
if(e.altKey||e.ctrlKey||e.metaKey){pause();return;}
|
||||
if(!keysFor(mode).includes(e.code)||!valid())return;
|
||||
if((e.target as HTMLElement)?.closest('input,textarea,select,[role=dialog],[role=listbox]')){pause();return;}
|
||||
if((e.target as HTMLElement)?.closest(editable)){pause();return;}
|
||||
// A repeat delivered after focus returns cannot become a fresh press.
|
||||
if(e.repeat&&!keyboard.has(e.code))return;
|
||||
e.preventDefault();suspended=false;keyboard.add(e.code);
|
||||
deadline=now()+(e.repeat?repeatKeyLeaseMs:firstKeyLeaseMs);publish();
|
||||
publish();
|
||||
};
|
||||
const up=(e:KeyboardEvent)=>{
|
||||
if(!e.isTrusted||closed||!keyboard.delete(e.code))return;
|
||||
e.preventDefault();if(!keyboard.size)deadline=0;publish();
|
||||
trace("key_up",{code:e.code});e.preventDefault();publish();
|
||||
};
|
||||
const blur=(e:Event)=>{if(e.target===win)pause();};
|
||||
const blur=(e:Event)=>{if(e.target===win)pause("window_blur");};
|
||||
const focusOut=(e:FocusEvent)=>{if(scope.contains(e.target as Node)&&!scope.contains(e.relatedTarget as Node|null))pause();};
|
||||
const focusIn=()=>{if(!focused())pause();};
|
||||
const hidden=()=>{if(doc.hidden)pause();};
|
||||
const outside=(e:Event)=>{if(!scope.contains(e.target as Node))pause();};
|
||||
const hidden=()=>{if(doc.hidden)pause("page_hidden");};
|
||||
const outside=(e:Event)=>{if(!scope.contains(e.target as Node))pause("outside_pointer");};
|
||||
const pointerUp=(e:PointerEvent)=>{if(!closed&&pointers.delete(e.pointerId))publish();};
|
||||
const pointerCancel=(e:PointerEvent)=>{if(pointers.has(e.pointerId))pause();};
|
||||
win.addEventListener('keydown',down,true);win.addEventListener('keyup',up,true);
|
||||
@@ -50,11 +59,11 @@ export function bindRoverHoldInput(scope:HTMLElement,mode:RoverMode,callbacks:{
|
||||
const timer=win.setInterval(valid,50);
|
||||
return {
|
||||
valid,
|
||||
pointerDown(id:number,code:string){if(valid()){suspended=false;pointers.set(id,code);publish();}},
|
||||
pointerDown(id:number,code:string){if(valid()){trace("pointer_down",{code});suspended=false;pointers.set(id,code);publish();}},
|
||||
pointerUp(id:number){if(!closed&&pointers.delete(id))publish();},
|
||||
pointerCancel(id:number){if(pointers.has(id))pause();},
|
||||
pointerCancel(id:number){if(pointers.has(id)){trace("pointer_cancel");pause("pointer_cancel");}},
|
||||
dispose(){
|
||||
closed=true;clear();callbacks.demand({left:0,right:0});win.clearInterval(timer);
|
||||
trace("lifecycle",{reason:"input_disposed"});closed=true;clear();callbacks.demand({left:0,right:0});win.clearInterval(timer);
|
||||
win.removeEventListener('keydown',down,true);win.removeEventListener('keyup',up,true);
|
||||
win.removeEventListener('blur',blur,true);win.removeEventListener('pagehide',stop);
|
||||
doc.removeEventListener('focusout',focusOut,true);doc.removeEventListener('focusin',focusIn,true);
|
||||
|
||||
@@ -8,13 +8,25 @@ export function keyDemand(mode:RoverMode,held:ReadonlySet<string>):Demand {
|
||||
const scale=Math.max(1,Math.abs(forward)+Math.abs(turn));
|
||||
return {left:(forward+turn)/scale,right:(forward-turn)/scale};
|
||||
}
|
||||
export const defaultRoverSettings={version:1,mode:'arcade' as RoverMode,currentA:30,maxErpm:2000,model:''};
|
||||
export const defaultRoverSettings={version:3,mode:'arcade' as RoverMode,currentA:30,maxErpm:2000,throttlePercent:10,model:''};
|
||||
export function roverSettings(value:unknown):typeof defaultRoverSettings {
|
||||
const v=value as Partial<typeof defaultRoverSettings>|null;
|
||||
return {...defaultRoverSettings,...(v?.version===1?{
|
||||
return {...defaultRoverSettings,...(v?.version===1||v?.version===2||v?.version===3?{
|
||||
mode:v.mode==='tank'?'tank':'arcade',
|
||||
currentA:typeof v.currentA==='number'&&Number.isFinite(v.currentA)?Math.max(.5,Math.min(30,v.currentA)):30,
|
||||
// Legacy forms persisted an empty field as 0, then clamped it to .5.
|
||||
// Repair that legacy floor once; v3 keeps an explicitly chosen .5 A.
|
||||
currentA:typeof v.currentA==='number'&&Number.isFinite(v.currentA)&&v.currentA>=.5&&!(v.version!==3&&v.currentA===.5)?v.currentA:30,
|
||||
maxErpm:typeof v.maxErpm==='number'&&Number.isFinite(v.maxErpm)?Math.max(300,Math.min(3000,v.maxErpm)):2000,
|
||||
// ERPM has no trustworthy conversion to throttle. Migrate at 10%, never
|
||||
// reinterpret an old saved number as a percentage or full throttle.
|
||||
throttlePercent:v.version!==1&&typeof v.throttlePercent==='number'&&Number.isFinite(v.throttlePercent)?Math.max(1,Math.min(100,v.throttlePercent)):10,
|
||||
model:v.model==='dcd006-v020'?v.model:'',
|
||||
}:{} )};
|
||||
}
|
||||
|
||||
export const roverNumberInput=(value:string)=>value.trim()===''?Number.NaN:Number(value);
|
||||
export function persistableRoverSettings(v:typeof defaultRoverSettings){
|
||||
return Number.isFinite(v.currentA)&&v.currentA>=.5
|
||||
&&Number.isFinite(v.throttlePercent)&&v.throttlePercent>=1&&v.throttlePercent<=100
|
||||
&&Number.isFinite(v.maxErpm)&&v.maxErpm>=300&&v.maxErpm<=3000;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
/** Stream the complete onboard snapshot to the operator's chosen file. */
|
||||
import {transferRoverLog} from './roverLogTransfer';
|
||||
type SaveWindow=Window&{showSaveFilePicker?:(options:unknown)=>Promise<FileSystemFileHandle>};
|
||||
export async function saveRoverLog(url:string,name:string){
|
||||
const picker=(window as SaveWindow).showSaveFilePicker;
|
||||
if(!picker){
|
||||
// Native download remains a streaming fallback; the browser owns its save UI.
|
||||
const a=document.createElement('a');a.href=url+'/diagnostics/export';a.download=name;a.click();return;
|
||||
}
|
||||
const handle=await picker.call(window,{suggestedName:name,types:[{description:'Лог сессии JSONL',accept:{'application/x-ndjson':['.jsonl']}}]});
|
||||
const writable=await handle.createWritable();
|
||||
try{
|
||||
await transferRoverLog(url,data=>writable.write(data));
|
||||
await writable.close();
|
||||
}catch(error){await writable.abort().catch(()=>{});throw error;}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/** Bounded transfer of an immutable onboard snapshot over the existing HTTP API. */
|
||||
export type LogCursor={capture_id:string;total_bytes:number;snapshot:string;offset:number};
|
||||
const MAX_LINE=100*1024;
|
||||
const failure=()=>new Error('Не удалось проверить файл с борта. Повторите сохранение.');
|
||||
|
||||
export async function readLogBlocks(response:Response,cursor:LogCursor|undefined,write:(data:Uint8Array<ArrayBuffer>)=>Promise<void>,confirmed:(value:LogCursor)=>void){
|
||||
if(!response.body)throw failure();
|
||||
const reader=response.body.getReader(),decoder=new TextDecoder('utf-8',{fatal:true});
|
||||
let pending='',complete=false;
|
||||
try{
|
||||
while(true){
|
||||
const {done,value}=await reader.read();
|
||||
if(done){if(pending||!complete)throw failure();return;}
|
||||
// Split before decoding so even an unexpectedly large HTTP read cannot create
|
||||
// an unbounded accumulated string. Only a single export block is retained.
|
||||
for(let start=0;start<value.length;start+=8192){
|
||||
pending+=decoder.decode(value.subarray(start,start+8192),{stream:true});
|
||||
let end:number;
|
||||
while((end=pending.indexOf('\n'))>=0){
|
||||
if(end>MAX_LINE||complete)throw failure();
|
||||
const row=JSON.parse(pending.slice(0,end));pending=pending.slice(end+1);
|
||||
if(!/^[a-f0-9]{32}$/.test(row.capture_id)||!/^[a-f0-9]{64}$/.test(row.snapshot)||!/^[a-f0-9]{64}$/.test(row.sha256)
|
||||
||![row.offset,row.next,row.total_bytes].every(Number.isSafeInteger)
|
||||
||row.offset<0||row.next<row.offset||row.next>row.total_bytes
|
||||
||typeof row.data!=='string'||row.data.length>87384)throw failure();
|
||||
if(cursor?(row.capture_id!==cursor.capture_id||row.snapshot!==cursor.snapshot||row.total_bytes!==cursor.total_bytes||row.offset!==cursor.offset):row.offset!==0)throw failure();
|
||||
const raw=Uint8Array.from(atob(row.data),c=>c.charCodeAt(0));
|
||||
if(raw.length>65536||raw.length!==row.next-row.offset||(!raw.length&&row.next!==row.total_bytes))throw failure();
|
||||
const digest=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',raw)),n=>n.toString(16).padStart(2,'0')).join('');
|
||||
if(digest!==row.sha256)throw failure();
|
||||
await write(raw);
|
||||
cursor={capture_id:row.capture_id,total_bytes:row.total_bytes,snapshot:row.snapshot,offset:row.next};
|
||||
confirmed(cursor);complete=cursor.offset===cursor.total_bytes;
|
||||
}
|
||||
if(pending.length>MAX_LINE)throw failure();
|
||||
}
|
||||
}
|
||||
}finally{await reader.cancel().catch(()=>{});reader.releaseLock();}
|
||||
}
|
||||
|
||||
export async function transferRoverLog(url:string,write:(data:Uint8Array<ArrayBuffer>)=>Promise<void>){
|
||||
let cursor:LogCursor|undefined;
|
||||
for(let attempt=0;attempt<4;attempt++){
|
||||
const params=new URLSearchParams({format:'chunks'});
|
||||
if(cursor)for(const [key,value] of Object.entries(cursor))params.set(key,String(value));
|
||||
const controller=new AbortController();
|
||||
let timer:ReturnType<typeof setTimeout>;
|
||||
const reset=()=>{clearTimeout(timer);timer=setTimeout(()=>controller.abort(),130000);};
|
||||
reset();
|
||||
try{
|
||||
const response=await fetch(url+'/diagnostics/export?'+params,{signal:controller.signal});
|
||||
if(!response.ok)throw new Error('Не удалось получить файл с борта. Проверьте связь и повторите сохранение.');
|
||||
await readLogBlocks(response,cursor,write,value=>{cursor=value;reset();});
|
||||
return;
|
||||
}catch(error){
|
||||
if(attempt===3)throw error;
|
||||
// No session-duration limit. Retry only a failed download, retaining the
|
||||
// exact snapshot and the last verified, successfully written offset.
|
||||
await new Promise(resolve=>setTimeout(resolve,1000*(attempt+1)));
|
||||
}finally{clearTimeout(timer!);controller.abort();}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type {RoverConnection} from './roverTransport';
|
||||
import type {RoverState} from './useRoverControl';
|
||||
|
||||
export interface RoverObservationStatus {label:string|null;pulse:boolean}
|
||||
/** Presentation only. A fresh driver snapshot owns its attachment lifecycle;
|
||||
* inventory and elapsed UI time cannot establish readiness or motor authority. */
|
||||
export function roverObservationStatus(state:RoverState,connection:RoverConnection):RoverObservationStatus{
|
||||
const pending=(label:string)=>({label,pulse:true});
|
||||
if(connection==='connecting')return pending('Подключение к Mission Core');
|
||||
if(connection!=='connected')return pending('Восстановление связи с Mission Core');
|
||||
if(!state.fresh)return pending('Ожидание телеметрии с борта');
|
||||
const snapshot=state.snapshot;
|
||||
if(!snapshot.supported)return {label:'Служба управления на борту недоступна',pulse:false};
|
||||
if(snapshot.message||snapshot.state==='fault')return {label:null,pulse:false};
|
||||
const readings=snapshot.devices??[],expected=Object.values(snapshot.profile?.bindings??{});
|
||||
const missing=expected.filter(b=>!readings.some(d=>d.id===b.device_id&&d.uuid===b.uuid));
|
||||
const initializing=snapshot.observation?.initializing_devices??[];
|
||||
if(initializing.length&&(missing.length?missing.every(b=>initializing.includes(b.device_id)):!expected.length&&!readings.length))return pending('Инициализация VESC');
|
||||
if(missing.length||!readings.length||readings.some(d=>!Number.isFinite(d.age_ms)||d.age_ms<0||d.age_ms>=1000))return pending('Ожидание свежих показаний VESC');
|
||||
return {label:null,pulse:false};
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/** Bounded local diagnostic download. No request to the board or motion API. */
|
||||
export async function saveOperatorCapture(url:string,id:string,beforeSnapshot:()=>Promise<void>=async()=>{}){
|
||||
if(!/^[a-f0-9]{32}$/.test(id))throw Error('Запись изменилась.');
|
||||
await beforeSnapshot();
|
||||
const response=await fetch(url+'/diagnostics/local/export?capture_id='+id,{cache:'no-store',signal:AbortSignal.timeout(5000)});
|
||||
if(!response.ok)throw Error('Не удалось выгрузить замер компьютера. Запись сохранена в Core.');
|
||||
const blob=await response.blob();if(blob.size>4*1024*1024)throw Error('Размер замера превышает допустимый.');
|
||||
// The bounded snapshot uses the browser's normal download flow, including fullscreen.
|
||||
const href=URL.createObjectURL(blob),a=document.createElement('a');
|
||||
try{a.href=href;a.download=`rover-operator-${id}.jsonl`;document.body.append(a);a.click();}
|
||||
finally{a.remove();setTimeout(()=>URL.revokeObjectURL(href),1000);}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import type {RoverState} from './useRoverControl';
|
||||
|
||||
export interface RoverArmSettings {currentA:number;speed:number;mode:'rpm'|'duty'}
|
||||
const MAX_RETRY_BACKOFF=3;
|
||||
const STABLE_CONNECTION_MS=30000;
|
||||
const MAX_READY_OBSERVATION_GAP_MS=1000;
|
||||
const profileKey=(s:RoverState['snapshot'])=>JSON.stringify(s.profile??null);
|
||||
const motorKey=(s:RoverState['snapshot'])=>(s.devices??[]).map(d=>d.uuid+'@'+(d.session_id??'')).sort().join(':');
|
||||
|
||||
// Reacquire a NEW neutral lease after transport loss. Never revive an expired
|
||||
// lease or remember motion. Explicit Stop, hardware faults and RC takeover end
|
||||
// the operator's request; navigation/reload never persists it.
|
||||
export class RoverRecovery {
|
||||
private request:{settings:RoverArmSettings;instance:string;profile:string;motors:string;previousSession:string|null|undefined}|null=null;
|
||||
private pendingSession:string|null=null;
|
||||
private quietSince:number|null=null;
|
||||
private retryAt=0;
|
||||
private attempts=0;
|
||||
private readySince:number|null=null;
|
||||
private lastReadyAt:number|null=null;
|
||||
private retiredSession:string|null=null;
|
||||
waiting=false;
|
||||
remember(settings:RoverArmSettings,value:RoverState){
|
||||
this.clear();
|
||||
if(value.fresh&&value.snapshot.instance&&value.snapshot.devices?.length&&value.snapshot.devices.every(d=>d.session_id))this.request={settings:{...settings},instance:value.snapshot.instance,profile:profileKey(value.snapshot),motors:motorKey(value.snapshot),previousSession:value.snapshot.session_id};
|
||||
}
|
||||
clear(){this.request=null;this.waiting=false;this.quietSince=null;this.attempts=0;this.retryAt=0;this.retiredSession=null;this.pendingSession=null;this.readySince=null;this.lastReadyAt=null;}
|
||||
started(session:string){if(!this.waiting)this.pendingSession=session;}
|
||||
previousStatus(value:RoverState,ownedSession:string|null){
|
||||
// An explicit new arm acknowledges the previous terminal session. Core may
|
||||
// still expose that snapshot until the board receives the new neutral lease.
|
||||
return !!this.request&&!!ownedSession&&ownedSession===this.pendingSession&&!this.waiting
|
||||
&&value.fresh&&value.controlling&&value.snapshot.session_id===this.request.previousSession
|
||||
&&value.snapshot.session_id!==ownedSession&&['fault','stopped','receiver','observing'].includes(value.snapshot.state??'');
|
||||
}
|
||||
connected(now:number){
|
||||
this.waiting=false;this.quietSince=null;this.pendingSession=null;
|
||||
// One ready snapshot is not a recovered link. Require continuous fresh
|
||||
// observations before forgiving repeated automatic rearm attempts.
|
||||
if(this.lastReadyAt===null||now<this.lastReadyAt||now-this.lastReadyAt>MAX_READY_OBSERVATION_GAP_MS)this.readySince=now;
|
||||
this.lastReadyAt=now;this.readySince??=now;
|
||||
if(now-this.readySince>=STABLE_CONNECTION_MS){this.attempts=0;this.retryAt=0;}
|
||||
}
|
||||
interrupt(now:number,session:string|null){
|
||||
if(!this.request)return false;
|
||||
this.readySince=null;this.lastReadyAt=null;
|
||||
if(!this.waiting){this.retryAt=Math.max(this.retryAt,now+500);this.quietSince=null;}
|
||||
this.retiredSession=session??this.retiredSession;this.waiting=true;this.pendingSession=null;return true;
|
||||
}
|
||||
blocker(value:RoverState,ownedSession:string|null=null){
|
||||
if(!this.request||!value.fresh)return null;
|
||||
const s=value.snapshot;
|
||||
if(s.instance!==this.request.instance)return 'Борт перезапустился. Проверьте состояние и включите управление.';
|
||||
if(motorKey(s)!==this.request.motors)return 'Подключение VESC изменилось. Проверьте состояние и включите управление.';
|
||||
if(profileKey(s)!==this.request.profile)return 'Назначение моторов изменилось. Проверьте настройки управления.';
|
||||
if(s.supported!==true||(this.request.settings.mode==='duty'&&!s.control_modes?.includes('duty')))return 'Режим управления на борту изменился.';
|
||||
if(s.session_id===ownedSession)this.pendingSession=null;
|
||||
if(this.previousStatus(value,ownedSession))return null;
|
||||
const ended=s.last_stop;
|
||||
if(ended?.state==='fault'&&(ended.session_id===ownedSession||ended.session_id===this.retiredSession))return ended.message||'Предыдущий сеанс завершился с ошибкой. Включите управление заново.';
|
||||
// Stopping is an interlock, not a terminal cancellation. The board may need
|
||||
// fresh passive samples to verify release. next() still requires confirmed
|
||||
// stopped state; a hardware fault (including historical fault) still blocks.
|
||||
if(s.state==='fault'||(s.release_confirmed===false&&s.state!=='stopping'))return s.message||'Борт сообщил об ошибке. Проверьте состояние перед включением.';
|
||||
if(s.state==='receiver')return 'Управление передано пульту.';
|
||||
if(this.waiting&&value.controlling&&s.session_id&&s.session_id!==this.retiredSession&&s.session_id!==ownedSession)return 'Управление включено в другом окне.';
|
||||
return null;
|
||||
}
|
||||
next(value:RoverState,now:number,focused:boolean):RoverArmSettings|null{
|
||||
if(!this.waiting||!this.request)return null;
|
||||
if(this.blocker(value)){this.clear();return null;}
|
||||
const s=value.snapshot,devices=s.devices??[];
|
||||
const quiet=value.fresh&&!value.controlling&&s.state==='stopped'&&s.release_confirmed===true
|
||||
&&motorKey(s)===this.request.motors&&devices.length>0&&devices.every(d=>Number.isFinite(d.age_ms)&&d.age_ms>=0&&d.age_ms<=500
|
||||
&&Number.isFinite(d.values.erpm)&&Math.abs(d.values.erpm)<60&&d.values.fault_code===0);
|
||||
if(!focused||!quiet){this.quietSince=null;return null;}
|
||||
this.quietSince??=now;
|
||||
if(now-this.quietSince<500||now<this.retryAt)return null;
|
||||
// Transport loss retains the operator request; only retry rate is bounded.
|
||||
// Saturate the exponent so a long outage cannot grow an attempt counter.
|
||||
this.retryAt=now+1000*2**this.attempts;this.attempts=Math.min(this.attempts+1,MAX_RETRY_BACKOFF);this.quietSince=null;
|
||||
return {...this.request.settings};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/** Bounded, volatile engineering evidence. Never participates in control decisions. */
|
||||
export class RoverTiming {
|
||||
private lastTick:number|null=null;
|
||||
private events:Record<string,string|number|boolean>[]=[];
|
||||
private started=performance.now();
|
||||
private tickGap=0;
|
||||
private requestMS=0;
|
||||
private samples=0;
|
||||
private staleSamples=0;
|
||||
private hadFresh=false;
|
||||
view(fresh:boolean){this.samples++;if(fresh)this.hadFresh=true;else if(this.hadFresh)this.staleSamples++;this.publish();}
|
||||
private event(value:Record<string,string|number|boolean>){
|
||||
this.events.push({at_ms:Math.round(performance.now()-this.started),...value});this.events=this.events.slice(-16);
|
||||
}
|
||||
tick(active:boolean){
|
||||
const now=performance.now();this.tickGap=this.lastTick===null?0:Math.round(now-this.lastTick);this.lastTick=now;
|
||||
if(this.tickGap>=200)this.event({kind:'heartbeat-gap',gap_ms:this.tickGap,active,hidden:document.hidden,focused:document.hasFocus()});
|
||||
this.publish();
|
||||
}
|
||||
request(kind:'view'|'arm'|'command',started:number,outcome:'ok'|'http'|'transport',url?:string){
|
||||
this.requestMS=Math.round(performance.now()-started);
|
||||
let network:Record<string,number>={};
|
||||
try{if(url&&typeof performance.getEntriesByName==='function'){
|
||||
const entry=performance.getEntriesByName(new URL(url,window.location.href).href,'resource').at(-1) as PerformanceResourceTiming|undefined;
|
||||
if(entry&&entry.startTime>=started-1&&entry.requestStart>0)network={browser_wait_ms:Math.round(entry.requestStart-entry.fetchStart),response_wait_ms:Math.round(entry.responseStart-entry.requestStart),body_ms:Math.round(entry.responseEnd-entry.responseStart)};
|
||||
}}catch{/* Diagnostics cannot interfere with a command. */}
|
||||
if(this.requestMS>=200||outcome!=='ok')this.event({kind,outcome,duration_ms:this.requestMS,hidden:document.hidden,focused:document.hasFocus(),...network});
|
||||
this.publish();
|
||||
}
|
||||
private publish(){
|
||||
// One replaceable DOM diagnostic record; no telemetry archive or product control.
|
||||
if(document.documentElement)document.documentElement.dataset.roverTiming=JSON.stringify({sampled_at_ms:Math.round(performance.now()),tick_gap_ms:this.tickGap,request_ms:this.requestMS,state_samples:this.samples,stale_after_fresh:this.staleSamples,events:this.events});
|
||||
}
|
||||
clear(){this.lastTick=null;this.events=[];this.samples=0;this.staleSamples=0;this.hadFresh=false;this.started=performance.now();if(document.documentElement)delete document.documentElement.dataset.roverTiming;}
|
||||
}
|
||||
export const roverTiming=new RoverTiming();
|
||||
@@ -0,0 +1,107 @@
|
||||
import {roverDevEvent,roverEvidenceForeground} from './roverDevEvents';
|
||||
/** Separate socket from HTTP asset/SSE queues. No queued or replayed commands. */
|
||||
export class RoverHttpError extends Error {constructor(message:string,readonly status:number){super(message);}}
|
||||
export type RoverConnection='connecting'|'connected'|'reconnecting'|'closed';
|
||||
type Pending={resolve:(value:any)=>void;reject:(reason:Error)=>void;timer:ReturnType<typeof setTimeout>};
|
||||
export class RoverTransport {
|
||||
private socket:WebSocket|null=null;
|
||||
private latest:unknown;
|
||||
private seen=-Infinity;
|
||||
private clock=0;
|
||||
private clockAt=0;
|
||||
private next=0;
|
||||
private socketID='';
|
||||
private lastSent:number|null=null;
|
||||
private pending=new Map<number,Pending>();
|
||||
private waiting=new Set<Pending>();
|
||||
private retry:ReturnType<typeof setTimeout>|undefined;
|
||||
private closed=false;
|
||||
private watchdog:ReturnType<typeof setTimeout>|undefined;
|
||||
private failures=0;
|
||||
private received=false;
|
||||
connection():RoverConnection{return this.closed?'closed':performance.now()-this.seen<600?'connected':this.received||this.failures>0?'reconnecting':'connecting';}
|
||||
private touch(socket:WebSocket){
|
||||
clearTimeout(this.watchdog);
|
||||
this.watchdog=setTimeout(()=>this.disconnect(socket,"watchdog"),1500);
|
||||
}
|
||||
private disconnect(socket:WebSocket,reason:string){
|
||||
if(this.socket!==socket)return;
|
||||
roverDevEvent(this.url,"transport",{reason,ready_state:socket.readyState,buffered_bytes:socket.bufferedAmount,pending:this.pending.size});
|
||||
this.socket=null;this.seen=-Infinity;clearTimeout(this.watchdog);this.fail();
|
||||
// Retire locally even when the browser never emits a close event.
|
||||
socket.onopen=socket.onmessage=socket.onclose=socket.onerror=null;socket.close();
|
||||
if(!this.closed)this.retry=setTimeout(()=>this.connect(),Math.min(250*2**Math.min(this.failures++,4),4000));
|
||||
}
|
||||
constructor(private url:string,private create:(url:string)=>WebSocket=url=>new WebSocket(url)){this.connect();}
|
||||
private connect(){
|
||||
if(this.closed)return;
|
||||
const url=new URL(this.url+'-channel',window.location.href);url.protocol=url.protocol==='https:'?'wss:':'ws:';
|
||||
const socket=this.create(url.href);this.socket=socket;this.socketID='';this.lastSent=null;
|
||||
// A browser handshake owns no motion authority. Do not repeatedly cancel a
|
||||
// cold connection with the live-state deadline before it can open. Once open,
|
||||
// the original watchdog and all sample/command deadlines still apply.
|
||||
clearTimeout(this.watchdog);
|
||||
this.watchdog=setTimeout(()=>this.disconnect(socket,'connect_timeout'),10000);
|
||||
socket.onopen=()=>{if(this.socket===socket)this.touch(socket);};
|
||||
if(socket.readyState===1)this.touch(socket);
|
||||
socket.onmessage=event=>{
|
||||
if(this.socket!==socket)return;
|
||||
try{const value=JSON.parse(event.data);
|
||||
if(typeof value.socket_id==='string')this.socketID=value.socket_id;
|
||||
if(value.type==='reply')roverDevEvent(this.url,'transport',{reason:'reply_received',request_id:value.id,socket_id:this.socketID,clock_ms:value.clock_ms,outcome:String(value.status??200)});
|
||||
if(value.type==='state'&&Number.isFinite(value.clock_ms)){
|
||||
this.received=true;this.latest=value.value;this.seen=performance.now();this.clock=value.clock_ms;this.clockAt=this.seen;this.failures=0;this.touch(socket);
|
||||
for(const p of this.waiting){clearTimeout(p.timer);p.resolve(this.latest);}this.waiting.clear();
|
||||
}else if(value.type==='reply'){
|
||||
const p=this.pending.get(value.id);if(!p)return;this.pending.delete(value.id);clearTimeout(p.timer);
|
||||
if(value.state&&Number.isFinite(value.clock_ms)){
|
||||
this.latest=value.state;this.seen=performance.now();this.clock=value.clock_ms;this.clockAt=this.seen;this.failures=0;this.touch(socket);
|
||||
for(const waiter of this.waiting){clearTimeout(waiter.timer);waiter.resolve(this.latest);}this.waiting.clear();
|
||||
}
|
||||
if(value.error)roverDevEvent(this.url,'transport',{reason:'reply_rejected',outcome:String(value.status??409)});
|
||||
if(value.error)p.reject(new RoverHttpError(value.error,value.status??409));else p.resolve(value.value);
|
||||
}
|
||||
}catch{/* Invalid frames never acknowledge a request. */}
|
||||
};
|
||||
socket.onclose=event=>{roverDevEvent(this.url,"transport",{reason:"close",close_code:event?.code});this.disconnect(socket,"close");};
|
||||
socket.onerror=()=>this.disconnect(socket,"error");
|
||||
}
|
||||
private fail(){
|
||||
for(const p of [...this.pending.values(),...this.waiting]){clearTimeout(p.timer);p.reject(new Error('Канал управления недоступен.'));}
|
||||
this.pending.clear();this.waiting.clear();
|
||||
}
|
||||
view():Promise<unknown>{
|
||||
if(this.closed)return Promise.reject(new Error('Канал управления недоступен.'));
|
||||
if(performance.now()-this.seen<600)return Promise.resolve(this.latest);
|
||||
return new Promise((resolve,reject)=>{const p:Pending={resolve,reject,timer:setTimeout(()=>{this.waiting.delete(p);reject(new Error('Нет свежих данных с борта.'));},1000)};this.waiting.add(p);});
|
||||
}
|
||||
command(action:'arm'|'command'|'hold',body:unknown):Promise<unknown>{
|
||||
const socket=this.socket,now=performance.now();
|
||||
if(!socket||socket.readyState!==1||socket.bufferedAmount>4096||now-this.seen>=600||this.pending.size>=4)return Promise.reject(new Error('Канал управления недоступен.'));
|
||||
const id=++this.next;
|
||||
return new Promise((resolve,reject)=>{
|
||||
this.pending.set(id,{resolve,reject,timer:setTimeout(()=>{this.pending.delete(id);roverDevEvent(this.url,'transport',{reason:'ack_timeout',action,request_id:id,socket_id:this.socketID});reject(new Error('Команда не подтверждена.'));},350)});
|
||||
try{
|
||||
const expires=this.clock+(now-this.clockAt)+400;
|
||||
const fields=body&&typeof body==='object'?body as Record<string,unknown>:{};
|
||||
roverDevEvent(this.url,'request',{reason:'socket_send',request_id:id,socket_id:this.socketID,action,
|
||||
session_id:fields.session_id,sequence:fields.sequence,expires_ms:expires,state_age_ms:now-this.seen,
|
||||
gap_ms:this.lastSent===null?0:now-this.lastSent,foreground:roverEvidenceForeground()});
|
||||
socket.send(JSON.stringify({id,action,body,expires_ms:expires}));this.lastSent=now;
|
||||
}
|
||||
catch{const p=this.pending.get(id);if(p){clearTimeout(p.timer);this.pending.delete(id);}reject(new Error('Канал управления недоступен.'));}
|
||||
});
|
||||
}
|
||||
close(){this.closed=true;clearTimeout(this.retry);clearTimeout(this.watchdog);const socket=this.socket;this.socket=null;this.seen=-Infinity;this.fail();socket?.close();}
|
||||
}
|
||||
const clients=new Map<string,{transport:RoverTransport;users:number}>();
|
||||
export function retainRoverTransport(url:string){
|
||||
let entry=clients.get(url);if(!entry){entry={transport:new RoverTransport(url),users:0};clients.set(url,entry);}entry.users++;
|
||||
return()=>{if(--entry!.users===0){entry!.transport.close();clients.delete(url);}};
|
||||
}
|
||||
export function roverRequest<T>(url:string,body?:unknown):Promise<T>{
|
||||
const action=url.endsWith('/arm')?'arm':url.endsWith('/hold')?'hold':'command',base=body?url.slice(0,url.lastIndexOf('/')):url,client=clients.get(base);
|
||||
if(!client)return Promise.reject(new Error('Канал управления недоступен.'));
|
||||
return (body?client.transport.command(action,body):client.transport.view()) as Promise<T>;
|
||||
}
|
||||
export function roverConnection(url:string):RoverConnection{return clients.get(url)?.transport.connection()??'closed';}
|
||||
@@ -1,17 +1,23 @@
|
||||
import type {SensorInventory, SensorTransport} from '../../../../../packages/sensor-ui/src/contracts';
|
||||
import type {SensorInventory, SensorTransport, SensorLiveFrame} from '../../../../../packages/sensor-ui/src/contracts';
|
||||
import {fleetRequest} from './useFleet';
|
||||
import {roverPreviewEvidence} from './roverDevEvents';
|
||||
|
||||
export function createFleetSensorTransport(vehicleID:string):SensorTransport {
|
||||
const path=`/${encodeURIComponent(vehicleID)}/devices`;
|
||||
const inventory=(fleet:{items:{id:string;connectivity:string;enrollment:string;sensor_state:SensorInventory}[]})=>{
|
||||
const inventory=(fleet:{items:{id:string;core_endpoint?:string;connectivity:string;enrollment:string;inventory_fresh?:boolean;sensor_state:SensorInventory}[]})=>{
|
||||
const value=fleet.items.find(v=>v.id===vehicleID);
|
||||
if(!value)throw new Error('Аппарат не найден.');
|
||||
return {...value.sensor_state,fresh:value.connectivity==='online'&&value.enrollment==='paired'};
|
||||
return {...value.sensor_state,items:value.sensor_state.items.map(item=>({...item,transport_generation:value.core_endpoint})),fresh:value.connectivity==='online'&&value.enrollment==='paired'&&value.inventory_fresh!==false};
|
||||
};
|
||||
return {
|
||||
previewEvidence:sample=>roverPreviewEvidence(`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`,sample),
|
||||
liveTelemetry:async signal=>{
|
||||
const value=await fleetRequest<{fresh:boolean;snapshot:Omit<SensorLiveFrame,'fresh'>}>(`/${encodeURIComponent(vehicleID)}/rover`,'GET',undefined,1200,signal);
|
||||
return {...value.snapshot,fresh:value.fresh};
|
||||
},
|
||||
configurationArchive:{list:(device,before)=>fleetRequest(`${path}/${encodeURIComponent(device)}/configurations${before?'?before='+encodeURIComponent(before):''}`),read:(device,version)=>fleetRequest(`${path}/${encodeURIComponent(device)}/configurations/${encodeURIComponent(version)}`)},
|
||||
enrollment:{state:()=>fleetRequest(`${path}/enrollment`),submit:value=>fleetRequest(`${path}/enrollment/operations`,'POST',value),operation:id=>fleetRequest(`${path}/enrollment/operations/${encodeURIComponent(id)}`)},
|
||||
inventory:async()=>inventory(await fleetRequest()),
|
||||
inventory:async signal=>inventory(await fleetRequest('','GET',undefined,12000,signal)),
|
||||
subscribe:(receive,unavailable)=>{const events=new EventSource('/api/v1/fleet/events');events.onmessage=e=>{try{receive(inventory(JSON.parse(e.data)));}catch{unavailable();}};events.onerror=unavailable;return()=>events.close();},
|
||||
submit:value=>fleetRequest(`${path}/operations`,'POST',value),
|
||||
operation:id=>fleetRequest(`${path}/operations/${encodeURIComponent(id)}`),
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {fleetRequest} from './useFleet';
|
||||
export type NetworkProvider='tailscale'|'wireguard';
|
||||
export interface SharedNetworkProfile {id:string;name:string;endpoint:string;state:string;boards:number}
|
||||
export interface BoardNetworkView {
|
||||
profiles:SharedNetworkProfile[];available:boolean;
|
||||
node:{provider:NetworkProvider;server_id?:string;revision:number;phase:string;error?:string;tailscale_endpoint?:string}|null;
|
||||
operation:{id:string;state:string;error?:string}|null;
|
||||
}
|
||||
export function useBoardNetwork(vehicleId:string){
|
||||
const [value,setValue]=useState<BoardNetworkView|null>(null),[provider,setProvider]=useState<NetworkProvider>('tailscale'),[profileId,setProfileId]=useState('');
|
||||
const [error,setError]=useState(''),[busy,setBusy]=useState(false);
|
||||
const revision=useRef<number|null>(null);
|
||||
const accept=useCallback((next:BoardNetworkView)=>{
|
||||
setValue(next);
|
||||
if(next.node&&revision.current!==next.node.revision){revision.current=next.node.revision;setProvider(next.node.provider);setProfileId(next.node.server_id||'');}
|
||||
},[]);
|
||||
const refresh=useCallback(async()=>{const next=await fleetRequest<BoardNetworkView>(`/${encodeURIComponent(vehicleId)}/network-profile`);accept(next);return next;},[vehicleId,accept]);
|
||||
useEffect(()=>{let active=true;let timer:ReturnType<typeof setTimeout>;const controller=new AbortController();
|
||||
const poll=async()=>{try{const next=await fleetRequest<BoardNetworkView>(`/${encodeURIComponent(vehicleId)}/network-profile`,'GET',undefined,12000,controller.signal);if(active)accept(next);}catch(e){if(active){setError(e instanceof Error?e.message:'Состояние подключения недоступно.');setValue(current=>current?{...current,available:false}:null);}}finally{if(active)timer=setTimeout(poll,2000);}};
|
||||
revision.current=null;void poll();return()=>{active=false;controller.abort();clearTimeout(timer);};
|
||||
},[vehicleId,accept]);
|
||||
const importing=async(file:File)=>{if(busy)return;setBusy(true);setError('');try{
|
||||
if(file.size>16384)throw Error('Выберите файл подключения, созданный установщиком VPS.');
|
||||
const item=await fleetRequest<SharedNetworkProfile>('/network-profiles/import','POST',{document:await file.text()},240000);
|
||||
await refresh();setProvider('wireguard');setProfileId(item.id);
|
||||
}catch(e){setError(e instanceof Error?e.message:'Файл не удалось импортировать.');}finally{setBusy(false);}};
|
||||
const applying=value?.operation?.state==='applying'||value?.operation?.state==='rolling_back';
|
||||
const dirty=Boolean(value?.node&&(provider!==value.node.provider||(provider==='wireguard'&&profileId!==value.node.server_id)));
|
||||
const save=async()=>{if(!value?.node||busy||applying)return;setBusy(true);setError('');try{
|
||||
await fleetRequest(`/${encodeURIComponent(vehicleId)}/network-profile`,'PUT',{provider,profile_id:provider==='wireguard'?profileId:null,expected_revision:value.node.revision});await refresh();
|
||||
}catch(e){setError(e instanceof Error?e.message:'Подключение не применено.');}finally{setBusy(false);}};
|
||||
return {value,provider,setProvider,profileId,setProfileId,error,busy,applying,dirty,importing,save,
|
||||
canSave:Boolean(value?.available&&dirty&&!busy&&!applying&&(provider==='tailscale'?value.node?.tailscale_endpoint:profileId))};
|
||||
}
|
||||
@@ -16,11 +16,11 @@ export interface FleetPreview {
|
||||
preview_id: string; node_id: string; name: string; host: BoardHost;
|
||||
endpoint: string; expires_at: number;
|
||||
}
|
||||
export async function fleetRequest<T>(path = "", method = "GET", body?: unknown, timeoutMs = 12000): Promise<T> {
|
||||
export async function fleetRequest<T>(path = "", method = "GET", body?: unknown, timeoutMs = 12000, signal?:AbortSignal): Promise<T> {
|
||||
const response = await fetch(`/api/v1/fleet${path}`, {
|
||||
method, credentials: "same-origin", cache: "no-store",
|
||||
headers: body === undefined ? {} : { "Content-Type": "application/json" },
|
||||
body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs),
|
||||
body: body === undefined ? undefined : JSON.stringify(body), signal: signal?AbortSignal.any([signal,AbortSignal.timeout(timeoutMs)]):AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => ({}));
|
||||
|
||||
@@ -1,79 +1,139 @@
|
||||
import {roverDevEvent} from './roverDevEvents';
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import type {Demand} from './roverInput';
|
||||
import {RoverRecovery,type RoverArmSettings} from './roverRecovery';
|
||||
import {RoverFaultNotice} from './roverFaultNotice';
|
||||
import {roverTiming} from './roverTiming';
|
||||
import {retainRoverTransport,roverRequest,roverConnection,RoverHttpError,type RoverConnection} from './roverTransport';
|
||||
|
||||
export interface RoverReading {
|
||||
id:string;uuid:string;slot:string|null;label:string;age_ms:number;
|
||||
id:string;uuid:string;session_id?:string;slot:string|null;label:string;age_ms:number;
|
||||
current_limits?:{motor_a:number;brake_a:number}|null;
|
||||
values:{motor_current_a:number;input_current_a:number;input_voltage_v:number;erpm:number;duty:number;mos_temperature_c:number;fault_code:number};
|
||||
}
|
||||
export interface RoverState {
|
||||
fresh:boolean;controlling:boolean;
|
||||
snapshot:{supported?:boolean;instance?:string;state?:string;session_id?:string|null;message?:string|null;devices?:RoverReading[];
|
||||
snapshot:{supported?:boolean;control_modes?:string[];instance?:string;state?:string;session_id?:string|null;message?:string|null;release_confirmed?:boolean|null;devices?:RoverReading[];
|
||||
observation?:{initializing_devices:string[]};
|
||||
last_stop?:{session_id:string;state:string;message:string|null;recovered_at?:string};
|
||||
profile?:{layout:null|'1x1'|'2x2';bindings:Record<string,{device_id:string;uuid:string}>}};
|
||||
}
|
||||
// Generate fresh intent at the command channel cadence. Keepalive frames do
|
||||
// not renew the original 400 ms deadline; duplicating a 100 ms-old sample
|
||||
// wastes half of the 50 ms carrier opportunities during a network burst.
|
||||
const INTENT_INTERVAL_MS=50;
|
||||
const empty:RoverState={fresh:false,controlling:false,snapshot:{}};
|
||||
async function request<T>(url:string,body?:unknown,keepalive=false):Promise<T>{
|
||||
const response=await fetch(url,{method:body?'POST':'GET',headers:body?{'Content-Type':'application/json'}:undefined,
|
||||
body:body?JSON.stringify(body):undefined,cache:'no-store',signal:AbortSignal.timeout(body?350:1000),keepalive});
|
||||
const result=await response.json();
|
||||
if(!response.ok)throw new Error(typeof result.detail==='string'?result.detail:'Канал управления недоступен.');
|
||||
const retryable=(e:unknown)=>!(e instanceof RoverHttpError)||e.status>=500||[408,429].includes(e.status)||['Управление завершено. Включите его заново.','Команда устарела до передачи на борт.','Канал управления бортом недоступен.','Дождитесь завершения предыдущего управления.'].includes(e.message);
|
||||
async function request<T>(url:string,body?:unknown,_keepalive=false):Promise<T>{
|
||||
const started=performance.now(),kind=url.endsWith('/arm')?'arm':body?'command':'view';let outcome:'ok'|'http'|'transport'='transport';
|
||||
try{
|
||||
const result=await roverRequest<T>(url,body);
|
||||
outcome='ok';
|
||||
return result;
|
||||
}catch(e){if(e instanceof RoverHttpError)outcome='http';throw e;}finally{roverTiming.request(kind,started,outcome);if(body)roverDevEvent(url.slice(0,url.lastIndexOf('/')),'request',{action:kind,outcome,elapsed_ms:performance.now()-started});}
|
||||
}
|
||||
export function useRoverControl(vehicleID:string,visible:boolean){
|
||||
const url=`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`;
|
||||
const [state,setState]=useState<RoverState>(empty),[armed,setArmed]=useState(false),[pending,setPending]=useState(false),[error,setError]=useState<string|null>(null);
|
||||
const [connecting,setConnecting]=useState(true),armPending=useRef(false);
|
||||
const session=useRef<string|null>(null),seq=useRef(0),demand=useRef<Demand>({left:0,right:0}),sending=useRef(false),generation=useRef(0);
|
||||
const [connection,setConnection]=useState<RoverConnection>('connecting'),armPending=useRef(false);
|
||||
const [recovering,setRecovering]=useState(false),recovery=useRef(new RoverRecovery()),latest=useRef<RoverState>(empty);
|
||||
const [controlMode,setControlMode]=useState<'unknown'|'rpm'|'duty'>('unknown');
|
||||
const session=useRef<string|null>(null),seq=useRef(0),demand=useRef<Demand>({left:0,right:0}),sending=useRef(new Set<string>()),acknowledged=useRef(0),generation=useRef(0);
|
||||
const holding=useRef<string|null>(null);
|
||||
const inputGuard=useRef<(()=>boolean)|null>(null);
|
||||
const setInputGuard=useCallback((guard:(()=>boolean)|null)=>{inputGuard.current=guard;},[]);
|
||||
const stop=useCallback(()=>{
|
||||
generation.current++;armPending.current=false;const id=session.current;session.current=null;demand.current={left:0,right:0};setArmed(false);setPending(false);
|
||||
const retire=useCallback(()=>{
|
||||
holding.current=null;generation.current++;armPending.current=false;const id=session.current;session.current=null;sending.current.clear();inputGuard.current=null;demand.current={left:0,right:0};setArmed(false);setPending(false);
|
||||
if(id)void request(url+'/command',{session_id:id,sequence:++seq.current,left:0,right:0,stop:true},true).catch(()=>{});
|
||||
},[url]);
|
||||
const stop=useCallback(()=>{recovery.current.clear();setRecovering(false);retire();},[retire]);
|
||||
const interrupt=useCallback((reason:string)=>{
|
||||
roverDevEvent(url,"lifecycle",{reason,action:"interrupt",session_id:session.current});
|
||||
const resume=recovery.current.interrupt(performance.now(),session.current);retire();setRecovering(resume);setError(resume?null:reason);
|
||||
},[retire]);
|
||||
const send=useCallback(async()=>{
|
||||
roverTiming.tick(session.current!==null);
|
||||
const id=session.current;if(!id)return;
|
||||
// Check on every heartbeat, even when a previous request is still pending.
|
||||
const inputValid=(demand.current.left===0&&demand.current.right===0)||inputGuard.current?.();
|
||||
if(document.hidden||!document.hasFocus()||!inputValid)demand.current={left:0,right:0};
|
||||
if(sending.current)return;
|
||||
sending.current=true;
|
||||
try{await request(url+'/command',{session_id:id,sequence:++seq.current,...demand.current,stop:false});}
|
||||
catch(e){if(session.current===id){stop();setError(e instanceof Error?e.message:'Команда не подтверждена.');}}
|
||||
finally{sending.current=false;}
|
||||
},[url,stop]);
|
||||
const setDemand=useCallback((next:Demand)=>{demand.current=next;void send();},[send]);
|
||||
const foreground=!document.hidden&&document.hasFocus();
|
||||
const inputValid=inputGuard.current?.()??false;
|
||||
roverDevEvent(url,"heartbeat",{session_id:id,sequence:seq.current,foreground,input_valid:inputValid,pending:sending.current.size,...demand.current});
|
||||
if(!foreground||!inputValid)demand.current={left:0,right:0};
|
||||
// A hidden renderer cannot provide a reliable heartbeat. Hand only neutral
|
||||
// readiness to the native Core owner socket; it can never renew movement.
|
||||
if(!foreground&&holding.current===id)return;
|
||||
// A delayed HTTP acknowledgement must not delay the next fresh intent.
|
||||
// Bound concurrent requests; keep no queue and never renew remembered input.
|
||||
if(sending.current.size>=4)return;
|
||||
const sequence=++seq.current,key=`${id}:${sequence}`;sending.current.add(key);
|
||||
const hold=!foreground;holding.current=hold?id:null;
|
||||
try{await request(url+(hold?'/hold':'/command'),hold?{session_id:id,sequence}:{session_id:id,sequence,...demand.current,stop:false});
|
||||
if(session.current===id)acknowledged.current=Math.max(acknowledged.current,sequence);
|
||||
}catch(e){if(session.current===id&&sequence>acknowledged.current&&sequence===seq.current){const reason=e instanceof Error?e.message:'Команда не подтверждена.';
|
||||
if(hold&&retryable(e)){holding.current=null;return;} // A delayed JS ack is not a lost board; poll verifies the lease.
|
||||
if(retryable(e))interrupt(reason);else{stop();setError(reason);}}}
|
||||
finally{sending.current.delete(key);}
|
||||
},[url,stop,interrupt]);
|
||||
const setDemand=useCallback((next:Demand)=>{roverDevEvent(url,"demand",next);demand.current=next;void send();},[send]);
|
||||
const pauseInput=useCallback(()=>{demand.current={left:0,right:0};void send();},[send]);
|
||||
const arm=useCallback(async(currentA:number,maxErpm:number)=>{
|
||||
if(session.current||armPending.current)return false;const g=++generation.current;armPending.current=true;setError(null);setPending(true);
|
||||
const start=useCallback(async({currentA,speed,mode}:RoverArmSettings)=>{
|
||||
if(document.hidden||!document.hasFocus()||session.current||armPending.current)return false;const g=++generation.current;armPending.current=true;setError(null);setPending(true);
|
||||
try{
|
||||
const result=await request<{session_id:string}>(url+'/arm',{standstill_confirmed:true,current_a:currentA,max_erpm:maxErpm});
|
||||
const result=await request<{session_id:string}>(url+'/arm',{standstill_confirmed:true,current_a:currentA,...(mode==='duty'?{max_duty_percent:speed}:{max_erpm:speed})});
|
||||
if(g!==generation.current){void request(url+'/command',{session_id:result.session_id,sequence:1,left:0,right:0,stop:true},true).catch(()=>{});return false;}
|
||||
// Retire every read started before this acknowledgement, including reads
|
||||
// begun while POST /arm was pending. They describe the previous authority.
|
||||
generation.current++;armPending.current=false;setPending(false);
|
||||
seq.current=0;demand.current={left:0,right:0};session.current=result.session_id;setArmed(true);void send();
|
||||
seq.current=0;acknowledged.current=0;demand.current={left:0,right:0};session.current=result.session_id;recovery.current.started(result.session_id);setArmed(true);void send();
|
||||
return true;
|
||||
}catch(e){if(g===generation.current)setError(e instanceof Error?e.message:'Не удалось включить управление.');return false;}
|
||||
}catch(e){if(g===generation.current){const reason=e instanceof Error?e.message:'Не удалось включить управление.';
|
||||
if(retryable(e)){interrupt(reason);return recovery.current.waiting;}stop();setError(reason);
|
||||
}return false;}
|
||||
finally{if(g===generation.current){armPending.current=false;setPending(false);}}
|
||||
},[url,send]);
|
||||
},[url,send,interrupt,stop]);
|
||||
const arm=useCallback((currentA:number,speed:number,mode:'rpm'|'duty'='rpm')=>{
|
||||
if(session.current||armPending.current||recovery.current.waiting)return Promise.resolve(false);
|
||||
const settings={currentA,speed,mode};recovery.current.remember(settings,latest.current);return start(settings);
|
||||
},[start]);
|
||||
useEffect(()=>{
|
||||
if(!visible){stop();setState(empty);setConnecting(false);return;}
|
||||
let alive=true,busy=false,lastFault='';const started=performance.now();setConnecting(true);
|
||||
if(!visible){stop();setState(empty);setError(null);setConnection('closed');return;}
|
||||
const releaseTransport=retainRoverTransport(url);
|
||||
let alive=true,busy=false;const notices=new RoverFaultNotice();setError(null);setConnection(roverConnection(url));setControlMode('unknown');
|
||||
const recover=(value:RoverState,focused:boolean)=>{
|
||||
if(session.current||armPending.current)return;
|
||||
const settings=recovery.current.next(value,performance.now(),focused);
|
||||
if(settings)void start(settings);
|
||||
};
|
||||
const poll=async()=>{
|
||||
if(busy)return;busy=true;const before=generation.current;
|
||||
try{const value=await request<RoverState>(url);if(alive&&before===generation.current){setState(value);
|
||||
setConnecting(!value.fresh&&performance.now()-started<2000);
|
||||
if(session.current&&(!value.fresh||!value.controlling)){stop();}
|
||||
const fault=value.snapshot.state==='fault'?value.snapshot.message??'':'';
|
||||
if(fault&&lastFault!==fault){lastFault=fault;setError(fault);}
|
||||
}}catch{if(alive&&before===generation.current){setState(empty);setConnecting(false);if(session.current)stop();}}finally{busy=false;}
|
||||
try{const value=await request<RoverState>(url);if(alive&&before===generation.current){roverTiming.view(value.fresh);setState(value);latest.current=value;
|
||||
setConnection(roverConnection(url));
|
||||
// Telemetry absence is not a declaration of an old RPM-only driver.
|
||||
if(value.fresh&&value.snapshot.supported)setControlMode(value.snapshot.control_modes?.includes('duty')?'duty':'rpm');
|
||||
const ownedSession=session.current;
|
||||
const previousStatus=armPending.current||recovery.current.previousStatus(value,ownedSession);
|
||||
const blocker=armPending.current?null:recovery.current.blocker(value,session.current);
|
||||
if(blocker){stop();setError(blocker);}
|
||||
else if(session.current&&(!value.fresh||!value.controlling||(value.snapshot.session_id===session.current&&value.snapshot.state==='stopping'))){
|
||||
const reason=value.snapshot.message||(!value.fresh?'Управление прервано: нет свежих данных с борта.':value.snapshot.state==='receiver'?'Управление передано пульту.':'Управление прервано: борт перестал подтверждать команды. Повторите включение.');
|
||||
interrupt(reason);
|
||||
}
|
||||
if(session.current&&value.fresh&&value.snapshot.session_id===session.current&&['ready','driving'].includes(value.snapshot.state??'')){
|
||||
recovery.current.connected(performance.now());setRecovering(false);
|
||||
}
|
||||
recover(value,!document.hidden&&document.hasFocus());
|
||||
if(!previousStatus){const notice=notices.update(value,ownedSession);if(notice.show)setError(notice.show);else if(notice.clear)setError(current=>current===notice.clear?null:current);}
|
||||
}}catch{if(alive&&before===generation.current){setState(empty);latest.current=empty;setConnection(roverConnection(url));if(session.current)interrupt('Управление прервано: не удалось проверить связь с бортом.');recover(empty,false);}}finally{busy=false;}
|
||||
};
|
||||
void poll();const timer=setInterval(()=>void poll(),200),heartbeat=setInterval(()=>void send(),100);
|
||||
const blur=()=>pauseInput(),hidden=()=>{if(document.hidden)pauseInput();};
|
||||
window.addEventListener('blur',blur);window.addEventListener('pagehide',stop);document.addEventListener('visibilitychange',hidden);
|
||||
return()=>{alive=false;clearInterval(timer);clearInterval(heartbeat);window.removeEventListener('blur',blur);window.removeEventListener('pagehide',stop);document.removeEventListener('visibilitychange',hidden);stop();};
|
||||
},[url,visible,stop,send,pauseInput]);
|
||||
void poll();const timer=setInterval(()=>void poll(),200),heartbeat=setInterval(()=>void send(),INTENT_INTERVAL_MS);
|
||||
const blur=()=>pauseInput();
|
||||
const foreground=()=>{if(document.hidden||!document.hasFocus())return;void poll();void send();};
|
||||
const hidden=()=>{if(document.hidden)pauseInput();else foreground();};
|
||||
window.addEventListener('blur',blur);window.addEventListener('focus',foreground);window.addEventListener('pagehide',stop);document.addEventListener('visibilitychange',hidden);
|
||||
return()=>{alive=false;clearInterval(timer);clearInterval(heartbeat);window.removeEventListener('blur',blur);window.removeEventListener('focus',foreground);window.removeEventListener('pagehide',stop);document.removeEventListener('visibilitychange',hidden);stop();releaseTransport();roverTiming.clear();};
|
||||
},[url,visible,stop,send,pauseInput,start,interrupt]);
|
||||
const ready=armed&&state.fresh&&state.snapshot.session_id===session.current&&['ready','driving'].includes(state.snapshot.state??'');
|
||||
const canArm=state.fresh&&state.snapshot.supported===true&&!state.controlling&&!['preparing','ready','driving','stopping'].includes(state.snapshot.state??'');
|
||||
return {state,armed,pending,error,connecting,canArm,arm,stop,pauseInput,setDemand,setInputGuard,ready,clearError:()=>setError(null)};
|
||||
const canArm=!recovering&&state.fresh&&state.snapshot.supported===true&&!state.controlling&&!['preparing','ready','driving','stopping'].includes(state.snapshot.state??'');
|
||||
return {state,armed,pending,error,connection,connecting:connection==='connecting',controlMode,recovering,canArm,arm,stop,pauseInput,setDemand,setInputGuard,ready,clearError:()=>setError(null)};
|
||||
}
|
||||
export type RoverController=ReturnType<typeof useRoverControl>;
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {connectRoverEvidence,roverDevEvent} from './roverDevEvents';
|
||||
import {saveRoverLog} from './roverLogSave';
|
||||
import {saveOperatorCapture} from './roverOperatorCapture';
|
||||
export type LocalCaptureOptions={enabled:boolean;preview:boolean};
|
||||
export type DevOptions={live:boolean;core_trace:boolean;motor_samples:boolean;network:boolean;live_kbps:number;core_kbps:number};
|
||||
export const localDevOptions:DevOptions={live:false,core_trace:false,motor_samples:true,network:true,live_kbps:16,core_kbps:16};
|
||||
export type DevRow={record_sequence:number;source:string;event:string;at_utc:string;record?:DevRow;[key:string]:unknown};
|
||||
export type DevState={local_capture?:{id:string|null;active:boolean;preview?:boolean;dropped?:number;sequence?:number};options?:DevOptions;options_supported?:boolean;id:string|null;active:boolean;closing:boolean;sequence:number;frames:DevRow[];
|
||||
node?:{active?:boolean;transport_error?:string;storage?:{file?:string;closed:boolean;written:number;dropped:number;error?:string}}};
|
||||
const empty:DevState={id:null,active:false,closing:false,sequence:0,frames:[]};
|
||||
export function useRoverDiagnostics(vehicleID:string){
|
||||
const url=`/api/v1/fleet/${encodeURIComponent(vehicleID)}/rover`;
|
||||
const [state,setState]=useState<DevState>(empty),[rows,setRows]=useState<DevRow[]>([]);
|
||||
const [pending,setPending]=useState(false),[saving,setSaving]=useState(false),[error,setError]=useState<string|null>(null);
|
||||
const savedLocal=useRef<string|null>(null);
|
||||
const evidence=useRef<ReturnType<typeof connectRoverEvidence>|null>(null),latest=useRef(empty);
|
||||
const accept=useCallback((value:DevState)=>{
|
||||
const previous=latest.current;latest.current=value;setState(value);evidence.current?.set(value.active&&value.options?.core_trace!==false?value.id:null,value.local_capture?.active?value.local_capture.id:null,value.local_capture?.preview!==false);
|
||||
const failure=value.node?.storage?.error;
|
||||
if(failure&&(previous.id!==value.id||previous.node?.storage?.error!==failure))
|
||||
setError(failure==='CaptureInterrupted'?'DEV-запись прервана перезапуском борта. Сохранившийся файл оставлен на борту. Можно начать новую запись.':failure==='CaptureNotFound'?'Предыдущая DEV-запись на борту не найдена. Можно начать новую запись.':`Запись остановлена: ${failure}. Файл может быть неполным.`);
|
||||
setRows(rows=>[...(previous.id===value.id?rows:[]),...value.frames.filter(r=>previous.id!==value.id||r.record_sequence>previous.sequence)].slice(-200));
|
||||
},[]);
|
||||
useEffect(()=>{
|
||||
let alive=true,busy=false;latest.current=empty;setState(empty);setRows([]);
|
||||
const client=connectRoverEvidence(url);evidence.current=client;
|
||||
const poll=async()=>{if(busy)return;busy=true;const started=performance.now();try{
|
||||
const r=await fetch(url+'/diagnostics?after='+latest.current.sequence,{cache:'no-store',signal:AbortSignal.timeout(3000)});
|
||||
if(!r.ok)throw Error();const value:DevState=await r.json();
|
||||
if(performance.now()-started>=200)roverDevEvent(url,'request',{action:'diagnostics_view',outcome:'slow',elapsed_ms:performance.now()-started});if(alive){accept(value);setError(current=>current==='Нет связи с Mission Core. Файл остаётся на борту.'?null:current);}
|
||||
}catch{roverDevEvent(url,'request',{action:'diagnostics_view',outcome:'transport',elapsed_ms:performance.now()-started});if(alive&&latest.current.active)setError('Нет связи с Mission Core. Файл остаётся на борту.');}finally{busy=false;}};
|
||||
void poll();const timer=setInterval(()=>void poll(),500);
|
||||
return()=>{alive=false;clearInterval(timer);client.close();evidence.current=null;};
|
||||
},[url,accept]);
|
||||
const toggle=useCallback(async(options?:DevOptions,local?:LocalCaptureOptions)=>{
|
||||
if(pending||latest.current.closing)return false;
|
||||
setPending(true);setError(null);
|
||||
try{
|
||||
const enabled=!latest.current.active;if(!enabled)await evidence.current?.flush();
|
||||
const previousID=latest.current.local_capture?.id;
|
||||
if(enabled&&local?.enabled&&previousID&&savedLocal.current!==previousID)throw Error("Сначала сохраните предыдущий замер компьютера в окне логов.");
|
||||
const r=await fetch(url+'/diagnostics',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(enabled?{enabled,options:options??localDevOptions,...(local?{local_options:{...local,previous_id:previousID??null}}:{})}:{enabled})});
|
||||
const value=await r.json();if(!r.ok)throw Error(value.detail??'Не удалось переключить DEV.');accept(value);return enabled;
|
||||
}catch(e){setError(e instanceof Error?e.message:'Не удалось переключить DEV.');return false;}finally{setPending(false);}
|
||||
},[url,pending,accept]);
|
||||
const save=useCallback(async()=>{
|
||||
if(saving)return;setSaving(true);setError(null);
|
||||
try{await saveRoverLog(url,latest.current.node?.storage?.file?.split('/').pop()??`rover-${latest.current.id}.jsonl`);}
|
||||
catch(e){if(!(e instanceof DOMException&&e.name==='AbortError'))setError(e instanceof Error?e.message:'Не удалось сохранить файл.');}
|
||||
finally{setSaving(false);}
|
||||
},[url,saving]);
|
||||
const saveLocal=useCallback(async()=>{
|
||||
const id=latest.current.local_capture?.id;if(!id||saving)return;setSaving(true);setError(null);
|
||||
try{await saveOperatorCapture(url,id,async()=>{await evidence.current?.flush();});if(latest.current.local_capture?.id===id&&!latest.current.local_capture.active)savedLocal.current=id;}
|
||||
catch(e){if(!(e instanceof DOMException&&e.name==='AbortError'))setError(e instanceof Error?e.message:'Не удалось сохранить замер.');}
|
||||
finally{setSaving(false);}
|
||||
},[url,saving]);
|
||||
return {state,rows,pending,saving,error,toggle,save,saveLocal,clearError:()=>setError(null)};
|
||||
}
|
||||
export type RoverDiagnostics=ReturnType<typeof useRoverDiagnostics>;
|
||||
@@ -4,56 +4,105 @@ import type {ObservationLayout} from './observationLayout';
|
||||
import {decodeObservationPresets,saveObservationPreset,selectObservationPreset,renameObservationPreset,removeObservationPreset,type ObservationPresets} from './observationPresets';
|
||||
import {fleetRequest} from './useFleet';
|
||||
import {sameConfiguration} from './configurationEquality';
|
||||
import {observationSerial,mergeObservation,saveObservation} from './observationSync';
|
||||
|
||||
interface Document {layouts:ObservationPresets;cameras:Record<string,CameraPresentation>}
|
||||
interface Receipt {schema:'missioncore.rover-configuration/v1';revision:number;document:Document|null;draft?:Document|null;source:'onboard'|'mirror';writable:boolean;available:boolean}
|
||||
interface Draft {revision:number;document:Document}
|
||||
interface Draft {revision:number;document:Document;base?:Document}
|
||||
export function useVehicleObservation(vehicleID:string) {
|
||||
const draftKey=`missioncore.observation.draft.v1:${vehicleID}`;
|
||||
const stored=(key:string)=>{try{return JSON.parse(localStorage.getItem(key)??'null');}catch{return null;}};
|
||||
const initial=():Document=>({layouts:decodeObservationPresets(null,stored(`missioncore.observation.v1:${vehicleID}`)),cameras:{}});
|
||||
const [recovery,setRecovery]=useState<Document|null>(null);
|
||||
const [connectionError,setConnectionError]=useState<string|null>(null);
|
||||
const [document,setDocument]=useState(initial),[ready,setReady]=useState(false),[error,setError]=useState<string|null>(null),[edit,setEdit]=useState(0),[pending,setPending]=useState(false),[errorDismissed,setErrorDismissed]=useState(false);
|
||||
const state=useRef({document,edit:0,saved:0,revision:0,ready:false});
|
||||
const state=useRef({document,base:document,edit:0,saved:0,revision:0,ready:false});
|
||||
const mounted=useRef(true),writes=useRef(Promise.resolve());
|
||||
const path=`/${encodeURIComponent(vehicleID)}/observation-configuration`;
|
||||
const normalize=(value:Document):Document=>({...value,layouts:decodeObservationPresets(value.layouts)});
|
||||
const remember=()=>{try{localStorage.setItem(draftKey,JSON.stringify({revision:state.current.revision,document:state.current.document}));}catch{/* The board acknowledgement remains the durable save. */}};
|
||||
const normalize=(value:Document|null):Document=>value?({...value,layouts:decodeObservationPresets(value.layouts)}):initial();
|
||||
const remember=(current=state.current)=>{try{localStorage.setItem(draftKey,JSON.stringify({revision:current.revision,document:current.document,base:current.base}));}catch{/* The board acknowledgement remains the durable save. */}};
|
||||
const flush=()=>{
|
||||
const current=state.current;
|
||||
const write=async()=>{
|
||||
const current=state.current;if(!current.ready||current.saved===current.edit)return;
|
||||
if(!current.ready||current.saved===current.edit)return;
|
||||
const version=current.edit,payload=current.document;
|
||||
if(mounted.current)setPending(true);
|
||||
if((mounted.current&&state.current===current))setPending(true);
|
||||
try {
|
||||
const receipt=await fleetRequest<Receipt>(path,'PUT',{expected_revision:current.revision,document:payload},20000);
|
||||
current.revision=receipt.revision;current.saved=version;
|
||||
if(current.edit===version){try{localStorage.removeItem(draftKey);}catch{}}else remember();
|
||||
if(mounted.current)setError(null);
|
||||
}catch(cause){if(mounted.current){setErrorDismissed(false);setError(cause instanceof Error?cause.message:'Подтверждение записи на борт не получено.');}}
|
||||
finally{if(mounted.current)setPending(current.saved!==current.edit);}
|
||||
const saved=await saveObservation(current.revision,current.base,payload,
|
||||
()=>fleetRequest<Receipt>(path),(revision,document)=>fleetRequest<Receipt>(path,'PUT',{expected_revision:revision,document},20000),normalize);
|
||||
current.revision=saved.receipt.revision;current.base=saved.document;current.saved=version;
|
||||
// Preserve edits made while the request was pending, plus unrelated changes
|
||||
// which were merged from the board. Conflicting new edits remain local.
|
||||
current.document=mergeObservation(payload,current.document,saved.document).value;
|
||||
if((mounted.current&&state.current===current))setDocument(current.document);
|
||||
if(current.edit===version){try{localStorage.removeItem(draftKey);}catch{}}else remember(current);
|
||||
if((mounted.current&&state.current===current))setError(null);
|
||||
}catch(cause){if((mounted.current&&state.current===current)){setErrorDismissed(false);setError(cause instanceof Error?cause.message:'Подтверждение записи на борт не получено.');}}
|
||||
finally{if((mounted.current&&state.current===current))setPending(current.saved!==current.edit);}
|
||||
};
|
||||
writes.current=writes.current.then(write,write);return writes.current;
|
||||
writes.current=observationSerial(vehicleID,write);return writes.current;
|
||||
};
|
||||
useEffect(()=>{
|
||||
mounted.current=true;let active=true;
|
||||
fleetRequest<Receipt>(path).then(receipt=>{
|
||||
mounted.current=true;let active=true,timer:ReturnType<typeof setTimeout>|undefined,wasWritable=false;
|
||||
const empty=initial();state.current={document:empty,base:empty,edit:0,saved:0,revision:0,ready:false};
|
||||
setReady(false);setError(null);setConnectionError(null);setErrorDismissed(false);setRecovery(null);
|
||||
const refresh=async()=>{
|
||||
let retrySave=false;
|
||||
try{await observationSerial(vehicleID,async()=>{
|
||||
if(!active)return;
|
||||
const saved=receipt.document?normalize(receipt.document):initial();
|
||||
const receipt=await fleetRequest<Receipt>(path);
|
||||
if(!active)return;
|
||||
setConnectionError(receipt.writable?null:'Связь с хранилищем конфигурации на борту не подтверждена. Изменения останутся черновиком.');
|
||||
const recovered=receipt.writable&&!wasWritable;wasWritable=receipt.writable;
|
||||
const current=state.current;
|
||||
if(current.ready){
|
||||
// Availability is rechecked independently of edits. A mirror cannot roll
|
||||
// back the acknowledged board version or overwrite an unsaved local draft.
|
||||
if(!receipt.writable||receipt.revision<current.revision)return;
|
||||
const remote=normalize(receipt.document),merged=mergeObservation(current.base,current.document,remote);
|
||||
if(merged.conflicts.length)return;
|
||||
current.document=merged.value;current.base=remote;current.revision=receipt.revision;
|
||||
if(sameConfiguration(current.document,remote)){
|
||||
// A timed-out save may already be committed on the board. Its fresh
|
||||
// read-back settles both the draft and the old acknowledgement error.
|
||||
if(current.saved!==current.edit)setError(null);
|
||||
current.saved=current.edit;try{localStorage.removeItem(draftKey);}catch{}
|
||||
}else remember(current);
|
||||
setDocument(current.document);setPending(current.saved!==current.edit);
|
||||
retrySave=recovered&¤t.saved!==current.edit;
|
||||
return;
|
||||
}
|
||||
const saved=normalize(receipt.document);
|
||||
const draft=stored(draftKey) as Draft|null;
|
||||
const candidate=draft?.document??(!receipt.document?receipt.draft:null);
|
||||
const same=candidate&&sameConfiguration(candidate,receipt.document);
|
||||
const dirty=!!candidate&&!same;
|
||||
const value=dirty?normalize(candidate):saved;
|
||||
const revision=draft&&dirty?draft.revision:receipt.revision;
|
||||
state.current={document:value,edit:dirty?1:0,saved:0,revision,ready:true};
|
||||
let value=candidate?normalize(candidate):saved;
|
||||
let dirty=!!candidate&&!sameConfiguration(value,saved);
|
||||
if(dirty&&draft&&draft.revision!==receipt.revision){
|
||||
const merge=draft.base?mergeObservation(normalize(draft.base),value,saved):null;
|
||||
if(merge&&!merge.conflicts.length){value=merge.value;dirty=!sameConfiguration(value,saved);}
|
||||
else {
|
||||
// Legacy drafts lack a merge ancestor. Keep a recoverable copy and open
|
||||
// the latest board version instead of endlessly replaying a stale revision.
|
||||
try{localStorage.setItem(draftKey+':recovery',JSON.stringify(value));}catch{}
|
||||
setRecovery(value);value=saved;dirty=false;
|
||||
}
|
||||
}
|
||||
if(!dirty){try{localStorage.removeItem(draftKey);}catch{}}
|
||||
const retained=stored(draftKey+':recovery');if(retained)setRecovery(normalize(retained));
|
||||
state.current={document:value,base:saved,edit:dirty?1:0,saved:0,revision:receipt.revision,ready:true};
|
||||
setDocument(value);setReady(true);setEdit(dirty?1:0);setPending(dirty);
|
||||
if(!receipt.writable)setError('Связь с хранилищем конфигурации на борту не подтверждена. Изменения останутся черновиком.');
|
||||
}).catch(cause=>{if(active)setError(cause instanceof Error?cause.message:'Настройки недоступны.');});
|
||||
return()=>{active=false;mounted.current=false;void flush();};
|
||||
});
|
||||
if(active&&retrySave)void flush();
|
||||
}catch(cause){if(active){wasWritable=false;setConnectionError(cause instanceof Error?cause.message:'Настройки недоступны.');}}
|
||||
finally{if(active)timer=setTimeout(()=>void refresh(),5000);}
|
||||
};
|
||||
void refresh();
|
||||
return()=>{active=false;clearTimeout(timer);mounted.current=false;void flush();};
|
||||
},[vehicleID]);
|
||||
useEffect(()=>{if(!ready||edit===0)return;const timer=setTimeout(()=>void flush(),350);return()=>clearTimeout(timer);},[edit,ready]);
|
||||
const update=(change:(value:Document)=>Document)=>{
|
||||
if(!state.current.ready)return;
|
||||
const current=state.current;current.document=change(current.document);current.edit++;remember();
|
||||
const current=state.current;const next=change(current.document);if(sameConfiguration(next,current.document))return;current.document=next;current.edit++;remember();
|
||||
setDocument(current.document);setEdit(current.edit);setPending(true);
|
||||
};
|
||||
const changeLayouts=(change:(value:ObservationPresets)=>ObservationPresets)=>{
|
||||
@@ -61,22 +110,32 @@ export function useVehicleObservation(vehicleID:string) {
|
||||
catch(cause){setError(cause instanceof Error?cause.message:'Раскладка не сохранена.');return false;}
|
||||
};
|
||||
const reload=async()=>{
|
||||
const current=state.current;
|
||||
if(state.current.saved!==state.current.edit){const copy=state.current.document;setRecovery(copy);try{localStorage.setItem(draftKey+':recovery',JSON.stringify(copy));}catch{}}
|
||||
await writes.current;
|
||||
try{
|
||||
const receipt=await fleetRequest<Receipt>(path);
|
||||
const receipt=await observationSerial(vehicleID,()=>fleetRequest<Receipt>(path));
|
||||
if(!mounted.current||state.current!==current)return false;
|
||||
if(!receipt.writable)throw Error('Не удалось получить актуальную конфигурацию с борта. Черновик сохранён.');
|
||||
const value=receipt.document?normalize(receipt.document):initial();
|
||||
state.current={document:value,edit:0,saved:0,revision:receipt.revision,ready:true};
|
||||
state.current={document:value,base:value,edit:0,saved:0,revision:receipt.revision,ready:true};
|
||||
setDocument(value);setReady(true);setEdit(0);setPending(false);setError(null);
|
||||
try{localStorage.removeItem(draftKey);}catch{}
|
||||
}catch(cause){setError(cause instanceof Error?cause.message:'Настройки недоступны.');}
|
||||
return true;
|
||||
}catch(cause){setError(cause instanceof Error?cause.message:'Настройки недоступны.');return false;}
|
||||
};
|
||||
const setLayout=(value:SetStateAction<ObservationLayout>)=>changeLayouts(current=>({...current,layout:typeof value==='function'?value(current.layout):value}));
|
||||
return {...document.layouts,ready,pending,cameras:document.cameras,setLayout,
|
||||
const restore=async()=>{
|
||||
const retained=recovery??state.current.document;
|
||||
if(!await reload())return;
|
||||
update(()=>retained);setRecovery(null);
|
||||
try{localStorage.removeItem(draftKey+':recovery');}catch{}
|
||||
};
|
||||
return {...document.layouts,recovery:!!recovery,restore,ready,pending,cameras:document.cameras,setLayout,
|
||||
setCamera:(id:string,value:CameraPresentation)=>update(current=>({...current,cameras:{...current.cameras,[id]:value}})),
|
||||
select:(id:string)=>changeLayouts(current=>selectObservationPreset(current,id)),
|
||||
save:(name:string)=>changeLayouts(current=>saveObservationPreset(current,name,`saved:${crypto.randomUUID()}`)),
|
||||
rename:(id:string,name:string)=>changeLayouts(current=>renameObservationPreset(current,id,name)),
|
||||
remove:(id:string)=>changeLayouts(current=>removeObservationPreset(current,id)),
|
||||
error,toastError:errorDismissed?null:error,clearError:()=>setErrorDismissed(true),retry:flush,reload};
|
||||
error:error??connectionError,toastError:errorDismissed?null:error??connectionError,clearError:()=>setErrorDismissed(true),retry:flush,reload};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import {useRef} from 'react';
|
||||
import {Button,Icon,Select,SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||
import {useBoardNetwork,type NetworkProvider} from '../../core/fleet/useBoardNetwork';
|
||||
import {InstallerCard} from './equipment/InstallerCard';
|
||||
export function BoardNetworkSettings({network}:{network:ReturnType<typeof useBoardNetwork>}){
|
||||
const input=useRef<HTMLInputElement>(null);
|
||||
const {value,provider,profileId,busy,applying,error}=network;
|
||||
const current=value?.node;
|
||||
const selected=value?.profiles.find(p=>p.id===profileId);
|
||||
const progress=value?.operation?.state;
|
||||
const label=progress==='rolling_back'?'Восстанавливаем прежнее подключение':progress==='applying'?'Проверяем связь с бортом':!value?.available?'Нет свежего подтверждения борта':current?.provider==='wireguard'?'WireGuard подключён':'Tailscale подключён';
|
||||
return <div className="fleet-form">
|
||||
<SettingsCard title="Связь с Core" description="Профиль связи этого бортового компьютера с Mission Core. Вычислительный Worker сохраняет своё подключение." actions={<StatusBadge tone={applying?'warning':value?.available?'success':'neutral'}>{label}</StatusBadge>}>
|
||||
<Select label="Способ подключения" value={provider} options={[{value:'tailscale',label:'Tailscale'},{value:'wireguard',label:'WireGuard · VPS'}]} onChange={v=>network.setProvider(v as NetworkProvider)} disabled={busy||applying}/>
|
||||
{provider==='tailscale'?<p>{current?.tailscale_endpoint?`Сохранённое подключение: ${current.tailscale_endpoint}`:current?'Подключите Tailscale в приложении Node.':'Параметры появятся после получения настроек БК.'}</p>:<>
|
||||
<Select label="Общий профиль VPS" value={profileId} options={[{value:'',label:'Выберите профиль'},...(value?.profiles??[]).filter(p=>p.state==='ready').map(p=>({value:p.id,label:p.name,description:`Подключено бортов: ${p.boards} · ${p.endpoint}`}))]} onChange={network.setProfileId} disabled={busy||applying}/>
|
||||
{selected&&<StatusBadge tone={selected.state==='ready'?'success':'warning'}>{selected.state==='ready'?`VPS подключён · Подключено бортов: ${selected.boards}`:'Подключение VPS не завершено'}</StatusBadge>}
|
||||
<p>Один профиль используется всем парком. У каждого борта будет отдельное защищённое подключение.</p>
|
||||
</>}
|
||||
{!value?.available&&<p>Для изменения настроек нужен доступный БК с актуальной версией Node.</p>}
|
||||
{(error||value?.operation?.error||current?.error)&&<StatusBadge tone="danger">{error||value?.operation?.error||current?.error}</StatusBadge>}
|
||||
</SettingsCard>
|
||||
{provider==='wireguard'&&<>
|
||||
<SettingsCard title="Подключить VPS" description="Если сервер уже подготовлен, загрузите полученный на нём файл подключения. Для нового сервера сначала скачайте и запустите установщик.">
|
||||
<input ref={input} type="file" accept=".json,application/json" hidden onChange={event=>{const file=event.currentTarget.files?.[0];event.currentTarget.value='';if(file)void network.importing(file);}}/>
|
||||
<Button icon={<Icon name="upload"/>} disabled={busy||applying} loading={busy} onClick={()=>input.current?.click()}>Загрузить файл подключения</Button>
|
||||
</SettingsCard>
|
||||
<InstallerCard kind="vps-wireguard"/>
|
||||
</>}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
async function module(path){const result=await build({entryPoints:[new URL(path,import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});return import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));}
|
||||
const {PreviewMetrics}=await module('../../../packages/sensor-ui/src/previewMetrics.ts');
|
||||
const {RoverTiming}=await module('../src/core/fleet/roverTiming.ts');
|
||||
const stats=(extra={})=>new Map([['video',{id:'a',type:'inbound-rtp',kind:'video',timestamp:1000,bytesReceived:1e6,framesDecoded:100,packetsLost:2,framesDropped:1,jitterBufferDelay:50,jitterBufferEmittedCount:100,totalDecodeTime:2,...extra}],['pair',{type:'candidate-pair',state:'succeeded',nominated:true,currentRoundTripTime:.012}]]);
|
||||
test('preview reports interval latency, not the lifetime mean or capture-to-screen age',()=>{
|
||||
const m=new PreviewMetrics();assert.equal(m.sample(stats()).jitter_buffer_ms,null);
|
||||
const v=m.sample(stats({timestamp:3000,bytesReceived:1.5e6,framesDecoded:130,packetsLost:3,framesDropped:3,jitterBufferDelay:53,jitterBufferEmittedCount:130,totalDecodeTime:2.06}));
|
||||
assert.equal(v.fps,15);assert.equal(v.mbps,2);assert.equal(v.jitter_buffer_ms,100);assert.equal(v.decode_ms,2);assert.equal(v.round_trip_ms,12);assert.equal(v.packets_lost,1);assert.equal(v.frames_dropped,2);assert.equal(v.scope,'receiver-interval');assert.equal(v.processing_ms,null);
|
||||
});
|
||||
test('missing counters and replacement streams cannot manufacture zero latency',()=>{
|
||||
const m=new PreviewMetrics();m.sample(stats());
|
||||
assert.equal(m.sample(stats({id:'b',timestamp:3000,jitterBufferDelay:55,jitterBufferEmittedCount:130})).jitter_buffer_ms,null);
|
||||
assert.equal(m.sample(stats({id:'b',timestamp:3000})).fps,null);
|
||||
assert.equal(m.sample(new Map()),null);
|
||||
});
|
||||
test('counter resets do not create negative rates or leaked endpoint data',()=>{
|
||||
const m=new PreviewMetrics();m.sample(stats());const v=m.sample(stats({timestamp:3000,framesDecoded:1,bytesReceived:1,remoteAddress:'private',sdp:'secret'}));
|
||||
assert.equal(v.fps,null);assert.equal(v.mbps,null);assert.ok(!JSON.stringify(v).includes('private'));assert.ok(!JSON.stringify(v).includes('secret'));
|
||||
});
|
||||
test('control timing separates scheduling gaps from HTTP time and remains bounded',()=>{
|
||||
const oldDocument=globalThis.document,oldPerformance=globalThis.performance;let now=0;
|
||||
globalThis.document={hidden:false,hasFocus:()=>true,documentElement:{dataset:{}}};globalThis.performance={now:()=>now};
|
||||
try{const m=new RoverTiming();m.tick(false);now=100;m.tick(false);assert.equal(JSON.parse(document.documentElement.dataset.roverTiming).events.length,0);
|
||||
now=500;document.hidden=true;m.tick(true);let v=JSON.parse(document.documentElement.dataset.roverTiming);assert.equal(v.events[0].kind,'heartbeat-gap');assert.equal(v.events[0].gap_ms,400);assert.equal(v.events[0].hidden,true);
|
||||
now=600;m.request('view',590,'transport');v=JSON.parse(document.documentElement.dataset.roverTiming);assert.equal(v.events.at(-1).duration_ms,10);assert.equal(v.events.at(-1).outcome,'transport');
|
||||
for(let i=0;i<100;i++){now+=300;m.tick(false);}assert.equal(JSON.parse(document.documentElement.dataset.roverTiming).events.length,16);
|
||||
m.clear();assert.equal(document.documentElement.dataset.roverTiming,undefined);
|
||||
}finally{globalThis.document=oldDocument;globalThis.performance=oldPerformance;}
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import {before,after,test} from 'node:test';
|
||||
import {createServer} from './support/vite-server.mjs';
|
||||
let server,sync;
|
||||
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});sync=await server.ssrLoadModule('/src/core/fleet/observationSync.ts');});
|
||||
after(async()=>{await server?.close();});
|
||||
const receipt=(document,revision=2)=>({document,revision,writable:true});
|
||||
test('disjoint camera and layout edits merge while conflicting leaves and arrays remain explicit',()=>{
|
||||
const base={camera:{yaw:0,flip:false},layout:{ratio:50,hidden:[]}},local={...base,camera:{...base.camera,yaw:90}},remote={...base,layout:{...base.layout,ratio:60}};
|
||||
assert.deepEqual(sync.mergeObservation(base,local,remote),{value:{camera:local.camera,layout:remote.layout},conflicts:[]});
|
||||
assert.deepEqual(sync.mergeObservation(base,local,{...base,camera:{...base.camera,yaw:180}}).conflicts,['camera.yaw']);
|
||||
assert.deepEqual(sync.mergeObservation({a:1,b:2},{b:2},{a:1,b:3}),{value:{b:3},conflicts:[]});
|
||||
assert.deepEqual(sync.mergeObservation([],['a'],['b']).conflicts,['']);
|
||||
});
|
||||
test('lost ACK is settled by equality without replay',async()=>{
|
||||
let writes=0;const doc={ratio:55};const saved=await sync.saveObservation(1,{ratio:50},doc,async()=>receipt(doc,2),async()=>{writes++;throw Error('timeout');},v=>v);
|
||||
assert.equal(saved.receipt.revision,2);assert.equal(writes,1);
|
||||
});
|
||||
test('revision conflict retries once with a fresh revision and merged document',async()=>{
|
||||
const calls=[];const saved=await sync.saveObservation(1,{a:1,b:1},{a:2,b:1},async()=>receipt({a:1,b:2},3),async(rev,doc)=>{calls.push([rev,doc]);if(rev===1)throw Error('conflict');return receipt(doc,4);},v=>v);
|
||||
assert.deepEqual(calls,[[1,{a:2,b:1}],[3,{a:2,b:2}]]);assert.deepEqual(saved.document,{a:2,b:2});
|
||||
});
|
||||
test('competing edits never overwrite and repeated failures are bounded',async()=>{
|
||||
let writes=0;
|
||||
await assert.rejects(sync.saveObservation(1,{x:1},{x:2},async()=>receipt({x:3}),async()=>{writes++;throw Error('conflict');},v=>v),/другом окне/);assert.equal(writes,1);
|
||||
writes=0;await assert.rejects(sync.saveObservation(1,{x:1},{x:2},async()=>receipt({x:1}),async()=>{writes++;throw Error('down');},v=>v),/down/);assert.equal(writes,2);
|
||||
});
|
||||
test('next mount reads after pending save, failed writes do not poison queue, vehicles are independent',async()=>{
|
||||
let release;const gate=new Promise(r=>{release=r;}),events=[];
|
||||
const a=sync.observationSerial('rover',async()=>{events.push('write');await gate;events.push('ack');});
|
||||
const b=sync.observationSerial('rover',async()=>events.push('read'));
|
||||
await sync.observationSerial('other',async()=>events.push('other'));assert.deepEqual(events,['write','other']);release();await Promise.all([a,b]);assert.deepEqual(events,['write','other','ack','read']);
|
||||
await assert.rejects(sync.observationSerial('rover',async()=>{throw Error('fail');}));assert.equal(await sync.observationSerial('rover',async()=>42),42);
|
||||
});
|
||||
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({entryPoints:[new URL('../src/core/fleet/useRoverControl.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'hook-fixture',setup(b){
|
||||
b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'}));
|
||||
b.onResolve({filter:/^\.\/roverTransport$/},()=>({path:'transport',namespace:'fixture-transport'}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture-transport'},()=>({contents:`export class RoverHttpError extends Error{constructor(message,status){super(message);this.status=status;}};export const retainRoverTransport=()=>()=>{};export const roverConnection=()=>"connected";export async function roverRequest(url,body){const response=await fetch(url,{body:body?JSON.stringify(body):undefined});const result=await response.json();if(!response.ok)throw new RoverHttpError(result.detail,response.status);return result;}`}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:`export const useRef=v=>({current:v});export const useState=v=>[v,()=>{}];export const useCallback=f=>f;export const useEffect=f=>globalThis.roverEffects.push(f);`}));
|
||||
}}]});
|
||||
const {useRoverControl}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
@@ -20,24 +22,24 @@ async function fixture(run){
|
||||
}
|
||||
test('command heartbeat sends neutral on lost blur, keeps session, and accepts new focused input',async()=>fixture(async f=>{
|
||||
f.c.setInputGuard(()=>true);f.c.setDemand({left:1,right:-1});await flush();
|
||||
assert.equal(f.calls.at(-1).body.left,1);f.blur();f.timers.find(t=>t.ms===100).f();await flush();
|
||||
assert.equal(f.calls.at(-1).body.stop,false);assert.equal(f.calls.at(-1).body.left,0);
|
||||
f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.left,0);
|
||||
f.focus();f.timers.find(t=>t.ms===100).f();await flush();assert.equal(f.calls.at(-1).body.left,0);
|
||||
assert.equal(f.calls.at(-1).body.left,1);f.blur();f.timers.find(t=>t.ms===50).f();await flush();
|
||||
assert.ok(f.calls.at(-1).url.endsWith('/hold'));assert.equal('left' in f.calls.at(-1).body,false);
|
||||
f.c.setDemand({left:1,right:1});await flush();assert.ok(f.calls.at(-1).url.endsWith('/hold'));
|
||||
f.focus();f.timers.find(t=>t.ms===50).f();await flush();assert.equal(f.calls.at(-1).body.left,0);
|
||||
f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.left,1);
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1);
|
||||
}));
|
||||
test('expired physical input prevents heartbeat from renewing remembered demand',async()=>fixture(async f=>{
|
||||
let valid=true;f.c.setInputGuard(()=>valid);f.c.setDemand({left:1,right:-1});await flush();valid=false;
|
||||
f.timers.find(t=>t.ms===100).f();await flush();assert.equal(f.calls.at(-1).body.stop,false);
|
||||
f.timers.find(t=>t.ms===50).f();await flush();assert.equal(f.calls.at(-1).body.stop,false);
|
||||
}));
|
||||
test('no registered input scope cannot issue motion',async()=>fixture(async f=>{
|
||||
f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.stop,false);
|
||||
assert.equal(f.calls.some(x=>x.body?.left===1),false);
|
||||
}));
|
||||
test('hidden document sends only neutral without a visibility event',async()=>fixture(async f=>{
|
||||
test('hidden document hands neutral readiness to Core even without a visibility event',async()=>fixture(async f=>{
|
||||
f.c.setInputGuard(()=>true);f.hide();f.c.setDemand({left:1,right:1});await flush();
|
||||
assert.equal(f.calls.at(-1).body.stop,false);assert.equal(f.calls.some(x=>x.body?.left===1),false);
|
||||
assert.ok(f.calls.at(-1).url.endsWith('/hold'));assert.equal(f.calls.some(x=>x.body?.left===1),false);
|
||||
}));
|
||||
|
||||
test('explicit pause clears demand without revoking session; explicit stop still revokes it',async()=>fixture(async f=>{
|
||||
|
||||
@@ -3,26 +3,34 @@ import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({entryPoints:[new URL('../src/core/fleet/useRoverControl.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'hook-fixture',setup(b){
|
||||
b.onResolve({filter:/^react$/},()=>({path:'react',namespace:'fixture'}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:`export const useRef=v=>({current:v});export const useState=v=>[v,()=>{}];export const useCallback=f=>f;export const useEffect=f=>globalThis.roverEffects.push(f);`}));
|
||||
b.onResolve({filter:/^\.\/roverTransport$/},()=>({path:'transport',namespace:'fixture-transport'}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture-transport'},()=>({contents:`export class RoverHttpError extends Error{constructor(message,status){super(message);this.status=status;}};export const retainRoverTransport=()=>()=>{};export const roverConnection=()=>"connected";export async function roverRequest(url,body){const response=await fetch(url,{body:body?JSON.stringify(body):undefined});const result=await response.json();if(!response.ok)throw new RoverHttpError(result.detail,response.status);return result;}`}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:`export const useRef=v=>({current:v});export const useState=v=>[v,next=>globalThis.roverStateWrites.push(next)];export const useCallback=f=>f;export const useEffect=f=>globalThis.roverEffects.push(f);`}));
|
||||
}}]});
|
||||
const {useRoverControl}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
const flush=()=>new Promise(resolve=>setImmediate(resolve));
|
||||
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};};
|
||||
const response=value=>({ok:true,json:async()=>value});
|
||||
const idle={fresh:true,controlling:false,snapshot:{supported:true,state:'observing'}};
|
||||
const idle={fresh:true,controlling:false,snapshot:{supported:true,control_modes:['rpm','duty'],instance:'driver-A',state:'observing',release_confirmed:true,devices:[{uuid:'motor-A',session_id:'usb-A',age_ms:0,values:{erpm:0,fault_code:0}}]}};
|
||||
const stopped={...idle,snapshot:{...idle.snapshot,state:'stopped',session_id:'new-session'}};
|
||||
async function fixture(run){
|
||||
const originals=Object.fromEntries(['window','document','fetch','roverEffects','setInterval','clearInterval'].map(k=>[k,globalThis[k]]));
|
||||
const calls=[],timers=[];globalThis.roverEffects=[];
|
||||
globalThis.window={addEventListener(){},removeEventListener(){}};globalThis.document={hidden:false,hasFocus:()=>true,addEventListener(){},removeEventListener(){}};
|
||||
const originals=Object.fromEntries(['window','document','fetch','roverEffects','roverStateWrites','setInterval','clearInterval','performance'].map(k=>[k,globalThis[k]]));
|
||||
let now=0;globalThis.performance={now:()=>now};const calls=[],timers=[];globalThis.roverEffects=[];globalThis.roverStateWrites=[];
|
||||
const windowEvents=new Map(),documentEvents=new Map();let focused=true;
|
||||
const events=target=>({addEventListener:(name,fn)=>target.set(name,fn),removeEventListener:name=>target.delete(name)});
|
||||
globalThis.window=events(windowEvents);globalThis.document={hidden:false,hasFocus:()=>focused,...events(documentEvents)};
|
||||
globalThis.setInterval=(f,ms)=>{timers.push({f,ms});return timers.length;};globalThis.clearInterval=()=>{};
|
||||
let armResponse=null,nextPoll=null;
|
||||
let armResponse=null,nextPoll=null,holdCommands=false;const commands=[];
|
||||
globalThis.fetch=async(url,init)=>{const body=init.body?JSON.parse(init.body):null;calls.push({url,body});
|
||||
if(url.endsWith('/arm'))return armResponse?armResponse.promise:response({session_id:'new-session'});
|
||||
if(!body)return nextPoll?nextPoll.promise:response(idle);
|
||||
if(holdCommands&&!body.stop){const gate=deferred();commands.push({body,gate});return gate.promise;}
|
||||
return response({accepted_sequence:body.sequence});
|
||||
};
|
||||
const c=useRoverControl('fixture',true),cleanup=globalThis.roverEffects.map(f=>f());
|
||||
try{await flush();await run({c,calls,poll:()=>timers.find(t=>t.ms===200).f(),heartbeat:()=>timers.find(t=>t.ms===100).f(),delayArm:()=>armResponse=deferred(),delayPoll:()=>nextPoll=deferred()});}
|
||||
try{await flush();await run({c,calls,stateWrites:globalThis.roverStateWrites,commands,timers,advance:ms=>{now+=ms;},hide:()=>{globalThis.document.hidden=true;focused=false;documentEvents.get('visibilitychange')?.();},
|
||||
show:()=>{globalThis.document.hidden=false;focused=true;documentEvents.get('visibilitychange')?.();windowEvents.get('focus')?.();},
|
||||
pagehide:()=>windowEvents.get('pagehide')?.(),holdCommands:()=>{holdCommands=true;},poll:()=>timers.find(t=>t.ms===200).f(),heartbeat:()=>timers.find(t=>t.ms===50).f(),delayArm:()=>armResponse=deferred(),delayPoll:()=>nextPoll=deferred()});}
|
||||
finally{cleanup.forEach(f=>f?.());await flush();for(const [key,value]of Object.entries(originals)){if(value===undefined)delete globalThis[key];else globalThis[key]=value;}}
|
||||
}
|
||||
test('idle poll begun during pending arm cannot revoke newly acknowledged session',async()=>fixture(async f=>{
|
||||
@@ -47,3 +55,209 @@ test('duplicate arm clicks while request pending create exactly one lease reques
|
||||
a.resolve(response({session_id:'new-session'}));await Promise.all([first,second]);await flush();
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1);
|
||||
}));
|
||||
test('throttle uses explicit percent units and starts with zero demand',async()=>fixture(async f=>{
|
||||
assert.equal(await f.c.arm(30,50,'duty'),true);await flush();
|
||||
assert.deepEqual(f.calls.find(x=>x.url.endsWith('/arm')).body,{standstill_confirmed:true,current_a:30,max_duty_percent:50});
|
||||
assert.equal(f.calls.at(-1).body.left,0);assert.equal(f.calls.at(-1).body.right,0);
|
||||
}));
|
||||
|
||||
test('delayed acknowledgements do not serialize fresh commands; bounded and no queue',async()=>fixture(async f=>{
|
||||
f.holdCommands();assert.equal(await f.c.arm(30,70,'duty'),true);await flush();
|
||||
f.heartbeat();f.heartbeat();f.heartbeat();f.heartbeat();await flush();
|
||||
assert.equal(f.commands.length,4,'fresh commands must proceed while earlier replies are pending, bounded to four');
|
||||
assert.deepEqual(f.commands.map(x=>x.body.sequence),[1,2,3,4]);
|
||||
f.commands[3].gate.resolve(response({accepted_sequence:4}));await flush();
|
||||
f.commands[0].gate.resolve({ok:false,json:async()=>({detail:'Устаревшая команда отклонена.'})});await flush();
|
||||
assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0,'late obsolete reply must not revoke newer acknowledged input');
|
||||
f.heartbeat();await flush();assert.equal(f.commands.length,5);
|
||||
f.commands[1].gate.resolve(response({accepted_sequence:2}));f.commands[2].gate.resolve(response({accepted_sequence:3}));
|
||||
f.commands[4].gate.resolve({ok:false,json:async()=>({detail:'Канал управления недоступен.'})});await flush();
|
||||
assert.equal(f.calls.at(-1).body.stop,true);
|
||||
assert.ok(f.stateWrites.includes('Канал управления недоступен.'));
|
||||
}));
|
||||
test('missing telemetry preserves the last verified control mode and reports session end',async()=>fixture(async f=>{
|
||||
let p=f.delayPoll();f.poll();p.resolve(response({fresh:true,controlling:false,snapshot:{supported:true,control_modes:['rpm','duty'],state:'observing'}}));await flush();
|
||||
assert.equal(f.stateWrites.at(-1),'duty');
|
||||
assert.equal(await f.c.arm(30,70,'duty'),true);await flush();
|
||||
const mark=f.stateWrites.length;p=f.delayPoll();f.poll();p.resolve(response({fresh:false,controlling:false,snapshot:{}}));await flush();
|
||||
assert.equal(f.calls.at(-1).body.stop,true);
|
||||
assert.ok(f.stateWrites.slice(mark).some(v=>typeof v==='string'&&v.includes('нет свежих данных')));
|
||||
assert.equal(f.stateWrites.slice(mark).includes('rpm'),false);
|
||||
}));
|
||||
test('unknown driver identity after preparation produces a visible reason',async()=>fixture(async f=>{
|
||||
await f.c.arm(30,70,'duty');await flush();const p=f.delayPoll();f.poll();
|
||||
p.resolve(response({fresh:true,controlling:false,snapshot:{supported:true,control_modes:['duty'],state:'stopped'}}));await flush();
|
||||
assert.ok(f.stateWrites.some(v=>typeof v==='string'&&v.includes('перезапустился')));
|
||||
assert.equal(f.calls.at(-1).body.stop,true);
|
||||
}));
|
||||
|
||||
|
||||
test('transport loss reacquires a new neutral session only after stable stopped observations',async()=>fixture(async f=>{
|
||||
await f.c.arm(30,70,'duty');await flush();
|
||||
f.c.setInputGuard(()=>true);f.c.setDemand({left:1,right:1});await flush();
|
||||
let p=f.delayPoll();f.poll();p.resolve(response({fresh:false,controlling:false,snapshot:{}}));await flush();
|
||||
assert.equal(f.calls.at(-1).body.stop,true);
|
||||
assert.equal(f.stateWrites.at(-1),null,'transient loss uses recovery state, not a terminal error');
|
||||
f.advance(600);p=f.delayPoll();f.poll();p.resolve(response(stopped));await flush();
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1);
|
||||
f.advance(600);f.poll();await flush();
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,2);
|
||||
assert.deepEqual(f.calls.filter(x=>x.url.endsWith('/arm')).at(-1).body,{standstill_confirmed:true,current_a:30,max_duty_percent:70});
|
||||
assert.equal(f.calls.at(-1).body.left,0);assert.equal(f.calls.at(-1).body.right,0);
|
||||
f.c.setDemand({left:1,right:1});await flush();assert.equal(f.calls.at(-1).body.left,0,'previous input guard must be retired');
|
||||
}));
|
||||
test('explicit Stop cancels recovery and a delayed successful rearm is retired',async()=>fixture(async f=>{
|
||||
await f.c.arm(30,70,'duty');await flush();let p=f.delayPoll();f.poll();p.resolve(response({fresh:false,controlling:false,snapshot:{}}));await flush();
|
||||
f.advance(600);p=f.delayPoll();f.poll();p.resolve(response(stopped));await flush();
|
||||
const a=f.delayArm();f.advance(600);f.poll();await flush();
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,2);f.c.stop();
|
||||
a.resolve(response({session_id:'replacement-session'}));await flush();
|
||||
assert.deepEqual(f.calls.at(-1).body,{session_id:'replacement-session',sequence:1,left:0,right:0,stop:true});
|
||||
f.advance(9000);f.poll();await flush();assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,2);
|
||||
}));
|
||||
test('receiver takeover is terminal and cannot automatically reacquire control',async()=>fixture(async f=>{
|
||||
await f.c.arm(30,70,'duty');await flush();let p=f.delayPoll();f.poll();p.resolve(response({...stopped,snapshot:{...stopped.snapshot,state:'receiver'}}));await flush();
|
||||
assert.ok(f.stateWrites.includes('Управление передано пульту.'));
|
||||
p=f.delayPoll();f.poll();p.resolve(response(stopped));await flush();f.advance(9000);f.poll();await flush();
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1);
|
||||
}));
|
||||
test('manual retry after USB recovery survives old fault polls before and after arm acknowledgement',async()=>fixture(async f=>{
|
||||
const failed={...idle,snapshot:{...idle.snapshot,session_id:'previous-session',state:'fault',release_confirmed:false,message:'Previous USB failure'}};
|
||||
let p=f.delayPoll();f.poll();p.resolve(response(failed));await flush();
|
||||
const mark=f.stateWrites.length,a=f.delayArm(),arming=f.c.arm(30,70,'duty');
|
||||
p=f.delayPoll();f.poll();p.resolve(response(failed));await flush();
|
||||
a.resolve(response({session_id:'new-session'}));assert.equal(await arming,true);await flush();
|
||||
p=f.delayPoll();f.poll();p.resolve(response({...failed,controlling:true}));await flush();f.heartbeat();await flush();
|
||||
assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0);
|
||||
assert.equal(f.stateWrites.slice(mark).includes('Previous USB failure'),false);
|
||||
assert.equal(f.calls.at(-1).body.left,0);assert.equal(f.calls.at(-1).body.right,0);
|
||||
const preparing={...idle,controlling:true,snapshot:{...idle.snapshot,session_id:'new-session',state:'preparing',release_confirmed:null}};
|
||||
p=f.delayPoll();f.poll();p.resolve(response(preparing));await flush();
|
||||
assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0);
|
||||
p=f.delayPoll();f.poll();p.resolve(response({...preparing,snapshot:{...preparing.snapshot,state:'fault',release_confirmed:false,message:'New hardware failure'}}));await flush();
|
||||
assert.equal(f.calls.at(-1).body.stop,true);assert.ok(f.stateWrites.includes('New hardware failure'));
|
||||
}));
|
||||
|
||||
|
||||
// No physical hardware is used. Core/socket tests separately prove that the
|
||||
// hold survives missing renderer heartbeats and cannot refresh movement.
|
||||
test('five-second hidden desktop retains the same lease and resumes without another arm',async()=>fixture(async f=>{
|
||||
await f.c.arm(30,70,'duty');await flush();
|
||||
f.c.setInputGuard(()=>true);f.c.setDemand({left:1,right:-1});await flush();
|
||||
f.hide();await flush();
|
||||
assert.ok(f.calls.at(-1).url.endsWith('/hold'));
|
||||
assert.deepEqual(f.calls.at(-1).body,{session_id:'new-session',sequence:3});
|
||||
const ready={...idle,controlling:true,snapshot:{...idle.snapshot,state:'ready',session_id:'new-session'}};
|
||||
let p=f.delayPoll();f.poll();p.resolve(response(ready));await flush();
|
||||
const count=f.calls.length;
|
||||
for(let n=0;n<5;n++){f.advance(1000);f.heartbeat();f.poll();await flush();}
|
||||
assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0);
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1);
|
||||
assert.ok(f.calls.slice(count).every(x=>!x.body),'native Core retains neutral without a JS command loop');
|
||||
f.show();await flush();
|
||||
assert.equal(f.calls.at(-1).body.session_id,'new-session');
|
||||
assert.equal(f.calls.at(-1).body.left,0);assert.equal(f.calls.at(-1).body.right,0);
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1,'return must not prepare another session');
|
||||
f.c.setDemand({left:.5,right:.5});await flush();
|
||||
assert.equal(f.calls.at(-1).body.left,.5,'a new input is accepted immediately');
|
||||
}));
|
||||
test('hide during pending preparation hands the acknowledged lease to neutral hold',async()=>fixture(async f=>{
|
||||
const a=f.delayArm(),arming=f.c.arm(30,70,'duty');f.hide();await flush();
|
||||
a.resolve(response({session_id:'late-session'}));await arming;await flush();
|
||||
assert.ok(f.calls.at(-1).url.endsWith('/hold'));
|
||||
assert.deepEqual(f.calls.at(-1).body,{session_id:'late-session',sequence:1});
|
||||
f.advance(5000);f.heartbeat();await flush();
|
||||
assert.equal(f.calls.filter(x=>x.body?.session_id==='late-session').length,1);
|
||||
assert.equal(f.calls.some(x=>x.body?.stop===true),false);
|
||||
}));
|
||||
test('Stop and page navigation terminate a held session without automatic rearm',async()=>{
|
||||
for(const action of ['stop','pagehide'])await fixture(async f=>{
|
||||
await f.c.arm(30,70,'duty');f.hide();await flush();
|
||||
if(action==='stop')f.c.stop();else f.pagehide();
|
||||
assert.equal(f.calls.at(-1).body.stop,true);
|
||||
const p=f.delayPoll();f.poll();p.resolve(response(stopped));await flush();
|
||||
f.show();await flush();f.advance(10000);f.poll();await flush();
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1);
|
||||
});
|
||||
});
|
||||
test('actual telemetry loss during neutral hold still retires the session',async()=>fixture(async f=>{
|
||||
await f.c.arm(30,70,'duty');f.hide();await flush();
|
||||
const p=f.delayPoll();f.poll();p.resolve(response({fresh:false,controlling:false,snapshot:{}}));await flush();
|
||||
assert.equal(f.calls.at(-1).body.stop,true);
|
||||
f.show();await flush();f.advance(10000);f.poll();await flush();
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1);
|
||||
}));
|
||||
test('manual arm while hidden cannot acquire a lease',async()=>fixture(async f=>{
|
||||
f.hide();assert.equal(await f.c.arm(30,70,'duty'),false);
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,0);
|
||||
}));
|
||||
|
||||
|
||||
test('USB reconnection retires control even when the controller UUID is unchanged',async()=>fixture(async f=>{
|
||||
await f.c.arm(30,70,'duty');await flush();
|
||||
const changed={...stopped,snapshot:{...stopped.snapshot,devices:stopped.snapshot.devices.map(d=>({...d,session_id:'usb-B'}))}};
|
||||
let p=f.delayPoll();f.poll();p.resolve(response(changed));await flush();
|
||||
assert.equal(f.calls.at(-1).body.stop,true);
|
||||
f.advance(9000);f.poll();await flush();
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,1);
|
||||
assert.ok(f.stateWrites.some(v=>typeof v==='string'&&v.includes('Подключение VESC изменилось')));
|
||||
}));
|
||||
|
||||
|
||||
test('fresh intent occupies each 50ms carrier opportunity without replaying invalid input',async()=>fixture(async f=>{
|
||||
await f.c.arm(30,70,'duty');await flush();f.c.setInputGuard(()=>true);
|
||||
const heartbeat=f.timers.find(t=>t.ms===50);assert.ok(heartbeat);
|
||||
assert.equal(f.timers.filter(t=>t.ms<200).length,1,'one producer timer');
|
||||
const start=f.calls.filter(x=>x.url.endsWith('/command')).length;
|
||||
for(let n=0;n<4;n++){f.advance(50);heartbeat.f();await flush();}
|
||||
const commands=f.calls.filter(x=>x.url.endsWith('/command')).slice(start);
|
||||
assert.equal(commands.length,4);assert.deepEqual(commands.map(x=>x.body.sequence),[2,3,4,5]);
|
||||
assert.ok(commands.every(x=>x.body.left===0&&x.body.right===0));
|
||||
f.c.setInputGuard(()=>false);f.c.setDemand({left:1,right:1});await flush();
|
||||
f.advance(50);heartbeat.f();await flush();assert.equal(f.calls.at(-1).body.left,0);
|
||||
f.c.stop();await flush();const count=f.calls.length;
|
||||
f.advance(50);heartbeat.f();await flush();assert.equal(f.calls.length,count,'stop retires timer authority');
|
||||
}));
|
||||
|
||||
|
||||
test('repeated failed automatic arm stays rate bounded until explicit Stop',async()=>fixture(async f=>{
|
||||
await f.c.arm(30,70,'duty');await flush();
|
||||
const p=f.delayPoll();f.poll();p.resolve(response(stopped));await flush();
|
||||
const a=f.delayArm();a.resolve({ok:false,status:503,json:async()=>({detail:'Канал временно недоступен.'})});
|
||||
for(let tick=0;tick<100;tick++){f.advance(200);f.poll();await flush();}
|
||||
const count=f.calls.filter(x=>x.url.endsWith('/arm')).length;
|
||||
assert.ok(count>=5&&count<=7,'rate bounded retries survive transient failures');
|
||||
assert.equal(f.stateWrites.some(v=>typeof v==='string'&&v.includes('Автовосстановление остановлено')),false);
|
||||
f.c.stop();await flush();
|
||||
for(let n=0;n<3;n++){f.advance(100000);f.poll();await flush();}
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,count,'explicit stop cancels all further attempts');
|
||||
}));
|
||||
|
||||
// Owner-requested transport continuity through repeated failed admissions.
|
||||
test('transport recovery persists beyond three failures and explicit Stop cancels it',async()=>fixture(async f=>{
|
||||
await f.c.arm(30,70,'duty');await flush();
|
||||
const p=f.delayPoll();f.poll();p.resolve(response(stopped));await flush();
|
||||
const a=f.delayArm();a.resolve({ok:false,status:503,json:async()=>({detail:'Канал временно недоступен.'})});
|
||||
for(let tick=0;tick<100;tick++){f.advance(200);f.poll();await flush();}
|
||||
const count=f.calls.filter(x=>x.url.endsWith('/arm')).length;
|
||||
assert.ok(count>=5&&count<=7,'bounded retry frequency without terminal cutoff');
|
||||
assert.equal(f.stateWrites.some(v=>typeof v==='string'&&v.includes('Автовосстановление остановлено')),false);
|
||||
f.c.stop();await flush();
|
||||
for(let n=0;n<3;n++){f.advance(100000);f.poll();await flush();}
|
||||
assert.equal(f.calls.filter(x=>x.url.endsWith('/arm')).length,count,'explicit stop cancels background recovery');
|
||||
}));
|
||||
|
||||
test('transient 409 admission races preserve recovery but ownership conflicts remain terminal',async()=>{
|
||||
for(const reason of ['Команда устарела до передачи на борт.','Канал управления бортом недоступен.','Дождитесь завершения предыдущего управления.','Аппаратом уже управляют. Сначала остановите управление.']){
|
||||
await fixture(async f=>{
|
||||
await f.c.arm(30,70,'duty');await flush();
|
||||
const p=f.delayPoll();f.poll();p.resolve(response(stopped));await flush();
|
||||
const a=f.delayArm();a.resolve({ok:false,status:409,json:async()=>({detail:reason})});
|
||||
for(let tick=0;tick<60;tick++){f.advance(200);f.poll();await flush();}
|
||||
const count=f.calls.filter(x=>x.url.endsWith('/arm')).length;
|
||||
if(reason.startsWith('Аппаратом уже'))assert.equal(count,2,'another owner cannot be automatically overridden');
|
||||
else assert.ok(count>2&&count<=6,'temporary conflict should retain rate bounded recovery: '+reason);
|
||||
assert.ok(f.calls.filter(x=>x.body&&'left' in x.body).every(x=>x.body.left===0&&x.body.right===0));
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const compiled=await build({entryPoints:[new URL('../src/core/fleet/roverDevEvents.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {connectRoverEvidence,roverDevEvent}=await import('data:text/javascript;base64,'+Buffer.from(compiled.outputFiles[0].contents).toString('base64'));
|
||||
test('browser evidence is opt-in, separate, and disabled again at session end',async()=>{
|
||||
const original=globalThis.fetch,calls=[];globalThis.fetch=async(_url,init)=>{calls.push(JSON.parse(init.body));return {ok:true};};
|
||||
const connection=connectRoverEvidence('/rover');
|
||||
try{
|
||||
roverDevEvent('/rover','demand',{left:1});await connection.flush();assert.equal(calls.length,0);
|
||||
connection.set('a'.repeat(32));roverDevEvent('/rover','demand',{left:1,right:-1});await connection.flush();
|
||||
assert.equal(calls.length,1);assert.equal(calls[0].events[0].right,-1);
|
||||
connection.set(null);roverDevEvent('/rover','demand',{left:1});await connection.flush();assert.equal(calls.length,1);
|
||||
}finally{connection.close();globalThis.fetch=original;}
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const source=await build({entryPoints:[new URL('../src/core/fleet/roverFaultNotice.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {RoverFaultNotice}=await import('data:text/javascript;base64,'+Buffer.from(source.outputFiles[0].contents).toString('base64'));
|
||||
const frame=(message='old fault',session_id='old',fresh=true)=>({fresh,snapshot:{instance_id:'node',session_id,state:message?'fault':'stopped',message}});
|
||||
test('opening an existing terminal snapshot is a baseline, not a new failure toast',()=>{
|
||||
const n=new RoverFaultNotice();assert.equal(n.update(frame(),null).show,undefined);
|
||||
assert.equal(n.update(frame(),null).show,undefined);
|
||||
assert.equal(n.update(frame(null),null).clear,'old fault');
|
||||
assert.equal(n.update(frame('new fault','new'),null).show,'new fault');
|
||||
assert.equal(n.update(frame('new fault','new'),null).show,undefined);
|
||||
});
|
||||
test('stale snapshots cannot establish baseline or clear a live error; owned new faults are immediate',()=>{
|
||||
const n=new RoverFaultNotice();assert.deepEqual(n.update(frame('ignored','old',false),null),{});
|
||||
assert.equal(n.update(frame('active fault','owned'),'owned').show,'active fault');
|
||||
assert.deepEqual(n.update(frame(null,'owned',false),'owned'),{});
|
||||
assert.equal(n.update(frame(null,'owned'),'owned').clear,'active fault');
|
||||
});
|
||||
@@ -13,7 +13,7 @@ class Events {
|
||||
tick(){for(const fn of this.timers.values())fn();}
|
||||
}
|
||||
function fixture(mode='arcade'){
|
||||
let time=0,focus=true;const win=new Events(),doc=new Events();doc.defaultView=win;doc.hidden=false;doc.hasFocus=()=>focus;
|
||||
let time=0,focus=true;const win=new Events(),doc=new Events();doc.defaultView=win;doc.hidden=false;doc.hasFocus=()=>focus;doc.querySelector=()=>null;doc.body={closest:()=>null};
|
||||
const scope={ownerDocument:doc,closest:()=>null},child={closest:()=>null};scope.contains=x=>x===scope||x===child;doc.activeElement=scope;
|
||||
const states=[],demands=[];let stops=0,pauses=0;
|
||||
const binding=bindRoverHoldInput(scope,mode,{held:k=>states.push([...k]),demand:d=>demands.push(d),stop:()=>stops++,pause:()=>{pauses++;demands.push({left:0,right:0});}},()=>time);
|
||||
@@ -34,12 +34,15 @@ test('heartbeat validity catches missing blur event using document focus',()=>{
|
||||
test('focus polling catches missing event or moving to another control',()=>{
|
||||
const f=fixture();f.key('KeyW');f.doc.activeElement={};f.advance(50);assert.equal(f.pauses(),1);f.binding.dispose();
|
||||
});
|
||||
test('lost keyup AND missing focus notifications still expire repeated D',()=>{
|
||||
const f=fixture();f.key('KeyD');f.advance(500);f.key('KeyD',true);f.advance(299);assert.equal(f.pauses(),0);
|
||||
f.advance(1);assert.equal(f.pauses(),1);assert.deepEqual(f.states.at(-1),[]);f.key('KeyD',true);assert.equal(f.pauses(),1);f.binding.dispose();
|
||||
test('releasing the repeated key in AD keeps A held without OS autorepeat',()=>{
|
||||
const f=fixture('tank');f.key('KeyA');f.key('KeyD');f.advance(500);f.key('KeyD',true);
|
||||
f.up('KeyD');f.advance(10000);assert.equal(f.pauses(),0);
|
||||
assert.deepEqual(f.demands.at(-1),{left:-1,right:0});
|
||||
f.up('KeyA');assert.deepEqual(f.demands.at(-1),{left:0,right:0});f.binding.dispose();
|
||||
});
|
||||
test('first press allows OS repeat delay but never an indefinite hold',()=>{
|
||||
const f=fixture();f.key('KeyW');f.advance(999);assert.equal(f.pauses(),0);f.advance(1);assert.equal(f.pauses(),1);f.binding.dispose();
|
||||
test('a held key does not require OS autorepeat, but focus still revokes it',()=>{
|
||||
const f=fixture();f.key('KeyW');f.advance(10000);assert.equal(f.pauses(),0);
|
||||
f.loseFocus();f.advance(50);assert.equal(f.pauses(),1);assert.deepEqual(f.states.at(-1),[]);f.binding.dispose();
|
||||
});
|
||||
test('continuous repeat renews hold; keyup immediately sends neutral',()=>{
|
||||
const f=fixture();f.key('KeyW');f.advance(600);
|
||||
@@ -83,3 +86,22 @@ test('modifier shortcuts pause; cleanup removes listeners, timer and held demand
|
||||
test('Space and Escape remain explicit session stops',()=>{
|
||||
for(const code of ['Space','Escape']){const f=fixture();f.key('KeyW');f.key(code);assert.equal(f.stops(),1);assert.equal(f.binding.valid(),false);f.binding.dispose();}
|
||||
});
|
||||
|
||||
test('a fresh key works from observation header or browser body without a canvas click',()=>{
|
||||
for(const mode of ['tank','arcade'])for(const focus of ['header','body']){
|
||||
const f=fixture(mode);f.doc.activeElement=focus==='header'?f.child:f.doc.body;
|
||||
f.key(mode==='tank'?'KeyQ':'KeyW');
|
||||
assert.deepEqual(f.demands.at(-1),mode==='tank'?{left:1,right:0}:{left:1,right:1});
|
||||
f.win.emit('blur');f.key(mode==='tank'?'KeyQ':'KeyW',true);
|
||||
assert.deepEqual(f.demands.at(-1),{left:0,right:0});f.binding.dispose();
|
||||
}
|
||||
});
|
||||
test('forms, content editors and modal layers never become driving input',()=>{
|
||||
for(const blocker of ['input','contenteditable','dialog','listbox','menu']){
|
||||
const f=fixture();f.key('KeyW');
|
||||
if(blocker==='input'||blocker==='contenteditable')f.child.closest=()=>({});
|
||||
else f.doc.querySelector=()=>({});
|
||||
f.doc.activeElement=f.child;f.advance(50);f.key('KeyD');
|
||||
assert.deepEqual(f.demands.at(-1),{left:0,right:0});assert.equal(f.binding.valid(),false);f.binding.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({entryPoints:[new URL('../src/core/fleet/roverInput.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {keyDemand,roverSettings}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
const {keyDemand,roverSettings,roverNumberInput,persistableRoverSettings}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
const keys=(...k)=>new Set(k.map(v=>'Key'+v));
|
||||
test('arcade mixes directions and opposite keys cancel',()=>{
|
||||
assert.deepEqual(keyDemand('arcade',keys('W')),{left:1,right:1});
|
||||
@@ -21,3 +21,34 @@ test('invalid stored settings never grant motion or invalid limits',()=>{
|
||||
assert.equal(roverSettings({version:1,model:'https://other/model.glb'}).model,'');
|
||||
assert.deepEqual(keyDemand('arcade',new Set()),{left:0,right:0});
|
||||
});
|
||||
test('saved RPM never becomes full throttle during migration',()=>{
|
||||
const migrated=roverSettings({version:1,maxErpm:3000,currentA:30,mode:'tank',model:'dcd006-v020',throttlePercent:100});
|
||||
assert.equal(migrated.version,3);assert.equal(migrated.throttlePercent,10);
|
||||
assert.equal(migrated.mode,'tank');assert.equal(migrated.model,'dcd006-v020');
|
||||
assert.equal(roverSettings({...migrated,throttlePercent:50}).throttlePercent,50);
|
||||
assert.equal(roverSettings({...migrated,throttlePercent:Infinity}).throttlePercent,10);
|
||||
assert.equal(roverSettings({...migrated,throttlePercent:101}).throttlePercent,100);
|
||||
});
|
||||
|
||||
test('legacy empty and clamped current recover to 30 A once',()=>{
|
||||
for(const version of [1,2])for(const currentA of [0,.5,null,undefined,-1])
|
||||
assert.equal(roverSettings({version,currentA}).currentA,30);
|
||||
assert.equal(roverSettings({version:2,currentA:12,throttlePercent:70}).currentA,12);
|
||||
assert.equal(roverSettings({version:2,currentA:.5,throttlePercent:70}).throttlePercent,70);
|
||||
assert.equal(roverSettings({version:3,currentA:.5}).currentA,.5);
|
||||
});
|
||||
test('empty and invalid number drafts cannot overwrite saved valid settings',()=>{
|
||||
const saved=roverSettings({version:3,currentA:30,throttlePercent:70});
|
||||
assert.ok(persistableRoverSettings(saved));
|
||||
for(const text of ['', ' ', '0', 'Infinity', 'NaN'])
|
||||
assert.equal(persistableRoverSettings({...saved,currentA:roverNumberInput(text)}),false);
|
||||
assert.ok(Number.isNaN(roverNumberInput('')));
|
||||
assert.ok(persistableRoverSettings({...saved,currentA:roverNumberInput('0.5')}));
|
||||
});
|
||||
|
||||
test('operator current above 30 A persists without silently changing it',()=>{
|
||||
for(const currentA of [35,60,100,120,150]){
|
||||
const saved=roverSettings({version:3,currentA});assert.equal(saved.currentA,currentA);
|
||||
assert.ok(persistableRoverSettings(saved));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({stdin:{contents:"export * from './roverDevEvents'; export * from './roverTransport';",resolveDir:new URL('../src/core/fleet/',import.meta.url).pathname,loader:'ts'},bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {BrowserEvidence,connectRoverEvidence,roverDevEvent,RoverTransport}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
test('local browser events use only the operator-host endpoint while remote DEV is disabled',async()=>{
|
||||
const previous=globalThis.fetch,calls=[];globalThis.fetch=async(url,options)=>{calls.push({url,body:JSON.parse(options.body)});return {ok:true,json:async()=>({accepted:true})};};
|
||||
const capture=connectRoverEvidence('/api/v1/fleet/fixture/rover');
|
||||
try{capture.set(null,'local');roverDevEvent('/api/v1/fleet/fixture/rover','request',{request_id:8,sequence:12});
|
||||
await new Promise(r=>setTimeout(r,300));assert.equal(calls.length,1);
|
||||
assert.equal(calls[0].url,'/api/v1/fleet/fixture/rover/diagnostics/local/events');
|
||||
assert.equal(calls[0].body.events[0].reason,'local_capture_attached');assert.equal(calls[0].body.id,'local');assert.equal(calls[0].body.events.find(e=>e.event==='request').request_id,8);
|
||||
}finally{capture.close();globalThis.fetch=previous;}
|
||||
});
|
||||
test('failed local transfers are bounded and never count a retry as a lost event',async()=>{
|
||||
const old=globalThis.fetch;globalThis.fetch=async()=>{throw Error('offline');};
|
||||
try{const e=new BrowserEvidence('/local',true);e.set('a');for(let n=0;n<300;n++)e.record('request',{sequence:n});
|
||||
assert.equal(e.rows.length,256);assert.equal(e.dropped,44);await e.flush();
|
||||
assert.equal(e.rows.length,256);assert.equal(e.dropped,44);
|
||||
e.set('b');assert.equal(e.rows.length,0);
|
||||
}finally{globalThis.fetch=old;}
|
||||
});
|
||||
test('old in-flight reply cannot disable or prepend rows to a newer capture',async()=>{
|
||||
const old=globalThis.fetch;let done;globalThis.fetch=()=>new Promise(r=>done=r);
|
||||
try{const e=new BrowserEvidence('/local',true);e.set('a');e.record('request');const f=e.flush();
|
||||
e.set('b');e.record('request',{sequence:2});done({ok:true,json:async()=>({accepted:false})});await f;
|
||||
assert.equal(e.id,'b');assert.equal(e.rows[0].sequence,2);
|
||||
}finally{globalThis.fetch=old;}
|
||||
});
|
||||
test('closed local capture stops ingestion and oversized events are not retained',async()=>{
|
||||
const old=globalThis.fetch;globalThis.fetch=async()=>({ok:true,json:async()=>({accepted:false})});
|
||||
try{const e=new BrowserEvidence('/local',true);e.set('a');e.record('request',{reason:'x'.repeat(3000)});
|
||||
assert.equal(e.rows.length,0);assert.equal(e.dropped,1);e.record('request');await e.flush();assert.equal(e.id,null);
|
||||
}finally{globalThis.fetch=old;}
|
||||
});
|
||||
|
||||
test('send and ack correlate with Core socket identity without altering the command envelope',async()=>{
|
||||
const oldFetch=globalThis.fetch,oldWindow=globalThis.window,calls=[];
|
||||
globalThis.window={location:{href:'http://127.0.0.1:8000/'}};
|
||||
globalThis.fetch=async(url,options)=>{calls.push(JSON.parse(options.body));return {ok:true,json:async()=>({accepted:true})};};
|
||||
let socket;
|
||||
const capture=connectRoverEvidence('/api/v1/fleet/fixture/rover');capture.set(null,'local');
|
||||
const transport=new RoverTransport('/api/v1/fleet/fixture/rover',()=>socket={readyState:1,bufferedAmount:0,sent:[],send(raw){this.sent.push(JSON.parse(raw));},close(){}});
|
||||
try{
|
||||
socket.onmessage({data:JSON.stringify({type:'state',socket_id:'core-socket',clock_ms:1000,value:{fresh:true}})});
|
||||
const p=transport.command('command',{session_id:'session',sequence:3,left:0,right:0});
|
||||
assert.deepEqual(Object.keys(socket.sent[0]).sort(),['action','body','expires_ms','id']);
|
||||
socket.onmessage({data:JSON.stringify({type:'reply',socket_id:'core-socket',id:socket.sent[0].id,value:{accepted_sequence:3}})});
|
||||
assert.equal((await p).accepted_sequence,3);await new Promise(r=>setTimeout(r,300));
|
||||
const rows=calls.flatMap(v=>v.events),sent=rows.find(r=>r.reason==='socket_send'),ack=rows.find(r=>r.reason==='reply_received');
|
||||
assert.equal(sent.sequence,3);assert.equal(sent.session_id,'session');
|
||||
assert.equal(sent.socket_id,ack.socket_id);assert.equal(sent.request_id,ack.request_id);
|
||||
}finally{transport.close();capture.close();globalThis.fetch=oldFetch;globalThis.window=oldWindow;}
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {createHash,webcrypto} from 'node:crypto';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({stdin:{contents:"export * from './src/core/fleet/roverLogSave';export * from './src/core/fleet/roverLogTransfer';",resolveDir:process.cwd()},bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {saveRoverLog,readLogBlocks,transferRoverLog}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
if(!globalThis.crypto)globalThis.crypto=webcrypto;
|
||||
const frame=(raw,offset=0,total=raw.length,extra={})=>JSON.stringify({capture_id:'a'.repeat(32),snapshot:'b'.repeat(64),offset,next:offset+raw.length,total_bytes:total,data:Buffer.from(raw).toString('base64'),sha256:createHash('sha256').update(raw).digest('hex'),...extra})+'\n';
|
||||
|
||||
test('save opens native chooser before network; closes only a verified complete file',async()=>{
|
||||
const oldWindow=globalThis.window,oldFetch=globalThis.fetch;const actions=[],chunks=[];
|
||||
globalThis.window={showSaveFilePicker:async(options)=>{actions.push(['picker',options.suggestedName]);return {createWritable:async()=>({write:async c=>chunks.push(Buffer.from(c)),close:async()=>actions.push(['closed']),abort:async()=>actions.push(['aborted'])})};}};
|
||||
globalThis.fetch=async url=>{actions.push(['fetch',url]);return new Response(frame('manifest\nrow1\nrow2\n'));};
|
||||
try{await saveRoverLog('/rover','session.jsonl');assert.deepEqual(actions,[['picker','session.jsonl'],['fetch','/rover/diagnostics/export?format=chunks'],['closed']]);assert.equal(Buffer.concat(chunks).toString(),'manifest\nrow1\nrow2\n');}
|
||||
finally{globalThis.window=oldWindow;globalThis.fetch=oldFetch;}
|
||||
});
|
||||
test('cancelled save dialog makes no export request',async()=>{
|
||||
const oldWindow=globalThis.window,oldFetch=globalThis.fetch;
|
||||
globalThis.window={showSaveFilePicker:async()=>{throw new DOMException('cancel','AbortError');}};
|
||||
globalThis.fetch=()=>{throw Error('must not fetch');};
|
||||
try{await assert.rejects(saveRoverLog('/rover','session.jsonl'),{name:'AbortError'});}
|
||||
finally{globalThis.window=oldWindow;globalThis.fetch=oldFetch;}
|
||||
});
|
||||
test('interrupted response resumes exact snapshot after last verified written block',async()=>{
|
||||
const oldFetch=globalThis.fetch,urls=[],bytes=[];
|
||||
globalThis.fetch=async url=>{urls.push(url);return new Response(urls.length===1?frame('abc',0,6)+'{"partial":':frame('def',3,6));};
|
||||
try{
|
||||
await transferRoverLog('/rover',async data=>bytes.push(Buffer.from(data)));
|
||||
assert.equal(Buffer.concat(bytes).toString(),'abcdef');assert.equal(urls.length,2);
|
||||
const resumed=new URL(urls[1],'http://test').searchParams;
|
||||
assert.equal(resumed.get('offset'),'3');assert.equal(resumed.get('total_bytes'),'6');
|
||||
assert.equal(resumed.get('snapshot'),'b'.repeat(64));assert.equal(resumed.get('capture_id'),'a'.repeat(32));
|
||||
}finally{globalThis.fetch=oldFetch;}
|
||||
});
|
||||
test('corruption, identity drift, duplicates, oversize and early EOF never confirm bad bytes',async()=>{
|
||||
const cursor={capture_id:'a'.repeat(32),snapshot:'b'.repeat(64),total_bytes:6,offset:3};
|
||||
for(const text of [frame('def',3,6,{sha256:'0'.repeat(64)}),frame('def',3,6,{snapshot:'c'.repeat(64)}),frame('abc',0,6),frame('def',3,7),frame('x'.repeat(65537),3,65540),'x'.repeat(110000)]){
|
||||
let written=0;await assert.rejects(readLogBlocks(new Response(text),cursor,async()=>written++,()=>{}));assert.equal(written,0);
|
||||
}
|
||||
await assert.rejects(readLogBlocks(new Response(frame('abc',0,6)),undefined,async()=>{},()=>{}));
|
||||
});
|
||||
test('HTTP segmentation, including split JSON lines, does not change file bytes',async()=>{
|
||||
const encoded=new TextEncoder().encode(frame('abc',0,6)+frame('def',3,6)),written=[];
|
||||
const response=new Response(new ReadableStream({start(c){for(let i=0;i<encoded.length;i+=17)c.enqueue(encoded.slice(i,i+17));c.close();}}));
|
||||
await readLogBlocks(response,undefined,async b=>written.push(Buffer.from(b)),()=>{});
|
||||
assert.equal(Buffer.concat(written).toString(),'abcdef');
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import {build} from 'esbuild';
|
||||
|
||||
// Real UI composition, with fixture transports/renderers. No hardware access.
|
||||
async function component(relative, overrides={}) {
|
||||
const path=new URL(relative,import.meta.url).pathname,source=readFileSync(path,'utf8');
|
||||
const imports=new Map([...source.matchAll(/import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/g)].map(([,names,path])=>[path,names.split(',').map(n=>n.trim()).filter(n=>!n.startsWith('type '))]));
|
||||
const result=await build({entryPoints:[path],bundle:true,write:false,platform:'node',format:'esm',jsx:'automatic',plugins:[{name:'component-fixture',setup(b){
|
||||
b.onResolve({filter:/.*/},a=>a.kind==='entry-point'?undefined:{path:a.path,namespace:'fixture'});
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},({path})=>{
|
||||
if(path==='react/jsx-runtime')return {contents:'export const Fragment="Fragment";export const jsx=(type,props)=>({type,props});export const jsxs=jsx;'};
|
||||
if(path==='react')return {contents:`export const useState=v=>globalThis.roverUI.state(v),useRef=v=>globalThis.roverUI.ref(v),useEffect=(f,d)=>globalThis.roverUI.effect(f,d),useLayoutEffect=useEffect,useCallback=f=>f,useMemo=f=>f(),lazy=()=>"Lazy",Suspense="Suspense";`};
|
||||
if(path==='react-dom')return {contents:'export const createPortal=(children,target)=>({type:"Portal",props:{children,target}});'};
|
||||
return {contents:overrides[path]??(imports.get(path)??[]).map(name=>`export const ${name}=${JSON.stringify(name)};`).join('\n')};
|
||||
});
|
||||
}}]});
|
||||
return import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
}
|
||||
const {VehiclesWorkspace}=await component('../src/workspaces/fleet/VehiclesWorkspace.tsx',{
|
||||
'../../core/fleet/useFleet':'export const useFleet=()=>globalThis.roverUI.fleet;export const fleetRequest=()=>{};',
|
||||
'./NodeInvitationForm':'export const NodeInvitationForm="NodeInvitationForm",platformLabel=()=>"UGV";',
|
||||
});
|
||||
const {BoardObservationCenter}=await component('../src/workspaces/fleet/observation/BoardObservationCenter.tsx',{
|
||||
'../../../core/device-plugins/DevicePluginHost':'export const useDevicePluginHost=()=>({registry:{sensorContributions:[]}});',
|
||||
'../../../core/fleet/sensorTransport':'export const createFleetSensorTransport=()=>({});',
|
||||
'../../../core/fleet/useVehicleObservation':'export const useVehicleObservation=()=>globalThis.roverUI.presets;',
|
||||
'../../../core/fleet/observationLayout':'export const orderedObservationIDs=(_,ids)=>ids;export const moveObservation=()=>{},withObservationTree=()=>{},observationTree=()=>{};',
|
||||
'../../../core/fleet/observationPresets':'export const observationArrangements=[],retainDormantObservationTree=()=>{};',
|
||||
'../../../../../../packages/sensor-ui/src/observation':'export const cameraObservationViews=()=>[],observationKey=(d,v)=>d+v;',
|
||||
'../../../../../../packages/sensor-ui/src/observationCatalog':'export const unboundObservationViews=()=>[];',
|
||||
'./useObservationInventory':'export const useObservationInventory=()=>globalThis.roverUI.inventory;',
|
||||
'../../../core/fleet/roverObservation':'export const roverObservationStatus=()=>({label:null,pulse:false});',
|
||||
'../../../core/fleet/useRoverControl':'export const useRoverControl=(id,visible)=>{globalThis.roverUI.watches.push({id,visible});return {state:{fresh:true,snapshot:{}},stop:()=>{}};};',
|
||||
'../../../core/fleet/useRoverDiagnostics':'export const useRoverDiagnostics=()=>({state:{active:false,closing:false}});',
|
||||
'../../../components/rover/RoverTelemetry':'export const RoverTelemetry="RoverTelemetry",roverTelemetryMinimum=()=>({width:1,height:1});',
|
||||
});
|
||||
const {RoverView}=await component('../src/components/rover/RoverView.tsx',{
|
||||
'../../core/fleet/roverObservation':'export const roverObservationStatus=()=>({label:null,pulse:false});',
|
||||
'../../core/fleet/roverInput':'export const keysFor=()=>[],roverSettings=()=>({mode:"tank",model:"",currentA:34.5,throttlePercent:20}),persistableRoverSettings=()=>false,roverNumberInput=Number;',
|
||||
'../../core/fleet/roverDevEvents':'export const roverDevEvent=()=>{};',
|
||||
'../../core/fleet/roverHoldInput':'export const bindRoverHoldInput=scope=>{globalThis.roverUI.inputScope=scope;return ({valid:()=>true,dispose:()=>{}});};',
|
||||
});
|
||||
function find(tree,predicate){if(!tree||typeof tree!=='object')return; if(Array.isArray(tree)){for(const node of tree){const found=find(node,predicate);if(found)return found;}return;}if(predicate(tree))return tree;return find(tree.props?.children,predicate);}
|
||||
function harness(){
|
||||
let slots=[],cursor=0,effects=[];const h={
|
||||
state(initial){const i=cursor++;if(!(i in slots))slots[i]=typeof initial==='function'?initial():initial;return [slots[i],v=>{slots[i]=typeof v==='function'?v(slots[i]):v;}];},
|
||||
ref(v){const i=cursor++;return slots[i]??={current:v};},
|
||||
effect(fn,deps){const i=cursor++,old=slots[i];if(!old||deps.some((v,j)=>!Object.is(v,old.deps[j])))effects.push(()=>{old?.cleanup?.();slots[i]={deps,cleanup:fn()};});},
|
||||
render(fn,props={}){cursor=0;return fn(props);},
|
||||
commit(){const list=effects;effects=[];list.forEach(f=>f());},
|
||||
reset(){slots=[];cursor=0;effects=[];},
|
||||
watches:[],presets:{layout:{hidden:[],layers:{}},presets:[],cameras:{},ready:true,setLayout(){}},inventory:{fresh:true,items:[]},
|
||||
};return h;
|
||||
}
|
||||
async function fixture(run){
|
||||
const keys=['roverUI','document','localStorage','requestAnimationFrame','cancelAnimationFrame'];const originals=new Map(keys.map(k=>[k,globalThis[k]]));
|
||||
const h=harness(),frames=new Map();let frame=0;
|
||||
globalThis.roverUI=h;globalThis.document={hidden:false,hasFocus:()=>true,querySelector:()=>null,createElement:()=>({append(){},remove(){}})};
|
||||
globalThis.localStorage={getItem:()=>null};globalThis.requestAnimationFrame=f=>{frames.set(++frame,f);return frame;};globalThis.cancelAnimationFrame=i=>frames.delete(i);
|
||||
h.frame=()=>{const list=[...frames.values()];frames.clear();list.forEach(f=>f());};
|
||||
try{await run(h);}finally{for(const [key,value]of originals){if(value===undefined)delete globalThis[key];else globalThis[key]=value;}}
|
||||
}
|
||||
test('registry error/offline cannot disable independently live rover channel; revocation still does',async()=>fixture(async h=>{
|
||||
const vehicle={id:'test-rover',name:'fixture',enrollment:'paired',connectivity:'online',platform:'ugv'};h.fleet={items:[vehicle],error:null};
|
||||
let tree=h.render(VehiclesWorkspace);find(tree,n=>n.type==='VehicleFleetRow').props.onObserve();
|
||||
const cases=[{error:null,connectivity:'online',paired:true},{error:'SSE failed',connectivity:'online',paired:true},{error:null,connectivity:'offline',paired:true},{error:null,connectivity:'online',paired:false}];
|
||||
const props=[];
|
||||
for(const c of cases){h.fleet.error=c.error;vehicle.connectivity=c.connectivity;vehicle.enrollment=c.paired?'paired':'revoked';tree=h.render(VehiclesWorkspace);props.push(find(tree,n=>n.type==='BoardObservationCenter').props);}
|
||||
h.reset();
|
||||
for(let i=0;i<props.length;i++){
|
||||
tree=h.render(BoardObservationCenter,props[i]);assert.equal(h.watches.at(-1).visible,cases[i].paired);
|
||||
if(i===1||i===2){assert.equal(find(tree,n=>n.type==='StatusBadge').props.children,'Нет свежих сведений об оборудовании');assert.ok(find(tree,n=>n.type==='RoverTelemetry'));}
|
||||
}
|
||||
}));
|
||||
test('hiding both rover panels releases channel independently of metadata',async()=>fixture(async h=>{
|
||||
const props={vehicleID:'fixture',name:'fixture',enabled:false,paired:true};
|
||||
for(const hidden of [[],['rover'],['telemetry'],['rover','telemetry']]){h.presets.layout.hidden=hidden;h.render(BoardObservationCenter,props);assert.equal(h.watches.at(-1).visible,hidden.length<2);}
|
||||
}));
|
||||
function controller(){return {connection:"connected",state:{fresh:true,snapshot:{supported:true}},controlMode:'duty',canArm:true,armed:false,ready:false,stop(){},setInputGuard(){},pauseInput(){},arm:async()=>true};}
|
||||
test('verified initialization pulses the existing lamp and blocks arm without closing settings',async()=>fixture(async h=>{
|
||||
const props={vehicleID:'fixture',controller:controller(),header:{actionsTarget:{},statusTarget:{}},active:true,observation:{label:'Инициализация VESC',pulse:true}};
|
||||
const tree=h.render(RoverView,props);
|
||||
assert.equal(find(tree,n=>n.type==='StatusBadge'&&n.props.variant==='indicator').props.pulse,true);
|
||||
assert.equal(find(tree,n=>n.type==='h3').props.children,'Инициализация VESC');
|
||||
assert.equal(find(tree,n=>n.type==='Button'&&n.props.children==='Включить управление').props.disabled,true);
|
||||
assert.equal(find(tree,n=>n.type==='IconButton'&&n.props.label==='Настройки управления ровером').props.disabled,undefined);
|
||||
}));
|
||||
async function armFixture(h,c,onFocus){
|
||||
const props={vehicleID:'fixture',controller:c,header:{actionsTarget:{},statusTarget:{}},active:true};
|
||||
let tree=h.render(RoverView,props);find(tree,n=>n.props?.className==='rover-view').props.ref.current={focus:onFocus,closest:()=>h.observationScope};h.commit();
|
||||
find(tree,n=>n.type==='IconButton'&&n.props.label==='Включить управление').props.onClick();tree=h.render(RoverView,props);h.commit();
|
||||
await find(tree,n=>n.type==='Button'&&n.props.children==='Включить управление').props.onClick();
|
||||
return props;
|
||||
}
|
||||
test('successful arm transfers focus after modal close; no repeat focus on telemetry updates',async()=>fixture(async h=>{
|
||||
const c=controller();let focused='opener';const props=await armFixture(h,c,()=>{focused='stage';});
|
||||
assert.equal(focused,'opener','must not focus under the open modal');c.armed=true;h.render(RoverView,props);h.commit();
|
||||
focused='modal-restored-opener';h.frame();assert.equal(focused,'stage');
|
||||
focused='another-panel';c.ready=true;h.render(RoverView,props);h.frame();assert.equal(focused,'another-panel');
|
||||
}));
|
||||
test('delayed focus handoff does not steal focus from another window or dialog',async()=>{
|
||||
for(const blocked of ['hidden','blurred','dialog'])await fixture(async h=>{
|
||||
let calls=0;const props=await armFixture(h,controller(),()=>calls++);h.render(RoverView,props);h.commit();
|
||||
if(blocked==='hidden')document.hidden=true;if(blocked==='blurred')document.hasFocus=()=>false;if(blocked==='dialog')document.querySelector=()=>({});
|
||||
h.frame();assert.equal(calls,0);
|
||||
});
|
||||
});
|
||||
|
||||
test('ready binding belongs to the observation center and header owns Play/Stop/status',async()=>fixture(async h=>{
|
||||
const c=controller();let stops=0;c.stop=()=>stops++;
|
||||
h.observationScope={id:'observation'};
|
||||
const props=await armFixture(h,c,()=>{});c.ready=true;c.armed=true;c.state.snapshot.state='ready';
|
||||
const tree=h.render(RoverView,props);h.commit();
|
||||
assert.equal(h.inputScope,h.observationScope);
|
||||
const action=find(tree,n=>n.type==='IconButton'&&n.props.label==='Остановить управление');
|
||||
assert.equal(action.props['aria-pressed'],true);assert.equal(action.props.children.props.name,'stop');
|
||||
assert.equal(find(tree,n=>n.type==='h3').props.children,'Управление вкл');
|
||||
assert.equal(find(tree,n=>n.props?.className==='rover-view__status'),undefined);
|
||||
assert.equal(find(tree,n=>n.props?.className==='rover-view__authority'),undefined);
|
||||
const before=stops;action.props.onClick();assert.equal(stops,before+1);
|
||||
}));
|
||||
|
||||
const {RoverDevWindow}=await component('../src/components/rover/RoverDevWindow.tsx',{
|
||||
'../../core/fleet/useRoverDiagnostics':'export const localDevOptions={live:false,core_trace:false,motor_samples:true,network:true,live_kbps:16,core_kbps:16};',
|
||||
});
|
||||
test('DEV opens configuration without beginning capture or retaining driving focus',async()=>fixture(async h=>{
|
||||
const props={vehicleID:'fixture',name:'fixture',paired:true,enabled:true};
|
||||
let tree=h.render(BoardObservationCenter,props);
|
||||
assert.equal(find(tree,n=>n.type==='RoverDevWindow'),undefined);
|
||||
find(tree,n=>n.type==='IconButton'&&n.props.label==='Включить DEV-запись').props.onClick();
|
||||
tree=h.render(BoardObservationCenter,props);
|
||||
assert.ok(find(tree,n=>n.type==='RoverDevWindow'));
|
||||
assert.equal(find(tree,n=>n.type==='RoverView').props.active,false);
|
||||
}));
|
||||
test('DEV defaults to board-only rows; options are explicit and start is capability gated',async()=>fixture(async h=>{
|
||||
const calls=[];let closed=0,started=0;
|
||||
const capture={state:{options_supported:false},pending:false,toggle:async options=>{calls.push(options);return true;}};
|
||||
const props={capture,close:()=>closed++,started:()=>started++};
|
||||
let tree=h.render(RoverDevWindow,props);
|
||||
assert.equal(find(tree.props.footer,n=>n.type==='Button'&&n.props.children==='Начать запись').props.disabled,true);
|
||||
assert.equal(find(tree,n=>n.type==='Switch'&&n.props.label==='Показывать события онлайн').props.checked,false);
|
||||
assert.equal(find(tree,n=>n.type==='Switch'&&n.props.label==='Добавлять события Core и браузера').props.checked,false);
|
||||
tree.props.onClose();assert.equal(calls.length,0);assert.equal(closed,1);
|
||||
capture.state.options_supported=true;tree=h.render(RoverDevWindow,props);
|
||||
find(tree,n=>n.type==='Switch'&&n.props.label==='Подробные замеры моторов').props.onChange(false);
|
||||
tree=h.render(RoverDevWindow,props);
|
||||
find(tree.props.footer,n=>n.type==='Button'&&n.props.children==='Начать запись').props.onClick();
|
||||
await new Promise(resolve=>setImmediate(resolve));
|
||||
assert.deepEqual(calls,[{live:false,core_trace:false,motor_samples:false,network:true,live_kbps:16,core_kbps:16}]);
|
||||
assert.equal(started,1);assert.equal(closed,2);
|
||||
}));
|
||||
@@ -0,0 +1,27 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const built=await build({entryPoints:[new URL('../src/core/fleet/roverObservation.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {roverObservationStatus:status}=await import('data:text/javascript;base64,'+Buffer.from(built.outputFiles[0].contents).toString('base64'));
|
||||
const empty={fresh:false,controlling:false,snapshot:{}};
|
||||
const board={fresh:true,controlling:false,snapshot:{supported:true,state:'observing',devices:[],profile:{bindings:{left:{device_id:'motor',uuid:'abc'}}}}};
|
||||
const initializing={...board,snapshot:{...board.snapshot,observation:{initializing_devices:['motor']}}};
|
||||
test('connecting to Core is different from receiving no fresh board telemetry',()=>{
|
||||
assert.equal(status(empty,'connecting').label,'Подключение к Mission Core');
|
||||
assert.equal(status(empty,'reconnecting').label,'Восстановление связи с Mission Core');
|
||||
assert.equal(status(empty,'connected').label,'Ожидание телеметрии с борта');
|
||||
assert.equal(status(empty,'connected').pulse,true);
|
||||
});
|
||||
test('initialization requires a fresh explicit driver phase for every missing VESC',()=>{
|
||||
assert.deepEqual(status(initializing,'connected'),{label:'Инициализация VESC',pulse:true});
|
||||
for(const value of [board,{...initializing,fresh:false},{...board,snapshot:{...board.snapshot,observation:{initializing_devices:['other']}}}]){
|
||||
assert.notEqual(status(value,'connected').label,'Инициализация VESC');
|
||||
}
|
||||
});
|
||||
test('ready readings end initialization; stale readings and actual faults cannot inherit it',()=>{
|
||||
const ready={...board,snapshot:{...board.snapshot,devices:[{id:'motor',uuid:'abc',age_ms:0}]}};
|
||||
assert.deepEqual(status(ready,'connected'),{label:null,pulse:false});
|
||||
assert.equal(status({...ready,snapshot:{...ready.snapshot,devices:[{id:'motor',uuid:'abc',age_ms:1000}]}},'connected').label,'Ожидание свежих показаний VESC');
|
||||
assert.deepEqual(status({...board,snapshot:{...board.snapshot,state:'fault',message:'Hardware failure'}},'connected'),{label:null,pulse:false});
|
||||
assert.equal(status({...board,snapshot:{}},'connected').pulse,false);
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const compiled=await build({stdin:{contents:"export * from './roverOperatorCapture';export * from './roverDevEvents';",resolveDir:new URL('../src/core/fleet/',import.meta.url).pathname,loader:'ts'},bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {saveOperatorCapture,connectRoverEvidence,roverPreviewEvidence}=await import('data:text/javascript;base64,'+Buffer.from(compiled.outputFiles[0].contents).toString('base64'));
|
||||
test('local export flushes before requesting only Core and downloads the bounded snapshot',async()=>{
|
||||
const priorDocument=globalThis.document,priorFetch=globalThis.fetch,steps=[];
|
||||
let anchor;
|
||||
globalThis.document={body:{append:a=>{anchor=a;steps.push('append');}},createElement:tag=>{assert.equal(tag,'a');return {click:()=>steps.push('click'),remove:()=>steps.push('remove')};}};
|
||||
globalThis.fetch=async(url)=>{assert.equal(url,'/rover/diagnostics/local/export?capture_id='+'a'.repeat(32));steps.push('fetch');return {ok:true,blob:async()=>new Blob(['sample'])};};
|
||||
try{await saveOperatorCapture('/rover','a'.repeat(32),async()=>steps.push('flush'));assert.deepEqual(steps,['flush','fetch','append','click','remove']);assert.equal(anchor.download,'rover-operator-'+ 'a'.repeat(32)+'.jsonl');assert.match(anchor.href,/^blob:/);}
|
||||
finally{globalThis.document=priorDocument;globalThis.fetch=priorFetch;}
|
||||
});
|
||||
test('invalid, failed and oversized exports never initiate a download or board request',async()=>{
|
||||
const priorDocument=globalThis.document,priorFetch=globalThis.fetch;let fetched=false;
|
||||
globalThis.document={createElement:()=>{throw Error('must not download failed export');}};
|
||||
globalThis.fetch=async(url)=>{assert.ok(url.includes('/diagnostics/local/export'));fetched=true;return {ok:false};};
|
||||
try{await assert.rejects(saveOperatorCapture('/rover','invalid'),/изменилась/);assert.equal(fetched,false);
|
||||
await assert.rejects(saveOperatorCapture('/rover','a'.repeat(32)),/выгрузить/);assert.equal(fetched,true);
|
||||
globalThis.fetch=async()=>({ok:true,blob:async()=>new Blob([new Uint8Array(4*1024*1024+1)])});
|
||||
await assert.rejects(saveOperatorCapture('/rover','a'.repeat(32)),/Размер/);
|
||||
}finally{globalThis.document=priorDocument;globalThis.fetch=priorFetch;}
|
||||
});
|
||||
test('preview checkbox independently excludes metrics from both routes',async()=>{
|
||||
const previous=globalThis.fetch,calls=[];
|
||||
globalThis.fetch=async(url,options)=>{calls.push({url,body:JSON.parse(options.body)});return {ok:true,json:async()=>({accepted:true})};};
|
||||
const capture=connectRoverEvidence('/rover');
|
||||
try{capture.set('remote','local',false);roverPreviewEvidence('/rover',{encoder_bps:100});await capture.flush();
|
||||
assert.ok(!calls.flatMap(x=>x.body.events).some(x=>x.event==='preview'));
|
||||
capture.set('remote','local',true);roverPreviewEvidence('/rover',{encoder_bps:101});await capture.flush();
|
||||
const entries=calls.filter(x=>x.body.events.some(y=>y.event==='preview'));assert.equal(entries.length,1);assert.equal(entries[0].url,'/rover/diagnostics/local/events');
|
||||
}finally{capture.close();globalThis.fetch=previous;}
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({entryPoints:[new URL('../src/core/fleet/roverRecovery.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {RoverRecovery}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
const settings={currentA:30,speed:70,mode:'duty'};
|
||||
const stopped={fresh:true,controlling:false,snapshot:{supported:true,control_modes:['rpm','duty'],instance:'boot-A',state:'stopped',session_id:'old-session',release_confirmed:true,profile:{layout:'1x1',bindings:{left:{uuid:'left'},right:{uuid:'right'}}},devices:['left','right'].map(uuid=>({uuid,session_id:'usb-'+uuid,age_ms:10,values:{erpm:0,fault_code:0}}))}};
|
||||
function recovery(){const r=new RoverRecovery();r.remember(settings,stopped);r.interrupt(0,'old-session');return r;}
|
||||
const change=patch=>({...stopped,snapshot:{...stopped.snapshot,...patch}});
|
||||
test('recovery requires consecutive fresh stopped evidence and preserves exact settings',()=>{
|
||||
const r=recovery();assert.equal(r.next(stopped,0,true),null);
|
||||
assert.equal(r.next(stopped,499,true),null);assert.deepEqual(r.next(stopped,500,true),settings);
|
||||
assert.equal(r.next(stopped,600,true),null);assert.equal(r.next(stopped,1200,true),null);
|
||||
assert.deepEqual(r.next(stopped,1500,true),settings,'retry delay is bounded and increases');
|
||||
});
|
||||
test('no retry with stale telemetry, moving/stale/faulted motors, missing devices or hidden UI',()=>{
|
||||
for(const bad of [{...stopped,fresh:false},change({state:'stopping'}),...['age_ms','erpm','fault_code'].map(k=>change({devices:stopped.snapshot.devices.map(d=>({...d,age_ms:k==='age_ms'?501:10,values:{...d.values,[k]:k==='erpm'?60:1}}))}))]){
|
||||
const r=recovery();r.next(stopped,0,true);assert.equal(r.next(bad,600,true),null);assert.equal(r.next(stopped,700,true),null);assert.deepEqual(r.next(stopped,1200,true),settings);
|
||||
}
|
||||
const r=recovery();r.next(stopped,0,true);assert.equal(r.next(stopped,600,false),null);assert.equal(r.next(stopped,700,true),null);
|
||||
});
|
||||
test('restart, motor reassignment, RC, hardware fault and another owner prohibit recovery',()=>{
|
||||
for(const bad of [change({devices:[]}),change({instance:'boot-B'}),change({profile:{layout:'2x2'}}),change({state:'receiver'}),change({state:'fault'}),change({release_confirmed:false}),change({control_modes:['rpm']}),{...change({session_id:'other-session'}),controlling:true}]){
|
||||
const r=recovery();assert.ok(r.blocker(bad));assert.equal(r.next(bad,9000,true),null);
|
||||
}
|
||||
});
|
||||
test('newly acquired own session is not mistaken for another operator',()=>{
|
||||
const r=recovery(),v={...change({session_id:'new-session',state:'preparing'}),controlling:true};
|
||||
assert.equal(r.blocker(v,'new-session'),null);assert.ok(r.blocker(v));r.connected(1000);assert.equal(r.waiting,false);assert.equal(r.next(stopped,9000,true),null);
|
||||
});
|
||||
test('explicit Stop and reload cannot restore an old request',()=>{
|
||||
const r=recovery();r.clear();assert.equal(r.next(stopped,9000,true),null);assert.equal(r.interrupt(10000,'old-session'),false);
|
||||
assert.equal(new RoverRecovery().next(stopped,9000,true),null);
|
||||
});
|
||||
test('unconfirmed stopping waits without cancelling request; settled stop starts a fresh quiet interval',()=>{
|
||||
const r=recovery(),pending=change({state:'stopping',release_confirmed:false,message:'Release not yet observed',last_stop:{session_id:'old-session',state:'stopping',message:'Release not yet observed'}});
|
||||
for(const at of [0,500,2000,60000]){
|
||||
assert.equal(r.blocker(pending),null);
|
||||
assert.equal(r.next(pending,at,true),null,'pending release never grants authority');
|
||||
assert.equal(r.waiting,true);
|
||||
}
|
||||
const settled=change({last_stop:{...pending.snapshot.last_stop,recovered_at:'fixture'}});
|
||||
assert.equal(r.next(settled,60100,true),null);
|
||||
assert.equal(r.next(settled,60599,true),null);
|
||||
assert.deepEqual(r.next(settled,60600,true),settings);
|
||||
});
|
||||
test('pending release never masks device faults, identity changes, receiver or explicit Stop',()=>{
|
||||
const pending=change({state:'stopping',release_confirmed:false});
|
||||
for(const bad of [change({state:'fault',release_confirmed:false}),change({state:'stopped',last_stop:{session_id:'old-session',state:'fault',message:'Hardware fault',recovered_at:'later'}}),change({state:'receiver'}),change({state:'stopping',instance:'other-boot'}),change({state:'stopping',devices:stopped.snapshot.devices.map(d=>({...d,session_id:'reattached'}))})]){
|
||||
const r=recovery();assert.equal(r.blocker(pending),null);assert.ok(r.blocker(bad));assert.equal(r.next(bad,90000,true),null);
|
||||
}
|
||||
const r=recovery();r.next(pending,0,true);r.clear();assert.equal(r.next(stopped,90000,true),null);
|
||||
});
|
||||
test('a recovered neutral snapshot retains terminal history and cannot auto-rearm its failed session',()=>{
|
||||
const r=recovery(),settled=change({state:'stopped',message:null,last_stop:{session_id:'old-session',state:'fault',message:'USB lost',recovered_at:'fixture'}});
|
||||
assert.equal(r.blocker(settled),'USB lost');assert.equal(r.next(settled,9000,true),null);
|
||||
r.remember(settings,settled);r.started('new-session');
|
||||
assert.equal(r.blocker({...change({state:'preparing',session_id:'new-session',last_stop:settled.snapshot.last_stop}),controlling:true},'new-session'),null);
|
||||
});
|
||||
test('explicit retry can await its own preparation after a previous terminal fault',()=>{
|
||||
const failed=change({state:'fault',release_confirmed:false,message:'Old USB disconnect'}),r=new RoverRecovery();
|
||||
r.remember(settings,failed);r.started('new-session');
|
||||
assert.equal(r.blocker({...failed,controlling:true},'new-session'),null);
|
||||
assert.ok(r.blocker(failed,'new-session'),'without a live Core lease the old fault still blocks');
|
||||
assert.ok(r.blocker({...failed,controlling:true,snapshot:{...failed.snapshot,instance:'boot-B'}},'new-session'));
|
||||
const preparing={...change({session_id:'new-session',state:'preparing',release_confirmed:null}),controlling:true};
|
||||
assert.equal(r.blocker(preparing,'new-session'),null);
|
||||
assert.ok(r.blocker({...failed,controlling:true},'new-session'),'after acknowledgement old states cannot be ignored');
|
||||
assert.ok(r.blocker({...preparing,snapshot:{...preparing.snapshot,state:'fault',message:'New failure'}},'new-session'));
|
||||
});
|
||||
test('explicit retry never permits automatic recovery from unconfirmed release',()=>{
|
||||
const failed=change({state:'fault',release_confirmed:false}),r=new RoverRecovery();
|
||||
r.remember(settings,failed);r.started('new-session');r.interrupt(0,'new-session');
|
||||
assert.ok(r.blocker({...failed,controlling:true},'new-session'));
|
||||
assert.equal(r.next(failed,9000,true),null);
|
||||
});
|
||||
|
||||
|
||||
test('same UUID after USB reconnect requires explicit arm and never auto-recovers',()=>{
|
||||
const r=recovery(),reconnected=change({devices:stopped.snapshot.devices.map(d=>({...d,session_id:d.session_id+'-new'}))});
|
||||
assert.ok(r.blocker(reconnected));assert.equal(r.next(reconnected,9000,true),null);
|
||||
const missing=change({devices:stopped.snapshot.devices.slice(0,1)});assert.ok(recovery().blocker(missing));
|
||||
assert.equal(r.next(stopped,15000,true),null);
|
||||
});
|
||||
test('legacy snapshots without attachment sessions cannot opt into automatic recovery',()=>{
|
||||
const r=new RoverRecovery();r.remember(settings,change({devices:stopped.snapshot.devices.map(({session_id,...d})=>d)}));
|
||||
assert.equal(r.interrupt(0,'old-session'),false);
|
||||
});
|
||||
|
||||
|
||||
test('unknown release evidence never admits an automatic rearm',()=>{
|
||||
for(const release_confirmed of [null,undefined]){
|
||||
const r=recovery(),unknown=change({release_confirmed});
|
||||
assert.equal(r.next(unknown,0,true),null);
|
||||
assert.equal(r.next(unknown,1000,true),null);
|
||||
assert.equal(r.next(stopped,1100,true),null,'confirmed evidence starts its own quiet interval');
|
||||
assert.deepEqual(r.next(stopped,1600,true),settings);
|
||||
}
|
||||
});
|
||||
test('brief ready states cannot reset the automatic recovery budget',()=>{
|
||||
const r=recovery();
|
||||
for(let attempt=0;attempt<3;attempt++){
|
||||
const base=attempt*10000;
|
||||
assert.equal(r.next(stopped,base,true),null);
|
||||
assert.deepEqual(r.next(stopped,base+5000,true),settings);
|
||||
r.connected(base+5100);r.connected(base+6000);
|
||||
assert.equal(r.interrupt(base+7000,'session-'+attempt),true);
|
||||
}
|
||||
assert.equal(r.waiting,true,'backoff retains operator request');
|
||||
assert.equal(r.next(stopped,1000000,true),null,'first stopped observation alone cannot grant another lease');
|
||||
r.remember(settings,stopped);
|
||||
assert.equal(r.waiting,false);
|
||||
assert.equal(r.interrupt(1000100,'explicit-new'),true);
|
||||
});
|
||||
test('only thirty seconds of continuously ready observation restores retry budget',()=>{
|
||||
const r=recovery();r.next(stopped,0,true);assert.deepEqual(r.next(stopped,500,true),settings);
|
||||
for(let at=600;at<=30600;at+=200)r.connected(at);
|
||||
assert.equal(r.interrupt(30700,'stable-session'),true);
|
||||
for(let attempt=0;attempt<3;attempt++){
|
||||
const base=40000+attempt*10000;
|
||||
assert.equal(r.next(stopped,base,true),null);
|
||||
assert.deepEqual(r.next(stopped,base+5000,true),settings);
|
||||
r.connected(base+5100);
|
||||
assert.equal(r.interrupt(base+7000,'short-'+attempt),true);
|
||||
}
|
||||
});
|
||||
test('separate short connections cannot add up to a stable connection',()=>{
|
||||
const r=recovery();
|
||||
for(let attempt=0;attempt<3;attempt++){
|
||||
const base=attempt*50000;
|
||||
assert.equal(r.next(stopped,base,true),null);
|
||||
assert.deepEqual(r.next(stopped,base+5000,true),settings);
|
||||
for(let at=base+5100;at<=base+34100;at+=200)r.connected(at);
|
||||
assert.equal(r.interrupt(base+35000,'short-'+attempt),true);
|
||||
}
|
||||
assert.equal(r.waiting,true);
|
||||
});
|
||||
|
||||
|
||||
test('a long unobserved gap cannot count as thirty seconds of stable connection',()=>{
|
||||
const r=recovery();
|
||||
for(let attempt=0;attempt<3;attempt++){
|
||||
const base=attempt*60000;
|
||||
assert.equal(r.next(stopped,base,true),null);
|
||||
assert.deepEqual(r.next(stopped,base+5000,true),settings);
|
||||
r.connected(base+5100);r.connected(base+36000);
|
||||
assert.equal(r.interrupt(base+37000,'gap-'+attempt),true);
|
||||
}
|
||||
assert.equal(r.waiting,true);
|
||||
});
|
||||
|
||||
|
||||
test('retry admission without a start result remains delayed and never ends request',()=>{
|
||||
const r=recovery();
|
||||
for(let attempt=0;attempt<3;attempt++){
|
||||
const base=attempt*10000;
|
||||
assert.equal(r.next(stopped,base,true),null);
|
||||
assert.deepEqual(r.next(stopped,base+5000,true),settings);
|
||||
}
|
||||
assert.equal(r.next(stopped,30000,true),null);
|
||||
assert.equal(r.waiting,true);assert.deepEqual(r.next(stopped,38000,true),settings,'capped retry preserves request');
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({entryPoints:[new URL('../src/core/fleet/roverRecovery.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {RoverRecovery}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
const settings={currentA:30,speed:70,mode:'duty'};
|
||||
const stopped={fresh:true,controlling:false,snapshot:{supported:true,control_modes:['rpm','duty'],instance:'boot-A',state:'stopped',session_id:'old-session',release_confirmed:true,profile:{layout:'1x1',bindings:{left:{uuid:'left'},right:{uuid:'right'}}},devices:['left','right'].map(uuid=>({uuid,session_id:'usb-'+uuid,age_ms:10,values:{erpm:0,fault_code:0}}))}};
|
||||
function recovery(){const r=new RoverRecovery();r.remember(settings,stopped);r.interrupt(0,'old-session');return r;}
|
||||
const change=patch=>({...stopped,snapshot:{...stopped.snapshot,...patch}});
|
||||
// Owner amendment 2026-10-27: retain operator intent through transport faults.
|
||||
// These are additional cases; pre-existing safety regressions stay in place.
|
||||
test('repeated transport faults retain request with bounded retry frequency',()=>{
|
||||
const r=recovery(),admissions=[];
|
||||
for(let at=0;at<=60000;at+=100){
|
||||
if(r.next(stopped,at,true)){
|
||||
admissions.push(at);r.connected(at+1);assert.equal(r.interrupt(at+2,'session-'+at),true);
|
||||
}
|
||||
}
|
||||
assert.ok(admissions.length>=5&&admissions.length<=11);
|
||||
for(let i=1;i<admissions.length;i++)assert.ok(admissions[i]-admissions[i-1]>=Math.min(8000,1000*2**Math.min(i-1,3)));
|
||||
assert.equal(r.waiting,true,'network retries cannot erase the operator request');
|
||||
});
|
||||
test('thirty seconds of observed ready resets backoff; short connections do not',()=>{
|
||||
const r=recovery();r.next(stopped,0,true);assert.deepEqual(r.next(stopped,500,true),settings);
|
||||
r.connected(501);r.interrupt(502,'short');r.next(stopped,503,true);
|
||||
assert.equal(r.next(stopped,1003,true),null,'brief readiness must not bypass backoff');
|
||||
assert.deepEqual(r.next(stopped,1500,true),settings);
|
||||
for(let at=1600;at<=31600;at+=200)r.connected(at);
|
||||
r.interrupt(31700,'stable');r.next(stopped,31700,true);
|
||||
assert.deepEqual(r.next(stopped,32200,true),settings);
|
||||
});
|
||||
test('long total outage creates no arm attempts and preserves original settings',()=>{
|
||||
const r=recovery();
|
||||
for(let at=0;at<600000;at+=200)assert.equal(r.next({fresh:false,controlling:false,snapshot:{}},at,true),null);
|
||||
assert.equal(r.waiting,true);
|
||||
assert.equal(r.next(stopped,600000,true),null);assert.deepEqual(r.next(stopped,600500,true),settings);
|
||||
r.clear();assert.equal(r.next(stopped,900000,true),null,'explicit stop always cancels recovery');
|
||||
});
|
||||
test('failed admission stays rate bounded without ever getting a start result',()=>{
|
||||
const r=recovery(),admissions=[];
|
||||
for(let at=0;at<=60000;at+=100)if(r.next(stopped,at,true))admissions.push(at);
|
||||
assert.equal(admissions.length,10);assert.equal(r.waiting,true);
|
||||
assert.equal(r.next({...stopped,fresh:false},100000,true),null);
|
||||
});
|
||||
|
||||
test('explicit new operator request does not inherit the old retry delay',()=>{
|
||||
const r=recovery();for(let at=0;at<=8000;at+=100)r.next(stopped,at,true);
|
||||
r.clear();r.remember(settings,stopped);r.interrupt(8100,'explicit-new');
|
||||
assert.equal(r.next(stopped,8100,true),null);assert.deepEqual(r.next(stopped,8600,true),settings);
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const compiled=await build({entryPoints:[new URL('../src/core/fleet/roverRecovery.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {RoverRecovery}=await import('data:text/javascript;base64,'+Buffer.from(compiled.outputFiles[0].contents).toString('base64'));
|
||||
const settings={currentA:30,speed:70,mode:'duty'};
|
||||
const initial={fresh:true,controlling:false,snapshot:{supported:true,control_modes:['rpm','duty'],instance:'stable-driver',state:'stopped',release_confirmed:true,session_id:null,profile:{layout:'1x1',bindings:{}},devices:['left','right'].map(uuid=>({uuid,session_id:'usb-'+uuid,age_ms:10,values:{erpm:0,fault_code:0}}))}};
|
||||
|
||||
test('ten consecutive network stops keep one operator request and never rearm before settled release',()=>{
|
||||
const r=new RoverRecovery();r.remember(settings,initial);
|
||||
for(let run=0;run<10;run++){
|
||||
const id='session-'+run,at=run*20000;
|
||||
r.started(id);r.connected(at);assert.equal(r.interrupt(at+100,id),true);
|
||||
const stopping={...initial,snapshot:{...initial.snapshot,session_id:id,state:'stopping',release_confirmed:false,last_stop:{session_id:id,state:'stopping',message:'Release not yet observed'}}};
|
||||
for(let t=at+200;t<at+10000;t+=200){assert.equal(r.blocker(stopping),null);assert.equal(r.next(stopping,t,true),null);assert.equal(r.waiting,true);}
|
||||
const settled={...stopping,snapshot:{...stopping.snapshot,state:'stopped',release_confirmed:true,last_stop:{...stopping.snapshot.last_stop,recovered_at:'observed'}}};
|
||||
assert.equal(r.next(settled,at+10000,true),null);
|
||||
assert.deepEqual(r.next(settled,at+10600,true),settings);
|
||||
}
|
||||
r.clear();assert.equal(r.next(initial,1e6,true),null);
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({entryPoints:[new URL('../src/core/fleet/roverTransport.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {RoverTransport}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
async function fixture(run){
|
||||
const previous=globalThis.window;globalThis.window={location:{href:'http://127.0.0.1:8000/'}};const sockets=[];
|
||||
const transport=new RoverTransport('/api/v1/fleet/fixture/rover',url=>{const s={url,readyState:1,bufferedAmount:0,sent:[],send(raw){this.sent.push(JSON.parse(raw));},close(){this.readyState=3;this.onclose?.();},message(value){this.onmessage?.({data:JSON.stringify(value)});}};sockets.push(s);return s;});
|
||||
const s=sockets[0],state={fresh:true,controlling:false,snapshot:{state:'observing'}};
|
||||
try{await run({transport,s,sockets,state,ready:()=>s.message({type:'state',clock_ms:10000,value:state})});}finally{transport.close();globalThis.window=previous;}
|
||||
}
|
||||
test('independent socket supplies state and acknowledgements without an HTTP fetch',async()=>fixture(async({transport,s,state,ready})=>{
|
||||
assert.equal(s.url,'ws://127.0.0.1:8000/api/v1/fleet/fixture/rover-channel');
|
||||
const pending=transport.view();ready();assert.deepEqual(await pending,state);
|
||||
const result=transport.command('command',{sequence:1});assert.equal(s.sent.length,1);assert.ok(s.sent[0].expires_ms>=10400&&s.sent[0].expires_ms<10420);
|
||||
s.message({type:'reply',id:s.sent[0].id,value:{accepted_sequence:1}});assert.deepEqual(await result,{accepted_sequence:1});
|
||||
}));
|
||||
test('unconfirmed connection and backpressure never queue a command',async()=>fixture(async({transport,s,ready})=>{
|
||||
await assert.rejects(transport.command('arm',{}));assert.equal(s.sent.length,0);ready();s.bufferedAmount=4097;
|
||||
await assert.rejects(transport.command('command',{}));assert.equal(s.sent.length,0);
|
||||
}));
|
||||
test('disconnect rejects in-flight work and reconnect never replays it',async()=>fixture(async({transport,s,sockets,ready})=>{
|
||||
ready();const p=transport.command('command',{sequence:1});s.close();await assert.rejects(p);
|
||||
await new Promise(resolve=>setTimeout(resolve,280));assert.equal(sockets.length,2);assert.equal(sockets[1].sent.length,0);
|
||||
await assert.rejects(transport.command('command',{sequence:2}));assert.equal(sockets[1].sent.length,0);
|
||||
}));
|
||||
test('late replies cannot acknowledge a timed-out command',async()=>fixture(async({transport,s,ready})=>{
|
||||
ready();const p=transport.command('command',{sequence:1});await assert.rejects(p,/не подтверждена/);
|
||||
s.message({type:'reply',id:s.sent[0].id,value:{accepted_sequence:1}});assert.equal(s.sent.length,1);
|
||||
}));
|
||||
test('arm acknowledgement replaces the cached pre-arm view before caller can poll',async()=>fixture(async({transport,s,state,ready})=>{
|
||||
ready();assert.equal((await transport.view()).controlling,false);
|
||||
const p=transport.command('arm',{}),postArm={...state,controlling:true};
|
||||
s.message({type:'reply',id:s.sent[0].id,value:{session_id:'new'},state:postArm,clock_ms:10002});
|
||||
assert.equal((await p).session_id,'new');assert.equal((await transport.view()).controlling,true);
|
||||
}));
|
||||
|
||||
test('neutral handoff is an explicit acknowledged owner action with a deadline',async()=>fixture(async({transport,s,ready})=>{
|
||||
ready();const p=transport.command('hold',{session_id:'owner',sequence:5});
|
||||
assert.equal(s.sent[0].action,'hold');assert.deepEqual(s.sent[0].body,{session_id:'owner',sequence:5});
|
||||
assert.ok(s.sent[0].expires_ms>=10400&&s.sent[0].expires_ms<10420);
|
||||
s.message({type:'reply',id:s.sent[0].id,value:{accepted_sequence:5}});
|
||||
assert.equal((await p).accepted_sequence,5);
|
||||
}));
|
||||
|
||||
|
||||
test('silent OPEN channel is retired and reconnect cannot replay commands',async()=>fixture(async({transport,s,sockets,ready})=>{
|
||||
ready();s.close=()=>{s.readyState=2;}; // Browser supplies no close callback.
|
||||
await new Promise(resolve=>setTimeout(resolve,1790));
|
||||
assert.equal(sockets.length,2);assert.equal(s.readyState,2);
|
||||
s.message({type:'state',clock_ms:1,value:{fresh:true}});
|
||||
await assert.rejects(transport.command('arm',{}));
|
||||
assert.equal(sockets[1].sent.length,0);
|
||||
}));
|
||||
|
||||
|
||||
|
||||
test('each fresh sample keeps its own 400ms expiry with bounded in-flight work',async()=>fixture(async({transport,s,ready})=>{
|
||||
const original=globalThis.performance;let now=0;globalThis.performance={now:()=>now};
|
||||
const pending=[];
|
||||
try{
|
||||
ready();
|
||||
for(let sequence=1;sequence<=4;sequence++){now=(sequence-1)*50;pending.push(transport.command('command',{sequence,left:0,right:0}));}
|
||||
assert.deepEqual(s.sent.map(x=>x.expires_ms),[10400,10450,10500,10550]);
|
||||
now=200;await assert.rejects(transport.command('command',{sequence:5}));assert.equal(s.sent.length,4);
|
||||
s.message({type:'reply',id:s.sent[3].id,value:{accepted_sequence:4}});await pending[3];
|
||||
pending.push(transport.command('command',{sequence:5,left:0,right:0}));
|
||||
assert.equal(s.sent[4].expires_ms,10600);assert.equal(s.sent[0].expires_ms,10400,'new sample must not extend old frame');
|
||||
for(const frame of s.sent)s.message({type:'reply',id:frame.id,value:{accepted_sequence:frame.body.sequence}});
|
||||
await Promise.all(pending);
|
||||
}finally{globalThis.performance=original;}
|
||||
}));
|
||||
@@ -0,0 +1,49 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const built=await build({entryPoints:[new URL('../src/core/fleet/roverTransport.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm'});
|
||||
const {RoverTransport}=await import('data:text/javascript;base64,'+Buffer.from(built.outputFiles[0].contents).toString('base64'));
|
||||
|
||||
// Deterministic browser handshake/scheduler, no network or motor commands.
|
||||
async function fixture(run){
|
||||
const keys=['window','performance','setTimeout','clearTimeout'],previous=Object.fromEntries(keys.map(k=>[k,globalThis[k]]));
|
||||
let now=0,next=0;const timers=new Map(),sockets=[];
|
||||
globalThis.window={location:{href:'http://127.0.0.1:8000/'}};globalThis.performance={now:()=>now};
|
||||
globalThis.setTimeout=(fn,ms)=>{const id=++next;timers.set(id,{fn,at:now+ms});return id;};globalThis.clearTimeout=id=>timers.delete(id);
|
||||
const advance=ms=>{const end=now+ms;while(true){const item=[...timers].filter(([,t])=>t.at<=end).sort((a,b)=>a[1].at-b[1].at)[0];if(!item)break;now=item[1].at;timers.delete(item[0]);item[1].fn();}now=end;};
|
||||
const transport=new RoverTransport('/api/v1/fleet/fixture/rover',()=>{
|
||||
const socket={readyState:0,bufferedAmount:0,sent:[],send(raw){this.sent.push(raw);},close(){this.readyState=3;},open(){if(this.readyState!==0)return;this.readyState=1;this.onopen?.();},state(){this.onmessage?.({data:JSON.stringify({type:'state',clock_ms:10000+now,value:{fresh:true,controlling:false,snapshot:{state:'observing'}}})});}};
|
||||
sockets.push(socket);return socket;
|
||||
});
|
||||
try{await run({transport,sockets,advance,timers});}finally{transport.close();for(const k of keys)globalThis[k]=previous[k];}
|
||||
}
|
||||
|
||||
test('a two-second initial handshake can finish without being killed by the live-state watchdog',async()=>fixture(async f=>{
|
||||
const first=f.sockets[0];f.advance(2000);
|
||||
assert.equal(first.readyState,0,'handshake was cancelled before any live state existed');
|
||||
await assert.rejects(f.transport.command('arm',{}));assert.equal(first.sent.length,0);
|
||||
first.open();first.state();assert.equal((await f.transport.view()).fresh,true);
|
||||
assert.equal(f.sockets.length,1);
|
||||
}));
|
||||
|
||||
test('an opened socket without state still has the original 1.5-second watchdog',async()=>fixture(async f=>{
|
||||
f.sockets[0].open();f.advance(1500);assert.equal(f.sockets[0].readyState,3);
|
||||
await assert.rejects(f.transport.command('arm',{}));
|
||||
f.advance(250);assert.equal(f.sockets.length,2);assert.equal(f.sockets[1].sent.length,0);
|
||||
}));
|
||||
|
||||
test('a never-opening handshake has a bounded retry and close removes every timer',async()=>fixture(async f=>{
|
||||
f.advance(10250);assert.equal(f.sockets.length,2);assert.equal(f.sockets[0].readyState,3);
|
||||
f.transport.close();assert.equal(f.timers.size,0);f.advance(30000);assert.equal(f.sockets.length,2);
|
||||
}));
|
||||
|
||||
for(let run=1;run<=10;run++)test(`startup/recovery cycle ${run}: delayed handshake, stale input refusal, new connection`,async()=>fixture(async f=>{
|
||||
const first=f.sockets[0];f.advance(1500+run*400);first.open();first.state();
|
||||
assert.equal((await f.transport.view()).fresh,true);assert.equal(f.sockets.length,1);
|
||||
f.advance(601);await assert.rejects(f.transport.command('arm',{}));
|
||||
f.advance(1149);assert.equal(f.sockets.length,2);assert.equal(first.readyState,3);
|
||||
const second=f.sockets[1];f.advance(2000);second.open();second.state();
|
||||
assert.equal((await f.transport.view()).fresh,true);
|
||||
assert.ok(f.sockets.every(s=>s.sent.length===0),'observation never sends a motor command');
|
||||
f.transport.close();assert.equal(f.timers.size,0);
|
||||
}));
|
||||
@@ -0,0 +1,17 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const result=await build({entryPoints:[new URL('../src/core/fleet/sensorTransport.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'fixture',setup(b){
|
||||
b.onResolve({filter:/^\.\/useFleet$/},()=>({path:'fleet',namespace:'fixture'}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},()=>({contents:'export const fleetRequest=async()=>globalThis.sensorFleet;'}));
|
||||
}}]});
|
||||
const {createFleetSensorTransport}=await import('data:text/javascript;base64,'+Buffer.from(result.outputFiles[0].contents).toString('base64'));
|
||||
test('lightweight presence cannot make stale equipment writable for camera activation',async()=>{
|
||||
const previous=globalThis.sensorFleet;
|
||||
try{
|
||||
const row={id:'rover',connectivity:'online',enrollment:'paired',inventory_fresh:false,sensor_state:{items:[],operations:[]}};
|
||||
globalThis.sensorFleet={items:[row]};const t=createFleetSensorTransport('rover');
|
||||
assert.equal((await t.inventory()).fresh,false);row.inventory_fresh=true;assert.equal((await t.inventory()).fresh,true);
|
||||
row.enrollment='revoked';assert.equal((await t.inventory()).fresh,false);
|
||||
}finally{if(previous===undefined)delete globalThis.sensorFleet;else globalThis.sensorFleet=previous;}
|
||||
});
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"time"
|
||||
|
||||
"nodedc.local/mission-core/node-agent/internal/node"
|
||||
"nodedc.local/mission-core/node-agent/internal/routers"
|
||||
"nodedc.local/mission-core/node-agent/web"
|
||||
)
|
||||
|
||||
@@ -69,6 +70,10 @@ func run() error {
|
||||
return err
|
||||
}
|
||||
app := &node.Server{Store: store, Assets: assets, Origin: "http://" + *listen, Version: version, Inventory: func() node.Inventory { return node.Host("/") }}
|
||||
app.Budget, err = node.OpenLinkBudget(*dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
app.Monitor = node.NewMonitor()
|
||||
app.Presentation = node.NewPresentationStore(*dir)
|
||||
pairing, err := node.OpenPairing(store, *dir, version, app.Inventory)
|
||||
@@ -76,7 +81,9 @@ func run() error {
|
||||
return err
|
||||
}
|
||||
app.Pairing = pairing
|
||||
pairing.Budget = app.Budget
|
||||
pairing.Monitor = app.Monitor
|
||||
pairing.Routers = routers.Open(*dir)
|
||||
nodeID, _ := store.Public()
|
||||
app.Sensors, err = node.OpenSensors(*dir, nodeID)
|
||||
if err != nil {
|
||||
@@ -90,7 +97,7 @@ func run() error {
|
||||
pairing.DeviceEnrollment = app.DeviceEnrollment
|
||||
app.Sensors.NetworkDevices = app.DeviceEnrollment
|
||||
app.Access = &node.AccessStore{Path: filepath.Join(*dir, "ssh-keys.json"), Users: func() []string { return node.LocalAdmins("/") }}
|
||||
if err := os.MkdirAll(filepath.Dir(*socket), 0700); err != nil {
|
||||
if err := os.MkdirAll(filepath.Dir(*socket), 0750); err != nil {
|
||||
return err
|
||||
}
|
||||
if info, e := os.Lstat(*socket); e == nil {
|
||||
@@ -119,12 +126,36 @@ func run() error {
|
||||
})
|
||||
public := &http.Server{Handler: app.Handler(), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 8192}
|
||||
private := &http.Server{Handler: admin, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 10 * time.Second, MaxHeaderBytes: 8192}
|
||||
errs := make(chan error, 2)
|
||||
// Separate local capability: media can request capacity, never obtain login.
|
||||
budgetPath := filepath.Join(filepath.Dir(*socket), "budget.sock")
|
||||
if info, e := os.Lstat(budgetPath); e == nil {
|
||||
if info.Mode()&os.ModeSocket == 0 {
|
||||
return errors.New("budget path is not a socket")
|
||||
}
|
||||
if e = os.Remove(budgetPath); e != nil {
|
||||
return e
|
||||
}
|
||||
} else if !os.IsNotExist(e) {
|
||||
return e
|
||||
}
|
||||
budgetListener, err := net.Listen("unix", budgetPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer budgetListener.Close()
|
||||
defer os.Remove(budgetPath)
|
||||
if err := os.Chmod(budgetPath, 0660); err != nil {
|
||||
return err
|
||||
}
|
||||
budgetServer := &http.Server{Handler: app.Budget.Handler(), ReadHeaderTimeout: time.Second, ReadTimeout: time.Second, WriteTimeout: time.Second, IdleTimeout: 5 * time.Second, MaxHeaderBytes: 1024}
|
||||
errs := make(chan error, 3)
|
||||
go func() { errs <- budgetServer.Serve(budgetListener) }()
|
||||
go func() { errs <- public.Serve(tcp) }()
|
||||
go func() { errs <- private.Serve(unix) }()
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
go app.Monitor.Run(ctx)
|
||||
go pairing.Routers.Run(ctx)
|
||||
go app.Sensors.WatchUSB(ctx)
|
||||
go pairing.Run(ctx)
|
||||
log.Print("Mission Core Node " + version + " listening on loopback")
|
||||
@@ -136,6 +167,7 @@ func run() error {
|
||||
defer cancel()
|
||||
public.Shutdown(shutdown)
|
||||
private.Shutdown(shutdown)
|
||||
budgetServer.Shutdown(shutdown)
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
package node
|
||||
|
||||
// One egress budget for optional application traffic. Control and critical
|
||||
// telemetry never acquire permits. No OS routes, queues or motor leases change.
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The aggregate burst covers the four bounded class buckets. A smaller
|
||||
// shared bucket allows an always-first video requester to starve bulk even
|
||||
// when bulk has earned tokens (packetization/rounding). No per-peer queues.
|
||||
const linkClassBurst = 4096
|
||||
const linkBurst = 4 * linkClassBurst
|
||||
const linkPacket = 2048
|
||||
const linkOverhead = 256
|
||||
|
||||
// Inventory cannot compete packet-by-packet with short DEV polls. Both remain
|
||||
// optional: these are shares of the same aggregate, not extra bandwidth.
|
||||
var linkWeights = map[string]float64{"video": 7, "cloud": 2, "bulk": 1, "inventory": 1}
|
||||
|
||||
type LinkPolicy struct {
|
||||
Schema string `json:"schema"`
|
||||
CeilingKbps int `json:"ceiling_kbps"`
|
||||
ReserveKbps int `json:"reserve_kbps"`
|
||||
}
|
||||
type linkClass struct {
|
||||
wanted float64
|
||||
tokens float64
|
||||
seen time.Time
|
||||
bytes uint64
|
||||
deferred uint64
|
||||
}
|
||||
type LinkBudget struct {
|
||||
mu sync.Mutex
|
||||
policy LinkPolicy
|
||||
path string
|
||||
now func() time.Time
|
||||
at time.Time
|
||||
tokens float64
|
||||
classes map[string]*linkClass
|
||||
producers map[string]linkProducer
|
||||
effective float64
|
||||
baseline time.Duration
|
||||
baselineAt time.Time
|
||||
changed time.Time
|
||||
healthy time.Time
|
||||
runtime linkRuntime
|
||||
}
|
||||
|
||||
func OpenLinkBudget(dir string) (*LinkBudget, error) {
|
||||
b := &LinkBudget{policy: LinkPolicy{"missioncore.link-budget/v1", 0, 512}, now: time.Now,
|
||||
classes: map[string]*linkClass{"video": {}, "cloud": {}, "bulk": {}, "inventory": {}},
|
||||
producers: map[string]linkProducer{}, runtime: linkRuntime{lastProtected: true, reason: "startup"}}
|
||||
if dir != "" {
|
||||
b.path = filepath.Join(dir, "link-budget.json")
|
||||
data, err := os.ReadFile(b.path)
|
||||
if err == nil {
|
||||
if len(data) > 1024 || json.Unmarshal(data, &b.policy) != nil {
|
||||
return nil, errors.New("invalid link budget")
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := validLinkPolicy(b.policy); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.effective = math.Min(4000, b.ceiling())
|
||||
b.at = b.now()
|
||||
return b, nil
|
||||
}
|
||||
func validLinkPolicy(p LinkPolicy) error {
|
||||
if p.Schema != "missioncore.link-budget/v1" || (p.CeilingKbps != 0 && (p.CeilingKbps < 1024 || p.CeilingKbps > 100000)) || p.ReserveKbps < 512 || p.ReserveKbps > 50000 || (p.CeilingKbps != 0 && p.ReserveKbps > p.CeilingKbps/2) {
|
||||
return errors.New("link budget requires ceiling 0 (automatic) or 1024..100000 kbps and reserve 512..ceiling/2 kbps")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (b *LinkBudget) Configure(p LinkPolicy) error {
|
||||
if err := validLinkPolicy(p); err != nil {
|
||||
return err
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if b.path != "" {
|
||||
raw, _ := json.Marshal(p)
|
||||
if err := os.WriteFile(b.path+".tmp", raw, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(b.path+".tmp", b.path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
b.policy = p
|
||||
// Raising the configured ceiling does not erase observed congestion.
|
||||
b.effective = math.Min(b.effective, b.ceiling())
|
||||
b.effective = math.Max(b.effective, float64(p.ReserveKbps+128))
|
||||
b.tokens = 0
|
||||
for _, c := range b.classes {
|
||||
c.tokens = 0
|
||||
}
|
||||
b.at = b.now()
|
||||
return nil
|
||||
}
|
||||
func (b *LinkBudget) refill(now time.Time) {
|
||||
dt := math.Max(0, now.Sub(b.at).Seconds())
|
||||
protected := b.protected(now)
|
||||
if protected && !b.runtime.lastProtected {
|
||||
b.tokens = 0
|
||||
for _, c := range b.classes {
|
||||
c.tokens = 0
|
||||
}
|
||||
}
|
||||
b.runtime.lastProtected = protected
|
||||
rates := b.classRates(now)
|
||||
rate := b.optional(now) * 125
|
||||
b.tokens = math.Min(linkBurst, b.tokens+dt*rate)
|
||||
for k, c := range b.classes {
|
||||
if rates[k] == 0 {
|
||||
c.tokens = 0
|
||||
continue
|
||||
}
|
||||
c.tokens = math.Min(linkClassBurst, c.tokens+dt*rates[k]/8)
|
||||
}
|
||||
b.at = now
|
||||
}
|
||||
|
||||
// Try is nonblocking, consumes actual bytes plus conservative packet overhead,
|
||||
// and has fixed memory regardless of peer/request count. Denials are not queued.
|
||||
func (b *LinkBudget) Try(class string, size int) (bool, time.Duration) {
|
||||
if b == nil {
|
||||
return true, 0
|
||||
} // Unwired unit fixtures only; production always owns a budget.
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.tryLocked(class, size)
|
||||
}
|
||||
|
||||
func (b *LinkBudget) tryLocked(class string, size int) (bool, time.Duration) {
|
||||
c := b.classes[class]
|
||||
if c == nil || size <= 0 || size > linkPacket {
|
||||
return false, time.Second
|
||||
}
|
||||
now := b.now()
|
||||
b.refill(now)
|
||||
c.seen = now
|
||||
if b.commandLimited(now) && class != "video" {
|
||||
c.deferred++
|
||||
return false, 10 * time.Millisecond
|
||||
}
|
||||
cost := float64(size + linkOverhead) // UDP/IP, encryption and overlay allowance; not a wire measurement.
|
||||
// Borrow idle optional credit only; the aggregate and control reserve remain
|
||||
// hard gates. Preserve a packet of credit for each donor's next useful burst.
|
||||
if c.tokens < cost && b.tokens >= cost {
|
||||
for k, other := range b.classes {
|
||||
if k != class && now.Sub(other.seen) > 100*time.Millisecond {
|
||||
take := math.Min(math.Max(0, other.tokens-float64(linkPacket+linkOverhead)), cost-c.tokens)
|
||||
other.tokens -= take
|
||||
c.tokens += take
|
||||
}
|
||||
}
|
||||
}
|
||||
if h := &b.runtime.feedback; h.enabled && h.sent-h.acknowledged+uint64(cost) > h.window {
|
||||
c.deferred++
|
||||
return false, 10 * time.Millisecond
|
||||
}
|
||||
if b.tokens >= cost && c.tokens >= cost {
|
||||
if b.runtime.feedback.enabled {
|
||||
b.runtime.feedback.sent += uint64(cost)
|
||||
}
|
||||
b.tokens -= cost
|
||||
c.tokens -= cost
|
||||
c.bytes += uint64(size)
|
||||
return true, 0
|
||||
}
|
||||
c.deferred++
|
||||
return false, 10 * time.Millisecond
|
||||
}
|
||||
|
||||
func (b *LinkBudget) Snapshot() map[string]any {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
now := b.now()
|
||||
rates := b.classRates(now)
|
||||
classes := map[string]any{}
|
||||
counts := map[string]int{}
|
||||
for _, p := range b.producers {
|
||||
if b.now().Sub(p.seen) < producerTTL {
|
||||
counts[p.class]++
|
||||
}
|
||||
}
|
||||
for k, c := range b.classes {
|
||||
classes[k] = map[string]any{"granted_bytes": c.bytes, "deferrals": c.deferred, "producers": counts[k], "allocation_bps": int(rates[k])}
|
||||
}
|
||||
return map[string]any{"policy": b.policy, "effective_kbps": int(b.effective), "optional_kbps": int(b.optional(now)), "runtime": b.runtimeView(now),
|
||||
"baseline_rtt_ms": b.baseline.Milliseconds(), "burst_bytes": linkBurst, "max_packet_bytes": linkPacket, "classes": classes}
|
||||
}
|
||||
|
||||
// Trusted local plugin socket exposes permits/status only, no configuration or
|
||||
// control authority. The existing authenticated UI API owns policy changes.
|
||||
func (b *LinkBudget) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
b.producerRoutes(mux)
|
||||
mux.HandleFunc("GET /status", func(w http.ResponseWriter, r *http.Request) { reply(w, 200, b.Snapshot()) })
|
||||
mux.HandleFunc("GET /events", func(w http.ResponseWriter, r *http.Request) {
|
||||
b.mu.Lock()
|
||||
events := append([]linkDecision{}, b.runtime.events...)
|
||||
b.mu.Unlock()
|
||||
reply(w, 200, events)
|
||||
})
|
||||
mux.HandleFunc("POST /permit", func(w http.ResponseWriter, r *http.Request) {
|
||||
var v struct {
|
||||
Class string `json:"class"`
|
||||
Bytes int `json:"bytes"`
|
||||
Producer string `json:"producer_id"`
|
||||
}
|
||||
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(&v) != nil || (v.Class != "video" && v.Class != "cloud" && v.Class != "bulk") || v.Bytes <= 0 || v.Bytes > linkPacket {
|
||||
reply(w, 400, map[string]string{"error": "invalid permit"})
|
||||
return
|
||||
}
|
||||
b.mu.Lock()
|
||||
valid := true
|
||||
if v.Producer != "" {
|
||||
p, exists := b.producers[v.Producer]
|
||||
valid = exists && p.class == v.Class && b.now().Sub(p.seen) < producerTTL
|
||||
}
|
||||
if b.commandLimited(b.now()) && v.Class == "video" {
|
||||
valid = valid && v.Producer != "" && v.Producer == b.primaryVideo(b.now())
|
||||
}
|
||||
granted, delay := false, 10*time.Millisecond
|
||||
if valid {
|
||||
granted, delay = b.tryLocked(v.Class, v.Bytes)
|
||||
}
|
||||
b.mu.Unlock()
|
||||
reply(w, 200, map[string]any{"granted": granted, "retry_ms": delay.Milliseconds()})
|
||||
})
|
||||
return mux
|
||||
}
|
||||
func (s *Server) linkBudgetRoutes(mux *http.ServeMux) {
|
||||
if s.Budget == nil {
|
||||
return
|
||||
}
|
||||
mux.HandleFunc("GET /api/network/budget", func(w http.ResponseWriter, r *http.Request) {
|
||||
if s.authorized(w, r) {
|
||||
reply(w, 200, s.Budget.Snapshot())
|
||||
}
|
||||
})
|
||||
mux.HandleFunc("PUT /api/network/budget", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorized(w, r) {
|
||||
return
|
||||
}
|
||||
var p LinkPolicy
|
||||
if !decode(w, r, &p) {
|
||||
return
|
||||
}
|
||||
if err := s.Budget.Configure(p); err != nil {
|
||||
reply(w, 400, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
reply(w, 200, s.Budget.Snapshot())
|
||||
})
|
||||
}
|
||||
|
||||
// Budget waits are part of upload time, not network failure. Size includes
|
||||
// every paced packet's overhead at the lowest allocation with all classes busy.
|
||||
// This is a per-request bound, never a recording/session duration limit.
|
||||
func pacedTimeout(size int) time.Duration {
|
||||
packets := (size + linkPacket - 1) / linkPacket
|
||||
cost := size + packets*linkOverhead
|
||||
total := 0.0
|
||||
for _, weight := range linkWeights {
|
||||
total += weight
|
||||
}
|
||||
seconds := float64(cost) / (128 * 125 / total)
|
||||
return 8*time.Second + time.Duration(math.Ceil(seconds*1.25))*time.Second
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func testBudget(t *testing.T) (*LinkBudget, *time.Time) {
|
||||
t.Helper()
|
||||
b, err := OpenLinkBudget("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now()
|
||||
b.now = func() time.Time { return now }
|
||||
b.at = now
|
||||
return b, &now
|
||||
}
|
||||
func TestLinkAggregateAndWeightedProgress(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
counts := map[string]int{}
|
||||
// Deterministic virtual time, no host/network load or sleeping.
|
||||
for tick := 0; tick < 1000; tick++ {
|
||||
*now = now.Add(10 * time.Millisecond)
|
||||
for _, k := range []string{"video", "cloud", "bulk"} {
|
||||
for attempt := 0; attempt < 10; attempt++ {
|
||||
if ok, _ := b.Try(k, 1000); ok {
|
||||
counts[k]++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
total := counts["video"] + counts["cloud"] + counts["bulk"]
|
||||
if total*(1000+linkOverhead) > (4000-512)*125*10+linkBurst {
|
||||
t.Fatal("aggregate budget exceeded", counts)
|
||||
}
|
||||
if counts["bulk"] < 100 || counts["cloud"] < counts["bulk"] || counts["video"] < 2*counts["cloud"] {
|
||||
t.Fatal("class starvation/priority", counts)
|
||||
}
|
||||
}
|
||||
func TestLinkCongestionDoesNotChangeMotionState(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
s := newRoverStreamState(*now)
|
||||
s.budget = b
|
||||
b.Observe(300*time.Millisecond, true)
|
||||
*now = now.Add(time.Second)
|
||||
b.Observe(600*time.Millisecond, true)
|
||||
if b.effective != 4000 {
|
||||
t.Fatal("isolated delay reduced budget")
|
||||
}
|
||||
for i := 0; i < 15; i++ {
|
||||
*now = now.Add(200 * time.Millisecond)
|
||||
b.Observe(600*time.Millisecond, true)
|
||||
}
|
||||
if b.effective >= 4000 {
|
||||
t.Fatal("sustained congestion ignored")
|
||||
}
|
||||
low := b.effective
|
||||
for i := 0; i < 100; i++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.Try("video", 1000)
|
||||
b.Observe(300*time.Millisecond, true)
|
||||
}
|
||||
if b.effective <= low {
|
||||
t.Fatal("recovery missing")
|
||||
}
|
||||
if s.command != nil || s.stopRevision != 1 || !s.stopPending {
|
||||
t.Fatal("budget changed authority")
|
||||
}
|
||||
}
|
||||
func TestLinkConfigAndLocalCapability(t *testing.T) {
|
||||
b, _ := OpenLinkBudget(t.TempDir())
|
||||
p := LinkPolicy{"missioncore.link-budget/v1", 8000, 512}
|
||||
if err := b.Configure(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restored, err := OpenLinkBudget(b.path[:len(b.path)-len("/link-budget.json")])
|
||||
if err != nil || restored.policy != p {
|
||||
t.Fatal("policy not durable", err)
|
||||
}
|
||||
for _, body := range []string{`{"class":"control","bytes":100}`, `{"class":"video","bytes":99999}`, `{"class":"bulk","bytes":0}`} {
|
||||
r := httptest.NewRequest("POST", "/permit", bytes.NewBufferString(body))
|
||||
w := httptest.NewRecorder()
|
||||
b.Handler().ServeHTTP(w, r)
|
||||
if w.Code != 400 {
|
||||
t.Fatal("untrusted permit accepted")
|
||||
}
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
b.Handler().ServeHTTP(w, httptest.NewRequest("POST", "/login", nil))
|
||||
if w.Code != 404 {
|
||||
t.Fatal("media socket acquired launcher authority")
|
||||
}
|
||||
}
|
||||
func TestBudgetReaderCancellationAndDevBound(t *testing.T) {
|
||||
b, _ := testBudget(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
r := &budgetReader{ctx: ctx, budget: b, class: "bulk", source: bytes.NewReader(make([]byte, 100))}
|
||||
if _, err := r.Read(make([]byte, 4096)); err != context.Canceled {
|
||||
t.Fatal("blocked cancellation", err)
|
||||
}
|
||||
rows := []any{}
|
||||
for i := 0; i < 24; i++ {
|
||||
rows = append(rows, map[string]any{"record_sequence": i, "value": strings.Repeat("x", 1000)})
|
||||
}
|
||||
packet := map[string]any{"id": "capture", "frames": rows, "storage": map[string]any{"closed": false}, "export": map[string]any{"data": "data"}}
|
||||
bounded := boundedDevPacket(packet)
|
||||
raw, _ := json.Marshal(bounded)
|
||||
if len(raw) > 12*1024 || len(bounded["frames"].([]any)) == 0 || len(packet["frames"].([]any)) != 24 || bounded["export"] == nil {
|
||||
t.Fatal("invalid network view")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLinkBaselineRelearnsAfterNetworkHandover(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.Observe(10*time.Millisecond, true)
|
||||
for i := 0; i < 15; i++ {
|
||||
*now = now.Add(200 * time.Millisecond)
|
||||
b.Observe(300*time.Millisecond, true)
|
||||
}
|
||||
low := b.effective
|
||||
*now = now.Add(31 * time.Second)
|
||||
for i := 0; i < 60; i++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.Try("video", 1000)
|
||||
b.Observe(300*time.Millisecond, true)
|
||||
}
|
||||
if b.baseline != 300*time.Millisecond || b.effective <= low {
|
||||
t.Fatal("old LAN minimum pinned new route", b.baseline, b.effective)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDevLargeExportDoesNotRemoveLiveRowsOrExceedRequestLimit(t *testing.T) {
|
||||
rows := []any{map[string]any{"record_sequence": 1, "event": "sample"}}
|
||||
for _, size := range []int{87384, 200000} {
|
||||
packet := map[string]any{"id": "capture", "frames": rows, "export": map[string]any{"data": strings.Repeat("A", size)}}
|
||||
bounded := boundedDevPacket(packet)
|
||||
raw, _ := json.Marshal(bounded)
|
||||
if len(raw) > 108*1024 || len(bounded["frames"].([]any)) != 1 {
|
||||
t.Fatal("export exceeded bounded lane or starved live evidence")
|
||||
}
|
||||
if size == 87384 && bounded["export"] == nil {
|
||||
t.Fatal("valid export lost")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package node
|
||||
|
||||
import "time"
|
||||
|
||||
// This is optional-traffic admission, never a motor lease or a replacement for
|
||||
// the stream watchdog. A healthy telemetry socket cannot certify command flow.
|
||||
const commandPressureAfter = 150 * time.Millisecond
|
||||
const commandRecoveryWindow = 200 * time.Millisecond
|
||||
const commandBackoffAfter = 200 * time.Millisecond
|
||||
|
||||
type linkCommandHealth struct {
|
||||
seen, healthy, pressure time.Time
|
||||
gap, age time.Duration
|
||||
limited bool
|
||||
}
|
||||
|
||||
func (b *LinkBudget) commandPressure(now time.Time, reason string) {
|
||||
h := &b.runtime.command
|
||||
// Invalidate old credit once on entering pressure. Repeated moderate-age
|
||||
// samples must not erase the selected camera's low-rate packet credit every
|
||||
// 50 ms: at 128 kbps a 1100-byte datagram needs longer than one sample period.
|
||||
// Moving the refill anchor prevents pre-pressure time recreating that credit.
|
||||
if !h.limited {
|
||||
b.tokens = 0
|
||||
for _, c := range b.classes {
|
||||
c.tokens = 0
|
||||
}
|
||||
b.at = now
|
||||
}
|
||||
h.limited = true
|
||||
h.healthy = time.Time{}
|
||||
if h.pressure.IsZero() {
|
||||
h.pressure = now
|
||||
}
|
||||
// An isolated jitter sample is reason to yield, not evidence that the
|
||||
// sustainable channel capacity fell by 25%. Require continuing pressure
|
||||
// for an estimate reduction; fresh receipt ends that evidence immediately.
|
||||
if now.Sub(h.pressure) < commandBackoffAfter {
|
||||
return
|
||||
}
|
||||
b.healthy = time.Time{}
|
||||
if now.Sub(b.changed) >= time.Second {
|
||||
next := max(float64(b.policy.ReserveKbps+128), b.effective*.75)
|
||||
if next < b.effective {
|
||||
b.decision(now, reason, next)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// age is the conservative Core-clock upper bound, not synchronized wall-clock
|
||||
// latency. It can safely overestimate pressure but cannot grant motion authority.
|
||||
func (b *LinkBudget) ObserveCommandFrame(gap, age time.Duration) {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
now := b.now()
|
||||
h := &b.runtime.command
|
||||
h.seen, h.gap, h.age = now, gap, age
|
||||
if !b.protected(now) {
|
||||
h.limited, h.healthy, h.pressure = false, time.Time{}, time.Time{}
|
||||
return
|
||||
}
|
||||
if gap >= commandPressureAfter || age >= commandPressureAfter {
|
||||
b.commandPressure(now, "command_stream_pressure")
|
||||
return
|
||||
}
|
||||
h.pressure = time.Time{}
|
||||
if h.limited {
|
||||
if h.healthy.IsZero() {
|
||||
h.healthy = now
|
||||
}
|
||||
if now.Sub(h.healthy) >= commandRecoveryWindow {
|
||||
h.limited = false
|
||||
// Several fresh arrivals over real elapsed time are required: a
|
||||
// queued burst cannot reopen optional traffic in a single instant.
|
||||
// Isolated jitter must not erase the independent exchange estimator's
|
||||
// recovery progress either. Sustained pressure resets it above.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Called by the existing local tick, even while the stream reader is blocked.
|
||||
func (b *LinkBudget) ObserveCommandSilence() {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
now := b.now()
|
||||
if b.protected(now) && !b.runtime.command.seen.IsZero() && now.Sub(b.runtime.command.seen) >= commandPressureAfter {
|
||||
b.commandPressure(now, "command_stream_silence")
|
||||
}
|
||||
}
|
||||
|
||||
func (b *LinkBudget) commandLimited(now time.Time) bool {
|
||||
return b.protected(now) && b.runtime.command.limited
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRedactedCommandJitterReplayPreservesAvailableCapacity(t *testing.T) {
|
||||
// Timings only: no UTC, identities, commands, locations or device values.
|
||||
// Replay the real admission code in virtual time, without sockets/motors.
|
||||
raw, err := os.ReadFile("testdata/command-jitter-redacted.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var rows [][3]float64 // elapsed receipt ms, inter-frame gap ms, conservative age ms
|
||||
if err = json.Unmarshal(raw, &rows); err != nil || len(rows) < 1000 {
|
||||
t.Fatal("invalid receipt fixture", err)
|
||||
}
|
||||
b, now := testBudget(t)
|
||||
start := *now
|
||||
initial := b.effective
|
||||
b.SetControl(true)
|
||||
blocked, total := time.Duration(0), time.Duration(0)
|
||||
// Independent 50 ms local watchdog ticks, just as on Node. They may pause
|
||||
// admission while the stream reader is blocked; fresh telemetry cannot hide it.
|
||||
nextTick := start.Add(50 * time.Millisecond)
|
||||
advance := func(at time.Time) {
|
||||
delta := at.Sub(*now)
|
||||
total += delta
|
||||
if b.commandLimited(*now) {
|
||||
blocked += delta
|
||||
}
|
||||
*now = at
|
||||
b.SetControl(true)
|
||||
}
|
||||
for _, row := range rows {
|
||||
at := start.Add(time.Duration(row[0] * float64(time.Millisecond)))
|
||||
for !nextTick.After(at) {
|
||||
advance(nextTick)
|
||||
b.ObserveCommandSilence()
|
||||
nextTick = nextTick.Add(50 * time.Millisecond)
|
||||
}
|
||||
advance(at)
|
||||
b.ObserveCommandFrame(time.Duration(row[1]*float64(time.Millisecond)), time.Duration(row[2]*float64(time.Millisecond)))
|
||||
}
|
||||
ratio := float64(blocked) / float64(total)
|
||||
t.Logf("optional admission paused %.1f%%; capacity %.0f -> %.0f kbps", ratio*100, initial, b.effective)
|
||||
if ratio > .35 || b.effective < initial*.9 {
|
||||
t.Fatal("isolated jitter still starves media", ratio, b.effective)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBudgetDiagnosticsAreBoundedAndDevOnly(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
s := newRoverStreamState(*now)
|
||||
s.budget = b
|
||||
s.recordBudgetDev(*now)
|
||||
if len(s.devEvents) != 0 {
|
||||
t.Fatal("DEV-off recorded budget")
|
||||
}
|
||||
s.setDev(map[string]any{"id": testClockID, "enabled": true})
|
||||
for i := 0; i < 20; i++ {
|
||||
s.recordBudgetDev(now.Add(time.Duration(i) * 100 * time.Millisecond))
|
||||
}
|
||||
if len(s.devEvents) != 2 || s.devEvents[0]["event"] != "link_budget" {
|
||||
t.Fatal("budget evidence rate is not bounded", len(s.devEvents))
|
||||
}
|
||||
s.setDev(map[string]any{"id": testClockID, "enabled": false})
|
||||
s.recordBudgetDev(now.Add(3 * time.Second))
|
||||
if len(s.devEvents) != 2 {
|
||||
t.Fatal("recording continued after DEV stop")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandSilenceBlocksOptionalBytesDespiteHealthyTelemetry(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.SetControl(true)
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
|
||||
for _, class := range []string{"video", "cloud", "inventory", "bulk"} {
|
||||
b.Try(class, 1000)
|
||||
}
|
||||
*now = now.Add(150 * time.Millisecond)
|
||||
b.ObserveExchange(50*time.Millisecond, 0, true)
|
||||
b.ObserveCommandSilence()
|
||||
for _, class := range []string{"video", "cloud", "inventory", "bulk"} {
|
||||
if ok, _ := b.Try(class, 100); ok {
|
||||
t.Fatal("optional cached credit escaped command pressure", class)
|
||||
}
|
||||
}
|
||||
if b.optional(*now) != 0 || b.reserve(*now) < 512 || !b.commandLimited(*now) {
|
||||
t.Fatal("critical stream was not independently protected")
|
||||
}
|
||||
// A reply on another socket cannot reopen the gate or raise the estimate.
|
||||
low := b.effective
|
||||
for i := 0; i < 40; i++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.SetControl(true)
|
||||
b.ObserveExchange(20*time.Millisecond, 0, true)
|
||||
}
|
||||
if b.optional(*now) != 0 || b.effective > low {
|
||||
t.Fatal("healthy telemetry concealed absent commands")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandRecoveryNeedsContinuousFreshFramesNotOneLateBurst(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.SetControl(true)
|
||||
b.ObserveCommandFrame(200*time.Millisecond, 20*time.Millisecond)
|
||||
low := b.effective
|
||||
for i := 0; i < 30; i++ {
|
||||
*now = now.Add(10 * time.Millisecond)
|
||||
b.ObserveCommandFrame(0, 200*time.Millisecond)
|
||||
}
|
||||
if !b.commandLimited(*now) {
|
||||
t.Fatal("buffered old frames reopened optional traffic")
|
||||
}
|
||||
for i := 0; i < 21; i++ {
|
||||
*now = now.Add(50 * time.Millisecond)
|
||||
b.SetControl(true)
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
|
||||
if i < 4 && !b.commandLimited(*now) {
|
||||
t.Fatal("recovery dwell skipped", i)
|
||||
}
|
||||
}
|
||||
if b.commandLimited(*now) || b.effective > low || b.optional(*now) <= 0 {
|
||||
t.Fatal("fresh recovery did not resume at reduced budget")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsolatedCommandJitterYieldsWithoutCollapsingCapacity(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.SetControl(true)
|
||||
initial := b.effective
|
||||
// One delayed frame per second, with fresh command flow in between. This
|
||||
// formerly held the gate shut forever and drove capacity to its floor.
|
||||
for cycle := 0; cycle < 20; cycle++ {
|
||||
*now = now.Add(150 * time.Millisecond)
|
||||
b.SetControl(true)
|
||||
b.ObserveCommandFrame(150*time.Millisecond, 170*time.Millisecond)
|
||||
if ok, _ := b.Try("video", 100); ok {
|
||||
t.Fatal("delayed command did not yield optional traffic")
|
||||
}
|
||||
for i := 0; i < 17; i++ {
|
||||
*now = now.Add(50 * time.Millisecond)
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 80*time.Millisecond)
|
||||
}
|
||||
if b.commandLimited(*now) || b.effective != initial {
|
||||
t.Fatal("isolated jitter was mistaken for sustained congestion", cycle, b.effective)
|
||||
}
|
||||
if ok, _ := b.Try("video", 100); !ok {
|
||||
t.Fatal("fresh command flow did not return optional capacity")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSustainedCommandPressureStillReducesCapacity(t *testing.T) {
|
||||
for _, silence := range []bool{false, true} {
|
||||
b, now := testBudget(t)
|
||||
b.SetControl(true)
|
||||
initial := b.effective
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
|
||||
for i := 0; i < 30; i++ {
|
||||
*now = now.Add(50 * time.Millisecond)
|
||||
b.SetControl(true)
|
||||
if silence {
|
||||
b.ObserveCommandSilence()
|
||||
} else {
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 200*time.Millisecond)
|
||||
}
|
||||
}
|
||||
if !b.commandLimited(*now) || b.effective >= initial || b.optional(*now) != 0 {
|
||||
t.Fatal("sustained command pressure was ignored", silence)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsolatedCommandJitterDoesNotEraseCapacityRecovery(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.effective = 1000
|
||||
for i := 0; i < 400; i++ {
|
||||
*now = now.Add(50 * time.Millisecond)
|
||||
b.SetControl(true)
|
||||
b.allocateDemand(testClockID, "video", true, 5000000)
|
||||
age := 80 * time.Millisecond
|
||||
if i%20 == 0 {
|
||||
age = 170 * time.Millisecond
|
||||
}
|
||||
b.ObserveCommandFrame(50*time.Millisecond, age)
|
||||
b.ObserveExchange(80*time.Millisecond, 0, true)
|
||||
}
|
||||
if b.effective < 4000 || b.reserve(*now) < 512 {
|
||||
t.Fatal("isolated command jitter erased measured exchange recovery", b.effective)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdleObservationDoesNotSacrificeVideoForCommandJitter(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.SetControl(false)
|
||||
before := b.optional(*now)
|
||||
b.ObserveCommandFrame(time.Second, time.Second)
|
||||
*now = now.Add(time.Second)
|
||||
b.ObserveCommandSilence()
|
||||
if b.commandLimited(*now) || b.optional(*now) != before {
|
||||
t.Fatal("idle command gap degraded observation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalCommandPressurePreservesExpiryAndNoAutomaticRearm(t *testing.T) {
|
||||
sensors, model, s, at := localDeliveryFixture(t)
|
||||
b, now := testBudget(t)
|
||||
*now = at
|
||||
b.at = at
|
||||
s.budget = b
|
||||
s.devID, s.devEnabled = testClockID, true
|
||||
s.receivedFrame(streamIntent(1331, 10000, 10400), at)
|
||||
calls := 0
|
||||
sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
return testSensorReply(map[string]any{"state": "driving"}), nil
|
||||
})
|
||||
var d roverLocalDelivery
|
||||
d.run(context.Background(), sensors, model, s, "relay", at)
|
||||
*now = at.Add(160 * time.Millisecond)
|
||||
d.run(context.Background(), sensors, model, s, "relay", *now)
|
||||
if calls != 1 || !b.commandLimited(*now) {
|
||||
t.Fatal("pressure changed duplicate delivery or ignored local tick")
|
||||
}
|
||||
*now = at.Add(401 * time.Millisecond)
|
||||
d.run(context.Background(), sensors, model, s, "relay", *now)
|
||||
if calls != 2 || s.stopCause != "command_deadline_expired" {
|
||||
t.Fatal("command expiry changed")
|
||||
}
|
||||
late := streamIntent(1332, 10401, 10801)
|
||||
s.accept(late)
|
||||
s.receivedFrame(late, *now)
|
||||
_, command, _ := s.delivery(*now)
|
||||
if command != nil || s.devEvents[len(s.devEvents)-1]["retired"] != true {
|
||||
t.Fatal("late input revived authority or missing receipt evidence")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiptEvidenceIsDevOnlyAndUsesCoreClockBound(t *testing.T) {
|
||||
for _, enabled := range []bool{false, true} {
|
||||
at := time.Now()
|
||||
s := newRoverStreamState(at)
|
||||
s.sampleClock(roverClock{testClockID, 10020}, at, at.Add(40*time.Millisecond))
|
||||
acknowledgeStop(s, at)
|
||||
s.devID, s.devEnabled = testClockID, enabled
|
||||
s.receivedFrame(streamIntent(1, 10050, 10400), at.Add(100*time.Millisecond))
|
||||
if !enabled && len(s.devEvents) != 0 {
|
||||
t.Fatal("DEV-off stored per-frame evidence")
|
||||
}
|
||||
if enabled {
|
||||
row := s.devEvents[0]
|
||||
if row["age_upper_ms"].(float64) < 70 || row["received_mono_ms"] != float64(100) {
|
||||
t.Fatal("receipt clock bound lost", row)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package node
|
||||
|
||||
// Independently bound optional egress when command UDP remains healthy but the
|
||||
// return path is congested. Probes never wait for permits; no authority lives here.
|
||||
import "time"
|
||||
|
||||
const feedbackMinWindow = uint64(linkPacket + linkOverhead)
|
||||
const feedbackMaxWindow = uint64(128 * 1024)
|
||||
|
||||
type linkDatagramFeedback struct {
|
||||
enabled bool
|
||||
seen, adjusted, healthy, delayed time.Time
|
||||
sent, acknowledged, window uint64
|
||||
rtt time.Duration
|
||||
limited bool
|
||||
pressure linkFeedbackPressure
|
||||
}
|
||||
|
||||
// Retain only the last initiating pressure event. Later healthy samples must
|
||||
// not erase why media was paused; this is evidence, never admission credit.
|
||||
type linkFeedbackPressure struct {
|
||||
count uint64
|
||||
at time.Time
|
||||
reason string
|
||||
gap, rtt, threshold time.Duration
|
||||
window uint64
|
||||
}
|
||||
|
||||
func (h *linkDatagramFeedback) recordPressure(now time.Time, reason string, gap, rtt, threshold time.Duration) {
|
||||
if h.limited {
|
||||
return
|
||||
}
|
||||
h.pressure = linkFeedbackPressure{count: h.pressure.count + 1, at: now,
|
||||
reason: reason, gap: gap, rtt: rtt, threshold: threshold, window: h.window}
|
||||
}
|
||||
|
||||
func (h *linkDatagramFeedback) pressureView(now time.Time) any {
|
||||
p := h.pressure
|
||||
if p.at.IsZero() {
|
||||
return nil
|
||||
}
|
||||
return map[string]any{"count": p.count, "reason": p.reason, "age_ms": now.Sub(p.at).Milliseconds(),
|
||||
"gap_ms": p.gap.Milliseconds(), "rtt_ms": p.rtt.Milliseconds(),
|
||||
"threshold_ms": p.threshold.Milliseconds(), "window_bytes": p.window}
|
||||
}
|
||||
|
||||
func (b *LinkBudget) EnableDatagramFeedback() {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if !b.runtime.feedback.enabled {
|
||||
b.runtime.feedback = linkDatagramFeedback{enabled: true, seen: b.now(), window: linkClassBurst}
|
||||
}
|
||||
}
|
||||
func (b *LinkBudget) DisableDatagramFeedback() {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.runtime.feedback = linkDatagramFeedback{}
|
||||
}
|
||||
func (b *LinkBudget) DatagramFeedbackMark() uint64 {
|
||||
if b == nil {
|
||||
return 0
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.runtime.feedback.sent
|
||||
}
|
||||
func (b *LinkBudget) feedbackLimited(now time.Time) bool {
|
||||
h := &b.runtime.feedback
|
||||
if !h.enabled {
|
||||
return false
|
||||
}
|
||||
if now.Sub(h.seen) > max(250*time.Millisecond, b.baseline+150*time.Millisecond) {
|
||||
h.recordPressure(now, "feedback_silence", now.Sub(h.seen), h.rtt, max(250*time.Millisecond, b.baseline+150*time.Millisecond))
|
||||
// A silent return path invalidates the previously grown send window.
|
||||
// Latch pressure before updating seen: one fresh ACK after a blackout
|
||||
// must not release old optional credit as a burst. Caller holds b.mu.
|
||||
h.limited = true
|
||||
h.healthy = time.Time{}
|
||||
h.window = min(h.window, uint64(linkClassBurst))
|
||||
h.adjusted = now
|
||||
b.healthy = time.Time{}
|
||||
b.tokens = 0
|
||||
for _, c := range b.classes {
|
||||
c.tokens = 0
|
||||
}
|
||||
b.at = now
|
||||
}
|
||||
return h.limited
|
||||
}
|
||||
func (b *LinkBudget) ObserveDatagramFeedback(elapsed time.Duration, coreMS float64, mark uint64) {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
// Use the existing exchange estimator with the measured Core scheduling wait
|
||||
// removed. No RTT/2 correction is used for command or observation clocks.
|
||||
b.ObserveExchange(elapsed, coreMS, true)
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
h := &b.runtime.feedback
|
||||
if !h.enabled || mark > h.sent || mark < h.acknowledged {
|
||||
return
|
||||
}
|
||||
now := b.now()
|
||||
b.feedbackLimited(now)
|
||||
outstanding := h.sent - h.acknowledged
|
||||
gap := now.Sub(h.seen)
|
||||
h.acknowledged = mark
|
||||
h.seen = now
|
||||
if coreMS >= 0 && coreMS <= float64(elapsed.Microseconds())/1000 {
|
||||
elapsed -= time.Duration(coreMS * float64(time.Millisecond))
|
||||
}
|
||||
h.rtt = elapsed
|
||||
if elapsed > b.baseline+75*time.Millisecond {
|
||||
if h.delayed.IsZero() {
|
||||
h.delayed = now
|
||||
}
|
||||
// Moderate jitter shrinks outstanding optional bytes without turning a
|
||||
// viable video stream off. Full suspension is reserved for severe delay
|
||||
// or silence; neither condition changes command authority or watchdogs.
|
||||
if elapsed > max(250*time.Millisecond, b.baseline+150*time.Millisecond) {
|
||||
h.recordPressure(now, "feedback_rtt", gap, elapsed, max(250*time.Millisecond, b.baseline+150*time.Millisecond))
|
||||
h.limited = true
|
||||
h.healthy = time.Time{}
|
||||
}
|
||||
b.healthy = time.Time{}
|
||||
// Delay-based admission must not mistake isolated RTT jitter for a
|
||||
// growing queue. Require a sustained trend before reducing its window;
|
||||
// severe delay and silence still suspend optional traffic immediately.
|
||||
if h.limited || now.Sub(h.delayed) >= 200*time.Millisecond {
|
||||
if h.adjusted.IsZero() || now.Sub(h.adjusted) >= 200*time.Millisecond {
|
||||
h.window = max(feedbackMinWindow, h.window/2)
|
||||
h.adjusted = now
|
||||
}
|
||||
b.tokens = 0
|
||||
for _, c := range b.classes {
|
||||
c.tokens = 0
|
||||
}
|
||||
b.at = now
|
||||
}
|
||||
return
|
||||
}
|
||||
h.delayed = time.Time{}
|
||||
if h.limited {
|
||||
if h.healthy.IsZero() {
|
||||
h.healthy = now
|
||||
}
|
||||
if now.Sub(h.healthy) < 200*time.Millisecond {
|
||||
return
|
||||
}
|
||||
h.limited = false
|
||||
}
|
||||
// Grow only when useful demand used the window, at most once per probe
|
||||
// period. ACK bursts after a stall cannot manufacture a large new window.
|
||||
if elapsed <= b.baseline+25*time.Millisecond && outstanding >= h.window/2 && (h.adjusted.IsZero() || now.Sub(h.adjusted) >= 100*time.Millisecond) {
|
||||
h.window = min(feedbackMaxWindow, h.window+linkPacket)
|
||||
h.adjusted = now
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDatagramFeedbackBoundsOptionalBytesDespiteHealthyDownlink(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.EnableDatagramFeedback()
|
||||
b.SetControl(true)
|
||||
b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0)
|
||||
initial := b.runtime.feedback.window
|
||||
// Pre-fill tokens as an already active producer; acknowledgement credit
|
||||
// remains the independent upper bound across all optional classes.
|
||||
for _, class := range []string{"video", "bulk", "cloud", "inventory"} {
|
||||
b.classes[class].tokens = linkClassBurst
|
||||
b.classes[class].seen = *now
|
||||
b.classes[class].wanted = 1000000
|
||||
}
|
||||
b.tokens = linkBurst
|
||||
for i := 0; i < 20; i++ {
|
||||
b.Try("video", 1100)
|
||||
}
|
||||
sent := b.DatagramFeedbackMark()
|
||||
if sent == 0 || sent > initial {
|
||||
t.Fatal("window bypass", sent, initial)
|
||||
}
|
||||
*now = now.Add(300 * time.Millisecond)
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 10*time.Millisecond)
|
||||
if !b.feedbackLimited(*now) {
|
||||
t.Fatal("fresh downlink erased return-path silence")
|
||||
}
|
||||
if ok, _ := b.Try("video", 1100); ok {
|
||||
t.Fatal("video bypassed feedback silence")
|
||||
}
|
||||
b.ObserveDatagramFeedback(300*time.Millisecond, 0, sent)
|
||||
if !b.runtime.feedback.limited {
|
||||
t.Fatal("delayed echo did not apply pressure")
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
b.ObserveDatagramFeedback(100*time.Millisecond, 0, sent)
|
||||
}
|
||||
if !b.runtime.feedback.limited {
|
||||
t.Fatal("queued ACK burst reopened video")
|
||||
}
|
||||
*now = now.Add(201 * time.Millisecond)
|
||||
b.ObserveDatagramFeedback(100*time.Millisecond, 0, sent)
|
||||
if b.runtime.feedback.limited {
|
||||
t.Fatal("sustained fresh feedback did not recover")
|
||||
}
|
||||
if b.runtime.feedback.window < feedbackMinWindow {
|
||||
t.Fatal("packet cannot fit")
|
||||
}
|
||||
b.DisableDatagramFeedback()
|
||||
if b.feedbackLimited(now.Add(time.Hour)) {
|
||||
t.Fatal("closed channel retained feedback gate")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDatagramFeedbackSilenceLatchesBeforeFreshEcho(t *testing.T) {
|
||||
for _, poll := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "idle-budget", true: "active-producer"}[poll], func(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.EnableDatagramFeedback()
|
||||
b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0)
|
||||
b.runtime.feedback.window = feedbackMaxWindow
|
||||
b.tokens = linkBurst
|
||||
b.classes["video"].tokens = linkClassBurst
|
||||
*now = now.Add(time.Second)
|
||||
if poll {
|
||||
b.Snapshot()
|
||||
}
|
||||
b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0)
|
||||
if !b.runtime.feedback.limited || b.runtime.feedback.window > linkClassBurst {
|
||||
t.Fatal("fresh echo restored the old send window", b.runtime.feedback)
|
||||
}
|
||||
if b.tokens != 0 || b.classes["video"].tokens != 0 {
|
||||
t.Fatal("old burst credit survived silence")
|
||||
}
|
||||
for i := 0; i < 20; i++ {
|
||||
b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0)
|
||||
}
|
||||
if !b.runtime.feedback.limited {
|
||||
t.Fatal("ACK burst recovered without elapsed healthy time")
|
||||
}
|
||||
*now = now.Add(201 * time.Millisecond)
|
||||
b.ObserveDatagramFeedback(100*time.Millisecond, 0, 0)
|
||||
if b.runtime.feedback.limited {
|
||||
t.Fatal("continuous healthy feedback did not recover")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDatagramFeedbackModerateJitterPreservesVideoAllocation(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.EnableDatagramFeedback()
|
||||
b.ObserveDatagramFeedback(10*time.Millisecond, 0, 0)
|
||||
b.runtime.feedback.window = 32768
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.ObserveDatagramFeedback(110*time.Millisecond, 0, 0)
|
||||
if b.runtime.feedback.limited || b.optional(*now) <= 0 {
|
||||
t.Fatal("one moderate delay disabled optional media")
|
||||
}
|
||||
if b.runtime.feedback.window != 32768 {
|
||||
t.Fatal("isolated jitter collapsed the media window")
|
||||
}
|
||||
for i := 0; i < 2; i++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.ObserveDatagramFeedback(110*time.Millisecond, 0, 0)
|
||||
}
|
||||
if b.runtime.feedback.window >= 32768 || b.optional(*now) <= 0 {
|
||||
t.Fatal("sustained moderate delay must reduce, not disable, media")
|
||||
}
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.ObserveDatagramFeedback(300*time.Millisecond, 0, 0)
|
||||
if !b.runtime.feedback.limited || b.optional(*now) != 0 {
|
||||
t.Fatal("severe return delay did not suspend media")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDatagramFeedbackRetainsInitiatingPressureAcrossRecovery(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.EnableDatagramFeedback()
|
||||
b.ObserveDatagramFeedback(10*time.Millisecond, 0, 0)
|
||||
if b.runtime.feedback.pressureView(*now) != nil {
|
||||
t.Fatal("invented pressure")
|
||||
}
|
||||
*now = now.Add(300 * time.Millisecond)
|
||||
b.feedbackLimited(*now)
|
||||
first := b.runtime.feedback.pressure
|
||||
if first.count != 1 || first.reason != "feedback_silence" || first.gap != 300*time.Millisecond || first.threshold != 250*time.Millisecond {
|
||||
t.Fatal("missing initiating silence", first)
|
||||
}
|
||||
b.feedbackLimited(*now)
|
||||
b.ObserveDatagramFeedback(300*time.Millisecond, 0, 0)
|
||||
if b.runtime.feedback.pressure != first {
|
||||
t.Fatal("poll or delayed ACK overwrote initiating event")
|
||||
}
|
||||
b.ObserveDatagramFeedback(10*time.Millisecond, 0, 0)
|
||||
*now = now.Add(201 * time.Millisecond)
|
||||
b.ObserveDatagramFeedback(10*time.Millisecond, 0, 0)
|
||||
if b.runtime.feedback.limited || b.runtime.feedback.pressure != first {
|
||||
t.Fatal("recovery lost evidence or retained gate")
|
||||
}
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.ObserveDatagramFeedback(300*time.Millisecond, 0, 0)
|
||||
second := b.runtime.feedback.pressure
|
||||
if second.count != 2 || second.reason != "feedback_rtt" || second.rtt != 300*time.Millisecond || second.gap != 100*time.Millisecond {
|
||||
t.Fatal("new pressure not retained", second)
|
||||
}
|
||||
b.DisableDatagramFeedback()
|
||||
if b.runtime.feedback.pressureView(*now) != nil {
|
||||
t.Fatal("new transport would inherit old diagnostic identity")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestExplicitOperatorViewPrecedesResidualTraffic(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
primary, secondary, cloud := "11111111111111111111111111111111", "22222222222222222222222222222222", "33333333333333333333333333333333"
|
||||
b.allocateRole(secondary, "video", true, 5000000, false)
|
||||
b.allocateRole(primary, "video", true, 5000000, true)
|
||||
b.allocateRole(cloud, "cloud", true, 2000000, false)
|
||||
b.RequestDemand("inventory", 1000)
|
||||
b.Try("inventory", 1000)
|
||||
b.RequestDemand("bulk", 1000)
|
||||
b.Try("bulk", 1000)
|
||||
a, _ := b.allocateRole(primary, "video", true, 5000000, true)
|
||||
c, _ := b.allocateRole(secondary, "video", true, 5000000, false)
|
||||
rates := b.classRates(*now)
|
||||
if a["allocation_bps"].(int) <= 0 || c["allocation_bps"] != 0 || rates["cloud"] != 0 || rates["bulk"] != 0 || rates["inventory"] <= 0 || a["class_producers"] != 2 {
|
||||
t.Fatal(a, c, rates)
|
||||
}
|
||||
*now = now.Add(time.Millisecond)
|
||||
b.allocateRole(secondary, "video", true, 5000000, true)
|
||||
if b.primaryVideo(*now) != secondary {
|
||||
t.Fatal("selection did not supersede earlier primary")
|
||||
}
|
||||
b.allocateRole(secondary, "video", false, 5000000, true)
|
||||
if b.primaryVideo(*now) != primary {
|
||||
t.Fatal("released view retained priority")
|
||||
}
|
||||
*now = now.Add(producerTTL)
|
||||
if b.primaryVideo(*now) != "" {
|
||||
t.Fatal("expired view retained priority")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectedViewHasBoundedModerateJitterProfileAndEmergencyYield(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
primary := "11111111111111111111111111111111"
|
||||
b.allocateRole(primary, "video", true, 5000000, true)
|
||||
b.SetControl(true)
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
|
||||
*now = now.Add(160 * time.Millisecond)
|
||||
b.ObserveCommandSilence()
|
||||
if rate := b.optional(*now); rate <= 0 || rate > 384 {
|
||||
t.Fatal("invalid low profile", rate)
|
||||
}
|
||||
permit := func(id string) bool {
|
||||
raw, _ := json.Marshal(map[string]any{"class": "video", "bytes": 100, "producer_id": id})
|
||||
w := httptest.NewRecorder()
|
||||
b.Handler().ServeHTTP(w, httptest.NewRequest("POST", "/permit", bytes.NewReader(raw)))
|
||||
var reply map[string]any
|
||||
json.Unmarshal(w.Body.Bytes(), &reply)
|
||||
return reply["granted"] == true
|
||||
}
|
||||
if permit("") {
|
||||
t.Fatal("unidentified video borrowed priority")
|
||||
}
|
||||
if permit(primary) {
|
||||
t.Fatal("pre-pressure time restored discarded credit")
|
||||
}
|
||||
*now = now.Add(20 * time.Millisecond)
|
||||
if !permit(primary) {
|
||||
t.Fatal("selected video could not use low profile")
|
||||
}
|
||||
for _, class := range []string{"cloud", "bulk", "inventory"} {
|
||||
if ok, _ := b.Try(class, 100); ok {
|
||||
t.Fatal("background escaped pressure", class)
|
||||
}
|
||||
}
|
||||
*now = now.Add(70 * time.Millisecond)
|
||||
b.ObserveCommandSilence()
|
||||
if b.optional(*now) != 0 || permit(primary) {
|
||||
t.Fatal("video escaped 250 ms emergency yield")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalRecorderSendsOnlyLifecycleAndStopsPollingClosedFile(t *testing.T) {
|
||||
s := newRoverStreamState(time.Now())
|
||||
options := map[string]any{"live": false, "network": true}
|
||||
s.setDev(map[string]any{"id": testClockID, "enabled": true, "options": options})
|
||||
s.recordDev("network", map[string]any{})
|
||||
if len(s.devRequest()["relay_events"].([]map[string]any)) != 1 {
|
||||
t.Fatal("local evidence omitted")
|
||||
}
|
||||
p := s.devPayload()
|
||||
if len(p["relay_events"].([]any)) != 0 || len(p["frames"].([]any)) != 0 || diagnosticTrafficClass(p) != "inventory" {
|
||||
t.Fatal("local recording streamed events", p)
|
||||
}
|
||||
s.devPacket = map[string]any{"sequence": 100, "storage": map[string]any{"closed": true}}
|
||||
s.setDev(map[string]any{"id": testClockID, "enabled": false, "options": options, "after": 0})
|
||||
if s.devRequest() != nil {
|
||||
t.Fatal("closed local recording kept polling")
|
||||
}
|
||||
if diagnosticTrafficClass(map[string]any{"export": map[string]any{"data": "abc"}}) != "bulk" {
|
||||
t.Fatal("export escaped bulk lane")
|
||||
}
|
||||
}
|
||||
|
||||
// Real-drive regression: a selected view used all optional capacity forever,
|
||||
// so a closed local recording could not export even with control inactive.
|
||||
func TestObservedPrimaryAllowsBoundedExportAtCongestedFloor(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.effective = 640
|
||||
primary := "11111111111111111111111111111111"
|
||||
left, inventory, video := 108*1024, 0, 0
|
||||
b.RequestDemand("bulk", left)
|
||||
b.RequestDemand("inventory", 40*1024)
|
||||
deadline := pacedTimeout(left)
|
||||
for elapsed := time.Duration(0); elapsed < deadline; elapsed += 10 * time.Millisecond {
|
||||
*now = now.Add(10 * time.Millisecond)
|
||||
b.SetControl(false)
|
||||
b.allocateRole(primary, "video", true, 5000000, true)
|
||||
// Persistent demand, including primary video always attempting first.
|
||||
for n := 0; n < 4; n++ {
|
||||
if ok, _ := b.Try("video", 1200); ok {
|
||||
video += 1200
|
||||
}
|
||||
}
|
||||
if inventory < 40*1024 {
|
||||
size := min(linkPacket, 40*1024-inventory)
|
||||
if ok, _ := b.Try("inventory", size); ok {
|
||||
inventory += size
|
||||
}
|
||||
}
|
||||
if left > 0 {
|
||||
if ok, _ := b.Try("bulk", min(linkPacket, left)); ok {
|
||||
left -= min(linkPacket, left)
|
||||
}
|
||||
}
|
||||
}
|
||||
if left != 0 || inventory != 40*1024 || video == 0 {
|
||||
t.Fatal("observer export/metadata starved", left, inventory, video)
|
||||
}
|
||||
var bytes uint64
|
||||
for _, c := range b.classes {
|
||||
bytes += c.bytes
|
||||
}
|
||||
if float64(bytes) > 128*125*deadline.Seconds()+linkBurst {
|
||||
t.Fatal("shared budget exceeded", bytes)
|
||||
}
|
||||
b.SetControl(true)
|
||||
b.Try("bulk", 1000)
|
||||
if b.classRates(*now)["bulk"] != 0 {
|
||||
t.Fatal("export displaced primary during active control")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandPrimaryLowRateProgressUnderPersistentModerateAge(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.effective = 640 // Existing floor: 512 reserved + 128 optional kbps.
|
||||
primary := "11111111111111111111111111111111"
|
||||
b.allocateRole(primary, "video", true, 4000000, true)
|
||||
b.SetControl(true)
|
||||
handler := b.Handler()
|
||||
admitted := 0
|
||||
for step := 0; step < 400; step++ {
|
||||
*now = now.Add(5 * time.Millisecond)
|
||||
if step%10 == 0 {
|
||||
b.SetControl(true)
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 180*time.Millisecond)
|
||||
}
|
||||
rr := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr, httptest.NewRequest("POST", "/permit", strings.NewReader(`{"class":"video","bytes":1100,"producer_id":"11111111111111111111111111111111"}`)))
|
||||
var reply struct {
|
||||
Granted bool `json:"granted"`
|
||||
}
|
||||
json.Unmarshal(rr.Body.Bytes(), &reply)
|
||||
if reply.Granted {
|
||||
admitted += 1100
|
||||
}
|
||||
}
|
||||
t.Logf("moderate-age primary payload over 2 s: %d bytes; optional %.0f kbps", admitted, b.optional(*now))
|
||||
if admitted < 1100 || admitted+admitted/1100*linkOverhead > 32000 {
|
||||
t.Fatal("declared low profile starved or exceeded its aggregate budget", admitted)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package node
|
||||
|
||||
// Producer leases provide sizing advice from the existing class budget. They
|
||||
// never reserve packet tokens, add queues, change control, or outlive a process.
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"math"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const producerTTL = 3 * time.Second
|
||||
const maxLinkProducers = 32
|
||||
|
||||
type linkProducer struct {
|
||||
class string
|
||||
seen time.Time
|
||||
demand int
|
||||
since time.Time
|
||||
primary bool
|
||||
selected time.Time
|
||||
}
|
||||
|
||||
func (b *LinkBudget) allocate(id, class string, active bool) (map[string]any, error) {
|
||||
return b.allocateDemand(id, class, active, 0)
|
||||
}
|
||||
func (b *LinkBudget) allocateDemand(id, class string, active bool, demand int) (map[string]any, error) {
|
||||
return b.allocateRole(id, class, active, demand, false)
|
||||
}
|
||||
func (b *LinkBudget) primaryVideo(now time.Time) string {
|
||||
selected := ""
|
||||
for id, p := range b.producers {
|
||||
if p.class != "video" || !p.primary || now.Sub(p.seen) >= producerTTL {
|
||||
continue
|
||||
}
|
||||
if selected == "" || p.selected.After(b.producers[selected].selected) || (p.selected.Equal(b.producers[selected].selected) && id < selected) {
|
||||
selected = id
|
||||
}
|
||||
}
|
||||
return selected
|
||||
}
|
||||
func (b *LinkBudget) allocateRole(id, class string, active bool, demand int, operatorPrimary bool) (map[string]any, error) {
|
||||
if operatorPrimary && class != "video" {
|
||||
return nil, errors.New("primary must be video")
|
||||
}
|
||||
if demand < 0 || demand > 100000000 {
|
||||
return nil, errors.New("invalid media demand")
|
||||
}
|
||||
if demand == 0 {
|
||||
demand = 5000000
|
||||
if class == "cloud" {
|
||||
demand = 2000000
|
||||
}
|
||||
}
|
||||
|
||||
if raw, err := hex.DecodeString(id); err != nil || len(raw) != 16 || (class != "video" && class != "cloud") {
|
||||
return nil, errors.New("invalid media producer")
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
now := b.now()
|
||||
for key, p := range b.producers {
|
||||
if now.Sub(p.seen) >= producerTTL {
|
||||
delete(b.producers, key)
|
||||
}
|
||||
}
|
||||
if old, exists := b.producers[id]; exists && old.class != class {
|
||||
return nil, errors.New("producer class changed")
|
||||
}
|
||||
if !active {
|
||||
delete(b.producers, id)
|
||||
return map[string]any{"schema": "missioncore.media-budget/v1", "allocation_bps": 0, "ttl_ms": 0}, nil
|
||||
}
|
||||
if _, exists := b.producers[id]; !exists && len(b.producers) >= maxLinkProducers {
|
||||
return nil, errors.New("media producer capacity")
|
||||
}
|
||||
b.refill(now)
|
||||
since := now
|
||||
if old, exists := b.producers[id]; exists {
|
||||
since = old.since
|
||||
}
|
||||
selected := now
|
||||
if old, exists := b.producers[id]; exists && old.primary == operatorPrimary {
|
||||
selected = old.selected
|
||||
}
|
||||
b.producers[id] = linkProducer{class: class, seen: now, demand: demand, since: since, primary: operatorPrimary, selected: selected}
|
||||
weights, demands := map[string]float64{}, map[string]float64{}
|
||||
primary := ""
|
||||
for key, p := range b.producers {
|
||||
if p.class != class {
|
||||
continue
|
||||
}
|
||||
weights[key] = 1
|
||||
demands[key] = float64(p.demand)
|
||||
if primary == "" || p.since.Before(b.producers[primary].since) || (p.since.Equal(b.producers[primary].since) && key < primary) {
|
||||
primary = key
|
||||
}
|
||||
}
|
||||
explicit := b.primaryVideo(now)
|
||||
if class == "video" && explicit != "" {
|
||||
primary = explicit
|
||||
}
|
||||
rate := b.classRates(now)[class]
|
||||
// When there is insufficient useful video for every viewer, retain the oldest
|
||||
// active view. Additional viewers wait without resetting acquisition/recording.
|
||||
count := len(weights)
|
||||
minimum := 512000.0
|
||||
shares := map[string]float64{}
|
||||
if class == "video" && explicit != "" {
|
||||
shares[primary] = math.Min(rate, demands[primary])
|
||||
delete(weights, primary)
|
||||
delete(demands, primary)
|
||||
for key, value := range waterfill(rate-shares[primary], weights, demands) {
|
||||
shares[key] = value
|
||||
}
|
||||
} else if class == "video" && rate < minimum*float64(len(weights)) {
|
||||
shares[primary] = math.Min(rate, demands[primary])
|
||||
} else {
|
||||
shares = waterfill(rate, weights, demands)
|
||||
}
|
||||
mode := "observing"
|
||||
if b.protected(now) {
|
||||
mode = "control_reserved"
|
||||
}
|
||||
return map[string]any{"schema": "missioncore.media-budget/v1", "allocation_bps": int(shares[id]),
|
||||
"ttl_ms": producerTTL.Milliseconds(), "class_producers": count, "mode": mode,
|
||||
"primary": id == primary, "reason": b.runtime.reason}, nil
|
||||
}
|
||||
|
||||
func (b *LinkBudget) producerRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /producer", func(w http.ResponseWriter, r *http.Request) {
|
||||
var v struct {
|
||||
ID string `json:"id"`
|
||||
Class string `json:"class"`
|
||||
Active *bool `json:"active"`
|
||||
Demand int `json:"demand_bps"`
|
||||
Primary bool `json:"primary"`
|
||||
}
|
||||
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 256))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(&v) != nil || v.Active == nil {
|
||||
reply(w, 400, map[string]string{"error": "invalid media producer"})
|
||||
return
|
||||
}
|
||||
result, err := b.allocateRole(v.ID, v.Class, *v.Active, v.Demand, v.Primary)
|
||||
if err != nil {
|
||||
reply(w, 409, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
reply(w, 200, result)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMediaProducersShareOneBudgetAndExpire(t *testing.T) {
|
||||
b, _ := OpenLinkBudget("")
|
||||
now := time.Now()
|
||||
b.now = func() time.Time { return now }
|
||||
b.at = now
|
||||
id := func(i int) string { return fmt.Sprintf("%032x", i) }
|
||||
for i := 1; i <= 2; i++ {
|
||||
if _, err := b.allocate(id(i), "video", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := b.allocate(id(3), "cloud", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b.Try("bulk", 100)
|
||||
a, _ := b.allocate(id(1), "video", true)
|
||||
c, _ := b.allocate(id(3), "cloud", true)
|
||||
if a["allocation_bps"] != 1220800 || c["allocation_bps"] != 697600 || b.tokens != 0 {
|
||||
t.Fatal("advice must divide existing class budget without minting permits", a, c, b.tokens)
|
||||
}
|
||||
b.allocate(id(2), "video", false)
|
||||
a, _ = b.allocate(id(1), "video", true)
|
||||
if a["allocation_bps"] != 2441600 {
|
||||
t.Fatal(a)
|
||||
}
|
||||
now = now.Add(4 * time.Second)
|
||||
a, _ = b.allocate(id(1), "video", true)
|
||||
if len(b.producers) != 1 || a["allocation_bps"] != 3488000 {
|
||||
t.Fatal("expired producer retained capacity", a)
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
now = now.Add(time.Second)
|
||||
b.Observe(time.Second, false)
|
||||
}
|
||||
a, _ = b.allocate(id(1), "video", true)
|
||||
if a["allocation_bps"].(int) >= 3488000 {
|
||||
t.Fatal("allocation ignored congestion", a)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaProducerAdmissionIsBoundedAndHasNoControlClass(t *testing.T) {
|
||||
b, _ := OpenLinkBudget("")
|
||||
for i := 0; i < maxLinkProducers; i++ {
|
||||
if _, err := b.allocate(fmt.Sprintf("%032x", i), "video", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := b.allocate(fmt.Sprintf("%032x", 99), "video", true); err == nil {
|
||||
t.Fatal("unbounded producer registry")
|
||||
}
|
||||
if _, err := b.allocate(fmt.Sprintf("%032x", 0), "cloud", true); err == nil {
|
||||
t.Fatal("producer changed class")
|
||||
}
|
||||
if _, err := b.allocate(fmt.Sprintf("%032x", 0), "control", true); err == nil {
|
||||
t.Fatal("control allocation admitted")
|
||||
}
|
||||
if _, err := b.allocate("bad", "video", true); err == nil {
|
||||
t.Fatal("bad identifier admitted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
package node
|
||||
|
||||
// Runtime policy for the existing egress gate. Rates are send budgets, not a
|
||||
// claim to have measured physical link capacity. No command authority lives here.
|
||||
import (
|
||||
"math"
|
||||
"time"
|
||||
)
|
||||
|
||||
type linkSample struct {
|
||||
at time.Time
|
||||
elapsed time.Duration
|
||||
ok bool
|
||||
}
|
||||
type linkDecision struct {
|
||||
AtMS int64 `json:"at_ms"`
|
||||
Reason string `json:"reason"`
|
||||
Kbps int `json:"kbps"`
|
||||
}
|
||||
type linkRuntime struct {
|
||||
feedback linkDatagramFeedback
|
||||
command linkCommandHealth
|
||||
criticalAt time.Time
|
||||
criticalBytes int
|
||||
criticalKbps float64
|
||||
lastProtected bool
|
||||
control bool
|
||||
modeAt time.Time
|
||||
samples []linkSample
|
||||
errors int
|
||||
reason string
|
||||
events []linkDecision
|
||||
started time.Time
|
||||
coreMS float64
|
||||
}
|
||||
|
||||
func (b *LinkBudget) ceiling() float64 {
|
||||
if b.policy.CeilingKbps == 0 {
|
||||
return 100000
|
||||
} // Contract bound, not inferred capacity.
|
||||
return float64(b.policy.CeilingKbps)
|
||||
}
|
||||
func (b *LinkBudget) protected(now time.Time) bool {
|
||||
return b.runtime.modeAt.IsZero() || now.Sub(b.runtime.modeAt) > 2*time.Second || b.runtime.control
|
||||
}
|
||||
func (b *LinkBudget) reserve(now time.Time) float64 {
|
||||
if b.protected(now) {
|
||||
return math.Max(float64(b.policy.ReserveKbps), b.runtime.criticalKbps*1.5)
|
||||
}
|
||||
if b.runtime.criticalAt.IsZero() {
|
||||
return float64(b.policy.ReserveKbps)
|
||||
}
|
||||
return math.Max(64, b.runtime.criticalKbps*1.5) // Actual critical traffic plus margin, never an idle constant alone.
|
||||
}
|
||||
|
||||
// Critical bytes are observed, never paced or rejected by this regulator.
|
||||
func (b *LinkBudget) ObserveCriticalBytes(size int) {
|
||||
if b == nil || size <= 0 {
|
||||
return
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
now := b.now()
|
||||
if b.runtime.criticalAt.IsZero() {
|
||||
b.runtime.criticalAt = now
|
||||
b.runtime.criticalKbps = float64(b.policy.ReserveKbps) / 1.5
|
||||
}
|
||||
b.runtime.criticalBytes += size + ((size+1199)/1200)*linkOverhead
|
||||
elapsed := now.Sub(b.runtime.criticalAt).Seconds()
|
||||
if elapsed >= 1 {
|
||||
rate := float64(b.runtime.criticalBytes) * 8 / 1000 / elapsed
|
||||
// Follow growth immediately; decay slowly so a quiet sample cannot under-size admission.
|
||||
b.runtime.criticalKbps = math.Max(rate, b.runtime.criticalKbps*.8)
|
||||
b.runtime.criticalAt = now
|
||||
b.runtime.criticalBytes = 0
|
||||
}
|
||||
}
|
||||
func (b *LinkBudget) optional(now time.Time) float64 {
|
||||
if b.feedbackLimited(now) {
|
||||
return 0
|
||||
}
|
||||
ceiling := math.Max(0, b.effective-b.reserve(now))
|
||||
if b.runtime.feedback.enabled {
|
||||
// A bounded acknowledgement window constrains useful optional traffic.
|
||||
// This is admission credit, never a claim of measured wire capacity.
|
||||
period := max(100*time.Millisecond, b.baseline)
|
||||
ceiling = math.Min(ceiling, float64(b.runtime.feedback.window)*8/period.Seconds()/1000)
|
||||
}
|
||||
|
||||
if b.commandLimited(now) {
|
||||
// A selected operator view gets only a bounded low profile during
|
||||
// moderate jitter. At 250 ms silence/age all optional payload yields.
|
||||
// The 400 ms command lease and 350/200 ms watchdogs are unchanged.
|
||||
h := b.runtime.command
|
||||
emergency := h.gap >= 250*time.Millisecond || h.age >= 250*time.Millisecond ||
|
||||
(!h.seen.IsZero() && now.Sub(h.seen) >= 250*time.Millisecond)
|
||||
if emergency || b.primaryVideo(now) == "" {
|
||||
return 0
|
||||
}
|
||||
return math.Min(384, ceiling)
|
||||
}
|
||||
return ceiling
|
||||
}
|
||||
func (b *LinkBudget) SetControl(active bool) {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
now := b.now()
|
||||
was := b.protected(now)
|
||||
b.runtime.control, b.runtime.modeAt = active, now
|
||||
if !active {
|
||||
// An intentionally closed observer stream is not packet loss. Do not
|
||||
// retain pressure/old receipt timestamps across completed sessions.
|
||||
b.runtime.command = linkCommandHealth{}
|
||||
}
|
||||
if !was && active {
|
||||
b.tokens = 0
|
||||
for _, c := range b.classes {
|
||||
c.tokens = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
func (b *LinkBudget) decision(now time.Time, reason string, next float64) {
|
||||
if b.runtime.started.IsZero() {
|
||||
b.runtime.started = now
|
||||
}
|
||||
if next < b.effective {
|
||||
b.tokens = 0
|
||||
for _, c := range b.classes {
|
||||
c.tokens = 0
|
||||
}
|
||||
}
|
||||
b.effective = next
|
||||
b.changed = now
|
||||
b.runtime.reason = reason
|
||||
b.runtime.events = append(b.runtime.events, linkDecision{now.Sub(b.runtime.started).Milliseconds(), reason, int(next)})
|
||||
if len(b.runtime.events) > 32 {
|
||||
b.runtime.events = b.runtime.events[len(b.runtime.events)-32:]
|
||||
}
|
||||
}
|
||||
|
||||
// Observe remains for transport failures / older Core peers. Application errors
|
||||
// are deliberately excluded by the caller; they are not bandwidth evidence.
|
||||
func (b *LinkBudget) Observe(elapsed time.Duration, ok bool) { b.ObserveExchange(elapsed, 0, ok) }
|
||||
func (b *LinkBudget) ObserveExchange(elapsed time.Duration, coreMS float64, ok bool) {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
now := b.now()
|
||||
if math.IsNaN(coreMS) || math.IsInf(coreMS, 0) || coreMS < 0 || coreMS > float64(elapsed.Microseconds())/1000 {
|
||||
coreMS = 0
|
||||
}
|
||||
b.runtime.coreMS = coreMS
|
||||
elapsed -= time.Duration(coreMS * float64(time.Millisecond))
|
||||
samples := b.runtime.samples[:0]
|
||||
for _, v := range b.runtime.samples {
|
||||
if now.Sub(v.at) < 30*time.Second {
|
||||
samples = append(samples, v)
|
||||
}
|
||||
}
|
||||
samples = append(samples, linkSample{now, elapsed, ok})
|
||||
if len(samples) > 320 {
|
||||
samples = samples[len(samples)-320:]
|
||||
}
|
||||
b.runtime.samples = samples
|
||||
b.baseline = 0
|
||||
for _, v := range samples {
|
||||
if v.ok && (b.baseline == 0 || v.elapsed < b.baseline) {
|
||||
b.baseline = v.elapsed
|
||||
}
|
||||
}
|
||||
if ok {
|
||||
b.runtime.errors = 0
|
||||
} else {
|
||||
b.runtime.errors++
|
||||
}
|
||||
total, bad := 0, 0
|
||||
var first time.Time
|
||||
for _, v := range samples {
|
||||
if now.Sub(v.at) > 2*time.Second {
|
||||
continue
|
||||
}
|
||||
if first.IsZero() {
|
||||
first = v.at
|
||||
}
|
||||
total++
|
||||
if !v.ok || v.elapsed > b.baseline+150*time.Millisecond {
|
||||
bad++
|
||||
}
|
||||
}
|
||||
ready := total >= 4 && now.Sub(first) >= time.Second
|
||||
congested := b.runtime.errors >= 3 || (ready && bad*2 >= total)
|
||||
if congested && now.Sub(b.changed) >= time.Second {
|
||||
next := math.Max(float64(b.policy.ReserveKbps+128), b.effective*.75)
|
||||
if next < b.effective {
|
||||
b.refill(now)
|
||||
b.decision(now, "sustained_delay_or_transport_loss", next)
|
||||
}
|
||||
b.healthy = time.Time{}
|
||||
} else if ready && bad*5 <= total && !b.commandLimited(now) && !b.feedbackLimited(now) {
|
||||
if b.healthy.IsZero() {
|
||||
b.healthy = now
|
||||
}
|
||||
if now.Sub(b.healthy) >= 2*time.Second && now.Sub(b.changed) >= 2*time.Second {
|
||||
// Bounded useful-traffic probing. Do not manufacture dummy network load or
|
||||
// ramp indefinitely on a quiet scene / when nobody requests optional data.
|
||||
demand := b.demand(now)/1000 + b.reserve(now)
|
||||
next := math.Min(b.ceiling(), math.Min(demand, b.effective+math.Max(128, b.effective*.20)))
|
||||
if next > b.effective {
|
||||
b.refill(now)
|
||||
b.decision(now, "healthy_demand_probe", next)
|
||||
}
|
||||
}
|
||||
}
|
||||
// An isolated outlier neither reduces the budget nor erases recovery progress.
|
||||
}
|
||||
func (b *LinkBudget) runtimeView(now time.Time) map[string]any {
|
||||
mode := "observing"
|
||||
if b.protected(now) {
|
||||
mode = "control_reserved"
|
||||
}
|
||||
return map[string]any{"schema": "missioncore.link-runtime/v1", "direction": "node_egress",
|
||||
"feedback_limited": b.feedbackLimited(now), "feedback_window_bytes": b.runtime.feedback.window, "feedback_outstanding_bytes": b.runtime.feedback.sent - b.runtime.feedback.acknowledged, "feedback_rtt_ms": b.runtime.feedback.rtt.Milliseconds(),
|
||||
"feedback_pressure": b.runtime.feedback.pressureView(now),
|
||||
"command_limited": b.commandLimited(now), "command_gap_ms": b.runtime.command.gap.Milliseconds(),
|
||||
"command_age_upper_ms": b.runtime.command.age.Milliseconds(),
|
||||
"mode": mode, "reserve_kbps": int(b.reserve(now)), "reason": b.runtime.reason,
|
||||
"core_processing_ms": b.runtime.coreMS, "samples": len(b.runtime.samples), "automatic": b.policy.CeilingKbps == 0,
|
||||
"critical_offered_kbps": int(b.runtime.criticalKbps), "capacity_measured": false}
|
||||
}
|
||||
|
||||
// Weighted water filling with demand caps redistributes unused allocations.
|
||||
// Class packet admission and producer sizing use the same result.
|
||||
func waterfill(total float64, weights, demands map[string]float64) map[string]float64 {
|
||||
out := map[string]float64{}
|
||||
active := map[string]float64{}
|
||||
for k, w := range weights {
|
||||
if demands[k] > 0 && w > 0 {
|
||||
active[k] = w
|
||||
}
|
||||
}
|
||||
remaining := total
|
||||
for len(active) > 0 && remaining > 0 {
|
||||
sum := 0.0
|
||||
for _, w := range active {
|
||||
sum += w
|
||||
}
|
||||
capped := []string{}
|
||||
for k, w := range active {
|
||||
if demands[k] <= remaining*w/sum {
|
||||
capped = append(capped, k)
|
||||
}
|
||||
}
|
||||
if len(capped) == 0 {
|
||||
for k, w := range active {
|
||||
out[k] = remaining * w / sum
|
||||
}
|
||||
break
|
||||
}
|
||||
for _, k := range capped {
|
||||
out[k] = demands[k]
|
||||
remaining -= demands[k]
|
||||
delete(active, k)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
func (b *LinkBudget) demands(now time.Time) map[string]float64 {
|
||||
d := map[string]float64{}
|
||||
for _, p := range b.producers {
|
||||
if now.Sub(p.seen) < producerTTL {
|
||||
d[p.class] += float64(p.demand)
|
||||
}
|
||||
}
|
||||
for k, c := range b.classes {
|
||||
if now.Sub(c.seen) <= 2*time.Second && (k == "inventory" || k == "bulk" || d[k] == 0) {
|
||||
d[k] = c.wanted
|
||||
if d[k] == 0 {
|
||||
d[k] = b.ceiling() * 1000
|
||||
}
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
func (b *LinkBudget) demand(now time.Time) float64 {
|
||||
total := 0.0
|
||||
for _, v := range b.demands(now) {
|
||||
total += v
|
||||
}
|
||||
return total
|
||||
}
|
||||
func (b *LinkBudget) classRates(now time.Time) map[string]float64 {
|
||||
total := b.optional(now) * 1000
|
||||
demands := b.demands(now)
|
||||
if b.commandLimited(now) {
|
||||
return map[string]float64{"video": math.Min(total, demands["video"])}
|
||||
}
|
||||
if b.primaryVideo(now) == "" {
|
||||
return waterfill(total, linkWeights, demands)
|
||||
}
|
||||
// During observation, explicitly requested recording transfer must make
|
||||
// bounded progress even when the selected camera demands all capacity.
|
||||
// Its floor is at most the ordinary 1/11 share and 32 kbit/s, taken from
|
||||
// the SAME optional budget. Active/stale control and command pressure
|
||||
// retain strict primary-video priority; exports never borrow its reserve.
|
||||
rates := map[string]float64{}
|
||||
if !b.protected(now) {
|
||||
rates["bulk"] = math.Min(demands["bulk"], math.Min(32000, total/11))
|
||||
total -= rates["bulk"]
|
||||
demands["bulk"] -= rates["bulk"]
|
||||
}
|
||||
rates["inventory"] = math.Min(total, math.Min(32000, demands["inventory"]))
|
||||
total -= rates["inventory"]
|
||||
rates["video"] = math.Min(total, demands["video"])
|
||||
total -= rates["video"]
|
||||
for key, value := range waterfill(total, map[string]float64{"cloud": 1, "bulk": 1}, demands) {
|
||||
rates[key] += value
|
||||
}
|
||||
return rates
|
||||
}
|
||||
|
||||
// Existing serialized HTTP lanes declare finite body demand rather than
|
||||
// permanently competing as unlimited streams. This never mints packet credit.
|
||||
func (b *LinkBudget) RequestDemand(class string, size int) {
|
||||
if b == nil || size <= 0 {
|
||||
return
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if c := b.classes[class]; c != nil {
|
||||
wire := size + ((size+linkPacket-1)/linkPacket)*linkOverhead
|
||||
c.wanted = math.Min(b.ceiling()*1000, math.Max(64000, float64(wire)*8))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRuntimeRecoversWithPeriodicOutliersAndRespectsExplicitCeiling(t *testing.T) {
|
||||
for _, limit := range []int{0, 4000} {
|
||||
b, now := testBudget(t)
|
||||
b.Configure(LinkPolicy{"missioncore.link-budget/v1", limit, 512})
|
||||
b.effective = 640
|
||||
for i := 0; i < 600; i++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
b.allocateDemand(fmt.Sprintf("%032x", 1), "video", true, 8000000)
|
||||
delay := 50 * time.Millisecond
|
||||
if i%80 == 0 {
|
||||
delay = 500 * time.Millisecond
|
||||
}
|
||||
b.Observe(delay, true)
|
||||
}
|
||||
if b.effective < 4000 || (limit == 0 && b.effective <= 4000) || (limit > 0 && b.effective > float64(limit)) {
|
||||
t.Fatal("recovery/cap", limit, b.effective)
|
||||
}
|
||||
if len(b.runtime.events) > 32 || len(b.runtime.samples) > 320 {
|
||||
t.Fatal("unbounded diagnostics")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestRuntimeSubtractsCoreProcessingAndNeverTreatsItAsLinkLoss(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
for i := 0; i < 60; i++ {
|
||||
*now = now.Add(100 * time.Millisecond)
|
||||
core := float64(i%6) * 100
|
||||
b.ObserveExchange(time.Duration(50+core)*time.Millisecond, core, true)
|
||||
}
|
||||
if b.effective != 4000 || b.baseline != 50*time.Millisecond {
|
||||
t.Fatal("server processing misclassified", b.effective, b.baseline)
|
||||
}
|
||||
}
|
||||
func TestControlReserveActivatesBeforeIntentAndReturnsOnStaleState(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.runtime.criticalAt = *now
|
||||
b.runtime.criticalKbps = 50
|
||||
b.SetControl(false)
|
||||
if b.reserve(*now) != 75 {
|
||||
t.Fatal("idle critical rate ignored")
|
||||
}
|
||||
b.Try("bulk", 1000)
|
||||
*now = now.Add(time.Second)
|
||||
b.Try("bulk", 1000)
|
||||
b.SetControl(true)
|
||||
if b.tokens != 0 || b.reserve(*now) != 512 {
|
||||
t.Fatal("first intent can inherit idle burst")
|
||||
}
|
||||
b.SetControl(false)
|
||||
*now = now.Add(3 * time.Second)
|
||||
if b.reserve(*now) != 512 {
|
||||
t.Fatal("stale state released control reserve")
|
||||
}
|
||||
b.runtime.criticalKbps = 600
|
||||
if b.reserve(*now) != 900 {
|
||||
t.Fatal("actual critical demand clipped")
|
||||
}
|
||||
}
|
||||
func TestDemandRedistributionAndUsefulVideoAdmission(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
first, second := fmt.Sprintf("%032x", 1), fmt.Sprintf("%032x", 2)
|
||||
b.allocateDemand(first, "video", true, 1000000)
|
||||
a, _ := b.allocateDemand(second, "video", true, 5000000)
|
||||
if a["allocation_bps"] != 2488000 {
|
||||
t.Fatal("unused producer demand not lent", a)
|
||||
}
|
||||
b.effective = 1000
|
||||
a, _ = b.allocateDemand(first, "video", true, 1000000)
|
||||
c, _ := b.allocateDemand(second, "video", true, 5000000)
|
||||
if a["allocation_bps"] != 488000 || c["allocation_bps"] != 0 {
|
||||
t.Fatal("all video degraded instead of admitting one", a, c)
|
||||
}
|
||||
*now = now.Add(4 * time.Second)
|
||||
c, _ = b.allocateDemand(second, "video", true, 5000000)
|
||||
if c["allocation_bps"] != 488000 {
|
||||
t.Fatal("expired viewer retained priority", c)
|
||||
}
|
||||
}
|
||||
func TestWaterfillIsBoundedAndDemandCapped(t *testing.T) {
|
||||
rates := waterfill(100, map[string]float64{"a": 1, "b": 1, "c": 1}, map[string]float64{"a": 5, "b": 10, "c": 200})
|
||||
if rates["a"] != 5 || rates["b"] != 10 || rates["c"] != 85 {
|
||||
t.Fatal(rates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSmallInventoryDoesNotReserveAnUnlimitedStream(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.allocateDemand(fmt.Sprintf("%032x", 1), "video", true, 5000000)
|
||||
b.RequestDemand("inventory", 6000)
|
||||
b.Try("inventory", 1000)
|
||||
rates := b.classRates(*now)
|
||||
if rates["inventory"] != 64000 || rates["video"] != 3424000 {
|
||||
t.Fatal("small metadata held camera bandwidth", rates)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTenStopRecoveryCyclesPreserveVideoAdmissionBounds(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
const primary = "11111111111111111111111111111111"
|
||||
for run := 0; run < 10; run++ {
|
||||
b.SetControl(true)
|
||||
b.allocateRole(primary, "video", true, 5000000, true)
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
|
||||
*now = now.Add(250 * time.Millisecond)
|
||||
b.ObserveCommandSilence()
|
||||
if b.optional(*now) != 0 {
|
||||
t.Fatal("expired commands admitted video", run)
|
||||
}
|
||||
for _, class := range []string{"video", "bulk", "cloud", "inventory"} {
|
||||
if ok, _ := b.Try(class, 100); ok {
|
||||
t.Fatal("cached credit bypassed pause", run, class)
|
||||
}
|
||||
}
|
||||
// Confirmed absence of authority ends command-specific pressure; it
|
||||
// does not increase capacity or remove other feedback/bandwidth caps.
|
||||
capacity := b.effective
|
||||
b.SetControl(false)
|
||||
if b.optional(*now) <= 0 || b.effective != capacity {
|
||||
t.Fatal("observation failed to resume within cap", run)
|
||||
}
|
||||
b.SetControl(true)
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
|
||||
*now = now.Add(50 * time.Millisecond)
|
||||
b.ObserveCommandFrame(50*time.Millisecond, 20*time.Millisecond)
|
||||
if b.optional(*now) <= 0 || b.reserve(*now) < float64(b.policy.ReserveKbps) {
|
||||
t.Fatal("fresh neutral recovery lost reserve", run)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
package node
|
||||
|
||||
// Network preferences belong to this board. Core observes acknowledged generations.
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"time"
|
||||
)
|
||||
|
||||
type NetworkPending struct {
|
||||
Deadline int64 `json:"deadline"`
|
||||
PreviousEndpoint string `json:"previous_endpoint"`
|
||||
Provider string `json:"provider"`
|
||||
ServerID string `json:"server_id"`
|
||||
Config json.RawMessage `json:"config,omitempty"`
|
||||
Local bool `json:"local,omitempty"`
|
||||
}
|
||||
type NetworkProfile struct {
|
||||
BindingID string `json:"binding_id"`
|
||||
Revision int64 `json:"revision"`
|
||||
Provider string `json:"provider"`
|
||||
ServerID string `json:"server_id,omitempty"`
|
||||
Config json.RawMessage `json:"config,omitempty"`
|
||||
TailscaleEndpoint string `json:"tailscale_endpoint,omitempty"`
|
||||
OperationID string `json:"operation_id,omitempty"`
|
||||
Phase string `json:"phase"`
|
||||
PublicKey string `json:"public_key,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Pending *NetworkPending `json:"pending,omitempty"`
|
||||
}
|
||||
type NetworkCommand struct {
|
||||
ID string `json:"id"`
|
||||
Action string `json:"action"`
|
||||
Provider string `json:"provider"`
|
||||
ServerID string `json:"server_id"`
|
||||
ExpectedRevision int64 `json:"expected_revision"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
CoreEndpoint string `json:"core_endpoint,omitempty"`
|
||||
Config json.RawMessage `json:"config,omitempty"`
|
||||
}
|
||||
|
||||
var networkID = regexp.MustCompile(`^wg_[a-f0-9]{32}$`)
|
||||
var networkOperationID = regexp.MustCompile(`^[a-f0-9]{32}$`)
|
||||
|
||||
func networkHelper(action, identity string, fields map[string]any) (map[string]json.RawMessage, error) {
|
||||
connection, err := net.DialTimeout("unix", "/run/mission-core-wireguard/control.sock", 3*time.Second)
|
||||
if err != nil {
|
||||
return nil, errors.New("Системная служба WireGuard недоступна. Обновите Node.")
|
||||
}
|
||||
defer connection.Close()
|
||||
_ = connection.SetDeadline(time.Now().Add(25 * time.Second))
|
||||
body := map[string]any{"action": action, "server_id": identity}
|
||||
for key, value := range fields {
|
||||
body[key] = value
|
||||
}
|
||||
if err = json.NewEncoder(connection).Encode(body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var result struct {
|
||||
OK bool `json:"ok"`
|
||||
Result map[string]json.RawMessage `json:"result"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
data, err := bufio.NewReaderSize(connection, 16385).ReadSlice('\n')
|
||||
if err != nil || len(data) > 16384 || json.Unmarshal(data, &result) != nil {
|
||||
return nil, errors.New("Нет подтверждения сетевой службы.")
|
||||
}
|
||||
if !result.OK {
|
||||
return nil, errors.New("Не удалось подготовить WireGuard на борту.")
|
||||
}
|
||||
return result.Result, nil
|
||||
}
|
||||
func (p *Pairing) callNetwork(action, identity string, fields map[string]any) (map[string]json.RawMessage, error) {
|
||||
if p.networkCall != nil {
|
||||
return p.networkCall(action, identity, fields)
|
||||
}
|
||||
return networkHelper(action, identity, fields)
|
||||
}
|
||||
func (p *Pairing) networkPath() string {
|
||||
return filepath.Join(filepath.Dir(p.path), "network-profile.json")
|
||||
}
|
||||
func (p *Pairing) loadNetworkLocked() error {
|
||||
if p.network != nil {
|
||||
if p.state.Binding == nil || p.network.BindingID == p.state.Binding.BindingID {
|
||||
return nil
|
||||
}
|
||||
p.network = nil
|
||||
}
|
||||
value := NetworkProfile{Provider: "tailscale", Phase: "applied"}
|
||||
raw, err := os.ReadFile(p.networkPath())
|
||||
if err == nil {
|
||||
info, e := os.Lstat(p.networkPath())
|
||||
if e != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 {
|
||||
return errors.New("Invalid network configuration permissions")
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
if len(raw) > 16384 || json.Unmarshal(raw, &value) != nil {
|
||||
return errors.New("Invalid network configuration")
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
if p.state.Binding != nil {
|
||||
if value.BindingID != p.state.Binding.BindingID {
|
||||
value = NetworkProfile{BindingID: p.state.Binding.BindingID, Provider: "tailscale", Phase: "applied"}
|
||||
}
|
||||
endpoint, _ := url.Parse(p.state.Binding.Endpoint)
|
||||
if tailnetAddress(endpoint.Hostname()) {
|
||||
value.TailscaleEndpoint = p.state.Binding.Endpoint
|
||||
}
|
||||
}
|
||||
p.network = &value
|
||||
return nil
|
||||
}
|
||||
func (p *Pairing) saveNetworkLocked() error { return savePrivateJSON(p.networkPath(), p.network) }
|
||||
func (p *Pairing) networkViewLocked() map[string]any {
|
||||
if p.loadNetworkLocked() != nil {
|
||||
return map[string]any{"phase": "unavailable"}
|
||||
}
|
||||
n := p.network
|
||||
result := map[string]any{"provider": n.Provider, "server_id": n.ServerID, "revision": n.Revision, "phase": n.Phase,
|
||||
"operation_id": n.OperationID, "public_key": n.PublicKey, "tailscale_endpoint": n.TailscaleEndpoint, "error": n.Error}
|
||||
if n.Pending != nil {
|
||||
result["pending_provider"] = n.Pending.Provider
|
||||
result["rollback_at"] = n.Pending.Deadline
|
||||
}
|
||||
return result
|
||||
}
|
||||
func (p *Pairing) networkSnapshot() map[string]any {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.networkViewLocked()
|
||||
}
|
||||
func (p *Pairing) networkEndpointLocked(endpoint string) error {
|
||||
b := p.state.Binding
|
||||
if b == nil || p.state.Phase != "paired" || !privateEndpoint(endpoint, CorePort) {
|
||||
return errors.New("Binding unavailable")
|
||||
}
|
||||
if b.Endpoint == endpoint {
|
||||
return nil
|
||||
}
|
||||
if b.EndpointRevision >= 1000000000 {
|
||||
return errors.New("Endpoint revision exhausted")
|
||||
}
|
||||
next := p.state
|
||||
copy := *b
|
||||
copy.Endpoint = endpoint
|
||||
copy.EndpointRevision++
|
||||
next.Binding = ©
|
||||
if err := p.save(next); err != nil {
|
||||
return err
|
||||
}
|
||||
p.connection = "offline"
|
||||
p.lastSeen = 0
|
||||
return nil
|
||||
}
|
||||
func (p *Pairing) rollbackNetwork() {
|
||||
p.mu.Lock()
|
||||
if p.loadNetworkLocked() != nil || p.network.Pending == nil {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
n := p.network
|
||||
pending := *n.Pending
|
||||
identity := pending.ServerID
|
||||
op := n.OperationID
|
||||
p.mu.Unlock()
|
||||
if networkID.MatchString(identity) {
|
||||
if _, err := p.callNetwork("rollback", identity, map[string]any{"operation_id": op}); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.network.Pending == nil || p.network.OperationID != op {
|
||||
return
|
||||
}
|
||||
if p.networkEndpointLocked(pending.PreviousEndpoint) != nil {
|
||||
return
|
||||
}
|
||||
n.Pending = nil
|
||||
n.Phase = "rolled_back"
|
||||
n.Error = "Новое подключение не подтверждено. Восстановлен прежний профиль."
|
||||
_ = p.saveNetworkLocked()
|
||||
}
|
||||
func (p *Pairing) networkWatch(ctx context.Context) {
|
||||
// A restart during a transaction restores the last confirmed endpoint.
|
||||
p.rollbackNetwork()
|
||||
timer := time.NewTicker(time.Second)
|
||||
defer timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
p.mu.Lock()
|
||||
expired := p.network != nil && p.network.Pending != nil && p.network.Pending.Deadline <= time.Now().Unix()
|
||||
p.mu.Unlock()
|
||||
if expired {
|
||||
p.rollbackNetwork()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func (p *Pairing) networkFailure(op string, err error) {
|
||||
p.mu.Lock()
|
||||
pending := p.network != nil && p.network.Pending != nil
|
||||
p.mu.Unlock()
|
||||
if pending {
|
||||
p.rollbackNetwork()
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.network != nil && p.network.OperationID == op {
|
||||
p.network.Phase = "failed"
|
||||
p.network.Error = err.Error()
|
||||
_ = p.saveNetworkLocked()
|
||||
}
|
||||
}
|
||||
func (p *Pairing) applyNetworkCommand(raw json.RawMessage) {
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return
|
||||
}
|
||||
var c NetworkCommand
|
||||
if decodeRoverJSON(raw, &c) != nil || !networkOperationID.MatchString(c.ID) || c.ExpiresAt <= time.Now().Unix() || c.ExpiresAt > time.Now().Unix()+180 {
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
if p.loadNetworkLocked() != nil || p.state.Binding == nil || p.state.Phase != "paired" {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
n := p.network
|
||||
if c.Action == "abort" && n.OperationID == c.ID {
|
||||
p.mu.Unlock()
|
||||
p.rollbackNetwork()
|
||||
return
|
||||
}
|
||||
if c.Action == "commit" && n.OperationID == c.ID && n.Phase == "applied" {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if c.ExpectedRevision != n.Revision || (c.Provider != "tailscale" && c.Provider != "wireguard") || (c.Provider == "wireguard" && !networkID.MatchString(c.ServerID)) {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if n.Pending != nil && n.OperationID != c.ID {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if c.Action == "prepare" {
|
||||
if n.OperationID == c.ID && n.Phase == "prepared" {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
n.OperationID = c.ID
|
||||
n.Phase = "preparing"
|
||||
n.Error = ""
|
||||
_ = p.saveNetworkLocked()
|
||||
p.mu.Unlock()
|
||||
reply, err := p.callNetwork("prepare", c.ServerID, nil)
|
||||
if err != nil {
|
||||
p.networkFailure(c.ID, err)
|
||||
return
|
||||
}
|
||||
var public string
|
||||
_ = json.Unmarshal(reply["public_key"], &public)
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.network.OperationID != c.ID || p.state.Binding == nil || p.network.BindingID != p.state.Binding.BindingID {
|
||||
return
|
||||
}
|
||||
p.network.PublicKey = public
|
||||
p.network.Phase = "prepared"
|
||||
_ = p.saveNetworkLocked()
|
||||
return
|
||||
}
|
||||
if c.Action == "apply" {
|
||||
if n.OperationID == c.ID && (n.Phase == "verifying" || n.Phase == "applied") {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if c.Provider == "tailscale" {
|
||||
if c.CoreEndpoint != n.TailscaleEndpoint || c.CoreEndpoint == "" {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
} else {
|
||||
var config struct {
|
||||
ServerID string `json:"server_id"`
|
||||
Address string `json:"address"`
|
||||
Subnet string `json:"subnet"`
|
||||
Role string `json:"role"`
|
||||
Allowed []string `json:"allowed_ips"`
|
||||
}
|
||||
if json.Unmarshal(c.Config, &config) != nil || config.ServerID != c.ServerID || config.Role != "node" {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
_, network, err := net.ParseCIDR(config.Subnet)
|
||||
u, e := url.Parse(c.CoreEndpoint)
|
||||
if err != nil || e != nil || !privateEndpoint(c.CoreEndpoint, CorePort) || !network.Contains(net.ParseIP(u.Hostname())) {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
found := false
|
||||
for _, address := range config.Allowed {
|
||||
if address == u.Hostname()+"/32" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
n.OperationID = c.ID
|
||||
n.Phase = "preparing"
|
||||
n.Error = ""
|
||||
n.Pending = &NetworkPending{Deadline: time.Now().Unix() + 100, PreviousEndpoint: p.state.Binding.Endpoint, Provider: c.Provider, ServerID: c.ServerID, Config: c.Config}
|
||||
if p.saveNetworkLocked() != nil {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
p.mu.Unlock()
|
||||
if c.Provider == "wireguard" {
|
||||
var config map[string]any
|
||||
_ = json.Unmarshal(c.Config, &config)
|
||||
if _, err := p.callNetwork("stage", c.ServerID, map[string]any{"config": config, "operation_id": c.ID}); err != nil {
|
||||
p.networkFailure(c.ID, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.network.OperationID != c.ID || p.network.Pending == nil || p.state.Binding == nil || p.network.BindingID != p.state.Binding.BindingID {
|
||||
return
|
||||
}
|
||||
if err := p.networkEndpointLocked(c.CoreEndpoint); err != nil {
|
||||
p.network.Phase = "failed"
|
||||
p.network.Error = "Не удалось сохранить адрес Core."
|
||||
} else {
|
||||
p.network.Phase = "verifying"
|
||||
}
|
||||
_ = p.saveNetworkLocked()
|
||||
return
|
||||
}
|
||||
if c.Action == "commit" && n.OperationID == c.ID && n.Phase == "verifying" && n.Pending != nil {
|
||||
pending := *n.Pending
|
||||
oldServer := n.ServerID
|
||||
p.mu.Unlock()
|
||||
if pending.Provider == "wireguard" {
|
||||
if _, err := p.callNetwork("confirm", pending.ServerID, map[string]any{"operation_id": c.ID}); err != nil {
|
||||
p.networkFailure(c.ID, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.network.Pending == nil || p.network.OperationID != c.ID {
|
||||
return
|
||||
}
|
||||
n = p.network
|
||||
previous := *n
|
||||
n.Provider = pending.Provider
|
||||
n.ServerID = pending.ServerID
|
||||
n.Config = pending.Config
|
||||
n.Pending = nil
|
||||
n.Phase = "applied"
|
||||
n.Revision++
|
||||
n.Error = ""
|
||||
if err := p.saveNetworkLocked(); err != nil {
|
||||
*n = previous
|
||||
return
|
||||
}
|
||||
if oldServer != "" && oldServer != pending.ServerID {
|
||||
// The confirmed endpoint is durable before retiring the previous tunnel.
|
||||
_, _ = p.callNetwork("disable", oldServer, nil)
|
||||
}
|
||||
return
|
||||
}
|
||||
p.mu.Unlock()
|
||||
}
|
||||
func (p *Pairing) networkAddressLocked(address string) bool {
|
||||
if p.network == nil || p.network.Provider != "wireguard" {
|
||||
return tailnetAddress(address)
|
||||
}
|
||||
var config struct {
|
||||
Address string `json:"address"`
|
||||
}
|
||||
return json.Unmarshal(p.network.Config, &config) == nil && config.Address == address
|
||||
}
|
||||
func (p *Pairing) networkPeerLocked(address string) bool {
|
||||
if tailnetAddress(address) {
|
||||
return true
|
||||
}
|
||||
for _, raw := range []json.RawMessage{func() json.RawMessage {
|
||||
if p.network != nil {
|
||||
return p.network.Config
|
||||
}
|
||||
return nil
|
||||
}(), func() json.RawMessage {
|
||||
if p.network != nil && p.network.Pending != nil {
|
||||
return p.network.Pending.Config
|
||||
}
|
||||
return nil
|
||||
}()} {
|
||||
var config struct {
|
||||
Allowed []string `json:"allowed_ips"`
|
||||
}
|
||||
if json.Unmarshal(raw, &config) == nil {
|
||||
for _, peer := range config.Allowed {
|
||||
if peer == address+"/32" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (p *Pairing) networkLocalRoutes(mux *http.ServeMux, s *Server) {
|
||||
mux.HandleFunc("GET /api/network/profile", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorized(w, r) {
|
||||
return
|
||||
}
|
||||
reply(w, 200, p.networkSnapshot())
|
||||
})
|
||||
mux.HandleFunc("POST /api/network/profile/tailscale", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorized(w, r) {
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
_ = p.loadNetworkLocked()
|
||||
if p.network == nil || p.network.TailscaleEndpoint == "" {
|
||||
p.mu.Unlock()
|
||||
reply(w, 409, map[string]string{"error": "Нет сохранённого подключения Tailscale."})
|
||||
return
|
||||
}
|
||||
op := digest(token())[:32]
|
||||
command := NetworkCommand{ID: op, Action: "apply", Provider: "tailscale", ExpectedRevision: p.network.Revision, ExpiresAt: time.Now().Unix() + 110, CoreEndpoint: p.network.TailscaleEndpoint}
|
||||
p.mu.Unlock()
|
||||
raw, _ := json.Marshal(command)
|
||||
p.applyNetworkCommand(raw)
|
||||
p.mu.Lock()
|
||||
if p.network.Pending != nil && p.network.OperationID == op {
|
||||
p.network.Pending.Local = true
|
||||
_ = p.saveNetworkLocked()
|
||||
}
|
||||
p.mu.Unlock()
|
||||
reply(w, 200, p.networkSnapshot())
|
||||
})
|
||||
}
|
||||
|
||||
// Only a successful authenticated heartbeat through the selected endpoint can
|
||||
// confirm the local recovery action. It cannot authorize a remote arbitrary path.
|
||||
func (p *Pairing) networkLocalAcknowledged(binding CoreBinding) {
|
||||
p.mu.Lock()
|
||||
n := p.network
|
||||
if n == nil || n.Pending == nil || !n.Pending.Local || n.Phase != "verifying" || p.state.Binding == nil || p.state.Binding.Endpoint != binding.Endpoint {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
c := NetworkCommand{ID: n.OperationID, Action: "commit", Provider: n.Pending.Provider, ServerID: n.Pending.ServerID, ExpectedRevision: n.Revision, ExpiresAt: time.Now().Unix() + 30}
|
||||
p.mu.Unlock()
|
||||
raw, _ := json.Marshal(c)
|
||||
p.applyNetworkCommand(raw)
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func networkFixture(t *testing.T) (*Pairing, NetworkCommand, *[]string) {
|
||||
p, _ := testPairing(t)
|
||||
b := testCoreBinding(t, p)
|
||||
b.Endpoint = "https://100.64.1.2:8782"
|
||||
b.EndpointRevision = 7
|
||||
if err := p.save(PairState{Schema: PairSchema, Phase: "paired", Binding: &b}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actions := []string{}
|
||||
p.networkCall = func(action, id string, fields map[string]any) (map[string]json.RawMessage, error) {
|
||||
actions = append(actions, action)
|
||||
return map[string]json.RawMessage{"public_key": json.RawMessage(`"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE="`)}, nil
|
||||
}
|
||||
config := json.RawMessage(`{"server_id":"wg_11111111111111111111111111111111","address":"10.203.1.3","subnet":"10.203.1.0/24","role":"node","allowed_ips":["10.203.1.1/32","10.203.1.2/32"]}`)
|
||||
c := NetworkCommand{ID: "22222222222222222222222222222222", Action: "apply", Provider: "wireguard", ServerID: "wg_11111111111111111111111111111111", ExpectedRevision: 0, ExpiresAt: time.Now().Unix() + 110, CoreEndpoint: "https://10.203.1.2:8782", Config: config}
|
||||
return p, c, &actions
|
||||
}
|
||||
func networkSend(p *Pairing, c NetworkCommand) { raw, _ := json.Marshal(c); p.applyNetworkCommand(raw) }
|
||||
func TestNetworkCommitIsIdempotentAndUsesNewEndpoint(t *testing.T) {
|
||||
p, c, actions := networkFixture(t)
|
||||
networkSend(p, c)
|
||||
if p.network.Phase != "verifying" || p.network.Provider != "tailscale" || p.state.Binding.Endpoint != c.CoreEndpoint {
|
||||
t.Fatal("unconfirmed profile became active")
|
||||
}
|
||||
revision := p.state.Binding.EndpointRevision
|
||||
networkSend(p, c)
|
||||
if p.state.Binding.EndpointRevision != revision {
|
||||
t.Fatal("repeat changed endpoint revision")
|
||||
}
|
||||
c.Action = "commit"
|
||||
networkSend(p, c)
|
||||
networkSend(p, c)
|
||||
if p.network.Revision != 1 || p.network.Provider != "wireguard" || p.network.Pending != nil {
|
||||
t.Fatal("commit failed")
|
||||
}
|
||||
if len(*actions) != 2 || (*actions)[0] != "stage" || (*actions)[1] != "confirm" {
|
||||
t.Fatal(*actions)
|
||||
}
|
||||
}
|
||||
func TestNetworkRestartAndFailedStageRestoreConfirmedBinding(t *testing.T) {
|
||||
p, c, _ := networkFixture(t)
|
||||
networkSend(p, c)
|
||||
p.network = nil // Reload durable state, exactly as a new Node process.
|
||||
p.rollbackNetwork()
|
||||
if p.state.Binding.Endpoint != "https://100.64.1.2:8782" || p.network.Phase != "rolled_back" || p.state.Binding.EndpointRevision != 9 {
|
||||
t.Fatal("restart did not restore prior endpoint")
|
||||
}
|
||||
p, c, _ = networkFixture(t)
|
||||
p.networkCall = func(action, id string, fields map[string]any) (map[string]json.RawMessage, error) {
|
||||
if action == "stage" {
|
||||
return nil, errors.New("test fault")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
networkSend(p, c)
|
||||
if p.state.Binding.Endpoint != "https://100.64.1.2:8782" || p.network.Pending != nil {
|
||||
t.Fatal("failed stage changed confirmed endpoint")
|
||||
}
|
||||
}
|
||||
func TestNetworkRejectsStaleAndUnrelatedEndpoint(t *testing.T) {
|
||||
for _, change := range []func(*NetworkCommand){func(c *NetworkCommand) { c.ExpectedRevision = 8 }, func(c *NetworkCommand) { c.CoreEndpoint = "https://192.168.1.10:8782" }, func(c *NetworkCommand) { c.ExpiresAt = time.Now().Unix() - 1 }} {
|
||||
p, c, actions := networkFixture(t)
|
||||
change(&c)
|
||||
networkSend(p, c)
|
||||
if len(*actions) != 0 || p.state.Binding.Endpoint != "https://100.64.1.2:8782" {
|
||||
t.Fatal("invalid change reached root helper")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkCommitStorageFailureKeepsRollbackState(t *testing.T) {
|
||||
if os.Geteuid() == 0 {
|
||||
t.Skip("permission fault requires unprivileged qualification")
|
||||
}
|
||||
p, c, _ := networkFixture(t)
|
||||
networkSend(p, c)
|
||||
dir := filepath.Dir(p.networkPath())
|
||||
if err := os.Chmod(dir, 0500); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Chmod(dir, 0700)
|
||||
c.Action = "commit"
|
||||
networkSend(p, c)
|
||||
if p.network.Provider != "tailscale" || p.network.Revision != 0 || p.network.Pending == nil || p.network.Phase != "verifying" {
|
||||
t.Fatal("failed persistence changed confirmed state")
|
||||
}
|
||||
if err := os.Chmod(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.rollbackNetwork()
|
||||
if p.network.Provider != "tailscale" || p.network.Pending != nil || p.state.Binding.Endpoint != "https://100.64.1.2:8782" {
|
||||
t.Fatal("rollback after storage failure failed")
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import (
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"nodedc.local/mission-core/node-agent/internal/routers"
|
||||
)
|
||||
|
||||
type Invitation struct {
|
||||
@@ -41,10 +43,14 @@ type PairState struct {
|
||||
Revocations []CoreBinding `json:"revocations,omitempty"`
|
||||
}
|
||||
type Pairing struct {
|
||||
Budget *LinkBudget
|
||||
Routers *routers.Collector
|
||||
RoverConfiguration *RoverConfigurationStore
|
||||
Monitor *Monitor
|
||||
Sensors *Sensors
|
||||
DeviceEnrollment *DeviceEnrollment
|
||||
networkCall func(string, string, map[string]any) (map[string]json.RawMessage, error)
|
||||
network *NetworkProfile
|
||||
mu sync.Mutex
|
||||
path string
|
||||
store *Store
|
||||
@@ -148,7 +154,7 @@ func (p *Pairing) status() map[string]any {
|
||||
defer p.mu.Unlock()
|
||||
_ = p.expire()
|
||||
id, _ := p.store.Public()
|
||||
out := map[string]any{"phase": p.state.Phase, "node_id": id, "connection": p.connection, "last_seen": p.lastSeen, "notice": p.listenError, "addresses": p.addresses(), "pending_revocations": len(p.state.Revocations)}
|
||||
out := map[string]any{"network_profile": p.networkViewLocked(), "phase": p.state.Phase, "node_id": id, "connection": p.connection, "last_seen": p.lastSeen, "notice": p.listenError, "addresses": p.addresses(), "pending_revocations": len(p.state.Revocations)}
|
||||
if i := p.state.Invitation; i != nil {
|
||||
out["invitation"] = map[string]any{"id": i.ID, "endpoint": i.Endpoint, "expires_at": i.ExpiresAt}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLinkHeartbeatWithDevAtFloor(t *testing.T) {
|
||||
for _, devSize := range []int{0, 400, linkPacket} {
|
||||
b, now := testBudget(t)
|
||||
b.effective = float64(b.policy.ReserveKbps + 128)
|
||||
delivered, devBytes := 0, 0
|
||||
deadline := pacedTimeout(40 * 1024)
|
||||
for elapsed := time.Duration(0); elapsed < deadline; elapsed += 10 * time.Millisecond {
|
||||
*now = now.Add(10 * time.Millisecond)
|
||||
// Persistent congestion must not erase earned tokens at the floor.
|
||||
if elapsed%time.Second == 0 {
|
||||
b.Observe(time.Second, false)
|
||||
}
|
||||
b.Try("video", 1200)
|
||||
b.Try("cloud", 1200)
|
||||
if devSize > 0 {
|
||||
if ok, _ := b.Try("bulk", devSize); ok {
|
||||
devBytes += devSize
|
||||
}
|
||||
}
|
||||
if delivered < 40*1024 {
|
||||
size := min(linkPacket, 40*1024-delivered)
|
||||
if ok, _ := b.Try("inventory", size); ok {
|
||||
delivered += size
|
||||
}
|
||||
}
|
||||
}
|
||||
t.Logf("DEV packet=%d: heartbeat=%d/40960, DEV=%d, deadline=%v", devSize, delivered, devBytes, deadline)
|
||||
if delivered != 40*1024 || (devSize > 0 && devBytes == 0) {
|
||||
t.Fatal("optional traffic starved")
|
||||
}
|
||||
var charged uint64
|
||||
for _, class := range b.classes {
|
||||
charged += class.bytes
|
||||
}
|
||||
if float64(charged) > 128*125*deadline.Seconds()+linkBurst {
|
||||
t.Fatal("aggregate allowance exceeded")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLinkPacedTimeoutCoversLargestDiagnosticBlock(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.effective = float64(b.policy.ReserveKbps + 128)
|
||||
left := 108 * 1024
|
||||
deadline := pacedTimeout(left)
|
||||
for elapsed := time.Duration(0); elapsed < deadline; elapsed += 10 * time.Millisecond {
|
||||
*now = now.Add(10 * time.Millisecond)
|
||||
for _, class := range []string{"video", "cloud", "inventory"} {
|
||||
b.Try(class, 1200)
|
||||
}
|
||||
size := min(linkPacket, left)
|
||||
if ok, _ := b.Try("bulk", size); ok {
|
||||
left -= size
|
||||
}
|
||||
if left == 0 {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatal("export deadline below worst-case budget", left)
|
||||
}
|
||||
|
||||
func TestHeartbeatLivenessDuringBlockedSnapshot(t *testing.T) {
|
||||
p, _ := testPairing(t)
|
||||
binding := testCoreBinding(t, p)
|
||||
p.state = PairState{Phase: "paired", Binding: &binding}
|
||||
var lives atomic.Int64
|
||||
started := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
p.clients[binding.BindingID+binding.Endpoint+digest(binding.ClientPEM)] = &http.Client{
|
||||
Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/v1/node/liveness" {
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
var envelope map[string]any
|
||||
json.Unmarshal(raw, &envelope)
|
||||
if len(raw) > 2048 || envelope["host"] != nil || envelope["sensor_results"] != nil || envelope["monitor"] != nil {
|
||||
t.Error("large snapshot or acknowledgements leaked into liveness")
|
||||
}
|
||||
if lives.Add(1) == 2 {
|
||||
close(release)
|
||||
}
|
||||
} else {
|
||||
close(started)
|
||||
select {
|
||||
case <-release:
|
||||
case <-r.Context().Done():
|
||||
return nil, r.Context().Err()
|
||||
}
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"ok":true}`)), Header: make(http.Header)}, nil
|
||||
}),
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 7*time.Second)
|
||||
defer cancel()
|
||||
payload := map[string]any{"schema": PairSchema, "binding_id": binding.BindingID,
|
||||
"node_id": "test", "execution_binding": map[string]string{"agent_instance_id": "test"},
|
||||
"core_endpoint": binding.Endpoint, "endpoint_revision": 0,
|
||||
"host": strings.Repeat("x", 40*1024), "monitor": strings.Repeat("x", 100*1024)}
|
||||
_, status, err := p.sendHeartbeat(ctx, binding, payload)
|
||||
if err != nil || status != 200 || lives.Load() != 2 {
|
||||
t.Fatal("snapshot blocked liveness", status, err, lives.Load())
|
||||
}
|
||||
select {
|
||||
case <-started:
|
||||
default:
|
||||
t.Fatal("snapshot was not sent")
|
||||
}
|
||||
if p.lastSeen == 0 || p.connection != "online" {
|
||||
t.Fatal("live binding remained offline")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHeartbeatCancelledUploadJoinsBeforeReturn(t *testing.T) {
|
||||
p, _ := testPairing(t)
|
||||
binding := testCoreBinding(t, p)
|
||||
p.state = PairState{Phase: "paired", Binding: &binding}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
var finished atomic.Bool
|
||||
p.clients[binding.BindingID+binding.Endpoint+digest(binding.ClientPEM)] = &http.Client{
|
||||
Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/v1/node/heartbeat" {
|
||||
cancel()
|
||||
<-r.Context().Done()
|
||||
finished.Store(true)
|
||||
return nil, r.Context().Err()
|
||||
}
|
||||
return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader(`{}`)), Header: make(http.Header)}, nil
|
||||
}),
|
||||
}
|
||||
_, _, err := p.sendHeartbeat(ctx, binding, map[string]any{})
|
||||
if err == nil || !finished.Load() {
|
||||
t.Fatal("upload leaked after cancellation")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHeartbeatCompressionNegotiatedOnExistingAuthenticatedChannel(t *testing.T) {
|
||||
for _, supported := range []bool{false, true} {
|
||||
p, _ := testPairing(t)
|
||||
b := testCoreBinding(t, p)
|
||||
p.state = PairState{Phase: "paired", Binding: &b}
|
||||
if supported {
|
||||
budget, now := testBudget(t)
|
||||
budget.tokens = linkBurst
|
||||
budget.classes["inventory"].tokens = linkClassBurst
|
||||
budget.classes["inventory"].seen = *now
|
||||
p.Budget = budget
|
||||
}
|
||||
payload := map[string]any{"node_id": "fixture", "host": strings.Repeat("metadata", 8000)}
|
||||
raw, _ := json.Marshal(payload)
|
||||
seen := 0
|
||||
p.clients[b.BindingID+b.Endpoint+digest(b.ClientPEM)] = &http.Client{Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
response := `{"ok":true}`
|
||||
if r.URL.Path == "/v1/node/liveness" {
|
||||
if supported {
|
||||
response = `{"ok":true,"heartbeat_encoding":"gzip"}`
|
||||
}
|
||||
} else {
|
||||
seen++
|
||||
wire, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decoded := wire
|
||||
if supported {
|
||||
if r.Header.Get("Content-Encoding") != "gzip" || len(wire) >= len(raw)/10 {
|
||||
t.Error("heartbeat not compressed")
|
||||
}
|
||||
reader, err := gzip.NewReader(bytes.NewReader(wire))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decoded, err = io.ReadAll(reader)
|
||||
reader.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else if r.Header.Get("Content-Encoding") != "" {
|
||||
t.Error("old Core received unsupported encoding")
|
||||
}
|
||||
if !bytes.Equal(decoded, raw) || r.ContentLength != int64(len(wire)) {
|
||||
t.Error("snapshot or framing changed")
|
||||
}
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(response))}, nil
|
||||
})}
|
||||
_, status, err := p.sendHeartbeat(context.Background(), b, payload)
|
||||
if err != nil || status != 200 || seen != 1 {
|
||||
t.Fatal(status, err, seen)
|
||||
}
|
||||
if supported && p.Budget.classes["inventory"].bytes == 0 {
|
||||
t.Fatal("compressed body bypassed shared budget")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A bounded keepalive on the existing authenticated Node HTTP transport.
|
||||
// It cannot carry inventory, operation receipts or a motor lease. Old Core
|
||||
// returns 404; full heartbeat remains backward-compatible. No retry queue.
|
||||
func (p *Pairing) sendHeartbeat(ctx context.Context, b CoreBinding, payload map[string]any) (map[string]json.RawMessage, int, error) {
|
||||
live := map[string]any{}
|
||||
for _, key := range []string{"schema", "node_id", "binding_id", "execution_binding", "core_endpoint", "endpoint_revision"} {
|
||||
live[key] = payload[key]
|
||||
}
|
||||
compressed := false
|
||||
keepalive := func() {
|
||||
result, status, err := p.send(ctx, b, "/v1/node/liveness", live)
|
||||
var encoding string
|
||||
if err == nil && status == 200 {
|
||||
_ = json.Unmarshal(result["heartbeat_encoding"], &encoding)
|
||||
}
|
||||
compressed = encoding == "gzip"
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.sameBinding(b) && err == nil && status == 200 {
|
||||
p.connection, p.lastSeen = "online", p.now().Unix()
|
||||
}
|
||||
}
|
||||
// Initializes the shared two-connection client before the concurrent upload;
|
||||
// the client map is owned by channel, and only read until this upload joins.
|
||||
keepalive()
|
||||
call, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
type outcome struct {
|
||||
body map[string]json.RawMessage
|
||||
status int
|
||||
err error
|
||||
}
|
||||
done := make(chan outcome, 1)
|
||||
go func(compress bool) {
|
||||
body, status, err := p.sendEncoded(call, b, "/v1/node/heartbeat", payload, compress)
|
||||
done <- outcome{body, status, err}
|
||||
}(compressed)
|
||||
ticker := time.NewTicker(5 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case result := <-done:
|
||||
return result.body, result.status, result.err
|
||||
case <-ctx.Done():
|
||||
cancel()
|
||||
result := <-done
|
||||
return result.body, result.status, result.err
|
||||
case <-ticker.C:
|
||||
p.mu.Lock()
|
||||
current := p.sameBinding(b)
|
||||
p.mu.Unlock()
|
||||
if !current {
|
||||
cancel()
|
||||
result := <-done
|
||||
return result.body, result.status, result.err
|
||||
}
|
||||
keepalive()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Caller holds p.mu. Endpoint revisions and certificate rotation invalidate an
|
||||
// in-flight snapshot; an old upload cannot refresh a replacement binding.
|
||||
func (p *Pairing) sameBinding(b CoreBinding) bool {
|
||||
current := p.state.Binding
|
||||
return p.state.Phase == "paired" && current != nil &&
|
||||
current.BindingID == b.BindingID && current.Endpoint == b.Endpoint &&
|
||||
current.EndpointRevision == b.EndpointRevision && current.ClientPEM == b.ClientPEM
|
||||
}
|
||||
@@ -50,7 +50,10 @@ func (p *Pairing) recoveryHandler() http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil || !tailnetAddress(host) || r.TLS == nil {
|
||||
p.mu.Lock()
|
||||
allowedNetwork := p.networkPeerLocked(host)
|
||||
p.mu.Unlock()
|
||||
if err != nil || !allowedNetwork || r.TLS == nil {
|
||||
http.Error(w, "Private authenticated channel required", 403)
|
||||
return
|
||||
}
|
||||
@@ -80,7 +83,7 @@ func (p *Pairing) recoveryHandler() http.Handler {
|
||||
case "/v1/channel/inspect":
|
||||
case "/v1/channel/migrate":
|
||||
u, err := url.Parse(body.Endpoint)
|
||||
if err != nil || !privateEndpoint(body.Endpoint, CorePort) || !tailnetAddress(u.Hostname()) || u.Hostname() != host {
|
||||
if err != nil || !privateEndpoint(body.Endpoint, CorePort) || !p.networkPeerLocked(u.Hostname()) || u.Hostname() != host {
|
||||
http.Error(w, "Endpoint must address the authenticated Core transport", 400)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -169,6 +169,9 @@ func TestOldHeartbeatCannotRevokeMigratedBinding(t *testing.T) {
|
||||
entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{})
|
||||
p.clients[old.BindingID+old.Endpoint+digest(old.ClientPEM)] = &http.Client{
|
||||
Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
if r.URL.Path == "/v1/node/liveness" {
|
||||
return &http.Response{StatusCode: 404, Body: io.NopCloser(strings.NewReader(`{}`)), Header: make(http.Header)}, nil
|
||||
}
|
||||
close(entered)
|
||||
<-release
|
||||
return &http.Response{StatusCode: 410, Body: io.NopCloser(strings.NewReader(`{}`)), Header: make(http.Header)}, nil
|
||||
|
||||
@@ -2,6 +2,7 @@ package node
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
@@ -151,6 +152,7 @@ func (p *Pairing) remoteHandler() http.Handler {
|
||||
}
|
||||
|
||||
func (p *Pairing) Run(ctx context.Context) {
|
||||
go p.networkWatch(ctx)
|
||||
go p.channel(ctx)
|
||||
go p.roverChannel(ctx)
|
||||
var server *http.Server
|
||||
@@ -181,7 +183,7 @@ func (p *Pairing) Run(ctx context.Context) {
|
||||
}
|
||||
if p.state.Phase == "paired" && p.state.Binding != nil {
|
||||
for _, address := range p.addresses() {
|
||||
if tailnetAddress(address) {
|
||||
if p.networkAddressLocked(address) {
|
||||
desired = "https://" + address + ":" + PairPort
|
||||
copy := *p.state.Binding
|
||||
recovery = ©
|
||||
@@ -230,6 +232,10 @@ func (p *Pairing) Run(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
func (p *Pairing) send(ctx context.Context, b CoreBinding, path string, payload any) (map[string]json.RawMessage, int, error) {
|
||||
return p.sendEncoded(ctx, b, path, payload, false)
|
||||
}
|
||||
|
||||
func (p *Pairing) sendEncoded(ctx context.Context, b CoreBinding, path string, payload any, compress bool) (map[string]json.RawMessage, int, error) {
|
||||
config, e := bindingTLS(b, p.store.pairingKey())
|
||||
if e != nil {
|
||||
return nil, 0, e
|
||||
@@ -237,19 +243,55 @@ func (p *Pairing) send(ctx context.Context, b CoreBinding, path string, payload
|
||||
cacheKey := b.BindingID + b.Endpoint + digest(b.ClientPEM)
|
||||
client := p.clients[cacheKey]
|
||||
if client == nil {
|
||||
transport := &http.Transport{TLSClientConfig: config, Proxy: nil, MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, IdleConnTimeout: 15 * time.Second, TLSHandshakeTimeout: 4 * time.Second, DialContext: (&net.Dialer{Timeout: 4 * time.Second}).DialContext}
|
||||
client = &http.Client{Transport: transport, Timeout: 8 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirects forbidden") }}
|
||||
transport := &http.Transport{TLSClientConfig: config, Proxy: nil, MaxConnsPerHost: 2, MaxIdleConnsPerHost: 2, IdleConnTimeout: 15 * time.Second, ResponseHeaderTimeout: 8 * time.Second, TLSHandshakeTimeout: 4 * time.Second, DialContext: (&net.Dialer{Timeout: 4 * time.Second}).DialContext}
|
||||
client = &http.Client{Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirects forbidden") }}
|
||||
p.clients[cacheKey] = client
|
||||
}
|
||||
data, e := json.Marshal(payload)
|
||||
if e != nil {
|
||||
return nil, 0, e
|
||||
}
|
||||
request, e := http.NewRequestWithContext(ctx, "POST", b.Endpoint+path, bytes.NewReader(data))
|
||||
if len(data) > 8*1024*1024 {
|
||||
return nil, 0, errors.New("Core envelope exceeds limit")
|
||||
}
|
||||
// Compress metadata only after the authenticated Core advertises support.
|
||||
// Budget the actual wire body, retaining admission even if it shrinks below
|
||||
// 4 KiB. The control reserve, transport and full-snapshot ACK stay unchanged.
|
||||
paced := len(data) > 4096 && p.Budget != nil
|
||||
encoding := ""
|
||||
if compress && path == "/v1/node/heartbeat" && len(data) > 4096 {
|
||||
var encoded bytes.Buffer
|
||||
writer, _ := gzip.NewWriterLevel(&encoded, gzip.BestSpeed)
|
||||
_, _ = writer.Write(data)
|
||||
_ = writer.Close()
|
||||
if encoded.Len() < len(data) {
|
||||
data, encoding = encoded.Bytes(), "gzip"
|
||||
}
|
||||
}
|
||||
timeout := 8 * time.Second
|
||||
class := "bulk"
|
||||
if path == "/v1/node/heartbeat" {
|
||||
class = "inventory"
|
||||
}
|
||||
if paced {
|
||||
timeout = pacedTimeout(len(data))
|
||||
}
|
||||
call, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
ctx = call
|
||||
var body io.Reader = bytes.NewReader(data)
|
||||
if paced {
|
||||
body = &budgetReader{ctx: ctx, source: body, budget: p.Budget, class: class}
|
||||
}
|
||||
request, e := http.NewRequestWithContext(ctx, "POST", b.Endpoint+path, body)
|
||||
if e != nil {
|
||||
return nil, 0, e
|
||||
}
|
||||
request.ContentLength = int64(len(data))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
if encoding != "" {
|
||||
request.Header.Set("Content-Encoding", encoding)
|
||||
}
|
||||
response, e := client.Do(request)
|
||||
if e != nil {
|
||||
return nil, 0, e
|
||||
@@ -304,6 +346,7 @@ func (p *Pairing) channel(ctx context.Context) {
|
||||
if p.RoverConfiguration != nil {
|
||||
payload["rover_configuration"] = p.RoverConfiguration.Snapshot()
|
||||
}
|
||||
payload["network_profile"] = p.networkSnapshot()
|
||||
payload["core_endpoint"] = binding.Endpoint
|
||||
payload["endpoint_revision"] = binding.EndpointRevision
|
||||
if p.Sensors != nil {
|
||||
@@ -322,11 +365,18 @@ func (p *Pairing) channel(ctx context.Context) {
|
||||
if p.Monitor != nil {
|
||||
payload["monitor"] = p.Monitor.Snapshot()
|
||||
}
|
||||
result, status, e := p.send(ctx, *binding, "/v1/node/heartbeat", payload)
|
||||
if p.Routers != nil {
|
||||
payload["routers"] = p.Routers.Snapshot()
|
||||
}
|
||||
result, status, e := p.sendHeartbeat(ctx, *binding, payload)
|
||||
var networkChange json.RawMessage
|
||||
var configurationChange json.RawMessage
|
||||
var routerCommands json.RawMessage
|
||||
p.mu.Lock()
|
||||
if p.state.Phase == "paired" && p.state.Binding != nil && p.state.Binding.BindingID == binding.BindingID && p.state.Binding.Endpoint == binding.Endpoint && p.state.Binding.EndpointRevision == binding.EndpointRevision {
|
||||
if e == nil && status == 200 {
|
||||
networkChange = result["network_profile_change"]
|
||||
routerCommands = result["router_commands"]
|
||||
if p.RoverConfiguration != nil {
|
||||
configurationChange = result["rover_configuration_change"]
|
||||
}
|
||||
@@ -375,11 +425,16 @@ func (p *Pairing) channel(ctx context.Context) {
|
||||
next.Phase = "revoked"
|
||||
_ = p.save(next)
|
||||
p.connection = "revoked"
|
||||
} else {
|
||||
} else if p.now().Unix()-p.lastSeen >= 20 {
|
||||
p.connection = "offline"
|
||||
}
|
||||
}
|
||||
p.mu.Unlock()
|
||||
if e == nil && status == http.StatusOK {
|
||||
p.networkLocalAcknowledged(*binding)
|
||||
}
|
||||
p.applyNetworkCommand(networkChange)
|
||||
p.applyRouterCommands(routerCommands)
|
||||
// Durable preference IO must not hold the pairing/control mutex.
|
||||
if p.RoverConfiguration != nil {
|
||||
p.RoverConfiguration.Apply(configurationChange)
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -57,12 +56,7 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
transport := func() *http.Transport {
|
||||
return &http.Transport{TLSClientConfig: config, Proxy: nil,
|
||||
MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, IdleConnTimeout: 10 * time.Second,
|
||||
TLSHandshakeTimeout: time.Second, ResponseHeaderTimeout: 2 * time.Second,
|
||||
DialContext: (&net.Dialer{Timeout: time.Second}).DialContext}
|
||||
}
|
||||
transport := func() *http.Transport { return newRoverHTTPTransport(config) }
|
||||
telemetry := &http.Client{Transport: transport(), Timeout: 300 * time.Millisecond, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect forbidden") }}
|
||||
stream := &http.Client{Transport: transport(), CheckRedirect: telemetry.CheckRedirect}
|
||||
defer telemetry.CloseIdleConnections()
|
||||
@@ -76,10 +70,14 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
|
||||
base := map[string]any{"schema": PairSchema, "node_id": id, "binding_id": b.BindingID,
|
||||
"core_endpoint": b.Endpoint, "endpoint_revision": b.EndpointRevision, "relay_id": relay}
|
||||
state := newRoverStreamState(time.Now())
|
||||
state.budget = p.Budget
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
var workers sync.WaitGroup
|
||||
defer func() { cancel(); workers.Wait() }()
|
||||
workers.Add(2)
|
||||
workers.Add(3)
|
||||
optional := &http.Client{Transport: transport(), CheckRedirect: telemetry.CheckRedirect}
|
||||
defer optional.CloseIdleConnections()
|
||||
go func() { defer workers.Done(); roverDiagnosticsLane(ctx, optional, b.Endpoint, base, state) }()
|
||||
go func() { defer workers.Done(); roverTelemetry(ctx, telemetry, b.Endpoint, base, state) }()
|
||||
go func() { defer workers.Done(); roverCommands(ctx, stream, b.Endpoint, base, state) }()
|
||||
var model *sensorModel
|
||||
@@ -92,32 +90,17 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
|
||||
if model == nil {
|
||||
return
|
||||
}
|
||||
var diagnostic roverDiagnostics
|
||||
workers.Add(1)
|
||||
go func() { defer workers.Done(); p.roverDev(ctx, model, state) }()
|
||||
diagnostic := roverDiagnostics{lane: "local", epoch: relay, started: state.origin}
|
||||
var delivery roverLocalDelivery
|
||||
for ctx.Err() == nil && sameRoverBinding(&b, p.roverBinding()) {
|
||||
select {
|
||||
case <-state.wake:
|
||||
default:
|
||||
}
|
||||
started := time.Now()
|
||||
watch, command, stop := state.delivery(started)
|
||||
frame := roverFrame{}
|
||||
if command != nil {
|
||||
frame.Session, _ = command["id"].(string)
|
||||
frame.Sequence, _ = command["sequence"].(float64)
|
||||
frame.TTLMS, _ = command["ttl_ms"].(float64)
|
||||
}
|
||||
call, done := context.WithTimeout(ctx, 25*time.Millisecond)
|
||||
result, driverErr := p.Sensors.modelDriver(call, model, "/remote", map[string]any{"watch": watch, "command": command, "relay_id": relay})
|
||||
done()
|
||||
frame.DriverMS = time.Since(started).Milliseconds()
|
||||
if driverErr != nil {
|
||||
state.stopStream()
|
||||
frame.Stage = "driver_transport"
|
||||
state.delivered(map[string]any{}, 0)
|
||||
} else {
|
||||
state.delivered(result, stop)
|
||||
frame.State, _ = result["state"].(string)
|
||||
}
|
||||
frame := delivery.run(ctx, p.Sensors, model, state, relay, started)
|
||||
diagnostic.record(started, frame)
|
||||
// New intent and stop signals bypass the periodic watchdog tick. The
|
||||
// buffered wake channel coalesces arrivals; it never queues commands.
|
||||
@@ -135,30 +118,86 @@ func (p *Pairing) runRoverChannel(parent context.Context, b CoreBinding) {
|
||||
done()
|
||||
}
|
||||
func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) {
|
||||
var diagnostic roverDiagnostics
|
||||
epoch, _ := base["relay_id"].(string)
|
||||
diagnostic := roverDiagnostics{lane: "telemetry", epoch: epoch, started: state.origin}
|
||||
var budgetAt time.Time
|
||||
var metadata roverMetadataEncoder
|
||||
connected := false
|
||||
for ctx.Err() == nil {
|
||||
if !connected {
|
||||
connected = roverConnectTelemetry(ctx, client, endpoint, base, state)
|
||||
budgetAt = time.Time{}
|
||||
metadata.reset()
|
||||
if !connected {
|
||||
if !roverWait(ctx, 250*time.Millisecond) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
// Keep transport liveness separate from sample freshness. A stamped
|
||||
// observation ages in transit; waiting for its reply cannot renew motion.
|
||||
started := time.Now()
|
||||
snapshot, _ := state.view()
|
||||
snapshot, sampleClock := state.telemetryView()
|
||||
payload := make(map[string]any, len(base)+1)
|
||||
for k, v := range base {
|
||||
payload[k] = v
|
||||
}
|
||||
payload["rover"] = snapshot
|
||||
state.mu.Lock()
|
||||
budgetInterval := state.budgetInterval
|
||||
compact := state.roverDetails
|
||||
state.mu.Unlock()
|
||||
if compact {
|
||||
live, details := metadata.encode(snapshot, started)
|
||||
if details != nil {
|
||||
payload["rover"], payload["rover_details_v1"] = live, details
|
||||
}
|
||||
}
|
||||
if state.budget != nil && (!budgetInterval || budgetAt.IsZero() || started.Sub(budgetAt) >= time.Second) {
|
||||
payload["link_budget"] = state.budget.Snapshot()
|
||||
budgetAt = started
|
||||
}
|
||||
requestClient := *client
|
||||
if sampleClock != nil {
|
||||
payload["sample_clock"] = sampleClock
|
||||
requestClient.Timeout = 2 * time.Second
|
||||
}
|
||||
state.mu.Lock()
|
||||
dedicated := state.diagnosticLane
|
||||
state.mu.Unlock()
|
||||
payload["diagnostic_lane_v1"] = dedicated
|
||||
payload["diagnostic_options_v1"] = true
|
||||
if !dedicated {
|
||||
if dev := state.devPayload(); dev != nil {
|
||||
payload["diagnostics"] = dev
|
||||
payload["diagnostic_relay_ack_v1"] = true
|
||||
}
|
||||
}
|
||||
marshalAt := time.Now()
|
||||
raw, _ := json.Marshal(payload)
|
||||
marshalMS := float64(time.Since(marshalAt).Microseconds()) / 1000
|
||||
state.budget.ObserveCriticalBytes(len(raw))
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", endpoint+"/v1/node/rover", bytes.NewReader(raw))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
frame := roverFrame{}
|
||||
var trace *roverHTTPTrace
|
||||
if state.devTraceEnabled() {
|
||||
trace = newRoverHTTPTrace(started, len(raw))
|
||||
req = req.WithContext(trace.context(req.Context()))
|
||||
}
|
||||
frame := roverFrame{MarshalMS: marshalMS, RequestBytes: len(raw), ReleaseConfirmed: roverReleaseEvidence(snapshot)}
|
||||
frame.State, _ = snapshot["state"].(string)
|
||||
if frame.State == "preparing" || frame.State == "ready" || frame.State == "driving" || frame.State == "stopping" {
|
||||
frame.Session, _ = snapshot["session_id"].(string)
|
||||
}
|
||||
response, err := client.Do(req)
|
||||
processingMS := 0.0
|
||||
response, err := requestClient.Do(req)
|
||||
if err != nil {
|
||||
frame.Stage = "telemetry_transport"
|
||||
} else {
|
||||
frame.Status = response.StatusCode
|
||||
var out roverStreamReply
|
||||
readErr := json.NewDecoder(io.LimitReader(response.Body, 32768)).Decode(&out)
|
||||
readErr := json.NewDecoder(io.LimitReader(response.Body, 128*1024)).Decode(&out)
|
||||
response.Body.Close()
|
||||
if readErr != nil || response.StatusCode != 200 {
|
||||
frame.Stage = "telemetry_response"
|
||||
@@ -166,10 +205,29 @@ func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, b
|
||||
frame.Stage = "clock_invalid"
|
||||
state.stopStream()
|
||||
} else {
|
||||
processingMS = out.CoreProcessingMS
|
||||
state.mu.Lock()
|
||||
state.diagnosticPending = out.DiagnosticsPending
|
||||
hasIntent := state.command != nil
|
||||
state.mu.Unlock()
|
||||
state.budget.SetControl(roverControlActive(snapshot, hasIntent, out.ControlActive))
|
||||
state.setWatch(out.Watch)
|
||||
state.setDev(out.Diagnostics)
|
||||
}
|
||||
}
|
||||
if frame.Stage != "" {
|
||||
connected = false
|
||||
}
|
||||
frame.CoreProcessingMS = processingMS
|
||||
frame.CoreMS = time.Since(started).Milliseconds()
|
||||
if frame.Stage == "" || frame.Stage == "telemetry_transport" {
|
||||
state.budget.ObserveExchange(time.Since(started), processingMS, frame.Stage == "")
|
||||
}
|
||||
details := map[string]any{"elapsed_ms": frame.CoreMS, "http_status": frame.Status, "error_stage": frame.Stage, "reason": roverErrorKind(err), "marshal_ms": marshalMS, "request_bytes": len(raw), "core_processing_ms": processingMS, "epoch": epoch, "sample_mono_ms": float64(started.Sub(state.origin).Microseconds()) / 1000}
|
||||
if trace != nil {
|
||||
details["transport"] = trace.snapshot()
|
||||
}
|
||||
state.recordDev("telemetry", details)
|
||||
diagnostic.record(started, frame)
|
||||
_, watch := state.view()
|
||||
delay := 500 * time.Millisecond
|
||||
@@ -182,18 +240,29 @@ func roverTelemetry(ctx context.Context, client *http.Client, endpoint string, b
|
||||
}
|
||||
}
|
||||
func roverCommands(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) {
|
||||
defer state.budget.DisableDatagramFeedback()
|
||||
for ctx.Err() == nil {
|
||||
_, watch := state.view()
|
||||
if !watch {
|
||||
state.budget.DisableDatagramFeedback()
|
||||
if !roverWait(ctx, 50*time.Millisecond) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
err := roverReadStream(ctx, client, endpoint, base, state)
|
||||
state.mu.Lock()
|
||||
datagram := state.latestDatagram
|
||||
state.mu.Unlock()
|
||||
var err error
|
||||
if datagram {
|
||||
err = roverReadDatagram(ctx, client, endpoint, base, state)
|
||||
} else {
|
||||
err = roverReadStream(ctx, client, endpoint, base, state)
|
||||
}
|
||||
state.stopStream()
|
||||
if err != nil && ctx.Err() == nil {
|
||||
log.Printf("{\"event\":\"rover-command-stream\",\"state\":\"disconnected\"}")
|
||||
log.Printf("{\"event\":\"rover-command-stream\",\"state\":\"disconnected\",\"reason\":%q}", roverErrorKind(err))
|
||||
state.recordDev("stream_disconnected", map[string]any{"reason": roverErrorKind(err)})
|
||||
}
|
||||
if !roverWait(ctx, 250*time.Millisecond) {
|
||||
return
|
||||
@@ -223,6 +292,7 @@ func roverReadStream(parent context.Context, client *http.Client, endpoint strin
|
||||
first := true
|
||||
for {
|
||||
line, err := reader.ReadSlice('\n')
|
||||
received := time.Now()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -239,6 +309,7 @@ func roverReadStream(parent context.Context, client *http.Client, endpoint strin
|
||||
if !state.accept(out) {
|
||||
return errors.New("invalid stream intent")
|
||||
}
|
||||
state.receivedFrame(out, received)
|
||||
if !out.Watch {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package node
|
||||
|
||||
// A terminal status is history, not continuing command authority. The driver
|
||||
// reports its actual worker/lease, including cleanup before the worker exits.
|
||||
// Older drivers use explicit known states; an unknown projection reserves
|
||||
// control until a fresh authoritative snapshot arrives.
|
||||
func roverControlActive(snapshot map[string]any, hasIntent bool, coreActive *bool) bool {
|
||||
if hasIntent || (coreActive != nil && *coreActive) {
|
||||
return true
|
||||
}
|
||||
if active, ok := snapshot["control_active"].(bool); ok {
|
||||
return active
|
||||
}
|
||||
switch snapshot["state"] {
|
||||
case "observing", "stopped", "receiver", "fault":
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRoverActivitySeparatesTerminalHistoryFromLiveAuthority(t *testing.T) {
|
||||
yes, no := true, false
|
||||
for _, state := range []string{"fault", "stopped", "receiver", "observing"} {
|
||||
for _, explicit := range []bool{false, true} {
|
||||
snapshot := map[string]any{"state": state, "release_confirmed": false}
|
||||
if explicit {
|
||||
snapshot["control_active"] = false
|
||||
}
|
||||
if roverControlActive(snapshot, false, &no) {
|
||||
t.Fatal("terminal history took control reserve", state)
|
||||
}
|
||||
if !roverControlActive(snapshot, true, &no) || !roverControlActive(snapshot, false, &yes) {
|
||||
t.Fatal("live intent lost priority", state)
|
||||
}
|
||||
snapshot["control_active"] = true
|
||||
if !roverControlActive(snapshot, false, &no) {
|
||||
t.Fatal("live cleanup worker lost priority", state)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, state := range []string{"preparing", "ready", "driving", "stopping", "", "future-state"} {
|
||||
if !roverControlActive(map[string]any{"state": state}, false, nil) {
|
||||
t.Fatal("legacy active/unknown state lost reserve", state)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalFaultAllowsInventoryWithoutAnObservatoryOrCommandFrames(t *testing.T) {
|
||||
b, now := testBudget(t)
|
||||
b.SetControl(true)
|
||||
b.ObserveCommandFrame(200*time.Millisecond, 20*time.Millisecond)
|
||||
if !b.commandLimited(*now) {
|
||||
t.Fatal("missing initial command pressure")
|
||||
}
|
||||
b.effective = float64(b.policy.ReserveKbps + 128)
|
||||
delivered := 0
|
||||
stopped := map[string]any{"state": "fault", "control_active": false, "release_confirmed": false}
|
||||
for elapsed := time.Duration(0); elapsed < 20*time.Second; elapsed += 10 * time.Millisecond {
|
||||
*now = now.Add(10 * time.Millisecond)
|
||||
// A closed observatory intentionally sends no stream frames. Driver and
|
||||
// board telemetry still refresh their actual inactive state.
|
||||
if elapsed%(500*time.Millisecond) == 0 {
|
||||
b.SetControl(roverControlActive(stopped, false, nil))
|
||||
}
|
||||
b.ObserveCommandSilence()
|
||||
if b.commandLimited(*now) {
|
||||
t.Fatal("closed observer starved inventory again")
|
||||
}
|
||||
if delivered < 40*1024 {
|
||||
size := min(linkPacket, 40*1024-delivered)
|
||||
if ok, _ := b.Try("inventory", size); ok {
|
||||
delivered += size
|
||||
}
|
||||
}
|
||||
}
|
||||
if delivered != 40*1024 {
|
||||
t.Fatal("inventory never recovered", delivered)
|
||||
}
|
||||
// Resuming real control must still respond to a new delayed frame.
|
||||
b.SetControl(true)
|
||||
b.ObserveCommandFrame(151*time.Millisecond, 20*time.Millisecond)
|
||||
if ok, _ := b.Try("inventory", 100); ok {
|
||||
t.Fatal("inventory bypassed active command pressure")
|
||||
}
|
||||
if b.reserve(*now) < 512 {
|
||||
t.Fatal("control reserve changed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type roverDatagramGrant struct {
|
||||
Channel string `json:"channel"`
|
||||
SendKey string `json:"send_key"`
|
||||
ReceiveKey string `json:"receive_key"`
|
||||
Port int `json:"port"`
|
||||
MaxPacket int `json:"max_packet"`
|
||||
Lifetime int `json:"lifetime_s"`
|
||||
}
|
||||
type roverDatagramFrame struct {
|
||||
Probe uint64 `json:"probe"`
|
||||
ProbeClock roverClock `json:"probe_clock"`
|
||||
Reply roverStreamReply `json:"reply"`
|
||||
}
|
||||
type roverDatagramReceived struct {
|
||||
raw []byte
|
||||
counter uint64
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func roverReadDatagram(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) error {
|
||||
// Only the paired mTLS connection can disclose the ephemeral keys. No UDP
|
||||
// packet establishes identity, grants motion or chooses a different endpoint.
|
||||
raw, _ := json.Marshal(base)
|
||||
setup, cancel := context.WithTimeout(ctx, 2500*time.Millisecond)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(setup, "POST", endpoint+"/v1/node/rover-datagram", bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var grant roverDatagramGrant
|
||||
err = json.NewDecoder(io.LimitReader(response.Body, 2048)).Decode(&grant)
|
||||
response.Body.Close()
|
||||
if err != nil || response.StatusCode != 200 || grant.Port < 1 || grant.Port > 65535 || grant.MaxPacket != roverDatagramLimit || grant.Lifetime != 86400 {
|
||||
return errors.New("datagram negotiation rejected")
|
||||
}
|
||||
tx, err := newRoverDatagramCipher(grant.Channel, grant.SendKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rx, err := newRoverDatagramCipher(grant.Channel, grant.ReceiveKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parsed, err := url.Parse(endpoint)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Hostname() == "" {
|
||||
return errors.New("invalid datagram endpoint")
|
||||
}
|
||||
address, err := net.ResolveUDPAddr("udp4", net.JoinHostPort(parsed.Hostname(), strconv.Itoa(grant.Port)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
conn, err := net.DialUDP("udp4", nil, address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return roverReceiveDatagrams(ctx, conn, tx, rx, grant.Channel, state)
|
||||
}
|
||||
|
||||
func roverReceiveDatagrams(ctx context.Context, conn *net.UDPConn, tx, rx *roverDatagramCipher, channel string, state *roverStreamState) error {
|
||||
// A one-element mailbox replaces unread datagrams; no old command backlog
|
||||
// is replayed after a scheduling pause. Only authenticated packets enter it.
|
||||
incoming := make(chan roverDatagramReceived, 1)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for {
|
||||
packet := make([]byte, roverDatagramLimit+1)
|
||||
n, err := conn.Read(packet)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
at := time.Now()
|
||||
raw, counter, ok := rx.open(packet[:n])
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
item := roverDatagramReceived{raw, counter, at}
|
||||
select {
|
||||
case incoming <- item:
|
||||
default:
|
||||
select {
|
||||
case <-incoming:
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case incoming <- item:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
defer func() { conn.Close(); <-done }()
|
||||
ticker := time.NewTicker(100 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
// Startup has no command authority. Once a valid first frame arrives, the
|
||||
// exact same 350 ms authority guard applies. Silence does not close a
|
||||
// usable UDP socket; a separate 2 s bound renegotiates expired transport keys.
|
||||
lastFrame := time.Now()
|
||||
seenFrame, suspended := false, false
|
||||
guard := time.NewTimer(2 * time.Second)
|
||||
defer guard.Stop()
|
||||
state.budget.EnableDatagramFeedback()
|
||||
suspend := func() {
|
||||
if suspended {
|
||||
return
|
||||
}
|
||||
state.stopStream() // Retire authority now; never replay it on recovery.
|
||||
suspended = true
|
||||
state.recordDev("stream_suspended", map[string]any{"reason": "datagram_stream_deadline", "channel": channel})
|
||||
}
|
||||
type probeSample struct {
|
||||
at time.Time
|
||||
optionalBytes uint64
|
||||
}
|
||||
probes := map[uint64]probeSample{}
|
||||
send := func() error {
|
||||
packet, err := tx.seal([]byte("{}"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
probes[tx.sent] = probeSample{now, state.budget.DatagramFeedbackMark()}
|
||||
state.budget.ObserveCriticalBytes(len(packet))
|
||||
for seq, sample := range probes {
|
||||
if now.Sub(sample.at) > 2*time.Second {
|
||||
delete(probes, seq)
|
||||
}
|
||||
}
|
||||
conn.SetWriteDeadline(now.Add(25 * time.Millisecond))
|
||||
_, err = conn.Write(packet)
|
||||
return err
|
||||
}
|
||||
if err := send(); err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-done:
|
||||
return errors.New("datagram socket closed")
|
||||
case <-guard.C:
|
||||
// A stale mailbox item may have suspended authority before this
|
||||
// timer branch runs. Only elapsed silence expires the transport;
|
||||
// suspension itself is never evidence of a 2 s link outage.
|
||||
if time.Since(lastFrame) >= 2*time.Second {
|
||||
return errors.New("datagram link timeout")
|
||||
}
|
||||
suspend()
|
||||
guard.Reset(max(0, 2*time.Second-time.Since(lastFrame)))
|
||||
case <-ticker.C:
|
||||
if err := send(); err != nil {
|
||||
return err
|
||||
}
|
||||
case item := <-incoming:
|
||||
// Check elapsed time even when both a packet and the timer are ready.
|
||||
// Receipt can restore transport health, never an interrupted lease.
|
||||
if time.Since(lastFrame) >= 2*time.Second {
|
||||
return errors.New("datagram link timeout")
|
||||
}
|
||||
if seenFrame && time.Since(lastFrame) >= 350*time.Millisecond {
|
||||
suspend()
|
||||
}
|
||||
if time.Since(item.at) >= 350*time.Millisecond {
|
||||
suspend()
|
||||
continue // Discard delayed local work without closing the receiver.
|
||||
}
|
||||
var frame roverDatagramFrame
|
||||
if json.Unmarshal(item.raw, &frame) != nil {
|
||||
return errors.New("invalid datagram frame")
|
||||
}
|
||||
if sent, ok := probes[frame.Probe]; ok {
|
||||
if !state.sampleClock(frame.ProbeClock, sent.at, item.at) {
|
||||
return errors.New("invalid datagram clock")
|
||||
}
|
||||
state.budget.ObserveDatagramFeedback(item.at.Sub(sent.at), frame.Reply.Clock.MonotonicMS-frame.ProbeClock.MonotonicMS, sent.optionalBytes)
|
||||
for seq := range probes {
|
||||
if seq <= frame.Probe {
|
||||
delete(probes, seq)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !state.accept(frame.Reply) {
|
||||
return errors.New("invalid datagram intent")
|
||||
}
|
||||
state.receivedFrame(frame.Reply, item.at)
|
||||
state.recordDev("datagram_received", map[string]any{"channel": channel, "packet_sequence": item.counter, "bytes": len(item.raw) + 44})
|
||||
if !frame.Reply.Watch {
|
||||
return nil
|
||||
}
|
||||
if suspended {
|
||||
state.recordDev("stream_resumed", map[string]any{"channel": channel, "gap_ms": float64(item.at.Sub(lastFrame).Microseconds()) / 1000})
|
||||
}
|
||||
lastFrame, seenFrame, suspended = item.at, true, false
|
||||
guard.Reset(max(0, 350*time.Millisecond-time.Since(item.at)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
)
|
||||
|
||||
const roverDatagramLimit = 1200
|
||||
const roverDatagramCounterLimit = 1<<32 - 1
|
||||
|
||||
// Keys are independent in each direction and exist only for this negotiated
|
||||
// generation. The authenticated counter is both nonce and anti-replay order.
|
||||
type roverDatagramCipher struct {
|
||||
channel []byte
|
||||
aead cipher.AEAD
|
||||
sent, received uint64
|
||||
}
|
||||
|
||||
func newRoverDatagramCipher(channel, key string) (*roverDatagramCipher, error) {
|
||||
id, e1 := hex.DecodeString(channel)
|
||||
raw, e2 := hex.DecodeString(key)
|
||||
if e1 != nil || e2 != nil || len(id) != 16 || len(raw) != 32 {
|
||||
return nil, errors.New("invalid datagram key")
|
||||
}
|
||||
block, err := aes.NewCipher(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aead, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &roverDatagramCipher{channel: id, aead: aead}, nil
|
||||
}
|
||||
func (c *roverDatagramCipher) seal(raw []byte) ([]byte, error) {
|
||||
if len(raw)+44 > roverDatagramLimit || c.sent >= roverDatagramCounterLimit {
|
||||
return nil, errors.New("datagram bound exceeded")
|
||||
}
|
||||
c.sent++
|
||||
header := make([]byte, 28)
|
||||
copy(header, "MCR1")
|
||||
copy(header[4:], c.channel)
|
||||
binary.BigEndian.PutUint64(header[20:], c.sent)
|
||||
nonce := make([]byte, 12)
|
||||
copy(nonce[4:], header[20:])
|
||||
return c.aead.Seal(header, nonce, raw, header), nil
|
||||
}
|
||||
func (c *roverDatagramCipher) open(packet []byte) ([]byte, uint64, bool) {
|
||||
if len(packet) <= 44 || len(packet) > roverDatagramLimit || string(packet[:4]) != "MCR1" || !bytes.Equal(packet[4:20], c.channel) {
|
||||
return nil, 0, false
|
||||
}
|
||||
counter := binary.BigEndian.Uint64(packet[20:28])
|
||||
if counter <= c.received || counter > roverDatagramCounterLimit {
|
||||
return nil, 0, false
|
||||
}
|
||||
nonce := make([]byte, 12)
|
||||
copy(nonce[4:], packet[20:28])
|
||||
raw, err := c.aead.Open(nil, nonce, packet[28:], packet[:28])
|
||||
if err != nil {
|
||||
return nil, 0, false
|
||||
}
|
||||
c.received = counter
|
||||
return raw, counter, true
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRoverDatagramAuthenticationAndOrdering(t *testing.T) {
|
||||
channel := "11111111111111111111111111111111"
|
||||
key := "2222222222222222222222222222222222222222222222222222222222222222"
|
||||
tx, _ := newRoverDatagramCipher(channel, key)
|
||||
rx, _ := newRoverDatagramCipher(channel, key)
|
||||
a, _ := tx.seal([]byte("{}"))
|
||||
b, _ := tx.seal([]byte("{\"fresh\":true}"))
|
||||
corrupt := append([]byte(nil), b...)
|
||||
corrupt[len(corrupt)-1] ^= 1
|
||||
if _, _, ok := rx.open(corrupt); ok {
|
||||
t.Fatal("forgery accepted")
|
||||
}
|
||||
if raw, seq, ok := rx.open(b); !ok || seq != 2 || !bytes.Equal(raw, []byte("{\"fresh\":true}")) {
|
||||
t.Fatal("fresh frame rejected")
|
||||
}
|
||||
for _, packet := range [][]byte{a, b, append(b, 0), b[:20]} {
|
||||
if _, _, ok := rx.open(packet); ok {
|
||||
t.Fatal("stale/malformed accepted")
|
||||
}
|
||||
}
|
||||
other, _ := newRoverDatagramCipher(channel, "3333333333333333333333333333333333333333333333333333333333333333")
|
||||
if _, _, ok := other.open(b); ok {
|
||||
t.Fatal("opposite direction accepted")
|
||||
}
|
||||
tx.sent = roverDatagramCounterLimit
|
||||
if _, err := tx.seal([]byte("{}")); err == nil {
|
||||
t.Fatal("counter wrapped")
|
||||
}
|
||||
if _, err := rx.seal(make([]byte, 1200)); err == nil {
|
||||
t.Fatal("oversized datagram")
|
||||
}
|
||||
if hex.EncodeToString(a) != "4d43523111111111111111111111111111111111000000000000000108b7c9b2eb8c526f9dc03ac92264617fd09b" {
|
||||
t.Fatal("Python/Go vector mismatch")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package node
|
||||
|
||||
// Bounded loopback receiver tests. No driver, serial port or physical actuator.
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type continuityRig struct {
|
||||
t *testing.T
|
||||
state *roverStreamState
|
||||
peer *net.UDPConn
|
||||
address *net.UDPAddr
|
||||
tx, rx *roverDatagramCipher
|
||||
result chan error
|
||||
ended bool
|
||||
origin time.Time
|
||||
}
|
||||
|
||||
func newContinuityRig(t *testing.T) *continuityRig {
|
||||
t.Helper()
|
||||
peer, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.ParseIP("127.0.0.1")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conn, err := net.DialUDP("udp4", nil, peer.LocalAddr().(*net.UDPAddr))
|
||||
if err != nil {
|
||||
peer.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
const channel = "11111111111111111111111111111111"
|
||||
const a = "2222222222222222222222222222222222222222222222222222222222222222"
|
||||
const b = "3333333333333333333333333333333333333333333333333333333333333333"
|
||||
tx, _ := newRoverDatagramCipher(channel, a)
|
||||
rx, _ := newRoverDatagramCipher(channel, b)
|
||||
ptx, _ := newRoverDatagramCipher(channel, b)
|
||||
prx, _ := newRoverDatagramCipher(channel, a)
|
||||
now := time.Now()
|
||||
s := newRoverStreamState(now)
|
||||
s.budget, err = OpenLinkBudget("")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.setDev(map[string]any{"id": testClockID, "enabled": true})
|
||||
f := &continuityRig{t: t, state: s, peer: peer, tx: ptx, rx: prx, result: make(chan error, 1), origin: now}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
go func() { f.result <- roverReceiveDatagrams(ctx, conn, tx, rx, channel, s) }()
|
||||
t.Cleanup(func() {
|
||||
cancel()
|
||||
peer.Close()
|
||||
if !f.ended {
|
||||
select {
|
||||
case <-f.result:
|
||||
case <-time.After(time.Second):
|
||||
t.Error("receiver leaked")
|
||||
}
|
||||
}
|
||||
})
|
||||
f.send("", 0)
|
||||
f.ackStop()
|
||||
return f
|
||||
}
|
||||
func (f *continuityRig) clock() roverClock {
|
||||
return roverClock{testClockID, 10000 + float64(time.Since(f.origin).Microseconds())/1000}
|
||||
}
|
||||
func (f *continuityRig) send(id string, seq float64) []byte {
|
||||
f.t.Helper()
|
||||
f.peer.SetReadDeadline(time.Now().Add(time.Second))
|
||||
packet := make([]byte, 1201)
|
||||
n, addr, err := f.peer.ReadFromUDP(packet)
|
||||
if err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
_, probe, ok := f.rx.open(packet[:n])
|
||||
if !ok {
|
||||
f.t.Fatal("invalid probe")
|
||||
}
|
||||
f.address = addr
|
||||
clock := f.clock()
|
||||
reply := roverStreamReply{Watch: true, Clock: clock}
|
||||
if id != "" {
|
||||
reply.Command = map[string]any{"id": id, "sequence": seq, "left": float64(0), "right": float64(0), "settings": map[string]any{}, "expires_mono_ms": clock.MonotonicMS + 400}
|
||||
}
|
||||
raw, _ := json.Marshal(roverDatagramFrame{Probe: probe, ProbeClock: clock, Reply: reply})
|
||||
sealed, err := f.tx.seal(raw)
|
||||
if err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
f.state.mu.Lock()
|
||||
before := f.state.streamReceived
|
||||
f.state.mu.Unlock()
|
||||
if _, err = f.peer.WriteToUDP(sealed, addr); err != nil {
|
||||
f.t.Fatal(err)
|
||||
}
|
||||
f.wait(func() bool { f.state.mu.Lock(); defer f.state.mu.Unlock(); return f.state.streamReceived.After(before) }, time.Second)
|
||||
return sealed
|
||||
}
|
||||
func (f *continuityRig) wait(check func() bool, limit time.Duration) {
|
||||
f.t.Helper()
|
||||
until := time.Now().Add(limit)
|
||||
for time.Now().Before(until) {
|
||||
if check() {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case err := <-f.result:
|
||||
f.ended = true
|
||||
f.t.Fatalf("transport ended instead of staying connected: %v", err)
|
||||
default:
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
f.t.Fatal("bounded condition not reached")
|
||||
}
|
||||
func (f *continuityRig) ackStop() {
|
||||
_, _, revision := f.state.delivery(time.Now())
|
||||
f.state.delivered(map[string]any{"state": "stopped", "release_confirmed": true}, revision)
|
||||
}
|
||||
func (f *continuityRig) command() map[string]any { _, c, _ := f.state.delivery(time.Now()); return c }
|
||||
func (f *continuityRig) awaitSafetyStop() {
|
||||
f.t.Helper()
|
||||
f.wait(func() bool { f.state.mu.Lock(); defer f.state.mu.Unlock(); return f.state.stopPending }, 450*time.Millisecond)
|
||||
if c := f.command(); c != nil {
|
||||
f.t.Fatal("motion authority retained after silence")
|
||||
}
|
||||
}
|
||||
func TestRoverDatagramSilenceStopsAuthorityWithoutClosingTransport(t *testing.T) {
|
||||
f := newContinuityRig(t)
|
||||
old := "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
|
||||
f.send(old, 1)
|
||||
if f.command() == nil {
|
||||
t.Fatal("neutral fixture not admitted")
|
||||
}
|
||||
f.awaitSafetyStop()
|
||||
f.ackStop()
|
||||
f.send(old, 2)
|
||||
if f.command() != nil {
|
||||
t.Fatal("retired authority revived")
|
||||
}
|
||||
f.send("cccccccccccccccccccccccccccccccc", 1)
|
||||
if c := f.command(); c == nil || c["left"] != float64(0) || c["right"] != float64(0) {
|
||||
t.Fatal("fresh neutral identity not admitted on existing transport")
|
||||
}
|
||||
}
|
||||
func TestRoverDatagramReplayCannotKeepAuthorityAlive(t *testing.T) {
|
||||
f := newContinuityRig(t)
|
||||
raw := f.send("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 1)
|
||||
for n := 0; n < 8; n++ {
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
f.peer.WriteToUDP(raw, f.address)
|
||||
}
|
||||
f.awaitSafetyStop()
|
||||
f.ackStop()
|
||||
f.send("cccccccccccccccccccccccccccccccc", 1)
|
||||
if f.command() == nil {
|
||||
t.Fatal("authenticated channel failed to recover")
|
||||
}
|
||||
}
|
||||
func TestRoverDatagramProlongedSilenceRenegotiatesAfterSafetyStop(t *testing.T) {
|
||||
f := newContinuityRig(t)
|
||||
f.send("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 1)
|
||||
f.awaitSafetyStop()
|
||||
f.ackStop()
|
||||
select {
|
||||
case err := <-f.result:
|
||||
f.ended = true
|
||||
if err == nil || err.Error() != "datagram link timeout" {
|
||||
t.Fatalf("wrong reconnect cause: %v", err)
|
||||
}
|
||||
case <-time.After(2100 * time.Millisecond):
|
||||
t.Fatal("silent transport did not renegotiate")
|
||||
}
|
||||
if f.command() != nil {
|
||||
t.Fatal("authority retained during reconnect")
|
||||
}
|
||||
}
|
||||
|
||||
// Both the expired guard and a stale mailbox item can be ready after local
|
||||
// scheduling pauses. Exercise both select orders without a physical driver.
|
||||
func TestRoverDatagramDelayedLocalWorkRetainsRecoveryWindow(t *testing.T) {
|
||||
for attempt := 0; attempt < 12; attempt++ {
|
||||
t.Run(fmt.Sprint(attempt), func(t *testing.T) {
|
||||
f := newContinuityRig(t)
|
||||
f.send("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", 1)
|
||||
f.state.mu.Lock()
|
||||
previousCommand := f.state.command
|
||||
f.state.mu.Unlock()
|
||||
queue := func() {
|
||||
raw, _ := json.Marshal(roverDatagramFrame{Reply: roverStreamReply{Watch: true, Clock: f.clock(), Command: previousCommand}})
|
||||
packet, err := f.tx.seal(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = f.peer.WriteToUDP(packet, f.address); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
func() {
|
||||
f.state.mu.Lock()
|
||||
defer f.state.mu.Unlock()
|
||||
queue()
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
queue()
|
||||
time.Sleep(400 * time.Millisecond)
|
||||
}()
|
||||
f.awaitSafetyStop()
|
||||
f.ackStop()
|
||||
f.send("cccccccccccccccccccccccccccccccc", 1)
|
||||
if f.command() == nil {
|
||||
t.Fatal("fresh neutral authority not admitted after local pause")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package node
|
||||
|
||||
// Optional recorder transport is independent of the 25 ms motor-delivery path.
|
||||
// No files, controller queries, command retries or lease changes originate here.
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
func roverErrorKind(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return "deadline"
|
||||
}
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return "cancelled"
|
||||
}
|
||||
if errors.Is(err, io.EOF) {
|
||||
return "eof"
|
||||
}
|
||||
var n net.Error
|
||||
if errors.As(err, &n) && n.Timeout() {
|
||||
return "network_timeout"
|
||||
}
|
||||
switch err.Error() {
|
||||
case "stream rejected", "invalid command frame", "invalid stream clock", "invalid stream intent", "stream deadline":
|
||||
return err.Error()
|
||||
// These fixed, locally generated failures must remain distinguishable.
|
||||
// Never emit arbitrary transport errors: they can contain paired URLs.
|
||||
case "datagram negotiation rejected":
|
||||
return "datagram_negotiation_rejected"
|
||||
case "invalid datagram endpoint":
|
||||
return "datagram_endpoint_invalid"
|
||||
case "datagram socket closed":
|
||||
return "datagram_socket_closed"
|
||||
case "datagram link timeout":
|
||||
return "datagram_link_timeout"
|
||||
case "datagram stream deadline":
|
||||
return "datagram_stream_deadline"
|
||||
case "invalid datagram frame":
|
||||
return "datagram_frame_invalid"
|
||||
case "invalid datagram clock":
|
||||
return "datagram_clock_invalid"
|
||||
case "datagram receipt stale":
|
||||
return "datagram_receipt_stale"
|
||||
case "invalid datagram intent":
|
||||
return "datagram_intent_invalid"
|
||||
}
|
||||
return "transport_error" // Raw errors can contain private URLs; never emit them.
|
||||
}
|
||||
|
||||
func (s *roverStreamState) setDev(value map[string]any) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if value == nil {
|
||||
return
|
||||
}
|
||||
id, ok := value["id"].(string)
|
||||
enabled, valid := value["enabled"].(bool)
|
||||
if !ok || len(id) != 32 || !valid {
|
||||
return
|
||||
}
|
||||
if s.devID != id {
|
||||
s.devID = id
|
||||
s.devSequence = 0
|
||||
s.devRelayAfter = 0
|
||||
s.devEvents = nil
|
||||
s.devPacket = nil
|
||||
s.devBudgetAt = time.Time{}
|
||||
}
|
||||
s.devEnabled = enabled
|
||||
s.devDesired = make(map[string]any, len(value))
|
||||
for k, v := range value {
|
||||
if k != "relay_after" {
|
||||
s.devDesired[k] = v
|
||||
}
|
||||
}
|
||||
if ack, ok := finiteNumber(value["relay_after"]); ok && ack >= 0 && ack <= float64(s.devSequence) {
|
||||
s.devRelayAfter = max(s.devRelayAfter, int64(ack))
|
||||
}
|
||||
s.devAfter = value["after"]
|
||||
}
|
||||
func devOption(options any, key string) bool {
|
||||
if value, ok := options.(map[string]any); ok {
|
||||
if flag, ok := value[key].(bool); ok {
|
||||
return flag
|
||||
}
|
||||
}
|
||||
return true // Legacy capture keeps its original explicit behavior.
|
||||
}
|
||||
|
||||
func (s *roverStreamState) recordDev(event string, data map[string]any) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.devID == "" || !s.devEnabled || !devOption(s.devDesired["options"], "network") {
|
||||
return
|
||||
}
|
||||
// UTC microseconds fit exactly in JSON and keep sequence unique across relay restarts.
|
||||
s.devSequence = max(s.devSequence+1, time.Now().UnixMicro())
|
||||
row := map[string]any{"source": "node", "event": event, "record_sequence": s.devSequence,
|
||||
"at_utc": time.Now().UTC().Format(time.RFC3339Nano), "monotonic_ms": float64(time.Since(s.origin).Microseconds()) / 1000}
|
||||
for k, v := range data {
|
||||
row[k] = v
|
||||
}
|
||||
s.devEvents = append(s.devEvents, row)
|
||||
if len(s.devEvents) > 64 {
|
||||
s.devEvents = s.devEvents[len(s.devEvents)-64:]
|
||||
}
|
||||
}
|
||||
func (s *roverStreamState) devRequest() map[string]any {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.devID == "" {
|
||||
return nil
|
||||
}
|
||||
if !s.devEnabled && s.devDesired["export"] == nil {
|
||||
if storage, ok := s.devPacket["storage"].(map[string]any); ok && storage["closed"] == true && (!devOption(s.devDesired["options"], "live") || s.devAfter == s.devPacket["sequence"]) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
result := map[string]any{}
|
||||
for k, v := range s.devDesired {
|
||||
result[k] = v
|
||||
}
|
||||
result["relay_events"] = append([]map[string]any{}, s.devEvents...)
|
||||
return result
|
||||
}
|
||||
func (s *roverStreamState) devPayload() map[string]any {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.devID == "" {
|
||||
return nil
|
||||
}
|
||||
result := map[string]any{"id": s.devID, "frames": []any{}, "vehicle": s.devDesired["vehicle"]}
|
||||
for k, v := range s.devPacket {
|
||||
result[k] = v
|
||||
}
|
||||
if !s.devEnabled && s.devDesired["export"] == nil {
|
||||
if storage, ok := s.devPacket["storage"].(map[string]any); ok && storage["closed"] == true && (!devOption(s.devDesired["options"], "live") || s.devAfter == s.devPacket["sequence"]) {
|
||||
return map[string]any{"id": s.devID, "active": false, "storage": storage, "frames": []any{}}
|
||||
}
|
||||
}
|
||||
pending := []map[string]any{}
|
||||
for _, event := range s.devEvents {
|
||||
if seq, ok := event["record_sequence"].(int64); ok && seq > s.devRelayAfter {
|
||||
pending = append(pending, event)
|
||||
}
|
||||
}
|
||||
if devOption(s.devDesired["options"], "live") {
|
||||
result["relay_events"] = pending
|
||||
} else {
|
||||
result["relay_events"] = []any{}
|
||||
result["frames"] = []any{}
|
||||
}
|
||||
return result
|
||||
}
|
||||
func (p *Pairing) roverDev(ctx context.Context, model *sensorModel, state *roverStreamState) {
|
||||
for ctx.Err() == nil {
|
||||
state.recordBudgetDev(time.Now())
|
||||
if request := state.devRequest(); request != nil {
|
||||
call, done := context.WithTimeout(ctx, 3*time.Second)
|
||||
result, err := p.Sensors.modelDriver(call, model, "/drive-trace", request)
|
||||
done()
|
||||
if err == nil {
|
||||
raw, _ := json.Marshal(result)
|
||||
if len(raw) <= 256*1024 {
|
||||
state.mu.Lock()
|
||||
state.devPacket = result
|
||||
state.mu.Unlock()
|
||||
}
|
||||
} else {
|
||||
state.recordDev("diagnostics_transport", map[string]any{"reason": roverErrorKind(err)})
|
||||
state.mu.Lock()
|
||||
if state.devPacket == nil {
|
||||
state.devPacket = map[string]any{}
|
||||
}
|
||||
state.devPacket["transport_error"] = roverErrorKind(err)
|
||||
state.mu.Unlock()
|
||||
}
|
||||
}
|
||||
if !roverWait(ctx, 100*time.Millisecond) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Budget evidence belongs to the optional local recorder lane, never to the
|
||||
// motor delivery loop. One snapshot per second, and none outside DEV.
|
||||
func (s *roverStreamState) recordBudgetDev(now time.Time) {
|
||||
s.mu.Lock()
|
||||
active := s.devEnabled && s.devID != "" && s.budget != nil &&
|
||||
(s.devBudgetAt.IsZero() || now.Sub(s.devBudgetAt) >= time.Second)
|
||||
if active {
|
||||
s.devBudgetAt = now
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if active {
|
||||
s.recordDev("link_budget", map[string]any{"budget": s.budget.Snapshot()})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDevCaptureOptInAndOff(t *testing.T) {
|
||||
s := newRoverStreamState(time.Now())
|
||||
s.recordDev("delivery", nil)
|
||||
if s.devRequest() != nil || len(s.devEvents) != 0 {
|
||||
t.Fatal("disabled recorder must be inert")
|
||||
}
|
||||
s.setDev(map[string]any{"id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "enabled": true, "after": float64(0)})
|
||||
s.recordDev("delivery", map[string]any{"sequence": 42})
|
||||
if len(s.devEvents) != 1 || s.devRequest()["enabled"] != true {
|
||||
t.Fatal("capture not enabled")
|
||||
}
|
||||
if s.devEvents[0]["sequence"] != 42 || s.devEvents[0]["record_sequence"].(int64) <= 42 {
|
||||
t.Fatal("command and trace cursors collide")
|
||||
}
|
||||
s.setDev(map[string]any{"id": s.devID, "enabled": false, "after": float64(0)})
|
||||
s.recordDev("late", nil)
|
||||
if len(s.devEvents) != 1 {
|
||||
t.Fatal("capture continues after off")
|
||||
}
|
||||
s.devPacket = map[string]any{"sequence": float64(0), "storage": map[string]any{"closed": true}}
|
||||
if s.devRequest() != nil {
|
||||
t.Fatal("finished capture keeps polling driver")
|
||||
}
|
||||
if _, ok := s.devPayload()["relay_events"]; ok {
|
||||
t.Fatal("finished capture keeps sending verbose events")
|
||||
}
|
||||
}
|
||||
func TestDevDoesNotExtendMotionLease(t *testing.T) {
|
||||
s := newRoverStreamState(time.Now())
|
||||
before := s.stopRevision
|
||||
s.setDev(map[string]any{"id": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "enabled": true, "after": float64(0)})
|
||||
if s.command != nil || s.stopRevision != before || !s.stopPending {
|
||||
t.Fatal("DEV changed motion authority")
|
||||
}
|
||||
for i := 0; i < 100; i++ {
|
||||
s.recordDev("sample", nil)
|
||||
}
|
||||
if len(s.devEvents) != 64 {
|
||||
t.Fatal("unbounded relay RAM")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDevNetworkAcknowledgementDoesNotDropOnboardRecords(t *testing.T) {
|
||||
s := newRoverStreamState(time.Now())
|
||||
id := "cccccccccccccccccccccccccccccccc"
|
||||
s.setDev(map[string]any{"id": id, "enabled": true, "after": float64(0)})
|
||||
s.recordDev("first", nil)
|
||||
first := s.devSequence
|
||||
s.recordDev("second", nil)
|
||||
s.setDev(map[string]any{"id": id, "enabled": true, "after": float64(0), "relay_after": float64(first)})
|
||||
network := s.devPayload()["relay_events"].([]map[string]any)
|
||||
if len(network) != 1 || network[0]["event"] != "second" {
|
||||
t.Fatal("acknowledged network events retransmitted")
|
||||
}
|
||||
request := s.devRequest()
|
||||
if _, exists := request["relay_after"]; exists {
|
||||
t.Fatal("Core ack leaked into native protocol")
|
||||
}
|
||||
if len(request["relay_events"].([]map[string]any)) != 2 {
|
||||
t.Fatal("network ack discarded records before onboard writer")
|
||||
}
|
||||
s.setDev(map[string]any{"id": "dddddddddddddddddddddddddddddddd", "enabled": true, "after": float64(0)})
|
||||
if s.devRelayAfter != 0 {
|
||||
t.Fatal("ack leaked across sessions")
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package node
|
||||
|
||||
// A bounded memory flight recorder. It never stores endpoints, certificates,
|
||||
// payloads or raw HTTP errors, and never changes admission or lease deadlines.
|
||||
// A bounded memory flight recorder. No endpoints, credentials or raw payloads.
|
||||
// Both lanes use the relay epoch and one origin. Reporting never renews a lease.
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
@@ -9,32 +9,51 @@ import (
|
||||
)
|
||||
|
||||
type roverFrame struct {
|
||||
AtMS int64 `json:"at_ms"`
|
||||
GapMS int64 `json:"gap_ms"`
|
||||
BindingMS int64 `json:"binding_ms"`
|
||||
CoreMS int64 `json:"core_ms"`
|
||||
DriverMS int64 `json:"driver_ms"`
|
||||
Status int `json:"http_status"`
|
||||
Stage string `json:"error_stage,omitempty"`
|
||||
Session string `json:"session,omitempty"`
|
||||
Sequence float64 `json:"sequence"`
|
||||
TTLMS float64 `json:"ttl_ms"`
|
||||
State string `json:"state"`
|
||||
Delivery string `json:"delivery_mode,omitempty"`
|
||||
Index uint64 `json:"index"`
|
||||
AtMS int64 `json:"at_ms"`
|
||||
GapMS int64 `json:"gap_ms"`
|
||||
BindingMS int64 `json:"binding_ms"`
|
||||
CoreMS int64 `json:"core_ms"`
|
||||
DriverMS int64 `json:"driver_ms"`
|
||||
Status int `json:"http_status"`
|
||||
Stage string `json:"error_stage,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Session string `json:"session,omitempty"`
|
||||
Sequence float64 `json:"sequence"`
|
||||
TTLMS float64 `json:"ttl_ms"`
|
||||
State string `json:"state"`
|
||||
ReleaseConfirmed *bool `json:"release_confirmed"`
|
||||
MarshalMS float64 `json:"marshal_ms,omitempty"`
|
||||
RequestBytes int `json:"request_bytes,omitempty"`
|
||||
CoreProcessingMS float64 `json:"core_processing_ms,omitempty"`
|
||||
}
|
||||
|
||||
type roverDiagnostics struct {
|
||||
frames []roverFrame
|
||||
last time.Time
|
||||
started time.Time
|
||||
state string
|
||||
session string
|
||||
emit func([]byte)
|
||||
frames []roverFrame
|
||||
last time.Time
|
||||
started time.Time
|
||||
state string
|
||||
session string
|
||||
lane string
|
||||
epoch string
|
||||
stage string
|
||||
pendingReason string
|
||||
release *bool
|
||||
lastEmit time.Time
|
||||
activeUntil time.Time
|
||||
controlSession string
|
||||
index uint64
|
||||
emitted uint64
|
||||
emit func([]byte)
|
||||
}
|
||||
|
||||
func (d *roverDiagnostics) record(at time.Time, frame roverFrame) {
|
||||
if d.started.IsZero() {
|
||||
d.started = at
|
||||
}
|
||||
d.index++
|
||||
frame.Index = d.index
|
||||
frame.AtMS = at.Sub(d.started).Milliseconds()
|
||||
if !d.last.IsZero() {
|
||||
frame.GapMS = at.Sub(d.last).Milliseconds()
|
||||
@@ -44,18 +63,78 @@ func (d *roverDiagnostics) record(at time.Time, frame roverFrame) {
|
||||
if len(d.frames) > 128 {
|
||||
d.frames = d.frames[len(d.frames)-128:]
|
||||
}
|
||||
active := frame.Session != "" || d.session != ""
|
||||
if frame.Session != "" {
|
||||
d.activeUntil = at.Add(5 * time.Second)
|
||||
d.controlSession = frame.Session
|
||||
}
|
||||
// Retirement used to suppress the ensuing stopping/fault/release result.
|
||||
// Keep a bounded post-control window; idle observation remains silent.
|
||||
active := frame.Session != "" || d.session != "" || at.Before(d.activeUntil)
|
||||
changed := frame.State != d.state || frame.Session != d.session
|
||||
if active && (changed || frame.Stage != "" || frame.GapMS >= 200) {
|
||||
reason := d.pendingReason
|
||||
releaseChanged := (frame.ReleaseConfirmed == nil) != (d.release == nil)
|
||||
if frame.ReleaseConfirmed != nil && d.release != nil {
|
||||
releaseChanged = *frame.ReleaseConfirmed != *d.release
|
||||
}
|
||||
if releaseChanged {
|
||||
reason = "release_changed"
|
||||
}
|
||||
if d.stage != "" && frame.Stage == "" {
|
||||
reason = "stage_recovered"
|
||||
}
|
||||
if changed {
|
||||
reason = "state_changed"
|
||||
}
|
||||
if frame.GapMS >= 200 {
|
||||
reason = "cycle_gap"
|
||||
}
|
||||
if frame.Stage != "" {
|
||||
reason = frame.Stage
|
||||
}
|
||||
if frame.Reason != "" {
|
||||
reason = frame.Reason
|
||||
}
|
||||
terminal := frame.State == "stopped" || frame.State == "stopping" || frame.State == "fault" || frame.State == "receiver"
|
||||
urgent := releaseChanged || frame.Session != d.session || (changed && terminal) || frame.Stage != d.stage || frame.Delivery == "stop"
|
||||
if active {
|
||||
d.pendingReason = reason
|
||||
} else {
|
||||
d.pendingReason = ""
|
||||
}
|
||||
if active && reason != "" && (urgent || d.lastEmit.IsZero() || at.Sub(d.lastEmit) >= time.Second) {
|
||||
// Emit newly captured frames plus at most two preceding context frames.
|
||||
// Indexes expose both deduplication and any overwritten bounded history.
|
||||
first := 0
|
||||
if d.emitted > 2 {
|
||||
for first < len(d.frames)-1 && d.frames[first].Index <= d.emitted-2 {
|
||||
first++
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(struct {
|
||||
Event string `json:"event"`
|
||||
Frames []roverFrame `json:"frames"`
|
||||
}{"rover-channel", d.frames})
|
||||
Event string `json:"event"`
|
||||
Schema string `json:"schema"`
|
||||
Epoch string `json:"epoch"`
|
||||
Lane string `json:"lane"`
|
||||
Origin string `json:"origin_utc"`
|
||||
Reason string `json:"reason"`
|
||||
ControlSession string `json:"control_session,omitempty"`
|
||||
Frames []roverFrame `json:"frames"`
|
||||
}{"rover-channel", "missioncore.rover-timeline/v1", d.epoch, d.lane,
|
||||
d.started.UTC().Format(time.RFC3339Nano), reason, d.controlSession, d.frames[first:]})
|
||||
if d.emit != nil {
|
||||
d.emit(raw)
|
||||
} else {
|
||||
log.Printf("%s", raw)
|
||||
}
|
||||
d.lastEmit, d.emitted = at, d.index
|
||||
d.pendingReason = ""
|
||||
}
|
||||
d.state, d.session = frame.State, frame.Session
|
||||
d.state, d.session, d.stage, d.release = frame.State, frame.Session, frame.Stage, frame.ReleaseConfirmed
|
||||
}
|
||||
|
||||
func roverReleaseEvidence(snapshot map[string]any) *bool {
|
||||
if value, ok := snapshot["release_confirmed"].(bool); ok {
|
||||
return &value
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Paces actual reads by net/http in bounded chunks. It holds no control/state
|
||||
// locks and cancellation interrupts the wait. Content-Length stays explicit.
|
||||
type budgetReader struct {
|
||||
started bool
|
||||
ctx context.Context
|
||||
source io.Reader
|
||||
budget *LinkBudget
|
||||
class string
|
||||
}
|
||||
|
||||
func (r *budgetReader) Read(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
if !r.started {
|
||||
r.started = true
|
||||
if source, ok := r.source.(interface{ Len() int }); ok {
|
||||
r.budget.RequestDemand(r.class, source.Len())
|
||||
}
|
||||
}
|
||||
n, err := r.source.Read(p[:min(len(p), linkPacket)])
|
||||
if n == 0 {
|
||||
return n, err
|
||||
}
|
||||
for {
|
||||
if e := r.ctx.Err(); e != nil {
|
||||
return 0, e
|
||||
}
|
||||
granted, wait := r.budget.Try(r.class, n)
|
||||
if granted {
|
||||
return n, err
|
||||
}
|
||||
if !roverWait(r.ctx, wait) {
|
||||
return 0, r.ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fit a network view without discarding the complete onboard session file.
|
||||
// Export and lifecycle metadata come first. Live-view gaps remain explicit at
|
||||
// Core; only delivered record sequences are acknowledged. Live rows use 12 KB;
|
||||
// one negotiated 64 KiB export block has a separate bounded allowance.
|
||||
func boundedDevPacket(packet map[string]any) map[string]any {
|
||||
if packet == nil {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string]any, len(packet))
|
||||
for k, v := range packet {
|
||||
if k != "frames" && k != "relay_events" {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
export, _ := json.Marshal(out["export"])
|
||||
if len(export) > 90*1024 {
|
||||
delete(out, "export")
|
||||
export = nil
|
||||
}
|
||||
liveBytes := 12 * 1024
|
||||
if options, ok := packet["options"].(map[string]any); ok {
|
||||
if rate, ok := finiteNumber(options["live_kbps"]); ok && rate >= 8 && rate <= 64 {
|
||||
liveBytes = min(liveBytes, int(rate*125))
|
||||
}
|
||||
}
|
||||
// The operator limit applies to event rows only. Lifecycle metadata and
|
||||
// export have separate accounting; subtracting them here can reduce every
|
||||
// 8-kbit/s live view to zero. Share unused capacity across both row sources.
|
||||
allowance := liveBytes - 4 // Two JSON array delimiters; row commas counted below.
|
||||
for _, key := range []string{"frames", "relay_events"} {
|
||||
rows := []any{}
|
||||
switch v := packet[key].(type) {
|
||||
case []any:
|
||||
rows = v
|
||||
case []map[string]any:
|
||||
for _, row := range v {
|
||||
rows = append(rows, row)
|
||||
}
|
||||
}
|
||||
kept := []any{}
|
||||
used := 0
|
||||
// Network view is latest-first admission, chronological delivery. A large
|
||||
// old row must not permanently block newer evidence; full rows stay on disk.
|
||||
for i := len(rows) - 1; i >= 0; i-- {
|
||||
raw, _ := json.Marshal(rows[i])
|
||||
if used+len(raw)+1 > allowance {
|
||||
continue
|
||||
}
|
||||
kept = append(kept, rows[i])
|
||||
used += len(raw) + 1
|
||||
}
|
||||
for i, j := 0, len(kept)-1; i < j; i, j = i+1, j-1 {
|
||||
kept[i], kept[j] = kept[j], kept[i]
|
||||
}
|
||||
out[key] = kept
|
||||
allowance -= used
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// A successful exchange has delivered this immutable block. Until Core asks
|
||||
// for the next offset, send only the small status poll, never the same 64 KiB
|
||||
// again. Failed exchanges retain the block for retry with the same identity.
|
||||
func devExportKey(packet map[string]any) string {
|
||||
export, ok := packet["export"].(map[string]any)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
key, _ := json.Marshal([]any{export["capture_id"], export["token"], export["offset"], export["next"], export["sha256"]})
|
||||
return string(key)
|
||||
}
|
||||
|
||||
// Recorder lifecycle/status is a bounded metadata request. Live records and
|
||||
// export bytes still use residual bulk capacity; they cannot hide in this lane.
|
||||
func diagnosticTrafficClass(packet map[string]any) string {
|
||||
if packet["export"] != nil {
|
||||
return "bulk"
|
||||
}
|
||||
for _, key := range []string{"frames", "relay_events"} {
|
||||
switch rows := packet[key].(type) {
|
||||
case []any:
|
||||
if len(rows) > 0 {
|
||||
return "bulk"
|
||||
}
|
||||
case []map[string]any:
|
||||
if len(rows) > 0 {
|
||||
return "bulk"
|
||||
}
|
||||
}
|
||||
}
|
||||
return "inventory"
|
||||
}
|
||||
|
||||
func roverDiagnosticsLane(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) {
|
||||
lastExport := ""
|
||||
for ctx.Err() == nil {
|
||||
state.mu.Lock()
|
||||
enabled := state.diagnosticLane && (state.diagnosticPending == nil || *state.diagnosticPending || state.devEnabled)
|
||||
state.mu.Unlock()
|
||||
if !enabled {
|
||||
if !roverWait(ctx, 250*time.Millisecond) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
payload := make(map[string]any, len(base)+1)
|
||||
for k, v := range base {
|
||||
payload[k] = v
|
||||
}
|
||||
packet := state.devPayload()
|
||||
exportKey := devExportKey(packet)
|
||||
if exportKey != "" && exportKey == lastExport {
|
||||
delete(packet, "export")
|
||||
}
|
||||
payload["diagnostic_export_v2"] = true
|
||||
payload["diagnostics"] = boundedDevPacket(packet)
|
||||
raw, _ := json.Marshal(payload)
|
||||
// On capable peers idle DEV sleeps until the existing telemetry reply
|
||||
// announces work. Legacy peers keep polling. No recorder rows or exports
|
||||
// travel on the critical lane; only a boolean wake hint does.
|
||||
call, cancel := context.WithTimeout(ctx, pacedTimeout(len(raw)))
|
||||
reader := &budgetReader{ctx: call, source: bytes.NewReader(raw), budget: state.budget, class: diagnosticTrafficClass(packet)}
|
||||
req, _ := http.NewRequestWithContext(call, "POST", endpoint+"/v1/node/rover-diagnostics", reader)
|
||||
req.ContentLength = int64(len(raw))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
response, err := client.Do(req)
|
||||
if err == nil {
|
||||
var reply struct {
|
||||
Diagnostics map[string]any `json:"diagnostics"`
|
||||
}
|
||||
err = json.NewDecoder(io.LimitReader(response.Body, 128*1024)).Decode(&reply)
|
||||
response.Body.Close()
|
||||
if err == nil && response.StatusCode == 200 {
|
||||
state.setDev(reply.Diagnostics)
|
||||
if exportKey != "" {
|
||||
lastExport = exportKey
|
||||
}
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
if !roverWait(ctx, time.Second) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDevMinimumRateDoesNotChargeLifecycleOrExportAgainstEvents(t *testing.T) {
|
||||
for _, exported := range []bool{false, true} {
|
||||
packet := map[string]any{
|
||||
"id": "capture",
|
||||
"options": map[string]any{"live_kbps": float64(8)},
|
||||
"storage": map[string]any{"file": strings.Repeat("metadata", 180), "closed": false},
|
||||
"frames": []any{map[string]any{"record_sequence": 1, "event": "capture_started"}},
|
||||
"relay_events": []any{
|
||||
map[string]any{"record_sequence": 2, "event": "oversized", "data": strings.Repeat("x", 2000)},
|
||||
map[string]any{"record_sequence": 3, "event": "network", "data": strings.Repeat("x", 580)},
|
||||
},
|
||||
}
|
||||
if exported {
|
||||
packet["export"] = map[string]any{"data": strings.Repeat("A", 87384)}
|
||||
}
|
||||
bounded := boundedDevPacket(packet)
|
||||
frames, relay := bounded["frames"].([]any), bounded["relay_events"].([]any)
|
||||
if len(frames) != 1 || len(relay) != 1 || relay[0].(map[string]any)["record_sequence"] != 3 {
|
||||
t.Fatal("minimum event rate starved by metadata or an oversized row", bounded["frames"], bounded["relay_events"])
|
||||
}
|
||||
eventBytes := 0
|
||||
for _, rows := range [][]any{frames, relay} {
|
||||
for _, row := range rows {
|
||||
raw, _ := json.Marshal(row)
|
||||
eventBytes += len(raw) + 1
|
||||
}
|
||||
}
|
||||
if eventBytes > 1000 {
|
||||
t.Fatal("event rate exceeded", eventBytes)
|
||||
}
|
||||
if bounded["storage"] == nil || (exported && bounded["export"] == nil) {
|
||||
t.Fatal("lifecycle/export lost")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDevMinimumRateAdmitsNearKilobyteMotorSample(t *testing.T) {
|
||||
sample := map[string]any{"record_sequence": 1, "event": "sample", "data": ""}
|
||||
raw, _ := json.Marshal(sample)
|
||||
sample["data"] = strings.Repeat("x", 985-len(raw))
|
||||
packet := map[string]any{
|
||||
"options": map[string]any{"live_kbps": float64(8)},
|
||||
"storage": map[string]any{"file": strings.Repeat("metadata", 180)},
|
||||
"frames": []any{sample},
|
||||
}
|
||||
bounded := boundedDevPacket(packet)
|
||||
frames := bounded["frames"].([]any)
|
||||
if len(frames) != 1 {
|
||||
t.Fatal("real-sized motor sample cannot pass minimum rate")
|
||||
}
|
||||
raw, _ = json.Marshal(frames)
|
||||
if len(raw) > 1000 {
|
||||
t.Fatal("sample exceeds event rate", len(raw))
|
||||
}
|
||||
}
|
||||
@@ -61,3 +61,86 @@ func TestRoverDiagnosticsRecordsBindingWaitAndDriverTerminalState(t *testing.T)
|
||||
t.Fatal(last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverTimelineSharesOriginAndKeepsReleaseAfterRetirement(t *testing.T) {
|
||||
origin := time.Unix(100, 0)
|
||||
var events []map[string]any
|
||||
d := roverDiagnostics{started: origin, epoch: "relay", lane: "local", emit: func(raw []byte) {
|
||||
var event map[string]any
|
||||
if err := json.Unmarshal(raw, &event); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
events = append(events, event)
|
||||
}}
|
||||
d.record(origin.Add(time.Second), roverFrame{Session: "intent", State: "driving"})
|
||||
d.record(origin.Add(1100*time.Millisecond), roverFrame{Delivery: "stop", Reason: "intent_expired", State: "stopping"})
|
||||
no, yes := false, true
|
||||
d.record(origin.Add(1500*time.Millisecond), roverFrame{State: "fault", ReleaseConfirmed: &no})
|
||||
d.record(origin.Add(2500*time.Millisecond), roverFrame{State: "stopped", ReleaseConfirmed: &yes})
|
||||
if len(events) != 4 {
|
||||
t.Fatalf("lost release after retirement: %d", len(events))
|
||||
}
|
||||
for _, event := range events {
|
||||
if event["epoch"] != "relay" || event["lane"] != "local" || event["origin_utc"] != origin.UTC().Format(time.RFC3339Nano) {
|
||||
t.Fatal(event)
|
||||
}
|
||||
if event["control_session"] != "intent" {
|
||||
t.Fatal("retired session correlation lost")
|
||||
}
|
||||
}
|
||||
first := events[0]["frames"].([]any)[0].(map[string]any)
|
||||
if first["at_ms"] != float64(1000) || first["release_confirmed"] != nil {
|
||||
t.Fatal(first)
|
||||
}
|
||||
for i := 0; i < 200; i++ {
|
||||
d.record(origin.Add(time.Duration(7+i)*time.Second), roverFrame{State: "stopped", Stage: "idle_error"})
|
||||
}
|
||||
if len(events) != 4 || len(d.frames) != 128 {
|
||||
t.Fatal("post-control window must be bounded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverTimelineAvoidsRepeatedFullRingOnStateFlapping(t *testing.T) {
|
||||
count, rows := 0, 0
|
||||
var previous uint64
|
||||
d := roverDiagnostics{emit: func(raw []byte) {
|
||||
var event struct {
|
||||
Frames []roverFrame `json:"frames"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &event); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
count++
|
||||
rows += len(event.Frames)
|
||||
if previous > 2 && event.Frames[0].Index < previous-1 {
|
||||
t.Fatal("repeated older context")
|
||||
}
|
||||
previous = event.Frames[len(event.Frames)-1].Index
|
||||
}}
|
||||
at := time.Unix(100, 0)
|
||||
for i := 0; i < 200; i++ {
|
||||
state := "ready"
|
||||
if i%2 == 0 {
|
||||
state = "driving"
|
||||
}
|
||||
d.record(at.Add(time.Duration(i)*50*time.Millisecond), roverFrame{Session: "live", State: state})
|
||||
}
|
||||
d.record(at.Add(10*time.Second), roverFrame{Session: "live", State: "driving"})
|
||||
if count > 11 || rows > 225 || previous != 201 {
|
||||
t.Fatalf("events=%d rows=%d last=%d", count, rows, previous)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverReleaseEvidencePreservesUnknownFalseTrue(t *testing.T) {
|
||||
for _, value := range []any{nil, "false", 0} {
|
||||
if roverReleaseEvidence(map[string]any{"release_confirmed": value}) != nil {
|
||||
t.Fatal("invalid release became proof")
|
||||
}
|
||||
}
|
||||
for _, value := range []bool{false, true} {
|
||||
got := roverReleaseEvidence(map[string]any{"release_confirmed": value})
|
||||
if got == nil || *got != value {
|
||||
t.Fatal("release truth changed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDatagramFailureReasonsAreDistinctAndRedacted(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"datagram negotiation rejected": "datagram_negotiation_rejected",
|
||||
"invalid datagram endpoint": "datagram_endpoint_invalid",
|
||||
"datagram socket closed": "datagram_socket_closed",
|
||||
"datagram link timeout": "datagram_link_timeout",
|
||||
"datagram stream deadline": "datagram_stream_deadline",
|
||||
"invalid datagram frame": "datagram_frame_invalid",
|
||||
"invalid datagram clock": "datagram_clock_invalid",
|
||||
"datagram receipt stale": "datagram_receipt_stale",
|
||||
"invalid datagram intent": "datagram_intent_invalid",
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for message, want := range cases {
|
||||
got := roverErrorKind(errors.New(message))
|
||||
if got != want || seen[got] {
|
||||
t.Fatalf("reason %q: got %q, want unique %q", message, got, want)
|
||||
}
|
||||
seen[got] = true
|
||||
}
|
||||
// Transport errors may embed private endpoints. Only the timeout category
|
||||
// may survive wrapping; never copy the raw URL, query or nested error.
|
||||
private := &url.Error{Op: "Post", URL: "https://private.invalid/pair?secret=synthetic", Err: errors.New("connection failed")}
|
||||
if got := roverErrorKind(private); got != "transport_error" {
|
||||
t.Fatalf("private error leaked: %q", got)
|
||||
}
|
||||
private.Err = fmt.Errorf("request: %w", context.DeadlineExceeded)
|
||||
if got := roverErrorKind(private); got != "deadline" {
|
||||
t.Fatalf("wrapped deadline: %q", got)
|
||||
}
|
||||
if got := roverErrorKind(errors.New("datagram stream deadline: secret=synthetic")); got != "transport_error" {
|
||||
t.Fatalf("prefix is not an allowlist: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDevExportSendsAcknowledgedBlockOnceAndRetriesFailedExchange(t *testing.T) {
|
||||
for _, failFirst := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "acknowledged", true: "failed-then-acknowledged"}[failFirst], func(t *testing.T) {
|
||||
var calls, blocks atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
if json.NewDecoder(r.Body).Decode(&body) != nil {
|
||||
t.Error("invalid lane request")
|
||||
}
|
||||
packet := body["diagnostics"].(map[string]any)
|
||||
if packet["export"] != nil {
|
||||
blocks.Add(1)
|
||||
}
|
||||
n := calls.Add(1)
|
||||
if failFirst && n == 1 {
|
||||
w.WriteHeader(503)
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"diagnostics": nil})
|
||||
}))
|
||||
defer server.Close()
|
||||
state := newRoverStreamState(time.Now())
|
||||
state.diagnosticLane = true
|
||||
state.devID = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
state.devDesired = map[string]any{"export": map[string]any{"offset": 0}}
|
||||
state.devPacket = map[string]any{"id": state.devID, "frames": []any{}, "export": map[string]any{
|
||||
"capture_id": state.devID, "token": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "offset": 0, "next": 3, "data": "YWJj"}}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2500*time.Millisecond)
|
||||
defer cancel()
|
||||
roverDiagnosticsLane(ctx, server.Client(), server.URL, map[string]any{}, state)
|
||||
expected := int64(1)
|
||||
if failFirst {
|
||||
expected = 2
|
||||
}
|
||||
if calls.Load() < 3 || blocks.Load() != expected {
|
||||
t.Fatal("unbounded duplicate or lost retry", calls.Load(), blocks.Load())
|
||||
}
|
||||
if state.devPacket["export"] == nil {
|
||||
t.Fatal("network suppression modified retained source")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdleDiagnosticLaneSleepsUntilTelemetryAnnouncesWork(t *testing.T) {
|
||||
var calls atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
json.NewEncoder(w).Encode(map[string]any{"diagnostics": nil})
|
||||
}))
|
||||
defer server.Close()
|
||||
state := newRoverStreamState(time.Now())
|
||||
state.diagnosticLane = true
|
||||
idle := false
|
||||
state.diagnosticPending = &idle
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
roverDiagnosticsLane(ctx, server.Client(), server.URL, map[string]any{}, state)
|
||||
cancel()
|
||||
if calls.Load() != 0 {
|
||||
t.Fatal("disabled DEV generated bulk polls")
|
||||
}
|
||||
busy := true
|
||||
state.diagnosticPending = &busy
|
||||
ctx, cancel = context.WithTimeout(context.Background(), 150*time.Millisecond)
|
||||
roverDiagnosticsLane(ctx, server.Client(), server.URL, map[string]any{}, state)
|
||||
cancel()
|
||||
if calls.Load() == 0 {
|
||||
t.Fatal("capture/export wake hint ignored")
|
||||
}
|
||||
if state.command != nil || !state.stopPending {
|
||||
t.Fatal("diagnostics affected control")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package node
|
||||
|
||||
// DEV-only transport timing. Never record endpoints, headers, keys or raw errors.
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"net/http/httptrace"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type roverHTTPTrace struct {
|
||||
mu sync.Mutex
|
||||
started time.Time
|
||||
fields map[string]any
|
||||
}
|
||||
|
||||
func newRoverHTTPTrace(started time.Time, requestBytes int) *roverHTTPTrace {
|
||||
return &roverHTTPTrace{started: started, fields: map[string]any{"phase": "waiting_connection", "request_bytes": requestBytes}}
|
||||
}
|
||||
func (t *roverHTTPTrace) mark(phase string, values map[string]any) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.fields["phase"] = phase
|
||||
t.fields[phase+"_ms"] = float64(time.Since(t.started).Microseconds()) / 1000
|
||||
for key, value := range values {
|
||||
t.fields[key] = value
|
||||
}
|
||||
}
|
||||
func (t *roverHTTPTrace) context(ctx context.Context) context.Context {
|
||||
return httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
|
||||
DNSStart: func(httptrace.DNSStartInfo) { t.mark("dns_start", nil) },
|
||||
DNSDone: func(v httptrace.DNSDoneInfo) { t.mark("dns_done", map[string]any{"dns_error": roverErrorKind(v.Err)}) },
|
||||
ConnectStart: func(_, _ string) { t.mark("connect_start", nil) },
|
||||
ConnectDone: func(_, _ string, err error) {
|
||||
t.mark("connect_done", map[string]any{"connect_error": roverErrorKind(err)})
|
||||
},
|
||||
TLSHandshakeStart: func() { t.mark("tls_start", nil) },
|
||||
TLSHandshakeDone: func(_ tls.ConnectionState, err error) {
|
||||
t.mark("tls_done", map[string]any{"tls_error": roverErrorKind(err)})
|
||||
},
|
||||
GotConn: func(v httptrace.GotConnInfo) {
|
||||
t.mark("connection_ready", map[string]any{"reused": v.Reused, "was_idle": v.WasIdle})
|
||||
},
|
||||
WroteRequest: func(v httptrace.WroteRequestInfo) {
|
||||
t.mark("request_written", map[string]any{"write_error": roverErrorKind(v.Err)})
|
||||
},
|
||||
GotFirstResponseByte: func() { t.mark("first_response_byte", nil) },
|
||||
})
|
||||
}
|
||||
func (t *roverHTTPTrace) snapshot() map[string]any {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
result := make(map[string]any, len(t.fields))
|
||||
for key, value := range t.fields {
|
||||
result[key] = value
|
||||
}
|
||||
return result
|
||||
}
|
||||
func (s *roverStreamState) devTraceEnabled() bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.devID != "" && s.devEnabled && devOption(s.devDesired["options"], "network")
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRoverHTTPTraceConnectionReuseAndPrivacy(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ok")) }))
|
||||
defer server.Close()
|
||||
client := &http.Client{Transport: &http.Transport{}, Timeout: time.Second}
|
||||
defer client.CloseIdleConnections()
|
||||
for i := 0; i < 2; i++ {
|
||||
trace := newRoverHTTPTrace(time.Now(), 7)
|
||||
req, _ := http.NewRequestWithContext(trace.context(context.Background()), "POST", server.URL+"/private-path", strings.NewReader("private"))
|
||||
req.Header.Set("Authorization", "private-key")
|
||||
response, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = io.Copy(io.Discard, response.Body)
|
||||
response.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fields := trace.snapshot()
|
||||
if fields["reused"] != (i == 1) || fields["phase"] != "first_response_byte" || fields["request_bytes"] != 7 {
|
||||
t.Fatalf("unexpected timing: %v", fields)
|
||||
}
|
||||
for _, key := range []string{"connection_ready_ms", "request_written_ms", "first_response_byte_ms"} {
|
||||
if _, ok := fields[key].(float64); !ok {
|
||||
t.Fatalf("missing timing %s: %v", key, fields)
|
||||
}
|
||||
}
|
||||
for _, value := range fields {
|
||||
if str, ok := value.(string); ok && (strings.Contains(str, "private") || strings.Contains(str, server.URL)) {
|
||||
t.Fatal("private request data escaped into diagnostic")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestRoverHTTPTraceDistinguishesWaitingForResponse(t *testing.T) {
|
||||
release := make(chan struct{})
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-release }))
|
||||
defer server.Close()
|
||||
defer close(release)
|
||||
client := &http.Client{Timeout: 200 * time.Millisecond}
|
||||
trace := newRoverHTTPTrace(time.Now(), 0)
|
||||
req, _ := http.NewRequestWithContext(trace.context(context.Background()), "GET", server.URL, nil)
|
||||
response, err := client.Do(req)
|
||||
if response != nil {
|
||||
response.Body.Close()
|
||||
}
|
||||
if roverErrorKind(err) != "deadline" {
|
||||
t.Fatalf("expected deadline, got %v", err)
|
||||
}
|
||||
fields := trace.snapshot()
|
||||
if fields["phase"] != "request_written" {
|
||||
t.Fatalf("lost failing phase: %v", fields)
|
||||
}
|
||||
if _, ok := fields["first_response_byte_ms"]; ok {
|
||||
t.Fatal("response was never sent")
|
||||
}
|
||||
}
|
||||
func TestRoverHTTPTraceOnlyEnabledDuringDev(t *testing.T) {
|
||||
state := newRoverStreamState(time.Now())
|
||||
if state.devTraceEnabled() {
|
||||
t.Fatal("trace enabled outside DEV")
|
||||
}
|
||||
state.setDev(map[string]any{"id": strings.Repeat("a", 32), "enabled": true})
|
||||
if !state.devTraceEnabled() {
|
||||
t.Fatal("DEV trace absent")
|
||||
}
|
||||
state.setDev(map[string]any{"id": strings.Repeat("a", 32), "enabled": false})
|
||||
if state.devTraceEnabled() {
|
||||
t.Fatal("trace survived session stop")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package node
|
||||
|
||||
// Establish the authenticated HTTP connection separately from fresh snapshots.
|
||||
// A probe returns a clock sample but cannot publish telemetry or renew a lease.
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func roverConnectTelemetry(ctx context.Context, client *http.Client, endpoint string, base map[string]any, state *roverStreamState) bool {
|
||||
started := time.Now()
|
||||
raw, _ := json.Marshal(base)
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", endpoint+"/v1/node/rover-link", bytes.NewReader(raw))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
var trace *roverHTTPTrace
|
||||
if state.devTraceEnabled() {
|
||||
trace = newRoverHTTPTrace(started, len(raw))
|
||||
req = req.WithContext(trace.context(req.Context()))
|
||||
}
|
||||
// Share the exact authenticated transport/pool. The normal client's timeout
|
||||
// stays unchanged; no connection or command queue is added.
|
||||
connectClient := &http.Client{Transport: client.Transport, Timeout: 2500 * time.Millisecond, CheckRedirect: client.CheckRedirect}
|
||||
response, err := connectClient.Do(req)
|
||||
ok := false
|
||||
status := 0
|
||||
if err == nil {
|
||||
status = response.StatusCode
|
||||
var reply struct {
|
||||
LatestDatagram bool `json:"latest_datagram_v1"`
|
||||
RoverDetails bool `json:"rover_details_v1"`
|
||||
BudgetInterval bool `json:"budget_interval_v1"`
|
||||
DiagnosticLane bool `json:"diagnostic_lane_v1"`
|
||||
Connected bool `json:"connected"`
|
||||
SampleClock bool `json:"sample_clock_v1"`
|
||||
Clock roverClock `json:"control_clock"`
|
||||
}
|
||||
err = json.NewDecoder(io.LimitReader(response.Body, 4096)).Decode(&reply)
|
||||
response.Body.Close()
|
||||
ok = err == nil && status == 200 && reply.Connected
|
||||
stamped := ok && reply.SampleClock
|
||||
if stamped {
|
||||
ok = state.sampleClock(reply.Clock, started, time.Now())
|
||||
}
|
||||
state.mu.Lock()
|
||||
state.telemetryStamped = stamped && ok
|
||||
state.diagnosticLane = ok && reply.DiagnosticLane
|
||||
state.budgetInterval = ok && reply.BudgetInterval
|
||||
state.roverDetails = ok && reply.RoverDetails
|
||||
state.latestDatagram = state.latestDatagram || (ok && reply.LatestDatagram)
|
||||
state.diagnosticPending = nil // One discovery exchange on every authenticated reconnect.
|
||||
state.mu.Unlock()
|
||||
}
|
||||
if !ok && status == 0 {
|
||||
state.budget.Observe(time.Since(started), false)
|
||||
}
|
||||
details := map[string]any{"elapsed_ms": time.Since(started).Milliseconds(), "http_status": status, "connected": ok, "reason": roverErrorKind(err)}
|
||||
if trace != nil {
|
||||
details["transport"] = trace.snapshot()
|
||||
}
|
||||
state.recordDev("link_connect", details)
|
||||
return ok
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRoverTelemetryCapturesFreshSnapshotAfterSlowConnection(t *testing.T) {
|
||||
state := newRoverStreamState(time.Now())
|
||||
state.delivered(map[string]any{"generation": float64(1)}, 0)
|
||||
received := make(chan map[string]any, 1)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if r.URL.Path == "/v1/node/rover-link" {
|
||||
if _, ok := body["rover"]; ok {
|
||||
t.Error("probe must not carry a stale snapshot")
|
||||
}
|
||||
if _, ok := body["command"]; ok {
|
||||
t.Error("probe cannot command a motor")
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]bool{"connected": true})
|
||||
return
|
||||
}
|
||||
if r.URL.Path != "/v1/node/rover" {
|
||||
t.Error("unexpected path")
|
||||
}
|
||||
select {
|
||||
case received <- body:
|
||||
default:
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(roverStreamReply{Clock: roverClock{testClockID, 10000}})
|
||||
}))
|
||||
defer server.Close()
|
||||
var dials atomic.Int32
|
||||
transport := &http.Transport{MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
dials.Add(1)
|
||||
// Connection takes longer than the snapshot budget. Data changes meanwhile.
|
||||
if !roverWait(ctx, 150*time.Millisecond) {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
state.delivered(map[string]any{"generation": float64(2)}, 0)
|
||||
return (&net.Dialer{}).DialContext(ctx, network, address)
|
||||
}}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := &http.Client{Transport: transport, Timeout: 75 * time.Millisecond}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
done := make(chan struct{})
|
||||
go func() { defer close(done); roverTelemetry(ctx, client, server.URL, map[string]any{}, state) }()
|
||||
select {
|
||||
case body := <-received:
|
||||
if body["rover"].(map[string]any)["generation"] != float64(2) {
|
||||
t.Fatal("stale pre-connect snapshot was transmitted")
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("connection never recovered beyond snapshot deadline")
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("cancelled telemetry worker leaked")
|
||||
}
|
||||
if dials.Load() != 1 {
|
||||
t.Fatalf("warm connection was not reused: %d", dials.Load())
|
||||
}
|
||||
if client.Timeout != 75*time.Millisecond {
|
||||
t.Fatal("snapshot deadline was relaxed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverDelayedReplyKeepsConnectionWithoutExtendingCommandDeadline(t *testing.T) {
|
||||
state := newRoverStreamState(time.Now())
|
||||
state.delivered(map[string]any{"generation": float64(1)}, 0)
|
||||
origin := time.Now()
|
||||
var probes atomic.Int32
|
||||
var snapshots atomic.Int32
|
||||
done := make(chan struct{}, 1)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
clock := func() roverClock {
|
||||
return roverClock{testClockID, 10000 + float64(time.Since(origin).Microseconds())/1000}
|
||||
}
|
||||
if r.URL.Path == "/v1/node/rover-link" {
|
||||
probes.Add(1)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"connected": true, "sample_clock_v1": true, "control_clock": clock()})
|
||||
return
|
||||
}
|
||||
var body map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
if body["sample_clock"] == nil {
|
||||
t.Error("long transport deadline without capture age")
|
||||
}
|
||||
// A valid observation reply exceeds the former 300 ms cutoff.
|
||||
time.Sleep(400 * time.Millisecond)
|
||||
_ = json.NewEncoder(w).Encode(roverStreamReply{Watch: true, Clock: clock()})
|
||||
if snapshots.Add(1) == 2 {
|
||||
done <- struct{}{}
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
transport := &http.Transport{MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := &http.Client{Transport: transport, Timeout: 75 * time.Millisecond}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
workerDone := make(chan struct{})
|
||||
go func() { defer close(workerDone); roverTelemetry(ctx, client, server.URL, map[string]any{}, state) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Error("delayed response caused retry loop")
|
||||
}
|
||||
cancel()
|
||||
<-workerDone
|
||||
if probes.Load() != 1 {
|
||||
t.Fatalf("unnecessary reconnects: %d", probes.Load())
|
||||
}
|
||||
if client.Timeout != 75*time.Millisecond {
|
||||
t.Fatal("shared command/client timeout changed")
|
||||
}
|
||||
if state.command != nil {
|
||||
t.Fatal("observation created motion authority")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSampleTimeUsesConservativeLowerClockSeparateFromCommandUpper(t *testing.T) {
|
||||
origin := time.Now()
|
||||
s := newRoverStreamState(origin)
|
||||
if !s.sampleClock(roverClock{testClockID, 10000}, origin, origin.Add(400*time.Millisecond)) {
|
||||
t.Fatal("clock")
|
||||
}
|
||||
s.telemetryStamped = true
|
||||
captured := origin.Add(450 * time.Millisecond)
|
||||
s.deliveredAt(map[string]any{}, 0, captured)
|
||||
_, clock := s.telemetryView()
|
||||
if clock == nil || clock.MonotonicMS > 10050 || clock.MonotonicMS < 10040 {
|
||||
t.Fatalf("incorrect capture bound: %+v", clock)
|
||||
}
|
||||
if s.upperMS < 10000 {
|
||||
t.Fatal("command upper bound was replaced by lower bound")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The local tick checks expiry even when no newer operator intent has arrived.
|
||||
// It owns no independent lease and cannot extend the Core's original deadline.
|
||||
type roverLocalDelivery struct {
|
||||
session string
|
||||
sequence float64
|
||||
sent bool
|
||||
}
|
||||
|
||||
func (d *roverLocalDelivery) run(ctx context.Context, sensors *Sensors, model *sensorModel, state *roverStreamState, relay string, started time.Time) roverFrame {
|
||||
state.budget.ObserveCommandSilence()
|
||||
watch, command, stop := state.delivery(started)
|
||||
frame := roverFrame{}
|
||||
mode := "observe"
|
||||
if stop != 0 {
|
||||
mode = "stop"
|
||||
frame.Reason, _ = state.stopDetails()["reason"].(string)
|
||||
if state.devTraceEnabled() {
|
||||
state.recordDev("delivery_stop", state.stopDetails())
|
||||
}
|
||||
}
|
||||
if command != nil {
|
||||
state.budget.SetControl(true) // Reserve before the first local intent, not after telemetry catches up.
|
||||
mode = "intent"
|
||||
frame.Session, _ = command["id"].(string)
|
||||
frame.Sequence, _ = command["sequence"].(float64)
|
||||
frame.TTLMS, _ = command["ttl_ms"].(float64)
|
||||
}
|
||||
// A successful RPC already carried this exact input to the owner. The
|
||||
// VESC owner's input lease rejects duplicates anyway. Do not turn a redundant
|
||||
// snapshot request into a second opportunity to retire valid authority.
|
||||
// delivery() above still enforces expiry/stop/clock barriers every tick;
|
||||
// skipping must NOT refresh the last snapshot's capture timestamp.
|
||||
if command != nil && d.sent && d.session == frame.Session && d.sequence == frame.Sequence {
|
||||
snapshot, _ := state.view()
|
||||
frame.State, _ = snapshot["state"].(string)
|
||||
frame.ReleaseConfirmed = roverReleaseEvidence(snapshot)
|
||||
frame.Delivery = "unchanged"
|
||||
state.recordDev("delivery", map[string]any{"session_id": frame.Session, "sequence": frame.Sequence,
|
||||
"ttl_ms": frame.TTLMS, "driver_ms": 0, "state": frame.State, "error_stage": "", "delivery_mode": frame.Delivery})
|
||||
return frame
|
||||
}
|
||||
frame.Delivery = mode
|
||||
call, done := context.WithTimeout(ctx, 25*time.Millisecond)
|
||||
var trace *roverHTTPTrace
|
||||
if state.devTraceEnabled() {
|
||||
trace = newRoverHTTPTrace(started, 0)
|
||||
call = trace.context(call)
|
||||
}
|
||||
result, err := sensors.modelDriver(call, model, "/remote", map[string]any{"watch": watch, "command": command, "relay_id": relay})
|
||||
reason := roverErrorKind(call.Err())
|
||||
if reason == "" && err != nil {
|
||||
reason = roverErrorKind(err)
|
||||
}
|
||||
done()
|
||||
frame.DriverMS = time.Since(started).Milliseconds()
|
||||
if err != nil {
|
||||
d.sent = false
|
||||
state.stopStream()
|
||||
frame.Stage = "driver_transport"
|
||||
state.deliveredAt(map[string]any{}, 0, started)
|
||||
} else {
|
||||
d.sent = command != nil
|
||||
d.session, d.sequence = frame.Session, frame.Sequence
|
||||
state.deliveredAt(result, stop, started)
|
||||
frame.State, _ = result["state"].(string)
|
||||
frame.ReleaseConfirmed = roverReleaseEvidence(result)
|
||||
}
|
||||
details := map[string]any{"session_id": frame.Session, "sequence": frame.Sequence, "ttl_ms": frame.TTLMS,
|
||||
"driver_ms": frame.DriverMS, "state": frame.State, "error_stage": frame.Stage, "delivery_mode": mode, "reason": reason}
|
||||
if trace != nil {
|
||||
timing := trace.snapshot()
|
||||
delete(timing, "request_bytes") // Encoding belongs to modelDriver; its size is not measured here.
|
||||
details["transport"] = timing
|
||||
}
|
||||
state.recordDev("delivery", details)
|
||||
return frame
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptrace"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func localDeliveryFixture(t *testing.T) (*Sensors, *sensorModel, *roverStreamState, time.Time) {
|
||||
t.Helper()
|
||||
sensors := isolatedSensors(t)
|
||||
var model *sensorModel
|
||||
for i := range sensorModels {
|
||||
if sensorModels[i].ID == "vesc.controller" {
|
||||
model = &sensorModels[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if model == nil {
|
||||
t.Fatal("missing VESC")
|
||||
}
|
||||
at := time.Now()
|
||||
state := newRoverStreamState(at)
|
||||
state.sampleClock(roverClock{testClockID, 10000}, at, at)
|
||||
acknowledgeStop(state, at)
|
||||
state.accept(streamIntent(1331, 10000, 10400))
|
||||
return sensors, model, state, at
|
||||
}
|
||||
|
||||
func TestRoverLocalDeliveryDoesNotResendAlreadyDeliveredIntent(t *testing.T) {
|
||||
sensors, model, state, at := localDeliveryFixture(t)
|
||||
calls := 0
|
||||
sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if calls > 1 {
|
||||
return nil, context.DeadlineExceeded
|
||||
}
|
||||
return testSensorReply(map[string]any{"state": "driving", "instance": "same", "session_id": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}), nil
|
||||
})
|
||||
var delivery roverLocalDelivery
|
||||
delivery.run(context.Background(), sensors, model, state, "relay", at)
|
||||
before, _ := state.view()
|
||||
sampled := state.snapshotAt
|
||||
delivery.run(context.Background(), sensors, model, state, "relay", at.Add(50*time.Millisecond))
|
||||
_, command, stop := state.delivery(at.Add(75 * time.Millisecond))
|
||||
if calls != 1 || command == nil || stop != 0 {
|
||||
t.Fatalf("duplicate RPC retired live intent: calls=%d command=%v stop=%d", calls, command, stop)
|
||||
}
|
||||
after, _ := state.view()
|
||||
if after["instance"] != before["instance"] || !state.snapshotAt.Equal(sampled) {
|
||||
t.Fatal("skipped RPC refreshed/replaced telemetry")
|
||||
}
|
||||
if command["ttl_ms"].(float64) >= 325 {
|
||||
t.Fatal("duplicate extended the original deadline")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverLocalDeliveryStillSendsExpiryAndExplicitStop(t *testing.T) {
|
||||
for _, explicit := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "expiry", true: "explicit"}[explicit], func(t *testing.T) {
|
||||
sensors, model, state, at := localDeliveryFixture(t)
|
||||
var requests []map[string]any
|
||||
sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
requests = append(requests, body)
|
||||
deadline, ok := r.Context().Deadline()
|
||||
if !ok || time.Until(deadline) > 25*time.Millisecond {
|
||||
t.Fatal("local RPC deadline relaxed")
|
||||
}
|
||||
return testSensorReply(map[string]any{"state": "driving"}), nil
|
||||
})
|
||||
var delivery roverLocalDelivery
|
||||
delivery.run(context.Background(), sensors, model, state, "relay", at)
|
||||
next := at.Add(450 * time.Millisecond)
|
||||
if explicit {
|
||||
state.stopStream()
|
||||
next = at.Add(50 * time.Millisecond)
|
||||
}
|
||||
delivery.run(context.Background(), sensors, model, state, "relay", next)
|
||||
if len(requests) != 2 || requests[1]["command"] != nil {
|
||||
t.Fatal("cached delivery suppressed stop")
|
||||
}
|
||||
state.accept(streamIntent(1332, 10450, 10850))
|
||||
_, command, _ := state.delivery(next)
|
||||
if command != nil {
|
||||
t.Fatal("retired session resumed")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverLocalDeliveryNewIntentFailureRemainsTerminal(t *testing.T) {
|
||||
sensors, model, state, at := localDeliveryFixture(t)
|
||||
calls := 0
|
||||
sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if calls == 2 {
|
||||
return nil, errors.New("synthetic failure")
|
||||
}
|
||||
return testSensorReply(map[string]any{"state": "driving"}), nil
|
||||
})
|
||||
var delivery roverLocalDelivery
|
||||
delivery.run(context.Background(), sensors, model, state, "relay", at)
|
||||
state.accept(streamIntent(1332, 10100, 10500))
|
||||
frame := delivery.run(context.Background(), sensors, model, state, "relay", at.Add(100*time.Millisecond))
|
||||
_, command, stop := state.delivery(at.Add(150 * time.Millisecond))
|
||||
if calls != 2 || frame.Stage != "driver_transport" || command != nil || stop == 0 || delivery.sent {
|
||||
t.Fatal("fresh intent failure no longer retires authority")
|
||||
}
|
||||
delivery.run(context.Background(), sensors, model, state, "relay", at.Add(150*time.Millisecond))
|
||||
if state.stopPending {
|
||||
t.Fatal("explicit stop not acknowledged")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverLocalDeliveryNewInputAfterSkippedTickIsNotCoalescedAway(t *testing.T) {
|
||||
sensors, model, state, at := localDeliveryFixture(t)
|
||||
var sequences []float64
|
||||
sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sequences = append(sequences, body["command"].(map[string]any)["sequence"].(float64))
|
||||
return testSensorReply(map[string]any{"state": "driving"}), nil
|
||||
})
|
||||
var delivery roverLocalDelivery
|
||||
delivery.run(context.Background(), sensors, model, state, "relay", at)
|
||||
skipped := delivery.run(context.Background(), sensors, model, state, "relay", at.Add(50*time.Millisecond))
|
||||
state.accept(streamIntent(1332, 10060, 10460))
|
||||
delivery.run(context.Background(), sensors, model, state, "relay", at.Add(60*time.Millisecond))
|
||||
if len(sequences) != 2 || sequences[0] != 1331 || sequences[1] != 1332 || skipped.Delivery != "unchanged" {
|
||||
t.Fatal("new input was suppressed", sequences)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverLocalDeliveryDeadlineTraceIsDevOnly(t *testing.T) {
|
||||
for _, dev := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "off", true: "on"}[dev], func(t *testing.T) {
|
||||
sensors, model, state, at := localDeliveryFixture(t)
|
||||
if dev {
|
||||
state.devID = testClockID
|
||||
state.devEnabled = true
|
||||
}
|
||||
sensors.clients[model.ID].Transport = sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
tr := httptrace.ContextClientTrace(r.Context())
|
||||
if (tr != nil) != dev {
|
||||
t.Fatal("trace state disagrees with DEV")
|
||||
}
|
||||
if tr != nil {
|
||||
tr.WroteRequest(httptrace.WroteRequestInfo{})
|
||||
}
|
||||
<-r.Context().Done()
|
||||
return nil, r.Context().Err()
|
||||
})
|
||||
var delivery roverLocalDelivery
|
||||
delivery.run(context.Background(), sensors, model, state, "relay", at)
|
||||
if !dev {
|
||||
if len(state.devEvents) != 0 {
|
||||
t.Fatal("DEV-off retained trace")
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(state.devEvents) != 1 {
|
||||
t.Fatal("trace missing")
|
||||
}
|
||||
row := state.devEvents[0]
|
||||
timing := row["transport"].(map[string]any)
|
||||
if row["reason"] != "deadline" || timing["phase"] != "request_written" || row["delivery_mode"] != "intent" {
|
||||
t.Fatal(row)
|
||||
}
|
||||
if _, ok := timing["request_bytes"]; ok {
|
||||
t.Fatal("invented request size")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Only presentation/identity metadata is cached. Every measured value, age,
|
||||
// attachment session, authority flag and release result stays in every frame.
|
||||
var roverMetadataFields = []string{"supported", "control_modes", "profile"}
|
||||
var roverDeviceMetadataFields = []string{"uuid", "slot", "label"}
|
||||
|
||||
type roverMetadataEncoder struct {
|
||||
instance string
|
||||
previous []byte
|
||||
revision uint64
|
||||
sentAt time.Time
|
||||
}
|
||||
|
||||
func (e *roverMetadataEncoder) reset() { e.sentAt = time.Time{} }
|
||||
|
||||
func (e *roverMetadataEncoder) encode(snapshot map[string]any, now time.Time) (map[string]any, map[string]any) {
|
||||
readings, ok := snapshot["devices"].([]any)
|
||||
instance, _ := snapshot["instance"].(string)
|
||||
if !ok || instance == "" {
|
||||
e.reset()
|
||||
return snapshot, nil
|
||||
}
|
||||
if e.instance != instance {
|
||||
e.instance = instance
|
||||
e.reset()
|
||||
}
|
||||
details := map[string]any{}
|
||||
compact := make(map[string]any, len(snapshot))
|
||||
for k, v := range snapshot {
|
||||
compact[k] = v
|
||||
}
|
||||
for _, k := range roverMetadataFields {
|
||||
if v, exists := compact[k]; exists {
|
||||
details[k] = v
|
||||
delete(compact, k)
|
||||
}
|
||||
}
|
||||
devices := map[string]any{}
|
||||
live := make([]any, 0, len(readings))
|
||||
for _, value := range readings {
|
||||
row, valid := value.(map[string]any)
|
||||
id, _ := row["id"].(string)
|
||||
session, _ := row["session_id"].(string)
|
||||
if !valid || id == "" || session == "" {
|
||||
e.reset()
|
||||
return snapshot, nil
|
||||
}
|
||||
if _, duplicate := devices[id]; duplicate {
|
||||
e.reset()
|
||||
return snapshot, nil
|
||||
}
|
||||
metadata, current := map[string]any{}, map[string]any{}
|
||||
for k, v := range row {
|
||||
current[k] = v
|
||||
}
|
||||
for _, k := range roverDeviceMetadataFields {
|
||||
if v, exists := current[k]; exists {
|
||||
metadata[k] = v
|
||||
delete(current, k)
|
||||
}
|
||||
}
|
||||
devices[id] = metadata
|
||||
live = append(live, current)
|
||||
}
|
||||
details["devices"], compact["devices"] = devices, live
|
||||
raw, err := json.Marshal(details)
|
||||
if err != nil {
|
||||
e.reset()
|
||||
return snapshot, nil
|
||||
}
|
||||
if !bytes.Equal(raw, e.previous) {
|
||||
e.previous = raw
|
||||
e.revision++
|
||||
e.reset()
|
||||
}
|
||||
envelope := map[string]any{"revision": e.revision}
|
||||
if e.sentAt.IsZero() || now.Sub(e.sentAt) >= time.Second {
|
||||
envelope["details"] = details
|
||||
e.sentAt = now
|
||||
}
|
||||
return compact, envelope
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func metadataSnapshot() map[string]any {
|
||||
return map[string]any{"instance": "driver", "supported": true, "control_modes": []any{"duty"},
|
||||
"profile": map[string]any{"revision": float64(2)}, "state": "stopped", "release_confirmed": false,
|
||||
"devices": []any{map[string]any{"id": "motor", "session_id": "attached", "uuid": "physical", "label": "Left", "slot": "left.1", "age_ms": float64(25),
|
||||
"values": map[string]any{"erpm": float64(123), "motor_current_a": 0.2}}}}
|
||||
}
|
||||
|
||||
func TestRoverMetadataKeepsLiveTruthAndRefreshesOnChange(t *testing.T) {
|
||||
var encoder roverMetadataEncoder
|
||||
at := time.Unix(100, 0)
|
||||
snapshot := metadataSnapshot()
|
||||
before, _ := json.Marshal(snapshot)
|
||||
first, details := encoder.encode(snapshot, at)
|
||||
if details["details"] == nil || details["revision"] != uint64(1) {
|
||||
t.Fatal(details)
|
||||
}
|
||||
current := first["devices"].([]any)[0].(map[string]any)
|
||||
if first["release_confirmed"] != false || current["age_ms"] != float64(25) || current["session_id"] != "attached" {
|
||||
t.Fatal(first)
|
||||
}
|
||||
if !reflect.DeepEqual(current["values"], snapshot["devices"].([]any)[0].(map[string]any)["values"]) {
|
||||
t.Fatal("live values changed")
|
||||
}
|
||||
if _, ok := current["uuid"]; ok {
|
||||
t.Fatal("metadata repeated")
|
||||
}
|
||||
after, _ := json.Marshal(snapshot)
|
||||
if string(before) != string(after) {
|
||||
t.Fatal("snapshot mutated")
|
||||
}
|
||||
_, ref := encoder.encode(snapshot, at.Add(100*time.Millisecond))
|
||||
if len(ref) != 1 || ref["revision"] != uint64(1) {
|
||||
t.Fatal(ref)
|
||||
}
|
||||
_, refresh := encoder.encode(snapshot, at.Add(time.Second))
|
||||
if refresh["details"] == nil {
|
||||
t.Fatal("metadata not refreshed")
|
||||
}
|
||||
snapshot["profile"] = map[string]any{"revision": float64(3)}
|
||||
_, changed := encoder.encode(snapshot, at.Add(1100*time.Millisecond))
|
||||
if changed["details"] == nil || changed["revision"] != uint64(2) {
|
||||
t.Fatal("configuration change delayed")
|
||||
}
|
||||
encoder.reset()
|
||||
_, reconnect := encoder.encode(snapshot, at.Add(1200*time.Millisecond))
|
||||
if reconnect["details"] == nil {
|
||||
t.Fatal("reconnect needs full metadata")
|
||||
}
|
||||
snapshot["instance"] = "restarted-driver"
|
||||
_, restarted := encoder.encode(snapshot, at.Add(1300*time.Millisecond))
|
||||
if restarted["details"] == nil {
|
||||
t.Fatal("driver restart must refresh metadata even with an identical profile")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoverMetadataCannotHideMalformedRoster(t *testing.T) {
|
||||
for _, change := range []string{"missing_session", "duplicate", "missing_instance"} {
|
||||
snapshot := metadataSnapshot()
|
||||
row := snapshot["devices"].([]any)[0].(map[string]any)
|
||||
switch change {
|
||||
case "missing_session":
|
||||
delete(row, "session_id")
|
||||
case "duplicate":
|
||||
snapshot["devices"] = []any{row, row}
|
||||
case "missing_instance":
|
||||
delete(snapshot, "instance")
|
||||
}
|
||||
var encoder roverMetadataEncoder
|
||||
live, details := encoder.encode(snapshot, time.Now())
|
||||
if details != nil || !reflect.DeepEqual(live, snapshot) {
|
||||
t.Fatal("malformed snapshot hidden")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package node
|
||||
|
||||
import "time"
|
||||
|
||||
// Record receipt before local delivery, including retired frames. This closes
|
||||
// the evidence gap between Core's socket write and the driver's input receipt.
|
||||
func (s *roverStreamState) receivedFrame(reply roverStreamReply, at time.Time) {
|
||||
s.mu.Lock()
|
||||
s.observeLowerClock(reply.Clock, at)
|
||||
gap := time.Duration(0)
|
||||
if !s.streamReceived.IsZero() {
|
||||
gap = at.Sub(s.streamReceived)
|
||||
}
|
||||
s.streamReceived = at
|
||||
upper := float64(at.Sub(s.origin).Microseconds())/1000 + s.upperMS + 5 + float64(at.Sub(s.anchored).Microseconds())/1e6
|
||||
age := max(0, upper-reply.Clock.MonotonicMS)
|
||||
id, _ := reply.Command["id"].(string)
|
||||
retired, pending := s.retired[id], s.stopPending
|
||||
s.mu.Unlock()
|
||||
s.budget.ObserveCommandFrame(gap, time.Duration(age*float64(time.Millisecond)))
|
||||
if s.devTraceEnabled() {
|
||||
s.recordDev("stream_frame_received", map[string]any{"session_id": id, "sequence": reply.Command["sequence"],
|
||||
"received_mono_ms": float64(at.Sub(s.origin).Microseconds()) / 1000,
|
||||
"core_clock_ms": reply.Clock.MonotonicMS, "gap_ms": float64(gap.Microseconds()) / 1000,
|
||||
"age_upper_ms": age, "retired": retired, "stop_pending": pending})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *roverStreamState) stopDetails() map[string]any {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return map[string]any{"reason": s.stopCause, "stop_revision": s.stopRevision,
|
||||
"last_frame_mono_ms": float64(s.streamReceived.Sub(s.origin).Microseconds()) / 1000}
|
||||
}
|
||||
@@ -12,29 +12,54 @@ type roverClock struct {
|
||||
MonotonicMS float64 `json:"monotonic_ms"`
|
||||
}
|
||||
type roverStreamReply struct {
|
||||
Watch bool `json:"watch"`
|
||||
Command map[string]any `json:"command"`
|
||||
Clock roverClock `json:"control_clock"`
|
||||
CoreProcessingMS float64 `json:"core_processing_ms"`
|
||||
ControlActive *bool `json:"control_active"`
|
||||
DiagnosticsPending *bool `json:"diagnostics_pending"`
|
||||
Diagnostics map[string]any `json:"diagnostics,omitempty"`
|
||||
Watch bool `json:"watch"`
|
||||
Command map[string]any `json:"command"`
|
||||
Clock roverClock `json:"control_clock"`
|
||||
}
|
||||
|
||||
// Clock bounds use the request-send time, never RTT/2 or synchronized wall
|
||||
// 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 {
|
||||
mu sync.Mutex
|
||||
origin time.Time
|
||||
clockID string
|
||||
upperMS float64
|
||||
anchored time.Time
|
||||
clockSeen time.Time
|
||||
command map[string]any
|
||||
watch bool
|
||||
stopPending bool
|
||||
stopRevision uint64
|
||||
snapshot map[string]any
|
||||
retired map[string]bool
|
||||
inhibited bool
|
||||
wake chan struct{}
|
||||
budget *LinkBudget
|
||||
latestDatagram bool
|
||||
roverDetails bool
|
||||
diagnosticLane bool
|
||||
budgetInterval bool
|
||||
diagnosticPending *bool
|
||||
devID string
|
||||
devEnabled bool
|
||||
devDesired map[string]any
|
||||
devAfter any
|
||||
devRelayAfter int64
|
||||
devSequence int64
|
||||
devEvents []map[string]any
|
||||
devPacket map[string]any
|
||||
devBudgetAt time.Time
|
||||
mu sync.Mutex
|
||||
origin time.Time
|
||||
clockID string
|
||||
upperMS float64
|
||||
anchored time.Time
|
||||
clockSeen time.Time
|
||||
streamReceived time.Time
|
||||
stopCause string
|
||||
command map[string]any
|
||||
watch bool
|
||||
stopPending bool
|
||||
stopRevision uint64
|
||||
snapshotAt time.Time
|
||||
telemetryStamped bool
|
||||
lowerClockMS float64
|
||||
lowerClockAt time.Time
|
||||
snapshot map[string]any
|
||||
retired map[string]bool
|
||||
inhibited bool
|
||||
wake chan struct{}
|
||||
}
|
||||
|
||||
func newRoverStreamState(now time.Time) *roverStreamState {
|
||||
@@ -58,17 +83,41 @@ func (s *roverStreamState) sampleClock(c roverClock, sent, received time.Time) b
|
||||
defer s.mu.Unlock()
|
||||
upper := c.MonotonicMS - float64(sent.Sub(s.origin).Microseconds())/1000 + 1
|
||||
if c.Instance != s.clockID {
|
||||
s.invalidate()
|
||||
s.invalidateCause("core_clock_changed")
|
||||
s.clockID = c.Instance
|
||||
s.lowerClockAt = time.Time{}
|
||||
s.upperMS = upper
|
||||
s.anchored = received
|
||||
} else if s.clockSeen.IsZero() || received.Sub(s.clockSeen) > 2*time.Second || upper < s.upperMS+float64(received.Sub(s.anchored).Microseconds())/1e6 {
|
||||
s.upperMS = upper
|
||||
s.anchored = received
|
||||
}
|
||||
s.observeLowerClock(c, received)
|
||||
s.clockSeen = received
|
||||
return true
|
||||
}
|
||||
|
||||
// Called with s.mu held. Every authenticated Core clock is a lower bound at
|
||||
// local receipt. A slow response cannot erase a tighter bound already learned
|
||||
// from another exchange or the command stream. Advance the old bound with the
|
||||
// same conservative 1000 ppm drift allowance as telemetryView; never use RTT/2.
|
||||
// This only timestamps observations. It does not touch the command-clock upper
|
||||
// bound, clockSeen, original expiry, stop barrier or any motion authority.
|
||||
func (s *roverStreamState) observeLowerClock(c roverClock, received time.Time) {
|
||||
if c.Instance != s.clockID || math.IsNaN(c.MonotonicMS) || math.IsInf(c.MonotonicMS, 0) || c.MonotonicMS < 0 {
|
||||
return
|
||||
}
|
||||
lower := c.MonotonicMS
|
||||
if !s.lowerClockAt.IsZero() {
|
||||
delta := float64(received.Sub(s.lowerClockAt).Microseconds()) / 1000
|
||||
if delta < 0 {
|
||||
return
|
||||
}
|
||||
lower = math.Max(lower, s.lowerClockMS+delta-delta*.001)
|
||||
}
|
||||
s.lowerClockMS, s.lowerClockAt = lower, received
|
||||
}
|
||||
|
||||
func (s *roverStreamState) accept(reply roverStreamReply) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
@@ -77,7 +126,7 @@ func (s *roverStreamState) accept(reply roverStreamReply) bool {
|
||||
}
|
||||
if reply.Command == nil {
|
||||
if s.command != nil {
|
||||
s.invalidate()
|
||||
s.invalidateCause("core_withdrew_command")
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -139,6 +188,10 @@ func (s *roverStreamState) retire(id string) {
|
||||
s.retired[id] = true
|
||||
}
|
||||
func (s *roverStreamState) invalidate() {
|
||||
s.invalidateCause("stream_unavailable")
|
||||
}
|
||||
func (s *roverStreamState) invalidateCause(cause string) {
|
||||
s.stopCause = cause
|
||||
wake := !s.stopPending || s.command != nil
|
||||
if s.command != nil {
|
||||
if id, ok := s.command["id"].(string); ok {
|
||||
@@ -162,7 +215,7 @@ func (s *roverStreamState) delivery(now time.Time) (bool, map[string]any, uint64
|
||||
return s.watch, nil, 0
|
||||
}
|
||||
if now.Sub(s.clockSeen) > 2*time.Second {
|
||||
s.invalidate()
|
||||
s.invalidateCause("clock_sample_stale")
|
||||
return s.watch, nil, s.stopRevision
|
||||
}
|
||||
expires, _ := finiteNumber(s.command["expires_mono_ms"])
|
||||
@@ -171,7 +224,7 @@ func (s *roverStreamState) delivery(now time.Time) (bool, map[string]any, uint64
|
||||
serverUpper := float64(now.Sub(s.origin).Microseconds())/1000 + s.upperMS + 5 + float64(now.Sub(s.anchored).Microseconds())/1e6
|
||||
ttl := math.Min(400, expires-serverUpper-25)
|
||||
if ttl <= 0 {
|
||||
s.invalidate()
|
||||
s.invalidateCause("command_deadline_expired")
|
||||
return s.watch, nil, s.stopRevision
|
||||
}
|
||||
out := make(map[string]any, 6)
|
||||
@@ -184,8 +237,12 @@ func (s *roverStreamState) delivery(now time.Time) (bool, map[string]any, uint64
|
||||
return s.watch, out, 0
|
||||
}
|
||||
func (s *roverStreamState) delivered(snapshot map[string]any, stop uint64) {
|
||||
s.deliveredAt(snapshot, stop, time.Now())
|
||||
}
|
||||
func (s *roverStreamState) deliveredAt(snapshot map[string]any, stop uint64, sampled time.Time) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.snapshotAt = sampled
|
||||
s.snapshot = snapshot
|
||||
if stop != 0 && stop == s.stopRevision {
|
||||
s.stopPending = false
|
||||
@@ -197,3 +254,20 @@ func (s *roverStreamState) view() (map[string]any, bool) {
|
||||
return s.snapshot, s.watch
|
||||
}
|
||||
func (s *roverStreamState) setWatch(watch bool) { s.mu.Lock(); s.watch = watch; s.mu.Unlock() }
|
||||
|
||||
// Conservative capture time in the Core epoch: the reply clock was sampled
|
||||
// before local receipt. Subtract drift/quantization margin, never RTT/2.
|
||||
// This is observation age only; command authority still uses its upper bound.
|
||||
func (s *roverStreamState) telemetryView() (map[string]any, *roverClock) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if !s.telemetryStamped || s.lowerClockAt.IsZero() || s.snapshotAt.IsZero() {
|
||||
return s.snapshot, nil
|
||||
}
|
||||
delta := float64(s.snapshotAt.Sub(s.lowerClockAt).Microseconds()) / 1000
|
||||
stamp := s.lowerClockMS + delta - 5 - math.Abs(delta)*.001
|
||||
if stamp < 0 {
|
||||
stamp = 0
|
||||
}
|
||||
return s.snapshot, &roverClock{s.clockID, stamp}
|
||||
}
|
||||
|
||||
@@ -233,3 +233,44 @@ func TestRoverStreamReadsMultipleFramesOnOneResponse(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelayedHTTPClockCannotMakeNewTelemetryArtificiallyStale(t *testing.T) {
|
||||
origin := time.Unix(100, 0)
|
||||
s := newRoverStreamState(origin)
|
||||
s.telemetryStamped = true
|
||||
s.sampleClock(roverClock{testClockID, 10000}, origin, origin.Add(50*time.Millisecond))
|
||||
// Fast command-stream receipt and a fresh local measurement, followed by
|
||||
// a late HTTP response sampled much earlier on Core.
|
||||
s.receivedFrame(roverStreamReply{Clock: roverClock{testClockID, 10750}}, origin.Add(800*time.Millisecond))
|
||||
s.deliveredAt(map[string]any{"state": "observing"}, 0, origin.Add(850*time.Millisecond))
|
||||
s.sampleClock(roverClock{testClockID, 10050}, origin.Add(50*time.Millisecond), origin.Add(900*time.Millisecond))
|
||||
_, stamp := s.telemetryView()
|
||||
if stamp == nil || stamp.MonotonicMS < 10790 || stamp.MonotonicMS > 10850 {
|
||||
t.Fatal("late response rolled the observation clock backwards", stamp)
|
||||
}
|
||||
// No new measurement: advancing the bounds cannot rejuvenate the sample.
|
||||
before := stamp.MonotonicMS
|
||||
s.receivedFrame(roverStreamReply{Clock: roverClock{testClockID, 11750}}, origin.Add(1800*time.Millisecond))
|
||||
_, stale := s.telemetryView()
|
||||
if stale.MonotonicMS > before+2 || s.command != nil {
|
||||
t.Fatal("old sample/authority renewed", stale, s.command)
|
||||
}
|
||||
}
|
||||
|
||||
func TestObservationClockEpochAndInvalidSamplesCannotReuseOldBound(t *testing.T) {
|
||||
origin := time.Unix(100, 0)
|
||||
s := newRoverStreamState(origin)
|
||||
s.telemetryStamped = true
|
||||
s.sampleClock(roverClock{testClockID, 10000}, origin, origin)
|
||||
s.receivedFrame(roverStreamReply{Clock: roverClock{"foreign", 99999}}, origin.Add(time.Millisecond))
|
||||
if s.lowerClockMS != 10000 {
|
||||
t.Fatal("foreign clock changed lower bound")
|
||||
}
|
||||
next := "cccccccccccccccccccccccccccccccc"
|
||||
s.sampleClock(roverClock{next, 10}, origin.Add(time.Second), origin.Add(time.Second))
|
||||
s.deliveredAt(map[string]any{}, 0, origin.Add(time.Second))
|
||||
_, stamp := s.telemetryView()
|
||||
if stamp.Instance != next || stamp.MonotonicMS > 10 || s.command != nil {
|
||||
t.Fatal("old epoch retained", stamp)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const roverConnectTimeout = 2 * time.Second
|
||||
|
||||
// Each rover lane owns its connection pool. Establishing a connection grants
|
||||
// neither a command lease nor permission to revive an interrupted session.
|
||||
func newRoverHTTPTransport(config *tls.Config) *http.Transport {
|
||||
return &http.Transport{TLSClientConfig: config, Proxy: nil,
|
||||
MaxConnsPerHost: 1, MaxIdleConnsPerHost: 1, IdleConnTimeout: 10 * time.Second,
|
||||
TLSHandshakeTimeout: time.Second, ResponseHeaderTimeout: 2 * time.Second,
|
||||
// A one-second connect deadline races the initial SYN retransmission.
|
||||
// Allow that retry; the probe's 2.5 s context and lane cancellation still
|
||||
// bound establishment. This never extends a command or the stream guard.
|
||||
DialContext: (&net.Dialer{Timeout: roverConnectTimeout}).DialContext}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSensorFailureKeepsNativeEvidenceForCore(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
s, _ := OpenSensors(root, "node_test")
|
||||
isolateSensorHost(t, s)
|
||||
c := sensorTestCommand()
|
||||
s.operations[c.ID] = &SensorOperation{Command: c, State: "running", Remote: true}
|
||||
s.client = &http.Client{Transport: sensorRoundTrip(func(r *http.Request) (*http.Response, error) {
|
||||
body := `{"items":[{"id":"` + c.Session.DeviceID + `"}]}`
|
||||
if r.URL.Path == "/operation" {
|
||||
body = `{"state":"error","error":"Read failed","result":{"failure":{"native_rpc":{"method":"diagnostic","command":"hw_status","error":"No response"}}}}`
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{}}, nil
|
||||
})}
|
||||
s.execute(c)
|
||||
value := s.Get(c.ID)
|
||||
if value.State != "error" || value.Error != "Read failed" || value.Result == nil {
|
||||
t.Fatalf("Lost driver failure: %+v", value)
|
||||
}
|
||||
failure := value.Result.(map[string]any)["failure"].(map[string]any)
|
||||
rpc := failure["native_rpc"].(map[string]any)
|
||||
if rpc["command"] != "hw_status" {
|
||||
t.Fatal("Wrong native request retained")
|
||||
}
|
||||
reopened, err := OpenSensors(root, "node_test")
|
||||
if err != nil || reopened.Get(c.ID) == nil || reopened.Get(c.ID).Result == nil {
|
||||
t.Fatal("Failure evidence lost after restart", err)
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ func actions(names ...string) map[string]bool {
|
||||
}
|
||||
|
||||
var sensorModels = []sensorModel{
|
||||
{ID: "realsense.d455", Name: "RealSense D455", Prefix: "rsd455", Plugin: "missioncore.realsense", Version: "0.6.6",
|
||||
{ID: "realsense.d455", Name: "RealSense D455", Prefix: "rsd455", Plugin: "missioncore.realsense", Version: "0.6.7",
|
||||
Vendor: "8086", Product: "0b5c", Socket: "/run/mission-core-sensors/driver.sock",
|
||||
PrepareUnit: "mission-core-node-realsense-prepare.service", Report: "/var/lib/mission-core-node-drivers/preparation.json",
|
||||
Actions: actions("prepare", "details", "rename", "verify", "start", "replay", "stop", "option", "offer", "close-peer")},
|
||||
@@ -46,11 +46,15 @@ var sensorModels = []sensorModel{
|
||||
PrepareUnit: "mission-core-node-insta360-x4-profile.service", Report: "/var/lib/mission-core-node-profiles/insta360-x4/preparation.json",
|
||||
ActionTimeouts: map[string]time.Duration{"power.wake": 55 * time.Second},
|
||||
Actions: actions("prepare", "details", "rename", "verify", "preview.start", "preview.stop", "record.start", "record.stop", "photo.capture", "settings.read", "settings.apply", "files.list", "offer", "close-peer", "recovery.configure", "power.wake")},
|
||||
{ID: "vesc.controller", Name: "VESC", Prefix: "vesc", Kind: "vesc.controller", Plugin: "missioncore.vesc", Version: "0.7.4",
|
||||
{ID: "vesc.controller", Name: "VESC", Prefix: "vesc", Kind: "vesc.controller", Plugin: "missioncore.vesc", Version: "0.20.11",
|
||||
Vendor: "0483", Product: "5740", USBName: "ChibiOS/RT Virtual COM Port", Socket: "/run/mission-core-vesc/driver.sock",
|
||||
PrepareUnit: "mission-core-node-vesc-prepare.service", Report: "/var/lib/mission-core-node-profiles/vesc/preparation.json",
|
||||
ActionTimeouts: map[string]time.Duration{"vesc.link.check": 45 * time.Second, "vesc.motor.run": 90 * time.Second, "vesc.drive.run": 120 * time.Second, "vesc.hall.measure": 60 * time.Second, "vesc.foc.calibrate": 300 * time.Second, "vesc.motor.pulse": 60 * time.Second, "vesc.control.release": 60 * time.Second},
|
||||
ProtocolIdentity: true, Actions: actions("prepare", "details", "rename", "verify", "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.drive.assign", "vesc.drive.layout", "vesc.drive.unassign", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release")},
|
||||
ActionTimeouts: map[string]time.Duration{"vesc.packages.apply": 350 * time.Second, "vesc.packages.prepare": 70 * time.Second, "vesc.packages.status": 70 * time.Second, "vesc.packages.restore": 70 * time.Second, "vesc.packages.reconcile": 70 * time.Second, "vesc.packages.remove_prepare": 70 * time.Second, "vesc.code.apply": 180 * time.Second, "vesc.firmware.apply": 300 * time.Second, "vesc.configuration.apply": 60 * time.Second, "vesc.link.check": 45 * time.Second, "vesc.motor.run": 90 * time.Second, "vesc.drive.run": 120 * time.Second, "vesc.hall.measure": 60 * time.Second, "vesc.foc.calibrate": 300 * time.Second, "vesc.motor.pulse": 60 * time.Second, "vesc.control.release": 60 * time.Second},
|
||||
ProtocolIdentity: true, Actions: actions("prepare", "details", "rename", "verify", "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.configuration.read", "vesc.configuration.preview", "vesc.configuration.apply", "vesc.bms.configuration.read", "vesc.bms.configuration.preview", "vesc.bms.configuration.apply", "vesc.bms.configuration.reconcile", "vesc.bms.configuration.restore", "vesc.packages.catalog", "vesc.packages.inspect", "vesc.packages.download", "vesc.packages.begin", "vesc.packages.chunk", "vesc.packages.load", "vesc.packages.forget", "vesc.packages.status", "vesc.packages.prepare", "vesc.packages.remove_prepare", "vesc.packages.restore", "vesc.packages.apply", "vesc.packages.reconcile", "vesc.packages.refresh", "vesc.samples.start", "vesc.samples.status", "vesc.samples.fetch", "vesc.samples.stop", "vesc.samples.read", "vesc.qml.begin", "vesc.qml.chunk", "vesc.qml.render", "vesc.qml.open", "vesc.qml.frame", "vesc.qml.close", "vesc.code.read", "vesc.code.begin", "vesc.code.chunk", "vesc.code.prepare", "vesc.code.erase_prepare", "vesc.code.apply", "vesc.code.reconcile", "vesc.code.control_prepare", "vesc.code.control_apply", "vesc.code.stats", "vesc.code.restore", "vesc.bms.read", "vesc.bms.prepare", "vesc.bms.apply", "vesc.tools.read", "vesc.terminal.read", "vesc.configuration.reconcile", "vesc.firmware.backup", "vesc.firmware.target", "vesc.firmware.catalog", "vesc.firmware.catalog_prepare", "vesc.firmware.begin", "vesc.firmware.chunk", "vesc.firmware.seal", "vesc.firmware.discard", "vesc.firmware.apply", "vesc.firmware.status", "vesc.firmware.cancel", "vesc.firmware.reconcile", "vesc.diagnostics.read", "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.transport.configure", "vesc.drive.assign", "vesc.drive.layout", "vesc.drive.unassign", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release")},
|
||||
{ID: "waveshare.usb-can-fd-b", Name: "Waveshare USB-CAN-FD-B", Prefix: "usbcan", Kind: "waveshare.usb-can-fd-b", Plugin: "missioncore.usb-can", Version: "0.2.7",
|
||||
Vendor: "04d8", Product: "0053", USBName: "USB CANFD DEBUG", Socket: "/run/mission-core-usb-can/driver.sock",
|
||||
PrepareUnit: "mission-core-node-usb-can-prepare.service", Report: "/var/lib/mission-core-node-profiles/usb-can/preparation.json",
|
||||
ProtocolIdentity: true, Actions: actions("prepare", "details", "rename", "verify", "can.status", "can.configure", "can.start", "can.stop", "can.clear", "can.transmit.preview", "can.transmit.apply", "can.transmit.stop")},
|
||||
}
|
||||
|
||||
func modelForDevice(id string) *sensorModel {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Configuration browsing is a bounded snapshot, not a durable backup or write receipt.
|
||||
func sensorSnapshot(action string) bool {
|
||||
return strings.HasPrefix(action, "can.") || action == "vesc.qml.open" || action == "vesc.qml.frame" || action == "vesc.qml.close" || action == "vesc.samples.start" || action == "vesc.samples.status" || action == "vesc.samples.fetch" || action == "vesc.samples.stop" || action == "vesc.samples.read" || action == "vesc.qml.begin" || action == "vesc.qml.chunk" || action == "vesc.qml.render" || action == "vesc.packages.catalog" || action == "vesc.packages.inspect" || action == "vesc.packages.download" || action == "vesc.packages.begin" || action == "vesc.packages.chunk" || action == "vesc.packages.load" || action == "vesc.packages.forget" || action == "vesc.packages.status" || action == "vesc.packages.prepare" || action == "vesc.packages.remove_prepare" || action == "vesc.packages.restore" || action == "vesc.packages.reconcile" || action == "vesc.packages.refresh" || action == "vesc.bms.configuration.read" || action == "vesc.bms.configuration.preview" || action == "vesc.bms.configuration.reconcile" || action == "vesc.bms.configuration.restore" || action == "vesc.code.read" || action == "vesc.code.begin" || action == "vesc.code.chunk" || action == "vesc.code.prepare" || action == "vesc.code.erase_prepare" || action == "vesc.code.reconcile" || action == "vesc.code.control_prepare" || action == "vesc.code.stats" || action == "vesc.code.restore" || action == "vesc.firmware.backup" || action == "vesc.firmware.target" || action == "vesc.bms.read" || action == "vesc.bms.prepare" || action == "vesc.firmware.catalog" || action == "vesc.tools.read" || action == "vesc.terminal.read" || action == "vesc.firmware.status" || action == "vesc.configuration.read" || action == "vesc.configuration.preview" || action == "vesc.diagnostics.read"
|
||||
}
|
||||
|
||||
func expiredSensorSnapshot(value SensorOperation) SensorOperation {
|
||||
value.State = "error"
|
||||
value.Error = "Снимок больше не хранится. Прочитайте данные заново."
|
||||
value.Result = nil
|
||||
return value
|
||||
}
|
||||
|
||||
// Caller owns s.mu. Retain at most eight payloads (8 MiB); never evict an
|
||||
// unacknowledged remote result to admit a new request. Tombstones retain
|
||||
// operation identity, so retrying an old ID cannot execute hardware work again.
|
||||
func (s *Sensors) writeOperation(value *SensorOperation) error {
|
||||
// CAN requests/results are bounded RAM. On restart every USB generation is
|
||||
// replaced; queued old-session commands cannot execute or replay TX.
|
||||
if strings.HasPrefix(value.Command.Action, "can.") && value.Result == nil { return nil }
|
||||
|
||||
if !sensorSnapshot(value.Command.Action) || value.Result == nil {
|
||||
return s.write(value.Command.ID+".json", value)
|
||||
}
|
||||
for {
|
||||
count, bytes := 0, 0
|
||||
var oldest *SensorOperation
|
||||
for _, entry := range s.operations {
|
||||
if !sensorSnapshot(entry.Command.Action) || entry.Result == nil {
|
||||
continue
|
||||
}
|
||||
raw, err := json.Marshal(entry.Result)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
count++
|
||||
bytes += len(raw)
|
||||
if entry != value && !entry.Remote && (oldest == nil || entry.Updated < oldest.Updated) {
|
||||
oldest = entry
|
||||
}
|
||||
}
|
||||
if count <= 8 && bytes <= 8*1024*1024 {
|
||||
break
|
||||
}
|
||||
if oldest == nil {
|
||||
*value = expiredSensorSnapshot(*value)
|
||||
break
|
||||
}
|
||||
*oldest = expiredSensorSnapshot(*oldest)
|
||||
}
|
||||
// Payloads expire even if the operator leaves this panel open overnight.
|
||||
for _, entry := range s.operations {
|
||||
if sensorSnapshot(entry.Command.Action) && entry.Result != nil && !entry.Remote && time.Now().Unix()-entry.Updated >= 600 {
|
||||
*entry = expiredSensorSnapshot(*entry)
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(value.Command.Action, "can.") { return nil }
|
||||
persisted := expiredSensorSnapshot(*value)
|
||||
return s.write(value.Command.ID+".json", &persisted)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSensorConfigurationSnapshotsBoundedAndNotPersisted(t *testing.T) {
|
||||
s := &Sensors{root: t.TempDir(), operations: map[string]*SensorOperation{}}
|
||||
for i := 0; i < 12; i++ {
|
||||
id := strings.Repeat("a", i+1)
|
||||
op := &SensorOperation{Command: SensorCommand{ID: id, Action: "vesc.configuration.read"}, State: "complete", Result: map[string]any{"xml": strings.Repeat("x", 100)}, Updated: time.Now().Unix() + int64(i)}
|
||||
s.operations[id] = op
|
||||
if err := s.writeOperation(op); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(s.root, id+".json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var disk SensorOperation
|
||||
if err = json.Unmarshal(raw, &disk); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if disk.Result != nil || disk.State != "error" {
|
||||
t.Fatal("read payload was persisted")
|
||||
}
|
||||
}
|
||||
count := 0
|
||||
for _, op := range s.operations {
|
||||
if op.Result != nil {
|
||||
count++
|
||||
}
|
||||
}
|
||||
if count != 8 {
|
||||
t.Fatalf("snapshot count %d", count)
|
||||
}
|
||||
if s.operations["a"].State != "error" {
|
||||
t.Fatal("old snapshot remained live")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigurationBackupsRemainDurable(t *testing.T) {
|
||||
s := &Sensors{root: t.TempDir(), operations: map[string]*SensorOperation{}}
|
||||
op := &SensorOperation{Command: SensorCommand{ID: "backup", Action: "vesc.config.backup"}, State: "complete", Result: map[string]any{"backup": true}}
|
||||
if err := s.writeOperation(op); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := os.ReadFile(filepath.Join(s.root, "backup.json"))
|
||||
var disk SensorOperation
|
||||
if err := json.Unmarshal(raw, &disk); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if disk.Result == nil || disk.State != "complete" {
|
||||
t.Fatal("backup receipt was discarded")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Only the existing observer owns USB sampling. This endpoint renews bounded
|
||||
// read interest; it cannot pass a relay, command, action or input lease.
|
||||
func (s *Sensors) telemetryRoutes(mux *http.ServeMux, server *Server) {
|
||||
mux.HandleFunc("GET /api/devices/telemetry", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !server.authorized(w, r) {
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
var model *sensorModel
|
||||
for i := range sensorModels {
|
||||
if sensorModels[i].ID == "vesc.controller" {
|
||||
model = &sensorModels[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if model == nil {
|
||||
reply(w, 503, map[string]string{"error": "Интеграция VESC недоступна."})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 800*time.Millisecond)
|
||||
defer cancel()
|
||||
result, err := s.modelDriver(ctx, model, "/observe", nil)
|
||||
if err != nil {
|
||||
reply(w, 503, map[string]string{"error": "Нет свежих показаний контроллеров."})
|
||||
return
|
||||
}
|
||||
result["fresh"] = true
|
||||
reply(w, 200, result)
|
||||
})
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user