feat(system): add worker and VPS catalogs with guarded local removal

This commit is contained in:
DCCONSTRUCTIONS
2026-11-10 01:11:24 +03:00
parent ad5a929e06
commit e8025bc99f
25 changed files with 1556 additions and 116 deletions
@@ -27,6 +27,8 @@ import { ContourHealthWorkspace } from "./ContourHealthWorkspace";
import { LaboratoryArchiveWorkspace } from "./laboratory/LaboratoryArchiveWorkspace";
import { SimulationWorkspace } from "./simulation/SimulationWorkspace";
import { ComputeModulesWorkspace } from "./system/ComputeModulesWorkspace";
import { WorkersWorkspace } from "./system/WorkersWorkspace";
import { ServersWorkspace } from "./system/ServersWorkspace";
import { NetworkWorkspace } from "./system/NetworkWorkspace";
import { WorldMapWorkspace } from "./map/WorldMapWorkspace";
import { ObservatoryWorkspace } from "./observatory/ObservatoryWorkspace";
@@ -441,6 +443,10 @@ export function WorkspaceRenderer(props: WorkspaceRendererProps) {
state={props.state}
/>
);
case "workers":
return <WorkersWorkspace headerToolsHost={props.headerToolsHost} onView={() => props.navigation.openView("modules")} />;
case "vps":
return <ServersWorkspace headerToolsHost={props.headerToolsHost} />;
case "compute-modules":
return <ComputeModulesWorkspace />;
case "network-monitor":
@@ -5,25 +5,27 @@ import type {SensorEnrollmentProps} from '../../../../../../packages/sensor-ui/s
import {InstallerCard} from './InstallerCard';
import type {Vehicle} from '../../../core/fleet/useFleet';
export function VPSHostSettings({host,hosts,vehicle,vehicles,onClose,onSaved,renderWindow}:{host?:VPSHost;hosts:VPSHost[];vehicle:Vehicle;vehicles:Vehicle[];onClose:()=>void;onSaved:()=>void;renderWindow?:SensorEnrollmentProps['renderWindow']}){
const [existing,setExisting]=useState(''),[name,setName]=useState(host?.name??'VPS Host ARNavi'),[code,setCode]=useState(''),[selected,setSelected]=useState(host?.vehicle_ids??[vehicle.id]);
export function VPSHostSettings({host,hosts,liveHost,connectionStatus,vehicle,vehicles,onClose,onSaved,renderWindow}:{host?:VPSHost;liveHost?:VPSHost;connectionStatus?:{online:boolean;label:string};hosts:VPSHost[];vehicle?:Vehicle;vehicles:Vehicle[];onClose:()=>void;onSaved:()=>void;renderWindow?:SensorEnrollmentProps['renderWindow']}){
const [existing,setExisting]=useState(''),[name,setName]=useState(host?.name??'VPS Host ARNavi'),[code,setCode]=useState(''),[selected,setSelected]=useState(host?.vehicle_ids??(vehicle?[vehicle.id]:[]));
const [advanced,setAdvanced]=useState(false),[replaces,setReplaces]=useState('');
const [network,setNetwork]=useState(host?.network_interface??''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(v=>{if(active)setInterfaces(v.items);}).catch(()=>{});return()=>{active=false;};},[]);
const [busy,setBusy]=useState(false),[error,setError]=useState('');
const current=host??hosts.find(h=>h.id===existing);
const observed=liveHost??current;
const online=connectionStatus?.online??(observed?hostOnline(observed):false);
async function save(){setBusy(true);setError('');try{if(current){await vpsRequest(`/${current.id}`,'PUT',{name:name.trim(),vehicle_ids:selected,network_interface:network||null,expected_revision:current.revision});}else{await vpsRequest('','POST',{code:code.trim(),name:name.trim(),vehicle_ids:selected,network_interface:network||null,replaces_id:replaces||null});}onSaved();}catch(e){setError(e instanceof Error?e.message:'Не удалось подключить VPS.');}finally{setBusy(false);}}
const actions=<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!name.trim()||(!current&&!code.trim())} onClick={()=>void save()}>{current?'Применить':'Подключить VPS'}</Button></>;
const footer=<WindowFooterActions>{actions}</WindowFooterActions>;
const content=<div className="fleet-form">
{!host&&<Select label="VPS Host ARNavi" value={existing} options={[{value:'',label:'Подключить новый VPS'},...hosts.filter(h=>h.state==='paired').map(h=>({value:h.id,label:h.name}))]} disabled={busy} onChange={id=>{setExisting(id);const value=hosts.find(h=>h.id===id);setName(value?.name??'VPS Host ARNavi');setNetwork(value?.network_interface??'');setSelected(Array.from(new Set([...(value?.vehicle_ids??[]),vehicle.id])));}}/>}
{!host&&<Select label="VPS Host ARNavi" value={existing} options={[{value:'',label:'Подключить новый VPS'},...hosts.filter(h=>h.state==='paired').map(h=>({value:h.id,label:h.name}))]} disabled={busy} onChange={id=>{setExisting(id);const value=hosts.find(h=>h.id===id);setName(value?.name??'VPS Host ARNavi');setNetwork(value?.network_interface??'');setSelected(Array.from(new Set([...(value?.vehicle_ids??[]),...(vehicle?[vehicle.id]:[])])));}}/>}
{!current&&<InstallerCard kind="vps-arnavi"/>}
<TextField label="Название" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
{!current&&<TextAreaField label="Ключ подключения VPS" value={code} rows={5} disabled={busy} onChange={e=>setCode(e.target.value)} hint="После установки VPS Host ARNavi ключ находится в /opt/nodedc-mission-vps/connect.key. Он действует 24 часа и используется один раз."/>}
{!current&&hosts.some(h=>h.state==='paired')&&<Select label="После переустановки" value={replaces} options={[{value:'',label:'Это новый VPS'},...hosts.filter(h=>h.state==='paired').map(h=>({value:h.id,label:`Заменить ${h.name}`}))]} onChange={setReplaces} disabled={busy}/>}
{interfaces.length>0&&<><Button disabled={busy} onClick={()=>setAdvanced(v=>!v)}>{advanced?'Скрыть параметры подключения':'Параметры подключения при использовании VPN'}</Button>{advanced&&<SettingsCard title="Подключение с этого компьютера" description="Если VPN мешает доступу к VPS, выберите прямое подключение. Это влияет только на соединение Mission Core с этим сервером."><Select label="Способ подключения" value={network} options={[{value:'',label:'Обычное подключение (с учётом VPN)'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} disabled={busy} onChange={setNetwork}/></SettingsCard>}</>}
{current&&<SettingsCard title="Связь с VPS" description={current.endpoint}><StatusBadge tone={hostOnline(current)?'success':'neutral'}>{hostOnline(current)?'На связи':current.state==='pending'?'Подключение не завершено':'Нет связи'}</StatusBadge><dl className="fleet-facts"><div><dt>Версия</dt><dd>{current.status?.version??'Нет сведений'}</dd></div><div><dt>Последняя синхронизация</dt><dd>{current.last_sync_at?new Date(current.last_sync_at*1000).toLocaleString('ru-RU'):'Ещё не было'}</dd></div><div><dt>Приём ARNavi B2</dt><dd>{current.status?`${current.status.tracker.host}:${current.status.tracker.port}`:'Не подтверждён'}</dd></div><div><dt>Трекеры</dt><dd>{current.status?.devices??0}</dd></div></dl></SettingsCard>}
{current&&<SettingsCard title="Связь с VPS" description={current.endpoint}><StatusBadge tone={online?'success':'neutral'}>{connectionStatus?.label??(online?'На связи':current.state==='pending'?'Подключение не завершено':'Нет свежих данных')}</StatusBadge><dl className="fleet-facts"><div><dt>Версия</dt><dd>{observed?.status?.version??'Нет сведений'}</dd></div><div><dt>Последняя синхронизация</dt><dd>{observed?.last_sync_at?new Date(observed.last_sync_at*1000).toLocaleString('ru-RU'):'Ещё не было'}</dd></div><div><dt>Приём ARNavi B2</dt><dd>{observed?.status?`${observed.status.tracker.host}:${observed.status.tracker.port}`:'Не подтверждён'}</dd></div><div><dt>Трекеры</dt><dd>{observed?.status?.devices??0}</dd></div></dl></SettingsCard>}
<SettingsCard title="Обслуживаемые аппараты" description="Один VPS может обслуживать несколько аппаратов. Его настройки общие для всех привязок."><div className="fleet-form">{vehicles.map(v=><Switch key={v.id} label={v.name} checked={selected.includes(v.id)} disabled={busy} onChange={checked=>setSelected(ids=>checked?[...ids,v.id]:ids.filter(id=>id!==v.id))}/>)}</div></SettingsCard>
</div>;
return <>{renderWindow?renderWindow({content,actions,busy}):host?<FeatureSettingsWindow open title="Настройки VPS Host ARNavi" subtitle={host.name} identity={{title:'VPS Host ARNavi',subtitle:host.endpoint,avatarLabel:'VPS'}} sections={[{id:'host',label:'Сервер и аппараты'}]} activeSection="host" onSectionChange={()=>{}} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</FeatureSettingsWindow>:<Window open title="Подключить VPS Host ARNavi" subtitle={vehicle.name} size="md" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</Window>}<ToastStack items={error?[{id:'vps-host-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
return <>{renderWindow?renderWindow({content,actions,busy}):host?<FeatureSettingsWindow open title="Настройки VPS Host ARNavi" subtitle={host.name} identity={{title:'VPS Host ARNavi',subtitle:host.endpoint,avatarLabel:'VPS'}} sections={[{id:'host',label:'Сервер и аппараты'}]} activeSection="host" onSectionChange={()=>{}} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</FeatureSettingsWindow>:<Window open title="Подключить VPS Host ARNavi" subtitle={vehicle?.name} size="md" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</Window>}<ToastStack items={error?[{id:'vps-host-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
}
@@ -0,0 +1,61 @@
import {useState} from 'react';
import {createPortal} from 'react-dom';
import {Description,Icon,IconButton,LoadingRegion,ResourceList,ResourceRow,SettingsCard,StatusBadge,Window} from '@nodedc/ui-react';
import {useServers,useServerHealth,serviceAvailability,serverAvailability,type ServiceObservation,type Server,type ServerService} from '../../core/system/servers';
import {useFleet} from '../../core/fleet/useFleet';
import type {VPSHost} from '../../core/fleet/vps';
import {ServerSettings} from '../../components/system/ServerSettings';
import {ServerServiceSetup} from '../../components/system/ServerServiceSetup';
import {VPSHostSettings} from '../fleet/equipment/VPSHostSettings';
import './system-catalog.css';
function Services({host,observations,onInspect}:{host:Server;observations?:ServiceObservation[];onInspect:(service:ServerService)=>void}) {
return host.services.length?<ResourceList aria-label={`Службы: ${host.name}`}>{host.services.map(service=>{const state=serviceAvailability(service,observations);return <li key={`${service.kind}:${service.id}`}>
<ResourceRow icon={<Icon name={service.kind==='wireguard'?'network':'activity'}/>} title={service.name} description={service.endpoint}
metadata={state.label} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={state.tone} aria-label={state.label} title={state.label}/>}
actions={<IconButton label={`Настройки ${service.name}: ${host.name}`} onClick={()=>onInspect(service)}><Icon name="sliders"/></IconButton>}/>
</li>;})}</ResourceList>:<SettingsCard title="Служб пока нет" description="Нажмите «+» у VPS, чтобы установить и подключить службу."/>;
}
export function ServersWorkspace({headerToolsHost}:{headerToolsHost?:HTMLElement|null}) {
const store=useServers();const fleet=useFleet();
const [expanded,setExpanded]=useState<string[]>([]);
const [editing,setEditing]=useState<Server|null|undefined>(),[addingService,setAddingService]=useState<Server|null>(null);
const [inspecting,setInspecting]=useState<ServerService|null>(null);
const health=useServerHealth(store.items,store.generation);
const inspectedHost=store.items?.find(host=>host.services.some(s=>s.id===inspecting?.id&&s.kind===inspecting?.kind));
const liveService=inspectedHost?.services.find(s=>s.id===inspecting?.id&&s.kind===inspecting?.kind);
const liveState=inspecting?serviceAvailability(inspecting,inspectedHost&&!store.error?health[inspectedHost.id]:[]):null;
const reload=()=>{store.refresh();setInspecting(null);};
const actions=<>
<IconButton label="Обновить список VPS" onClick={store.refresh}><Icon name="refresh"/></IconButton>
<IconButton label="Добавить VPS" onClick={()=>setEditing(null)}><Icon name="plus"/></IconButton>
</>;
return <>
{headerToolsHost?createPortal(actions,headerToolsHost):actions}
<LoadingRegion loading={!store.items&&!store.error} label="Получение VPS">
<ResourceList aria-label="VPS">{store.items?.map(host=>{const state=serverAvailability(host,store.error?[]:health[host.id]);return <li key={host.id}>
<ResourceRow icon={<Icon name="globe"/>} title={host.name} description={host.address} metadata={`Служб: ${host.services.length}`}
statusPlacement="leading" status={<StatusBadge variant="indicator" tone={state.tone} aria-label={state.label} title={state.label}/>}
actions={<>
<IconButton label={`Добавить службу: ${host.name}`} disabled={!!store.error} onClick={()=>setAddingService(host)}><Icon name="plus"/></IconButton>
<IconButton label={`Настройки VPS: ${host.name}`} disabled={!!store.error} onClick={()=>setEditing(host)}><Icon name="sliders"/></IconButton>
<IconButton label={`${expanded.includes(host.id)?'Свернуть':'Показать'} службы: ${host.name}`} aria-expanded={expanded.includes(host.id)} aria-controls={`services-${host.id}`} onClick={()=>setExpanded(ids=>ids.includes(host.id)?ids.filter(id=>id!==host.id):[...ids,host.id])}><Icon name={expanded.includes(host.id)?'chevron-up':'chevron-down'}/></IconButton>
</>}/>
{expanded.includes(host.id)&&<div className="system-catalog-services" id={`services-${host.id}`} role="region" aria-label={`Службы: ${host.name}`}><Services host={host} observations={store.error?[]:health[host.id]} onInspect={setInspecting}/></div>}
</li>;})}</ResourceList>
{store.items?.length===0&&!store.error&&<SettingsCard title="VPS пока нет" description="Добавьте сервер через «+», затем подключите нужные службы."/>}
</LoadingRegion>
{editing!==undefined&&<ServerSettings key={editing?.id??'new'} server={editing??undefined} onClose={()=>setEditing(undefined)} onRemoved={()=>{setEditing(undefined);store.refresh();}} onSaved={item=>{setEditing(undefined);setExpanded(ids=>[...new Set([...ids,item.id])]);store.refresh();}}/>}
{addingService&&<ServerServiceSetup server={addingService} onClose={()=>setAddingService(null)} onSaved={()=>{setAddingService(null);store.refresh();}}/>}
{inspecting?.kind==='arnavi'&&<VPSHostSettings host={inspecting.details as VPSHost} liveHost={liveService?.details as VPSHost|undefined} connectionStatus={liveState??undefined} hosts={[inspecting.details as VPSHost]} vehicles={fleet.items??[]} onClose={()=>setInspecting(null)} onSaved={reload}/>}
{inspecting?.kind==='wireguard'&&<Window open title="WireGuard" subtitle={inspecting.endpoint} size="md" onClose={()=>setInspecting(null)}>
<SettingsCard title={inspecting.details.name} description="Общая сеть доступна в настройках подключения устройств.">
<StatusBadge tone={liveState?.tone??'neutral'}>{liveState?.label??'Связь не проверена'}</StatusBadge>
<Description>Проверяется доступность службы. VPN для устройства выбирается в его настройках подключения.</Description>
<Description>Подключено бортов: {'boards' in inspecting.details?inspecting.details.boards:0}</Description>
</SettingsCard>
</Window>}
{store.error&&<SettingsCard title="Не удалось получить VPS" description={store.error}/>}
</>;
}
@@ -0,0 +1,39 @@
import {useState} from "react";
import {createPortal} from "react-dom";
import {Icon, IconButton, LoadingRegion, ResourceList, ResourceRow, SettingsCard, StatusBadge} from "@nodedc/ui-react";
import {useComputeContours} from "../../core/system/ComputeContourContext";
import {WorkerConnectionSettings} from "../../components/system/WorkerConnectionSettings";
import {useWorkerTelemetry} from '../../core/system/useWorkerTelemetry';
import {workerAvailable} from '../../core/system/contourHealth';
function WorkerStatus({id,generation}:{id:string;generation:number}) {
const {telemetry}=useWorkerTelemetry(id,5000,true,generation,1);
const online=workerAvailable(telemetry);
const label=online?'В сети':'Нет свежих данных о связи';
return <StatusBadge variant="indicator" tone={online?'success':'neutral'} aria-label={label} title={label}/>;
}
export function WorkersWorkspace({headerToolsHost, onView}: {headerToolsHost?: HTMLElement | null; onView: () => void}) {
const store = useComputeContours();
const [editing, setEditing] = useState<string | null | undefined>();
const actions = <><IconButton label="Обновить список воркеров" onClick={()=>{store.refresh();store.refreshTelemetry();}}><Icon name="refresh"/></IconButton>
<IconButton label="Добавить воркер" onClick={() => setEditing(null)}><Icon name="plus"/></IconButton></>;
return <>
{headerToolsHost ? createPortal(actions, headerToolsHost) : actions}
<LoadingRegion loading={store.loading && !store.contours.length} label="Получение воркеров">
{!store.loading && !store.error && !store.contours.length && <SettingsCard title="Воркеров пока нет" description="Добавьте вычислительный узел через «+»."/>}
<ResourceList aria-label="Воркеры">{store.contours.map(item => <li key={item.contour_id}>
<ResourceRow icon={<Icon name="apps"/>} title={item.display_name} description={item.expected_node_id}
statusPlacement="leading" status={<WorkerStatus id={item.contour_id} generation={store.telemetryRefreshGeneration}/>}
actions={<>
<IconButton label={`Настройки воркера: ${item.display_name}`} disabled={!!store.error} onClick={() => setEditing(item.contour_id)}><Icon name="sliders"/></IconButton>
<IconButton label={`Посмотреть воркер: ${item.display_name}`} disabled={!!store.error} onClick={() => {store.selectContour(item.contour_id); onView();}}><Icon name="eye"/></IconButton>
</>}/>
</li>)}</ResourceList>
</LoadingRegion>
{editing !== undefined && <WorkerConnectionSettings open mode={editing === null ? "create" : "edit"}
contour={store.contours.find(item => item.contour_id === editing) ?? null} onClose={() => setEditing(undefined)}
onChanged={store.refresh} onUpdate={store.updateContour}/>}
{store.error && <SettingsCard title="Не удалось получить воркеры" description={store.error}/>}
</>;
}
@@ -0,0 +1,7 @@
.system-catalog-form {
display: grid;
gap: var(--nodedc-space-4);
}
.system-catalog-services {
margin: var(--nodedc-space-3) 0 var(--nodedc-space-4) var(--nodedc-space-5);
}