Files
NODEDC_MISSION_CORE/apps/control-station/test/roverControlStartup.test.mjs

272 lines
21 KiB
JavaScript

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/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,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,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','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,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,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=>{
const a=f.delayArm();const arming=f.c.arm(30,2000);const p=f.delayPoll();f.poll();
a.resolve(response({session_id:'new-session'}));assert.equal(await arming,true);await flush();
p.resolve(response(idle));await flush();f.heartbeat();await flush();
assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0,'old idle poll revoked the new session');
assert.equal(f.calls.at(-1).body.session_id,'new-session');
}));
test('failed poll begun during pending arm cannot revoke newly acknowledged session',async()=>fixture(async f=>{
const a=f.delayArm();const arming=f.c.arm(30,2000);const p=f.delayPoll();f.poll();
a.resolve(response({session_id:'new-session'}));assert.equal(await arming,true);await flush();
p.resolve({ok:false,json:async()=>({detail:'stale read failure'})});await flush();
assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0,'old failed poll revoked the new session');
}));
test('a current poll still revokes control when server reports lease lost',async()=>fixture(async f=>{
assert.equal(await f.c.arm(30,2000),true);await flush();f.poll();await flush();
assert.equal(f.calls.at(-1).body.stop,true);
}));
test('duplicate arm clicks while request pending create exactly one lease request',async()=>fixture(async f=>{
const a=f.delayArm();const first=f.c.arm(30,2000),second=f.c.arm(30,2000);
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,telemetry_stop_ms:1000});
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,telemetry_stop_ms:1000});
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));
});
}
});
test('active telemetry tolerance does not relabel data fresh or change command inputs',async()=>fixture(async f=>{
assert.equal(await f.c.arm(30,70,'duty',2000),true);await flush();
assert.equal(f.calls.find(x=>x.url.endsWith('/arm')).body.telemetry_stop_ms,2000);
const p=f.delayPoll();f.poll();p.resolve(response({...idle,fresh:false,control_fresh:true,controlling:true,telemetry_age_ms:1300,telemetry_stop_ms:2000,snapshot:{...idle.snapshot,state:'ready',session_id:'new-session'}}));await flush();
assert.equal(f.calls.filter(x=>x.body?.stop===true).length,0);
f.heartbeat();await flush();assert.equal('telemetry_stop_ms' in f.calls.at(-1).body,false);
}));