feat(system): add worker and VPS catalogs with guarded local removal
This commit is contained in:
@@ -444,7 +444,7 @@ export default function App() {
|
||||
workspace.openNavigation();
|
||||
if (rootId === "system") {
|
||||
workspace.openView(
|
||||
activeDefinition?.root === "system" ? activeDefinition.id : "modules",
|
||||
activeDefinition?.id === "vps" ? "vps" : "workers",
|
||||
);
|
||||
} else {
|
||||
workspace.closeView();
|
||||
@@ -666,7 +666,7 @@ export default function App() {
|
||||
connectionScenarioResetting: runtime.pendingAction === "mode",
|
||||
saveWorkspaceLayout,
|
||||
workspaceLayoutSaving: workspaceLayoutProfile.state === "saving",
|
||||
systemUtilityActions: computeContourSettings.utilityActions,
|
||||
systemUtilityActions: [...computeContourSettings.utilityActions, {label: "К списку воркеров", icon: "chevron-left", onClick: () => openNavigationView("workers")}],
|
||||
sessionOverview: { ...sessionOverview, available: Boolean(recordedReplay && replayPresented && !sourceSwitchBlocked) },
|
||||
});
|
||||
|
||||
@@ -738,8 +738,8 @@ export default function App() {
|
||||
navigation={currentRoot && activeRoot === "system" ? (
|
||||
<SystemNavigationPanel
|
||||
title={currentRoot.title}
|
||||
onAdd={computeContourSettings.openCreate}
|
||||
onNavigateRoot={() => openNavigationView("modules")}
|
||||
activeId={activeDefinition?.id ?? "workers"}
|
||||
onNavigate={openNavigationView}
|
||||
onClose={workspace.closeNavigation}
|
||||
/>
|
||||
) : currentRoot ? (
|
||||
@@ -844,6 +844,8 @@ export default function App() {
|
||||
<StatusBadge tone="neutral">Только наблюдение</StatusBadge>
|
||||
) : activeDefinition.kind === "contour-health" ? (
|
||||
<div ref={setWorkspaceHeaderToolsHost} />
|
||||
) : activeDefinition.kind === "workers" || activeDefinition.kind === "vps" ? (
|
||||
<div className="fleet-header-tools" ref={setWorkspaceHeaderToolsHost} />
|
||||
) : activeDefinition.root === "system" ? (
|
||||
<SystemWorkspaceSelector
|
||||
value={activeDefinition.id}
|
||||
|
||||
@@ -2,10 +2,10 @@ import {Fragment,useEffect,useState} from 'react';
|
||||
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
|
||||
|
||||
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
|
||||
export function InstallerCard({kind}:{kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'}){
|
||||
export function InstallerCard({kind,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'}){
|
||||
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
|
||||
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
|
||||
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
|
||||
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((original,index)=>{const step=connectionInstruction&&index===item.instructions.length-1?connectionInstruction:original;return <Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>;})}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
|
||||
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
|
||||
</SettingsCard>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import {useEffect,useRef,useState} from 'react';
|
||||
import {Button,Description,Icon,Select,SettingsCard,TextAreaField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {InstallerCard} from '../network/InstallerCard';
|
||||
import {serverRequest,type Server} from '../../core/system/servers';
|
||||
import {vpsRequest} from '../../core/fleet/vps';
|
||||
|
||||
export function ServerServiceSetup({server,onClose,onSaved}:{server:Server;onClose:()=>void;onSaved:()=>void}) {
|
||||
const [kind,setKind]=useState<'wireguard'|'arnavi'>('wireguard'),[document,setDocument]=useState(''),[filename,setFilename]=useState('');
|
||||
const [network,setNetwork]=useState(''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState('');const file=useRef<HTMLInputElement>(null);
|
||||
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(r=>{if(active)setInterfaces(r.items);}).catch(()=>{});return()=>{active=false;};},[]);
|
||||
async function connect(){setBusy(true);setError('');try{
|
||||
await serverRequest(`/${server.id}/services`,'POST',{kind,document:document.trim(),expected_revision:server.revision,network_interface:network||null});
|
||||
setDocument('');onSaved();
|
||||
}catch(e){setError(e instanceof Error?e.message:'Не удалось подключить службу.');}finally{setBusy(false);}}
|
||||
return <><Window open title="Добавить службу" subtitle={`${server.name} · ${server.address}`} size="lg" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}}
|
||||
footer={<WindowFooterActions><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!document.trim()} onClick={()=>void connect()}>Подключить службу</Button></WindowFooterActions>}>
|
||||
<div className="system-catalog-form">
|
||||
<Select label="Служба" value={kind} disabled={busy} options={[{value:'wireguard',label:'WireGuard'},{value:'arnavi',label:'ARNavi'}]} onChange={value=>{setKind(value as typeof kind);setDocument('');setFilename('');setError('');}}/>
|
||||
<InstallerCard key={kind} connectionInstruction="Вернитесь в это окно и подключите установленную службу с выданным приглашением." kind={kind==='wireguard'?'vps-wireguard':'vps-arnavi'}/>
|
||||
<SettingsCard title="Подключение установленной службы" description="Запустите установщик на выбранном VPS. Затем передайте выданное им приглашение — Mission Core проверит сервер и сохранит подключение.">
|
||||
{kind==='wireguard'?<>
|
||||
<input ref={file} type="file" accept=".json,application/json" hidden onChange={event=>{const chosen=event.target.files?.[0];event.target.value='';if(!chosen)return;setDocument('');setFilename('');void (async()=>{if(chosen.size>16384)throw Error('Выберите файл приглашения WireGuard (до 16 КБ).');setDocument(await chosen.text());setFilename(chosen.name);})().catch(e=>setError(e.message));}}/>
|
||||
<Button icon={<Icon name="upload"/>} disabled={busy} onClick={()=>file.current?.click()}>Выбрать приглашение WireGuard</Button>
|
||||
{filename&&<Description>{filename}</Description>}
|
||||
<Description>Файл на VPS: /var/lib/ndc-wireguard-vps/mission-core-wireguard.json. Скопируйте его по защищённому соединению (например, SFTP). Приглашение действует 24 часа; новое выпускается командой connection того же установщика. Экспорт .conf из клиента WireGuard не подходит.</Description>
|
||||
</>:<TextAreaField label="Ключ подключения ARNavi" value={document} disabled={busy} rows={4} onChange={e=>setDocument(e.target.value)} hint="Ключ находится на VPS в /opt/nodedc-mission-vps/connect.key. Действует 24 часа и используется один раз."/>}
|
||||
</SettingsCard>
|
||||
{interfaces.length>0&&<Select label="Подключение к VPS" disabled={busy} value={network} options={[{value:'',label:'Через текущую сеть'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} onChange={setNetwork}/>}
|
||||
</div>
|
||||
</Window><ToastStack items={error?[{id:'server-connect',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import {useState} from 'react';
|
||||
import {Button, Description, Icon, IconButton, LoadingRegion, SettingsCard, TextField, ToastStack, Window, WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {serverRequest,type Server,type ServerRemovalPlan} from '../../core/system/servers';
|
||||
|
||||
export function ServerSettings({server,onClose,onSaved,onRemoved}:{server?:Server;onClose:()=>void;onSaved:(server:Server)=>void;onRemoved?:()=>void}) {
|
||||
const [name,setName]=useState(server?.name??''),[address,setAddress]=useState(server?.address??'');
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
const [removing,setRemoving]=useState(false),[plan,setPlan]=useState<ServerRemovalPlan|null>(null);
|
||||
async function prepareRemoval(){if(!server)return;setRemoving(true);setPlan(null);setBusy(true);setError('');try{
|
||||
setPlan(await serverRequest<ServerRemovalPlan>(`/${server.id}/removal`,'POST',{expected_revision:server.revision}));
|
||||
}catch(e){setError(e instanceof Error?e.message:'Не удалось проверить подключения VPS.');}finally{setBusy(false);}}
|
||||
async function remove(){if(!server||!plan||plan.blocked.length)return;setBusy(true);setError('');try{
|
||||
await serverRequest(`/${server.id}`,'DELETE',{expected_revision:server.revision,confirmation:plan.confirmation});
|
||||
onRemoved?.();
|
||||
}catch(e){setPlan(null);setError(e instanceof Error?e.message:'Удаление не завершено. Повторите проверку.');}finally{setBusy(false);}}
|
||||
async function save(){setBusy(true);setError('');try{
|
||||
const item=await serverRequest<Server>(server?`/${server.id}`:'',server?'PUT':'POST',{name:name.trim(),address:address.trim(),...(server?{expected_revision:server.revision}:{})});
|
||||
onSaved(item);
|
||||
}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить VPS.');}finally{setBusy(false);}}
|
||||
return <><Window open title={removing?'Удалить VPS?':server?'Настройки VPS':'Добавить VPS'} subtitle={server?.name}
|
||||
size="md" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}}
|
||||
headerActionsPlacement="before-close" headerActions={server&&!removing&&<IconButton label="Удалить VPS" disabled={busy} onClick={()=>void prepareRemoval()}><Icon name="trash"/></IconButton>}
|
||||
footer={<WindowFooterActions>{removing?<><Button disabled={busy} onClick={()=>{setRemoving(false);setPlan(null);setError('');}}>Отменить</Button>{plan?<Button loading={busy} disabled={busy||!!plan.blocked.length} onClick={()=>void remove()}>Удалить</Button>:<Button loading={busy} disabled={busy} onClick={()=>void prepareRemoval()}>Повторить проверку</Button>}</>:<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!name.trim()||!address.trim()} onClick={()=>void save()}>{server?'Сохранить':'Добавить VPS'}</Button></>}</WindowFooterActions>}>
|
||||
{removing?<LoadingRegion loading={busy&&!plan} label="Проверка подключений"><SettingsCard title={`Удалить «${server?.name}» из Mission Core?`} description="Это действие нельзя отменить.">
|
||||
<Description>Будут удалены карточка VPS, сохранённые подключения его служб и локальные туннели WireGuard. Для повторного подключения понадобятся новые приглашения.</Description>
|
||||
<Description>Сам VPS, установленные на нём службы и данные останутся на сервере.</Description>
|
||||
{plan&&<><Description>Подключения служб: {plan.services.join(', ')||'нет'}. Связанные подключения аппаратов: {plan.vehicle_connections}; воркеров: {plan.worker_connections}.</Description>{plan.blocked.map(message=><Description key={message}>{message}</Description>)}</>}
|
||||
</SettingsCard></LoadingRegion>:<div className="system-catalog-form">
|
||||
<TextField label="Название" placeholder="Например, Макхост · сеть парка" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
|
||||
<TextField label="Адрес сервера" hint={server?.services.length?'Адрес используется подключёнными службами.':'Публичный IP-адрес или DNS-имя, без протокола и порта.'} value={address} maxLength={253} disabled={busy||!!server?.services.length} onChange={e=>setAddress(e.target.value)}/>
|
||||
</div>}
|
||||
</Window><ToastStack items={error?[{id:'server-save',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
|
||||
}
|
||||
@@ -1,59 +1,13 @@
|
||||
import {
|
||||
AdminNavigationPanel,
|
||||
Icon,
|
||||
IconButton,
|
||||
} from "@nodedc/ui-react";
|
||||
import {AdminNavigationPanel, Icon} from "@nodedc/ui-react";
|
||||
import {workspacesForRoot} from "../../productModel";
|
||||
|
||||
import { useComputeContours } from "../../core/system/ComputeContourContext";
|
||||
|
||||
interface SystemNavigationPanelProps {
|
||||
title: string;
|
||||
onAdd: () => void;
|
||||
onNavigateRoot: () => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function SystemNavigationPanel({
|
||||
title,
|
||||
onAdd,
|
||||
onNavigateRoot,
|
||||
onClose,
|
||||
}: SystemNavigationPanelProps) {
|
||||
const { contours, selectedContour, selectContour } = useComputeContours();
|
||||
const contourCountLabel = contours.length === 1
|
||||
? "1 конфигурация"
|
||||
: `${contours.length} конфигураций`;
|
||||
|
||||
return (
|
||||
<AdminNavigationPanel
|
||||
eyebrow="MISSION CORE"
|
||||
title={title}
|
||||
closeLabel={`Закрыть раздел «${title}»`}
|
||||
navigationLabel="Вычислительные контуры"
|
||||
onClose={onClose}
|
||||
headerActions={(
|
||||
<IconButton label="Добавить вычислительный контур" onClick={onAdd}>
|
||||
<Icon name="plus" size={16} strokeWidth={1.6} />
|
||||
</IconButton>
|
||||
)}
|
||||
contexts={contours.map((contour) => ({
|
||||
id: contour.contour_id,
|
||||
label: contour.display_name,
|
||||
description: contour.expected_node_id,
|
||||
icon: <Icon name="apps" />,
|
||||
active: selectedContour?.contour_id === contour.contour_id,
|
||||
onSelect: () => { selectContour(contour.contour_id); onNavigateRoot(); },
|
||||
}))}
|
||||
items={[]}
|
||||
onItemChange={() => undefined}
|
||||
footer={(
|
||||
<>
|
||||
<span className="nodedc-admin-panel__nav-icon" aria-hidden="true">
|
||||
<Icon name="activity" />
|
||||
</span>
|
||||
<span>{contourCountLabel}</span>
|
||||
</>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
export function SystemNavigationPanel({title, activeId, onNavigate, onClose}: {
|
||||
title: string; activeId: string; onNavigate: (id: string) => void; onClose: () => void;
|
||||
}) {
|
||||
const categories = workspacesForRoot("system").filter(item => item.kind === "workers" || item.kind === "vps");
|
||||
return <AdminNavigationPanel eyebrow="MISSION CORE" title={title}
|
||||
closeLabel={`Закрыть раздел «${title}»`} navigationLabel="Система" onClose={onClose}
|
||||
contexts={categories.map(item => ({id: item.id, label: item.label, icon: <Icon name={item.icon}/>,
|
||||
active: item.id === (activeId === "vps" ? "vps" : "workers"),
|
||||
onSelect: () => onNavigate(item.id)}))} items={[]} onItemChange={() => undefined}/>;
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ export function useApplicationPanelActions({
|
||||
onClick: () => void saveWorkspaceLayout(),
|
||||
});
|
||||
}
|
||||
if (definition?.root === "system") actions.push(...systemUtilityActions);
|
||||
if (definition && ["compute-modules", "network-monitor"].includes(definition.kind)) actions.push(...systemUtilityActions);
|
||||
if (definition?.kind === "recordings" && sessionOverview) actions.push({
|
||||
label: sessionOverview.open ? "Закрыть информацию о записи" : "Информация о записи",
|
||||
icon: "info", pressed: sessionOverview.open, disabled: !sessionOverview.available,
|
||||
|
||||
@@ -42,7 +42,7 @@ const defaultQuickActions: Record<
|
||||
observation: ["cameras", "world-map"],
|
||||
missions: ["routes", null],
|
||||
data: ["recordings", "datasets"],
|
||||
system: ["modules", "integrations"],
|
||||
system: ["modules", "network"],
|
||||
polygon: ["observatory", "local-device"],
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import {useCallback, useEffect, useState} from 'react';
|
||||
import type {VPSHost} from '../fleet/vps';
|
||||
import {startSequentialPolling} from './sequentialPolling';
|
||||
|
||||
export type ServerService = {kind:'arnavi'|'wireguard';id:string;name:string;endpoint:string;state:string;last_seen:number|null;details:VPSHost|{id:string;name:string;endpoint:string;boards:number;last_verified:number|null;state:string}};
|
||||
export type Server = {id:string;name:string;address:string;revision:number;services:ServerService[]};
|
||||
export type ServerRemovalPlan = {confirmation:string;name:string;blocked:string[];services:string[];vehicle_connections:number;worker_connections:number};
|
||||
export async function serverRequest<T>(path='', method='GET', body?:unknown, signal?:AbortSignal):Promise<T> {
|
||||
const response = await fetch(`/api/v1/system/servers${path}`, {method, cache:'no-store', credentials:'same-origin',
|
||||
signal:AbortSignal.any([...(signal?[signal]:[]),AbortSignal.timeout(method === 'GET' ? 20000 : 240000)]),
|
||||
headers:body === undefined ? {} : {'Content-Type':'application/json'}, body:body === undefined ? undefined : JSON.stringify(body)});
|
||||
const value = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw Error(typeof value.detail === 'string' ? value.detail : 'Не удалось получить данные VPS.');
|
||||
return value as T;
|
||||
}
|
||||
export function useServers() {
|
||||
const [items,setItems]=useState<Server[]|null>(null),[error,setError]=useState(''),[generation,setGeneration]=useState(0);
|
||||
const refresh=useCallback(()=>setGeneration(n=>n+1),[]);
|
||||
useEffect(()=>{
|
||||
const controller=new AbortController();
|
||||
const stop=startSequentialPolling(async()=>{try{const value=await serverRequest<{items:Server[]}>('', 'GET', undefined, controller.signal);if(!controller.signal.aborted){setItems(value.items);setError('');}}catch(e){if(!controller.signal.aborted)setError(e instanceof Error?e.message:'Не удалось получить VPS.');}},5000);
|
||||
return()=>{stop();controller.abort();};
|
||||
},[generation]);
|
||||
return {items,error,refresh,generation};
|
||||
}
|
||||
export interface ServiceObservation {id:string;kind:ServerService['kind'];state:'online'|'unavailable';checked_at:number}
|
||||
export function useServerHealth(servers:Server[]|null,generation=0) {
|
||||
const [observations,setObservations]=useState<Record<string,ServiceObservation[]>>({});
|
||||
const keys=(servers??[]).map(s=>s.id).sort().join('|');
|
||||
useEffect(()=>{
|
||||
const controller=new AbortController();setObservations({});
|
||||
const stop=startSequentialPolling(async()=>{
|
||||
await Promise.all(keys.split('|').filter(Boolean).map(async id=>{
|
||||
let items:ServiceObservation[]=[];
|
||||
try{items=(await serverRequest<{items:ServiceObservation[]}>(`/${id}/health`,'GET',undefined,controller.signal)).items;}catch{/* Unknown is distinct from a successful observation. */}
|
||||
if(!controller.signal.aborted)setObservations(current=>({...current,[id]:items}));
|
||||
}));
|
||||
},15000);
|
||||
return()=>{stop();controller.abort();};
|
||||
},[keys,generation]);
|
||||
return observations;
|
||||
}
|
||||
export function serviceAvailability(service:ServerService, observations:ServiceObservation[]=[], now=Date.now()/1000) {
|
||||
const item=observations.find(s=>s.kind===service.kind&&s.id===service.id);
|
||||
if(!item||now-item.checked_at>40)return {tone:'neutral' as const,label:'Связь не проверена',online:false};
|
||||
return item.state==='online'?{tone:'success' as const,label:'На связи',online:true}:{tone:'neutral' as const,label:'Нет ответа',online:false};
|
||||
}
|
||||
export function serverAvailability(server:Server,observations:ServiceObservation[]=[]) {
|
||||
const states=server.services.map(s=>serviceAvailability(s,observations));
|
||||
if(!states.length)return {tone:'neutral' as const,label:'Нет подключённых служб'};
|
||||
if(states.every(s=>s.online))return {tone:'success' as const,label:'На связи'};
|
||||
if(states.some(s=>s.online))return {tone:'warning' as const,label:'Часть служб доступна'};
|
||||
return {tone:'neutral' as const,label:states.some(s=>s.label==='Нет ответа')?'Нет ответа от служб':'Связь не проверена'};
|
||||
}
|
||||
@@ -20,6 +20,8 @@ export type WorkspaceKind =
|
||||
| "catalog"
|
||||
| "contour-health"
|
||||
| "compute-modules"
|
||||
| "workers"
|
||||
| "vps"
|
||||
| "network-monitor"
|
||||
| "datasets"
|
||||
| "artifact-health"
|
||||
@@ -567,6 +569,16 @@ export const workspaces: WorkspaceDefinition[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "workers", root: "system", label: "Воркеры", title: "Воркеры",
|
||||
eyebrow: "СИСТЕМА / ВОРКЕРЫ", description: "Вычислительные узлы и их подключения.",
|
||||
icon: "apps", kind: "workers", groups: [],
|
||||
},
|
||||
{
|
||||
id: "vps", root: "system", label: "VPS", title: "VPS",
|
||||
eyebrow: "СИСТЕМА / VPS", description: "Серверы и установленные на них службы.",
|
||||
icon: "globe", kind: "vps", groups: [],
|
||||
},
|
||||
{
|
||||
id: "modules",
|
||||
root: "system",
|
||||
@@ -591,29 +603,7 @@ export const workspaces: WorkspaceDefinition[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "integrations",
|
||||
root: "system",
|
||||
label: "Интеграции",
|
||||
title: "Интеграции",
|
||||
eyebrow: "СИСТЕМА / ИНТЕГРАЦИИ",
|
||||
description: "Адаптеры данных и внешние контуры с явной границей ответственности.",
|
||||
icon: "network",
|
||||
kind: "catalog",
|
||||
groups: [
|
||||
{
|
||||
title: "Точки интеграции",
|
||||
description: "Внешние системы не определяют продуктовую навигацию.",
|
||||
capabilities: [
|
||||
active("Локальный API устройства", "Текущий контур управления FastAPI."),
|
||||
ready("Визуализатор Rerun", "Открытый веб-визуализатор встроен в пространственную рабочую поверхность."),
|
||||
contract("Мост ROS 2", "Стандартные PointCloud2, Pose, Odometry, TF и диагностика."),
|
||||
contract("Шлюз Zenoh", "Маршрутизация разрешённых потоков между бортом и сервером."),
|
||||
later("Сервисы парка", "Задачи, зарядки и координация нескольких аппаратов."),
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
{
|
||||
id: "network",
|
||||
root: "system",
|
||||
@@ -637,28 +627,7 @@ export const workspaces: WorkspaceDefinition[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "audit",
|
||||
root: "system",
|
||||
label: "Журнал и аудит",
|
||||
title: "Журнал и аудит",
|
||||
eyebrow: "СИСТЕМА / АУДИТ",
|
||||
description: "Технические события, действия оператора и воспроизводимость эксперимента.",
|
||||
icon: "clipboard",
|
||||
kind: "timeline",
|
||||
groups: [
|
||||
{
|
||||
title: "Доказательность",
|
||||
description: "Git хранит код, обезличенные метаданные и правила воспроизведения.",
|
||||
capabilities: [
|
||||
active("Первичное сохранение сырья", "Сырые сообщения сохраняются до декодирования предпросмотра."),
|
||||
active("Манифест сессии", "Версии, хэши и обезличенные сведения о прогоне."),
|
||||
contract("События аудита интерфейса", "Переходы, операции и подтверждения пользователя."),
|
||||
later("Центральный сервис аудита", "Поиск и корреляция событий нескольких аппаратов."),
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
];
|
||||
|
||||
export function rootById(id: RootId | null): RootDefinition | null {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import React from 'react';
|
||||
import {before,after,test} from 'node:test';
|
||||
import {createServer} from './support/vite-server.mjs';
|
||||
let server,Navigation,Workers,availability;
|
||||
before(async()=>{
|
||||
server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true,hmr:false}});
|
||||
({SystemNavigationPanel:Navigation}=await server.ssrLoadModule('/src/components/system/SystemNavigationPanel.tsx'));
|
||||
({WorkersWorkspace:Workers}=await server.ssrLoadModule('/src/workspaces/system/WorkersWorkspace.tsx'));
|
||||
availability=await server.ssrLoadModule('/src/core/system/servers.ts');
|
||||
});
|
||||
after(async()=>{await server?.close();});
|
||||
function withHooks(hooks,fn){const internals=React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,previous=internals.H;internals.H=hooks;try{return fn();}finally{internals.H=previous;}}
|
||||
function find(tree,predicate){if(!tree)return null;if(Array.isArray(tree)){for(const item of tree){const r=find(item,predicate);if(r)return r;}return null;}if(typeof tree!=='object')return null;if(predicate(tree))return tree;return find(tree.props?.children,predicate)??find(tree.props?.actions,predicate);}
|
||||
|
||||
test('system category returns to catalog from worker detail and has no global add action',()=>{
|
||||
const selected=[];
|
||||
const tree=Navigation({title:'System',activeId:'network',onNavigate:id=>selected.push(id),onClose:()=>{}});
|
||||
assert.deepEqual(tree.props.contexts.map(x=>x.id),['workers','vps']);
|
||||
assert.equal(tree.props.contexts[0].active,true);
|
||||
assert.equal(tree.props.headerActions,undefined);
|
||||
tree.props.contexts[0].onSelect();tree.props.contexts[1].onSelect();
|
||||
assert.deepEqual(selected,['workers','vps']);
|
||||
});
|
||||
test('worker eye selects the requested worker before opening telemetry; settings does not navigate',()=>{
|
||||
const events=[],states=[];
|
||||
const store={contours:[{contour_id:'one',display_name:'First',expected_node_id:'node-a'},{contour_id:'two',display_name:'Second',expected_node_id:'node-b'}],selectContour:id=>events.push(id),refresh:()=>{},loading:false,error:null};
|
||||
const tree=withHooks({useContext:()=>store,useState:()=>[undefined,value=>states.push(value)]},()=>Workers({onView:()=>events.push('view')}));
|
||||
const eye=find(tree,x=>x.props?.label==='Посмотреть воркер: Second');
|
||||
eye.props.onClick();assert.deepEqual(events,['two','view']);
|
||||
const settings=find(tree,x=>x.props?.label==='Настройки воркера: First');
|
||||
settings.props.onClick();assert.deepEqual(states,['one']);assert.deepEqual(events,['two','view']);
|
||||
find(tree,x=>x.props?.label==='Добавить воркер').props.onClick();assert.equal(states.at(-1),null);
|
||||
});
|
||||
|
||||
|
||||
test('service readiness is not liveness; expired and wrong-service observations never show online',()=>{
|
||||
const service={kind:'wireguard',id:'one',state:'ready',last_seen:100};
|
||||
const now=Date.now()/1000;
|
||||
assert.equal(availability.serviceAvailability(service,[],now).online,false);
|
||||
assert.equal(availability.serviceAvailability(service,[{kind:'wireguard',id:'other',state:'online',checked_at:now}],now).online,false);
|
||||
const observed={kind:'wireguard',id:'one',state:'online',checked_at:now};
|
||||
assert.equal(availability.serviceAvailability(service,[observed],now).online,true);
|
||||
assert.equal(availability.serviceAvailability(service,[observed],now+41).online,false);
|
||||
const host={services:[service,{kind:'arnavi',id:'two'}]};
|
||||
assert.equal(availability.serverAvailability(host,[observed]).tone,'warning');
|
||||
assert.equal(availability.serverAvailability(host,[observed,{kind:'arnavi',id:'two',state:'online',checked_at:now}]).tone,'success');
|
||||
assert.equal(availability.serverAvailability(host,[]).tone,'neutral');
|
||||
});
|
||||
@@ -345,9 +345,25 @@ class Manager:
|
||||
raise ValueError("Invalid helper request")
|
||||
with self.lock:
|
||||
action = body.get("action")
|
||||
if action not in ("prepare", "status", "stage", "confirm", "apply", "disable", "rollback"):
|
||||
if action not in (
|
||||
"prepare", "status", "stage", "confirm", "apply", "disable", "rollback", "forget",
|
||||
):
|
||||
raise ValueError("Unknown action")
|
||||
identity = server_id(body.get("server_id"))
|
||||
if action == "forget":
|
||||
row = self.profiles.get(identity)
|
||||
if row is not None:
|
||||
if row.get("pending"):
|
||||
raise ValueError("A network change is pending")
|
||||
self.down(row)
|
||||
del self.profiles[identity]
|
||||
try:
|
||||
self.persist()
|
||||
except Exception:
|
||||
self.profiles[identity] = row
|
||||
raise
|
||||
self.restore_retry.pop(identity, None)
|
||||
return {"server_id": identity, "removed": True}
|
||||
row = self.prepare(identity)
|
||||
if action in ("stage", "apply"):
|
||||
config = body["config"]
|
||||
|
||||
Reference in New Issue
Block a user