fix(fleet): derive contour status from registered nodes and remove obsolete tabs
This commit is contained in:
@@ -1,41 +1,8 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Button, Icon, StatusBadge } from "@nodedc/ui-react";
|
||||
|
||||
import type { MissionRuntimeState } from "../core/runtime/contracts";
|
||||
import {
|
||||
fetchPolygonWorkerStatus,
|
||||
type PolygonWorkerStatus,
|
||||
} from "../core/polygon/liveWorker";
|
||||
|
||||
interface ControlPlaneHealth {
|
||||
ok: boolean;
|
||||
status: string;
|
||||
service: string;
|
||||
version: string;
|
||||
plugin_runtimes: {
|
||||
ready: number;
|
||||
total: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface PluginRuntimeHealth {
|
||||
runtime_instance_id: string;
|
||||
plugin_id: string;
|
||||
plugin_version: string;
|
||||
status: string;
|
||||
observed_at: string;
|
||||
detail_code: string | null;
|
||||
}
|
||||
|
||||
interface ContourSnapshot {
|
||||
controlPlane: ControlPlaneHealth | null;
|
||||
pluginRuntimes: PluginRuntimeHealth[];
|
||||
simulationWorker: PolygonWorkerStatus | null;
|
||||
controlPlaneLatencyMs: number | null;
|
||||
simulationGatewayLatencyMs: number | null;
|
||||
observedAt: Date;
|
||||
error: string | null;
|
||||
}
|
||||
import {useEffect,useState} from 'react';
|
||||
import {Button,Icon,StatusBadge} from '@nodedc/ui-react';
|
||||
import type {MissionRuntimeState} from '../core/runtime/contracts';
|
||||
import {boardAvailable,contourSummary,readContourSnapshot,workerAvailable,type ContourSnapshot} from '../core/system/contourHealth';
|
||||
import {startSequentialPolling} from '../core/system/sequentialPolling';
|
||||
|
||||
export function contourRuntimeAuthorityPresentation(
|
||||
state: MissionRuntimeState | null,
|
||||
@@ -56,310 +23,61 @@ export function contourRuntimeAuthorityPresentation(
|
||||
};
|
||||
}
|
||||
|
||||
function validControlPlaneHealth(value: unknown): value is ControlPlaneHealth {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const item = value as Partial<ControlPlaneHealth>;
|
||||
return typeof item.ok === "boolean"
|
||||
&& typeof item.status === "string"
|
||||
&& typeof item.service === "string"
|
||||
&& typeof item.version === "string"
|
||||
&& Boolean(item.plugin_runtimes)
|
||||
&& typeof item.plugin_runtimes?.ready === "number"
|
||||
&& typeof item.plugin_runtimes?.total === "number";
|
||||
function observed(value:number|string|null|undefined){
|
||||
if(value===null||value===undefined)return '—';
|
||||
const date=new Date(value);
|
||||
return Number.isFinite(date.getTime())?date.toLocaleString('ru-RU'):'—';
|
||||
}
|
||||
|
||||
function validPluginRuntime(value: unknown): value is PluginRuntimeHealth {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const item = value as Partial<PluginRuntimeHealth>;
|
||||
return typeof item.runtime_instance_id === "string"
|
||||
&& typeof item.plugin_id === "string"
|
||||
&& typeof item.plugin_version === "string"
|
||||
&& typeof item.status === "string"
|
||||
&& typeof item.observed_at === "string";
|
||||
}
|
||||
|
||||
async function timedJson(
|
||||
url: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<{ payload: unknown; latencyMs: number }> {
|
||||
const started = performance.now();
|
||||
const response = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: { Accept: "application/json" },
|
||||
signal,
|
||||
});
|
||||
const latencyMs = performance.now() - started;
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
return { payload: await response.json(), latencyMs };
|
||||
}
|
||||
|
||||
function formatLatency(value: number | null): string {
|
||||
if (value === null) return "—";
|
||||
return `${Math.max(1, Math.round(value))} мс`;
|
||||
}
|
||||
|
||||
function formatObservedAt(value: Date | string | null): string {
|
||||
if (!value) return "—";
|
||||
const date = value instanceof Date ? value : new Date(value);
|
||||
if (!Number.isFinite(date.getTime())) return "—";
|
||||
return new Intl.DateTimeFormat("ru-RU", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
export function ContourHealthWorkspace({
|
||||
state,
|
||||
}: {
|
||||
state: MissionRuntimeState | null;
|
||||
}) {
|
||||
const [snapshot, setSnapshot] = useState<ContourSnapshot | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [generation, setGeneration] = useState(0);
|
||||
|
||||
const refresh = useCallback(() => setGeneration((value) => value + 1), []);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
void Promise.allSettled([
|
||||
timedJson("/api/health", controller.signal),
|
||||
timedJson("/api/v1/device-plugin-runtimes", controller.signal),
|
||||
(async () => {
|
||||
const started = performance.now();
|
||||
const worker = await fetchPolygonWorkerStatus({ signal: controller.signal });
|
||||
return { worker, latencyMs: performance.now() - started };
|
||||
})(),
|
||||
]).then(([healthResult, runtimesResult, workerResult]) => {
|
||||
if (controller.signal.aborted) return;
|
||||
const healthPayload = healthResult.status === "fulfilled"
|
||||
? healthResult.value.payload
|
||||
: null;
|
||||
const runtimesPayload = runtimesResult.status === "fulfilled"
|
||||
? runtimesResult.value.payload
|
||||
: null;
|
||||
const runtimeItems = runtimesPayload
|
||||
&& typeof runtimesPayload === "object"
|
||||
&& Array.isArray((runtimesPayload as { items?: unknown }).items)
|
||||
? (runtimesPayload as { items: unknown[] }).items.filter(validPluginRuntime)
|
||||
: [];
|
||||
const failures = [healthResult, runtimesResult, workerResult]
|
||||
.filter((result) => result.status === "rejected").length;
|
||||
setSnapshot({
|
||||
controlPlane: validControlPlaneHealth(healthPayload) ? healthPayload : null,
|
||||
pluginRuntimes: runtimeItems,
|
||||
simulationWorker: workerResult.status === "fulfilled"
|
||||
? workerResult.value.worker
|
||||
: null,
|
||||
controlPlaneLatencyMs: healthResult.status === "fulfilled"
|
||||
? healthResult.value.latencyMs
|
||||
: null,
|
||||
simulationGatewayLatencyMs: workerResult.status === "fulfilled"
|
||||
? workerResult.value.latencyMs
|
||||
: null,
|
||||
observedAt: new Date(),
|
||||
error: failures === 0
|
||||
? null
|
||||
: `Не ответили ${failures} из 3 диагностических контрактов.`,
|
||||
});
|
||||
}).finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [generation]);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(refresh, 5_000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [refresh]);
|
||||
|
||||
const {
|
||||
aiActive,
|
||||
deviceControlConnectivity,
|
||||
controlledDevice,
|
||||
} = contourRuntimeAuthorityPresentation(state);
|
||||
const simulationWorker = snapshot?.simulationWorker ?? null;
|
||||
const controlPlaneReady = Boolean(snapshot?.controlPlane?.ok);
|
||||
const runtimeReady = snapshot?.pluginRuntimes.filter(
|
||||
(runtime) => runtime.status === "ready",
|
||||
).length ?? 0;
|
||||
const processCount = (snapshot?.pluginRuntimes.length ?? 0) + 2;
|
||||
const readyProcessCount = runtimeReady
|
||||
+ (controlPlaneReady ? 1 : 0)
|
||||
+ (simulationWorker?.available ? 1 : 0);
|
||||
const nodeStatus = useMemo(() => {
|
||||
if (!snapshot) return "Проверяем";
|
||||
if (controlPlaneReady && snapshot.error === null) return "Контур отвечает";
|
||||
if (controlPlaneReady) return "Частично доступен";
|
||||
return "Нет связи";
|
||||
}, [controlPlaneReady, snapshot]);
|
||||
|
||||
return (
|
||||
<div className="contour-health-dashboard">
|
||||
<section className="contour-health-summary">
|
||||
<div>
|
||||
<span className="section-eyebrow">ЖИВОЙ ДИАГНОСТИЧЕСКИЙ СРЕЗ</span>
|
||||
<h2>Локальный вычислительный контур</h2>
|
||||
<p>
|
||||
Статусы читаются из Control Plane, plugin runtime и шлюза Simulation Worker.
|
||||
Пустые значения не подменяются демонстрационными числами.
|
||||
</p>
|
||||
</div>
|
||||
<div className="contour-health-summary__status">
|
||||
<StatusBadge tone={controlPlaneReady ? "success" : "danger"}>
|
||||
{nodeStatus}
|
||||
</StatusBadge>
|
||||
<Button
|
||||
size="compact"
|
||||
variant="secondary"
|
||||
disabled={loading}
|
||||
onClick={refresh}
|
||||
>
|
||||
<Icon name="refresh" size={14} />
|
||||
{loading ? "Проверяем" : "Обновить"}
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="contour-health-kpis" aria-label="Сводка состояния контура">
|
||||
<div>
|
||||
<span>Узлы</span>
|
||||
<strong>{snapshot ? 2 : "—"}</strong>
|
||||
<small>локальный + внешний worker</small>
|
||||
</div>
|
||||
<div>
|
||||
<span>Процессы готовы</span>
|
||||
<strong>{snapshot ? `${readyProcessCount} / ${processCount}` : "—"}</strong>
|
||||
<small>по живым health-контрактам</small>
|
||||
</div>
|
||||
<div>
|
||||
<span>Локальный API</span>
|
||||
<strong>{formatLatency(snapshot?.controlPlaneLatencyMs ?? null)}</strong>
|
||||
<small>браузер → Control Plane</small>
|
||||
</div>
|
||||
<div>
|
||||
<span>Последняя проверка</span>
|
||||
<strong>{formatObservedAt(snapshot?.observedAt ?? null)}</strong>
|
||||
<small>автообновление каждые 5 секунд</small>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="contour-node-grid" aria-label="Вычислительные узлы">
|
||||
<article className="contour-node" data-state={controlPlaneReady ? "online" : "offline"}>
|
||||
<header>
|
||||
<div>
|
||||
<span className="section-eyebrow">УЗЕЛ 01 · ЛОКАЛЬНЫЙ</span>
|
||||
<h3>Mission Core Control Plane</h3>
|
||||
</div>
|
||||
<StatusBadge tone={controlPlaneReady ? "success" : "danger"}>
|
||||
{controlPlaneReady ? "Доступен" : "Недоступен"}
|
||||
</StatusBadge>
|
||||
</header>
|
||||
<dl>
|
||||
<div><dt>Версия</dt><dd>{snapshot?.controlPlane?.version ?? "—"}</dd></div>
|
||||
<div><dt>API latency</dt><dd>{formatLatency(snapshot?.controlPlaneLatencyMs ?? null)}</dd></div>
|
||||
<div><dt>Plugin runtimes</dt><dd>{snapshot ? `${runtimeReady} / ${snapshot.pluginRuntimes.length}` : "—"}</dd></div>
|
||||
<div><dt>Активный режим</dt><dd>{state?.sourceMode ?? "idle"}</dd></div>
|
||||
</dl>
|
||||
<div className="contour-process-list">
|
||||
{snapshot?.pluginRuntimes.map((runtime) => (
|
||||
<div key={runtime.runtime_instance_id}>
|
||||
<i data-state={runtime.status === "ready" ? "online" : "offline"} />
|
||||
<span>
|
||||
<strong>Device runtime · {runtime.plugin_id}</strong>
|
||||
<small>v{runtime.plugin_version} · {formatObservedAt(runtime.observed_at)}</small>
|
||||
</span>
|
||||
<em>{runtime.status}</em>
|
||||
</div>
|
||||
))}
|
||||
<div>
|
||||
<i data-state={aiActive ? "online" : "idle"} />
|
||||
<span>
|
||||
<strong>AI perception</strong>
|
||||
<small>
|
||||
{aiActive
|
||||
? `${Math.round(state?.metrics?.aiFrameRateHz ?? 0)} кадр/с`
|
||||
: "Нет активного задания"}
|
||||
</small>
|
||||
</span>
|
||||
<em>{aiActive ? "active" : "idle"}</em>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<article
|
||||
className="contour-node"
|
||||
data-state={simulationWorker?.available ? "online" : "offline"}
|
||||
>
|
||||
<header>
|
||||
<div>
|
||||
<span className="section-eyebrow">УЗЕЛ 02 · ВНЕШНИЙ</span>
|
||||
<h3>{simulationWorker?.workerId ?? "Simulation Worker"}</h3>
|
||||
</div>
|
||||
<StatusBadge tone={simulationWorker?.available ? "success" : "neutral"}>
|
||||
{simulationWorker?.available ? "Доступен" : "Offline"}
|
||||
</StatusBadge>
|
||||
</header>
|
||||
<dl>
|
||||
<div><dt>Gateway latency</dt><dd>{formatLatency(snapshot?.simulationGatewayLatencyMs ?? null)}</dd></div>
|
||||
<div><dt>Сеть worker</dt><dd>{simulationWorker?.isolation.network ?? "unavailable"}</dd></div>
|
||||
<div><dt>Политика данных</dt><dd>{simulationWorker?.isolation.artifactPolicy ?? "d-only"}</dd></div>
|
||||
<div><dt>Активный прогон</dt><dd>{simulationWorker?.activeRunId ?? "нет"}</dd></div>
|
||||
</dl>
|
||||
<div className="contour-process-list">
|
||||
<div>
|
||||
<i data-state={simulationWorker?.available ? "online" : "offline"} />
|
||||
<span>
|
||||
<strong>Simulation orchestration</strong>
|
||||
<small>
|
||||
{simulationWorker?.runState
|
||||
? `Прогон: ${simulationWorker.runState}`
|
||||
: "Нет активного прогона"}
|
||||
</small>
|
||||
</span>
|
||||
<em>{simulationWorker?.available ? "ready" : "offline"}</em>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section className="contour-network-strip" aria-label="Состояние сети">
|
||||
<div>
|
||||
<span className="section-eyebrow">СЕТЬ</span>
|
||||
<strong>Браузер</strong>
|
||||
<small>127.0.0.1:8000</small>
|
||||
</div>
|
||||
<Icon name="chevron-right" />
|
||||
<div>
|
||||
<i data-state={controlPlaneReady ? "online" : "offline"} />
|
||||
<strong>Control Plane</strong>
|
||||
<small>{formatLatency(snapshot?.controlPlaneLatencyMs ?? null)}</small>
|
||||
</div>
|
||||
<Icon name="chevron-right" />
|
||||
<div>
|
||||
<i data-state={simulationWorker?.available ? "online" : "offline"} />
|
||||
<strong>Worker gateway</strong>
|
||||
<small>{formatLatency(snapshot?.simulationGatewayLatencyMs ?? null)}</small>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{controlledDevice ? (
|
||||
<section className="contour-connected-device">
|
||||
<span className="section-eyebrow">ПОДТВЕРЖДЁННАЯ УПРАВЛЯЮЩАЯ СЕССИЯ</span>
|
||||
<strong>{controlledDevice.displayName}</strong>
|
||||
<small>
|
||||
{controlledDevice.endpointLabel ?? controlledDevice.modelId}
|
||||
{deviceControlConnectivity === "degraded"
|
||||
? " · управление подтверждено, поток данных нарушен"
|
||||
: " · управление подтверждено"}
|
||||
</small>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{snapshot?.error ? (
|
||||
<p className="contour-health-error" role="status">{snapshot.error}</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
export function ContourHealthWorkspace({state}:{state:MissionRuntimeState|null}){
|
||||
const [snapshot,setSnapshot]=useState<ContourSnapshot|null>(null);
|
||||
const [loading,setLoading]=useState(true),[generation,setGeneration]=useState(0);
|
||||
useEffect(()=>{
|
||||
const controller=new AbortController();
|
||||
const stop=startSequentialPolling(async()=>{
|
||||
setLoading(true);
|
||||
try{const next=await readContourSnapshot(controller.signal);if(!controller.signal.aborted)setSnapshot(next);}
|
||||
finally{if(!controller.signal.aborted)setLoading(false);}
|
||||
},5000);
|
||||
return ()=>{stop();controller.abort();};
|
||||
},[generation]);
|
||||
const summary=contourSummary(snapshot);
|
||||
const core=snapshot?.core;
|
||||
const {controlledDevice,deviceControlConnectivity}=contourRuntimeAuthorityPresentation(state);
|
||||
return <div className="contour-health-dashboard">
|
||||
<section className="contour-health-summary">
|
||||
<div><h2>Узлы и связь</h2><p>Mission Core, зарегистрированные вычислители и бортовые компьютеры аппаратов.</p></div>
|
||||
<div className="contour-health-summary__status"><StatusBadge tone={loading?'warning':summary.tone}>{loading?'Проверяем состояние':summary.label}</StatusBadge><Button size="compact" variant="secondary" disabled={loading} onClick={()=>setGeneration(value=>value+1)}><Icon name="refresh" size={14}/>{loading?'Проверяем':'Обновить'}</Button></div>
|
||||
</section>
|
||||
<section className="contour-health-kpis" aria-label="Сводка состояния контура">
|
||||
<div><span>Узлы на связи</span><strong>{summary.online??'—'} / {summary.total??'—'}</strong><small>Core, вычислители и бортовые ПК</small></div>
|
||||
<div><span>Вычислители</span><strong>{snapshot?.workers?.length??'—'}</strong><small>из настроек системы</small></div>
|
||||
<div><span>Бортовые компьютеры</span><strong>{snapshot?.vehicles?.length??'—'}</strong><small>из реестра аппаратов</small></div>
|
||||
<div><span>Последняя проверка</span><strong>{observed(snapshot?.observedAt)}</strong><small>обновление каждые 5 секунд</small></div>
|
||||
</section>
|
||||
<section className="contour-node-grid" aria-label="Узлы контура">
|
||||
<article className="contour-node" data-state={core?.ok?'online':'offline'}>
|
||||
<header><div><span className="section-eyebrow">КОМПЬЮТЕР ОПЕРАТОРА</span><h3>Mission Core</h3></div><StatusBadge tone={core?.ok?'success':core?'danger':'warning'}>{core?(core.ok?'Доступен':'Недоступен'):snapshot?'Нет свежих данных':'Проверяем'}</StatusBadge></header>
|
||||
<dl><div><dt>Версия</dt><dd>{core?.version??'—'}</dd></div><div><dt>Время ответа</dt><dd>{snapshot?.latency==null?'—':`${Math.max(1,Math.round(snapshot.latency))} мс`}</dd></div><div><dt>Обработчики устройств готовы</dt><dd>{core?`${core.plugin_runtimes.ready} / ${core.plugin_runtimes.total}`:'—'}</dd></div></dl>
|
||||
</article>
|
||||
{snapshot?.workers?.map(({contour,telemetry})=>{
|
||||
const online=workerAvailable(telemetry);
|
||||
const mismatch=telemetry?.connection.reachable&&!telemetry.connection.identity_matches;
|
||||
return <article key={contour.contour_id} className="contour-node" data-state={online?'online':'offline'}>
|
||||
<header><div><span className="section-eyebrow">ВЫЧИСЛИТЕЛЬ</span><h3>{contour.display_name}</h3></div><StatusBadge tone={online?'success':!telemetry||mismatch?'warning':'neutral'}>{online?'На связи':mismatch?'Другой узел':telemetry?'Нет свежих данных':'Проверка недоступна'}</StatusBadge></header>
|
||||
<dl><div><dt>Узел</dt><dd>{contour.expected_node_id}</dd></div><div><dt>Телеметрия</dt><dd>{contour.telemetry_mode==='agent-mqtt'?'Агент':'Диагностика SSH'}</dd></div><div><dt>Проверено</dt><dd>{observed(telemetry?.connection.observed_at_utc)}</dd></div><div><dt>Последнее измерение</dt><dd>{observed(telemetry?.node?.observed_at_utc)}</dd></div><div><dt>Операционная система</dt><dd>{telemetry?.node?.os.caption??'—'}</dd></div></dl>
|
||||
</article>;
|
||||
})}
|
||||
{snapshot?.vehicles?.map(vehicle=>{
|
||||
const online=boardAvailable(vehicle);
|
||||
const status=vehicle.enrollment==='revoked'?'Привязка отозвана':vehicle.enrollment==='pending'?'Подключение':vehicle.enrollment==='failed'?'Не подключён':online?'На связи':'Нет связи';
|
||||
return <article key={vehicle.id} className="contour-node" data-state={online?'online':'offline'}>
|
||||
<header><div><span className="section-eyebrow">БОРТОВОЙ КОМПЬЮТЕР</span><h3>{vehicle.name}</h3></div><StatusBadge tone={online?'success':'neutral'}>{status}</StatusBadge></header>
|
||||
<dl><div><dt>Имя БК</dt><dd>{vehicle.host?.hostname??'—'}</dd></div><div><dt>Операционная система</dt><dd>{vehicle.host?.os??'—'}</dd></div><div><dt>Последняя связь</dt><dd>{observed(vehicle.last_seen===null?null:vehicle.last_seen*1000)}</dd></div></dl>
|
||||
{!online&&vehicle.host&&<small>Сведения о БК сохранены с последнего подключения.</small>}
|
||||
</article>;
|
||||
})}
|
||||
</section>
|
||||
{controlledDevice&&<section className="contour-connected-device"><span className="section-eyebrow">ПОДКЛЮЧЁННОЕ УСТРОЙСТВО ОПЕРАТОРА</span><strong>{controlledDevice.displayName}</strong><small>{deviceControlConnectivity==='degraded'?'Поток данных нарушен':'Управляющая связь подтверждена'}</small></section>}
|
||||
{snapshot?.errors.map(error=><p key={error} className="contour-health-error" role="status">{error}</p>)}
|
||||
</div>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user