feat(worker): supervise VPN connections and recover batched telemetry

This commit is contained in:
DCCONSTRUCTIONS
2026-11-10 01:10:37 +03:00
parent fe5900ff3b
commit ad5a929e06
46 changed files with 2996 additions and 640 deletions
@@ -0,0 +1,48 @@
import {useCallback, useEffect, useRef, useState} from "react";
import {connectionRequest, type ConnectionCatalog} from "./workerConnections";
/** One request at a time; refresh while visible and when returning from the VPN app. */
export function useConnectionCatalog(open: boolean, suspended: boolean) {
const [catalog, setCatalog] = useState<ConnectionCatalog | null>(null);
const [error, setError] = useState<string | null>(null);
const [initializing, setInitializing] = useState(false);
const active = useRef(false);
const pause = useRef(suspended); pause.current = suspended;
const request = useRef<{controller: AbortController; promise: Promise<ConnectionCatalog>} | null>(null);
const refresh = useCallback((): Promise<ConnectionCatalog> => {
if (request.current) return request.current.promise;
const controller = new AbortController();
const promise = connectionRequest<ConnectionCatalog>("", undefined, controller.signal)
.then(value => {
if (active.current && !controller.signal.aborted) {setCatalog(value); setError(null);}
return value;
}).catch(reason => {
if (active.current && !controller.signal.aborted) setError(reason instanceof Error ? reason.message : "Не удалось обновить подключения.");
throw reason;
}).finally(() => {if (request.current?.controller === controller) request.current = null;});
request.current = {controller, promise};
return promise;
}, []);
useEffect(() => {
if (!open) return;
active.current = true;
let disposed = false;
setCatalog(null); setError(null); setInitializing(true);
void refresh().catch(() => {}).finally(() => {if (!disposed) setInitializing(false);});
const update = () => {
if (!pause.current && document.visibilityState === "visible") void refresh().catch(() => {});
};
const timer = window.setInterval(update, 5000);
window.addEventListener("focus", update);
document.addEventListener("visibilitychange", update);
return () => {
disposed = true; active.current = false;
window.clearInterval(timer);
window.removeEventListener("focus", update);
document.removeEventListener("visibilitychange", update);
request.current?.controller.abort(); request.current = null;
};
}, [open, refresh]);
return {catalog, refresh, discoveryError: error, initializing};
}
@@ -21,6 +21,7 @@ export function useWorkerTelemetry(
pollMilliseconds = DEFAULT_WORKER_TELEMETRY_POLL_MILLISECONDS,
enabled = true,
externalRefreshGeneration = 0,
historyLimit = 90,
): WorkerTelemetryState {
const normalizedPollMilliseconds = normalizeWorkerTelemetryPollMilliseconds(
pollMilliseconds,
@@ -44,7 +45,7 @@ export function useWorkerTelemetry(
const stopPolling = startSequentialPolling(async () => {
setLoading(true);
try {
const document = await fetchWorkerTelemetry(contourId, controller.signal);
const document = await fetchWorkerTelemetry(contourId, controller.signal, historyLimit);
if (controller.signal.aborted) return;
setTelemetry(document);
setError(null);
@@ -70,6 +71,7 @@ export function useWorkerTelemetry(
externalRefreshGeneration,
generation,
normalizedPollMilliseconds,
historyLimit,
]);
return { telemetry, loading, error, refresh };
@@ -5,7 +5,12 @@ export function workerConnectionStatus(telemetry: WorkerTelemetry | null) {
const connection = telemetry?.connection;
if (!connection) return {state:'unknown', tone:'warning', label:'Не в сети', detail:'Состояние вычислителя пока не подтверждено.'} as const;
if (connection.reachable && !connection.identity_matches) return {state:'unknown', tone:'warning', label:'Не в сети', detail:'Ответивший узел не совпадает с выбранным вычислителем.'} as const;
if (connection.reachable && connection.identity_matches && telemetry.node) return {state:'online', tone:'success', label:'В сети', detail:null} as const;
if (connection.reachable && connection.identity_matches && telemetry.node) {
if (typeof telemetry.node.cpu?.load_percent !== 'number' || typeof telemetry.node.memory?.used_percent !== 'number') {
return {state:'unknown', tone:'warning', label:'Телеметрия неполная', detail:'Устройство отвечает, но свежие показатели нагрузки не получены.'} as const;
}
return {state:'online', tone:'success', label:'В сети', detail:null} as const;
}
if (['telemetry-receiver-unavailable','telemetry-agent-unavailable','invalid-telemetry-response'].includes(connection.error_code ?? '')) {
return {state:'unknown', tone:'warning', label:'Не в сети', detail:'Mission Core не получает данные через службу телеметрии. Состояние самого вычислителя не подтверждено.'} as const;
}
@@ -0,0 +1,48 @@
export interface NetworkProfile {
id: string; name: string; provider: "tailscale" | "wireguard"; network_id: string;
}
export interface WorkerPath {id: string; profile_id: string; endpoint: string; peer_id: string}
export interface WorkerBinding {
contour_id: string; revision: number; active_connection_id: string | null;
connections: WorkerPath[];
}
export interface ConnectionCatalog {
revision: number; profiles: NetworkProfile[]; available_profile_ids: string[];
peers: {id: string; profile_id: string; name: string; online: boolean | null}[];
workers: WorkerBinding[];
prepared: {id: string; contour_id: string; name: string; hostname: string; platform: string}[];
notice: string | null;
tailscale_client?: TailscaleClient;
}
export interface TailscaleClient {
state: "not_installed" | "unavailable" | "needs_login" | "stopped" | "needs_approval" | "starting" | "connected";
message: string; can_open: boolean; version: string | null;
}
export function keepAvailableSelection(current: string, ids: string[], fallback = "") {
return ids.includes(current) ? current : fallback;
}
export interface ConnectionCheck {
identity: {hostname: string; platform: string}; active: boolean;
channels: {id: string; label: string; connected: boolean}[];
}
// A name match only selects an installed credential binding. Admission still
// verifies the pinned host key and the remote identity on the server.
export function workerCandidate(catalog: ConnectionCatalog | null, profileId: string, peerId: string) {
const peer = catalog?.peers.find(x => x.profile_id === profileId && x.id === peerId);
const enrolled = catalog?.workers.find(w => w.connections.some(x => x.profile_id === profileId && x.peer_id === peerId));
const matches = peer ? catalog?.prepared.filter(x => x.hostname.toLowerCase() === peer.name.toLowerCase()
&& !catalog.workers.some(w => w.contour_id === x.contour_id)) ?? [] : [];
return {peer, enrolled, binding: matches.length === 1 ? matches[0] : null};
}
export async function connectionRequest<T>(path = "", body?: unknown, signal?: AbortSignal): Promise<T> {
const response = await fetch(`/api/v1/system/connections${path}`, {
method: body === undefined ? "GET" : "POST", cache: "no-store", signal,
headers: body === undefined ? undefined : {"Content-Type": "application/json"},
body: body === undefined ? undefined : JSON.stringify(body),
});
const value = await response.json();
if (!response.ok) throw new Error(typeof value.detail === "string" ? value.detail : "Подключение не подтверждено.");
return value as T;
}
@@ -193,10 +193,11 @@ async function requestJson(
export async function fetchWorkerTelemetry(
contourId: string,
signal?: AbortSignal,
historyLimit = 90,
): Promise<WorkerTelemetry> {
const document = requireJsonRecord(
await requestJson(
`/api/v1/system/contours/${encodeURIComponent(contourId)}/telemetry?history=90`,
`/api/v1/system/contours/${encodeURIComponent(contourId)}/telemetry?history=${historyLimit}`,
{
method: "GET",
signal: signal