feat(network): verify selected uplinks, roll back failures and manage NetBird policy

This commit is contained in:
DCCONSTRUCTIONS
2026-11-21 20:58:26 +03:00
parent a50d638ced
commit 43d4916331
63 changed files with 6743 additions and 12 deletions
@@ -0,0 +1,38 @@
export interface UplinkCandidate {id:string;label:string;interface:string;kind:'wifi'|'ethernet';verified:boolean;available?:boolean;active?:boolean}
export interface BoardUplinkView {
path_verified?:boolean;available:boolean;reason:string;revision:string;runtime:string;current_id:string;candidates:UplinkCandidate[];
operation:{id:string;phase:string;message:string}|null;
fallback?:{enabled:boolean;revision:number;operation_id:string}|null;
fallback_operation?:{id:string;phase:string;message:string}|null;
}
export const uplinkPending=(value:BoardUplinkView|null)=>['queued','applying','verifying','rolling_back','recovering','unknown','rollback_failed'].includes(value?.operation?.phase||'');
export const fallbackPending=(value:BoardUplinkView|null)=>value?.fallback_operation?.phase==='queued';
export const canSetFallback=(value:BoardUplinkView|null)=>Boolean(value?.available&&value.path_verified&&value.fallback&&!uplinkPending(value)&&!fallbackPending(value));
export const canSelectUplink=(value:BoardUplinkView|null,target:string)=>Boolean(value?.available&&!uplinkPending(value)&&!fallbackPending(value)&&value.current_id&&(target!==value.current_id||value.path_verified===false)&&value.candidates.some(c=>c.id===target&&(c.available||c.verified)));
export const uplinkOptions=(value:BoardUplinkView|null)=>(value?.candidates??[]).map(c=>({value:c.id,label:`${c.kind==='wifi'?'Wi-Fi':'Ethernet'} · ${c.label}`,description:`${c.interface}${c.id===value?.current_id?' · Текущее':''}${!c.verified?(c.active?' · Интернет не подтверждён':' · Не подключено'):''}`,disabled:!(c.available||c.verified)}));
export const uplinkStatusMessage=(value:BoardUplinkView|null)=>{
if(!value)return '';
if(!value.available)return value.reason;
if(uplinkPending(value))return value.operation?.message||'Проверяем подключение.';
const op=value.operation;
if(op?.phase==='applied'||op?.phase==='rolled_back'){
if(!value.path_verified)return 'Текущий путь к Core не подтверждён.';
const result=op.phase==='applied'?'Подключение выбрано.':'Возвращено прежнее подключение.';
return `${result} ${value.path_verified?'Путь к Core подтверждён.':'Текущий путь к Core не подтверждён.'}`;
}
return op?.message||'';
};
// Follow observed state unless the operator is deliberately choosing an alternative.
export const uplinkReceipt=(value:BoardUplinkView|null)=>value?.operation?`${value.operation.id}:${value.operation.phase}`:'';
export const reconcileUplinkSelection=(selected:string,previousCurrent:string,next:BoardUplinkView,previousReceipt='')=>{
const settled=Boolean(next.operation&&!uplinkPending(next)&&uplinkReceipt(next)!==previousReceipt);
return settled||selected===previousCurrent||!next.candidates.some(c=>c.id===selected&&(c.available||c.verified))?next.current_id:selected;
};
export const uplinkCurrentLabel=(value:BoardUplinkView|null)=>{
if(!value?.available)return value?.reason||'Получаем состояние сети с борта.';
if(uplinkPending(value))return 'Текущее подключение: проверяется.';
const current=value.candidates.find(c=>c.id===value.current_id);
if(!current)return 'Основное подключение не определено.';
return `Текущее подключение: ${current.kind==='wifi'?'Wi-Fi':'Ethernet'} · ${current.label}${value.path_verified?'':' · путь к Core не подтверждён'}.`;
};
@@ -0,0 +1,43 @@
import {useEffect,useRef,useState} from 'react';
import {fleetRequest} from './useFleet';
import {canSelectUplink,canSetFallback,fallbackPending,uplinkPending,uplinkReceipt,reconcileUplinkSelection,type BoardUplinkView} from './boardUplink';
export function useBoardUplink(vehicleId:string){
const [value,setValue]=useState<BoardUplinkView|null>(null),[target,setTarget]=useState(''),[error,setError]=useState(''),[loadError,setLoadError]=useState(''),[busy,setBusy]=useState(false);
const selected=useRef(''),previousCurrent=useRef(''),previousReceipt=useRef(''),generation=useRef(0);
useEffect(()=>{const epoch=++generation.current;let live=true;let timer:ReturnType<typeof setTimeout>;const abort=new AbortController();
selected.current='';previousCurrent.current='';previousReceipt.current='';setTarget('');setValue(null);setError('');setLoadError('');setBusy(false);
const poll=async()=>{try{
const next=await fleetRequest<BoardUplinkView>(`/${encodeURIComponent(vehicleId)}/uplink`,'GET',undefined,12000,abort.signal);
if(!live||generation.current!==epoch)return;
setValue(next);setLoadError('');
const choice=reconcileUplinkSelection(selected.current,previousCurrent.current,next,previousReceipt.current);
previousReceipt.current=uplinkReceipt(next);
previousCurrent.current=next.current_id;selected.current=choice;setTarget(choice);
}catch(e){if(live){setValue(old=>old?{...old,available:false}:null);setLoadError(e instanceof Error?e.message:'Нет сведений о подключении.');}}
finally{if(live)timer=setTimeout(poll,2000);}};
void poll();return()=>{live=false;abort.abort();clearTimeout(timer);};
},[vehicleId]);
const choose=(id:string)=>{selected.current=id;setTarget(id);setError('');};
const connect=async()=>{
if(busy||!value||!canSelectUplink(value,target))return;
const epoch=generation.current;setBusy(true);setError('');
try{
const operation=await fleetRequest<NonNullable<BoardUplinkView['operation']>>(`/${encodeURIComponent(vehicleId)}/uplink`,'POST',{target,revision:value.revision,runtime:value.runtime,operation_id:crypto.randomUUID().replaceAll('-','')});
if(generation.current===epoch)setValue(old=>old?{...old,operation}:old);
}catch(e){if(generation.current===epoch)setError(e instanceof Error?e.message:'Нет подтверждения команды. Проверьте состояние подключения.');}
finally{if(generation.current===epoch)setBusy(false);}
};
const setFallback=async(enabled:boolean)=>{
if(busy||!canSetFallback(value)||!value?.fallback)return;
const epoch=generation.current;setBusy(true);setError('');
try{
const operation=await fleetRequest<NonNullable<BoardUplinkView['operation']>>(`/${encodeURIComponent(vehicleId)}/uplink/fallback`,'PATCH',{enabled,revision:value.fallback.revision,runtime:value.runtime,operation_id:crypto.randomUUID().replaceAll('-','')});
if(generation.current===epoch)setValue(old=>old?{...old,fallback_operation:operation}:old);
}catch(e){if(generation.current===epoch)setError(e instanceof Error?e.message:'Настройка не сохранена.');}
finally{if(generation.current===epoch)setBusy(false);}
};
return {value,target,choose,error:error||loadError,busy,connect,setFallback,
fallbackPending:fallbackPending(value),canSetFallback:!busy&&canSetFallback(value),
pending:uplinkPending(value),canConnect:!busy&&canSelectUplink(value,target)};
}
@@ -23,7 +23,7 @@ export function BoardComputerSettings({vehicle,enabled,onClose,onRevoke}:{vehicl
identity={{title:vehicle.host?.hostname||'Mission Core Node',subtitle:vehicle.node_id,avatarLabel:'БК'}}
sections={[{id:'binding',label:'Привязка',icon:'apps'},{id:'network',label:'Связь с Core',icon:'network'},{id:'interfaces',label:'Сеть',icon:'network'}]} activeSection={section} onSectionChange={setSection} onClose={onClose}
footer={<WindowFooterActions><Button variant="secondary" onClick={onClose}>Закрыть</Button>{section==='network'&&<Button variant="primary" disabled={!network.canSave} onClick={()=>void network.save()}>{network.applying?'Применяем…':'Сохранить'}</Button>}</WindowFooterActions>}>
{section==='network'?<BoardNetworkSettings network={network}/>:section==='interfaces'?<BoardNetworkStatus status={interfaces}/>:
{section==='network'?<BoardNetworkSettings network={network}/>:section==='interfaces'?<BoardNetworkStatus status={interfaces} vehicleId={vehicle.id}/>:
<div className="fleet-form"><StatusBadge tone={enabled?'success':vehicle.enrollment==='pending'?'warning':'neutral'}>{boardStatus(vehicle,enabled)}</StatusBadge>
{vehicle.notice&&<Description role="status">{vehicle.notice}</Description>}
<dl className="fleet-facts"><div><dt>Идентификатор БК</dt><dd>{vehicle.node_id}</dd></div><div><dt>Последняя связь</dt><dd>{vehicle.last_seen?new Date(vehicle.last_seen*1000).toLocaleString('ru-RU'):'Соединение ещё не получено'}</dd></div>
@@ -1,4 +1,5 @@
import {memo} from 'react';
import {BoardUplinkControl} from './BoardUplinkControl';
import {Description,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import type {BoardNetworkStatusValue} from '../../core/fleet/boardNetworkStatus';
@@ -15,10 +16,11 @@ const NetworkCard=memo(function NetworkCard(link:BoardNetworkStatusValue['links'
</dl>
</SettingsCard>;
});
export function BoardNetworkStatus({status}:{status:BoardNetworkStatusValue}) {
export function BoardNetworkStatus({status,vehicleId}:{status:BoardNetworkStatusValue;vehicleId:string}) {
const {links,readable,live,collectedAt}=status;
return <div className="fleet-form">
<Description>Состояние Wi-Fi и Ethernet по последним полученным данным борта. Карточки обновляются при изменении сведений. Изменение сети здесь недоступно.</Description>
<BoardUplinkControl vehicleId={vehicleId}/>
<Description>Состояние Wi-Fi и Ethernet по последним полученным данным борта. Карточки обновляются при изменении сведений.</Description>
<StatusBadge tone={live?'success':'neutral'}>{live?'Связь с бортом установлена':'Связь с бортом не подтверждена'}</StatusBadge>
<Description>Данные борта на {collectedAt&&Number.isFinite(Date.parse(collectedAt))?new Date(collectedAt).toLocaleString('ru-RU'):'ещё не получен'}.</Description>
{!links.length?<SettingsCard title={readable?'Нет сведений о Wi-Fi и Ethernet':'Сведения о сети недоступны'} description="Борт пока не передал данные физических подключений."/>:
@@ -0,0 +1,23 @@
import {Button,Description,Select,SettingsCard,Switch} from '@nodedc/ui-react';
import {useBoardUplink} from '../../core/fleet/useBoardUplink';
import {uplinkOptions,uplinkStatusMessage,uplinkCurrentLabel} from '../../core/fleet/boardUplink';
import './boardUplink.css';
export function BoardUplinkControl({vehicleId}:{vehicleId:string}){
const state=useBoardUplink(vehicleId);
const {value,target,busy,pending,error}=state;
const message=error||uplinkStatusMessage(value);
return <SettingsCard title="Текущее активное соединение">
<div className="board-uplink-selection">
<Select label="Подключение борта" value={target} onChange={state.choose} disabled={!value?.available||busy||pending}
options={value?.candidates.length?uplinkOptions(value):[{value:'',label:value?'Нет доступных подключений':'Получаем подключения…'}]}/>
<Button disabled={!state.canConnect} loading={busy||pending} onClick={()=>void state.connect()}>Подключить</Button>
</div>
<Description>{uplinkCurrentLabel(value)}</Description>
<Switch label="Переключаться на резервный канал" checked={value?.fallback?.enabled??false}
disabled={!state.canSetFallback} onChange={enabled=>void state.setFallback(enabled)}/>
{state.fallbackPending&&<Description role="status">Сохраняем настройку на борту…</Description>}
{value?.fallback_operation?.phase==='failed'&&<Description role="status">{value.fallback_operation.message}</Description>}
{message&&<Description role="status">{message}</Description>}
</SettingsCard>;
}
@@ -0,0 +1,2 @@
.board-uplink-selection { display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:end; gap:var(--nodedc-space-3); }
.board-uplink-selection > * { min-width:0; }
@@ -41,10 +41,10 @@ test('invalid signal and failed address reads remain unknown',()=>{
const v=fixture();v.host.networks[0].connection.signal_percent=101;v.host.networks[0].addresses_readable=false;
assert.equal(project(v,true).links[0].signal,null);assert.equal(project(v,true).links[0].addresses,null);
});
test('network section displays escaped real facts and exposes no mutation controls',()=>{
test('network section keeps escaped adapter facts and adds guarded uplink control',()=>{
const html=renderToStaticMarkup(createElement(View,{status:project(fixture(),true)}));
assert.match(html,/Test &lt;network&gt;/);assert.match(html,/0%/);assert.match(html,/192\.0\.2\.4/);assert.match(html,/Ethernet/);
assert.doesNotMatch(html,/<button|<input|<select|tunnel|Сохранить/);
assert.match(html,/Текущее активное соединение/);assert.match(html,/Подключить/);assert.match(html,/disabled/);assert.doesNotMatch(html,/tunnel|Сохранить/);
const stale=renderToStaticMarkup(createElement(View,{status:project(fixture(0),true)}));
assert.doesNotMatch(stale,/Данные устарели/);assert.match(stale,/по последним полученным данным/);
});
@@ -0,0 +1,27 @@
import assert from 'node:assert/strict';
import {after,before,test} from 'node:test';
import {createServer} from './support/vite-server.mjs';
let server,can,pending,options,reconcile,message,currentLabel;
before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});
({canSelectUplink:can,uplinkPending:pending,uplinkOptions:options,reconcileUplinkSelection:reconcile,uplinkStatusMessage:message,uplinkCurrentLabel:currentLabel}=await server.ssrLoadModule('/src/core/fleet/boardUplink.ts'));});
after(async()=>{await server?.close();});
const sample=()=>({available:true,current_id:'a',operation:null,candidates:[{id:'a',kind:'wifi',label:'Saved network',interface:'random-radio',verified:true,active:true},{id:'b',kind:'ethernet',label:'Cable',interface:'random-port',verified:true,active:true}]});
test('only verified fresh alternatives can be selected',()=>{const v=sample();assert.ok(can(v,'b'));assert.ok(!can(v,'a'));assert.ok(!can(v,'missing'));assert.ok(!can(null,'b'));v.available=false;assert.ok(!can(v,'b'));v.available=true;v.candidates[1].verified=false;assert.ok(!can(v,'b'));});
test('pending phases exclude a second command without hiding receipt',()=>{for(const phase of ['queued','applying','verifying','rolling_back','recovering','unknown','rollback_failed']){const v={...sample(),operation:{phase}};assert.ok(pending(v));assert.ok(!can(v,'b'));}assert.ok(!pending({...sample(),operation:{phase:'rolled_back'}}));});
test('options use board profile identities and disclose unverified alternatives',()=>{const v=sample();v.candidates[1].verified=false;const items=options(v);assert.equal(items[1].disabled,true);assert.match(items[0].description,/Текущее/);assert.match(items[1].description,/Интернет не подтверждён/);});
test('observed state updates an unchanged selection without replacing a deliberate draft',()=>{const next={...sample(),current_id:'b'};assert.equal(reconcile('a','a',next),'b');assert.equal(reconcile('b','a',sample()),'b');next.candidates[0].verified=false;assert.equal(reconcile('a','b',next),'b');});
test('same default can be repaired when VPN path was not verified',()=>{const v={...sample(),path_verified:false};assert.ok(can(v,'a'));v.path_verified=true;assert.ok(!can(v,'a'));});
test('current path proof overrides historical success text',()=>{const v={...sample(),operation:{phase:'applied',message:'Путь к Core подтверждён.'},path_verified:false};assert.match(message(v),/не подтверждён/);v.path_verified=true;assert.match(message(v),/Путь к Core подтверждён/);v.available=false;v.reason='Нет свежих данных';assert.equal(message(v),v.reason);});
test('disconnected available profile permits a trial but is never called verified',()=>{const v=sample();Object.assign(v.candidates[1],{verified:false,active:false,available:true});assert.ok(can(v,'b'));assert.equal(options(v)[1].disabled,false);assert.match(options(v)[1].description,/Не подключено/);});
test('pending default route never presents a completed current connection',()=>{const v={...sample(),current_id:'b',path_verified:false,operation:{phase:'verifying',message:'Проверяем путь связи с Core.'}};assert.match(currentLabel(v),/проверяется/);assert.doesNotMatch(currentLabel(v),/Cable/);assert.doesNotMatch(message(v),/подтверждён/);});
test('settled rollback resets failed draft once, then permits a new deliberate selection',()=>{
const v={...sample(),operation:{id:'attempt',phase:'rolled_back'},path_verified:true};
assert.equal(reconcile('b','a',v,'attempt:recovering'),'a');
assert.equal(reconcile('b','a',v,'attempt:rolled_back'),'b');
assert.equal(reconcile('b','a',v,'older:rolled_back'),'a');
});