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
@@ -1,579 +0,0 @@
import { useEffect, useMemo, useState } from "react";
import {
Button,
FeatureSettingsWindow,
FieldFrame,
Icon,
Select,
SettingsCard,
StatusBadge,
TextField,
WindowFooterActions,
} from "@nodedc/ui-react";
import {
applyComputeContourNetwork,
fetchComputeContourAgentInstall,
fetchComputeContourNetwork,
type ComputeContour,
type ComputeContourAgentInstall,
type ComputeContourDraft,
type ComputeContourNetworkStatus,
type ComputeContourPlatform,
} from "../../core/system/computeContours";
import {
DEFAULT_TELEMETRY_POLL_INTERVAL_SECONDS,
parseTelemetryPollIntervalDraft,
resolveTelemetryPollIntervalDraft,
} from "../../core/system/telemetryPollInterval";
interface ComputeContourSettingsWindowProps {
open: boolean;
contour: ComputeContour | null;
mode: "create" | "edit";
onClose: () => void;
onCreate: (draft: ComputeContourDraft) => Promise<ComputeContour>;
onUpdate: (
contour: ComputeContour,
draft: ComputeContourDraft,
) => Promise<ComputeContour>;
}
const platformOptions = [
{ value: "windows", label: "Windows", description: "Worker с Windows service" },
{ value: "linux", label: "Linux", description: "Worker с systemd service" },
{ value: "unknown", label: "Не определено", description: "Платформа будет уточнена" },
] satisfies Array<{
value: ComputeContourPlatform;
label: string;
description: string;
}>;
function emptyDraft(): ComputeContourDraft {
return {
display_name: "",
expected_node_id: "",
platform: "unknown",
telemetry_mode: "agent-mqtt",
address: "",
ssh_port: 22,
mqtt_host: "127.0.0.1",
mqtt_port: 1883,
mqtt_bind_address: "127.0.0.1",
telemetry_poll_interval_seconds: DEFAULT_TELEMETRY_POLL_INTERVAL_SECONDS,
mqtt_publish_interval_seconds: 2,
};
}
function draftFromContour(contour: ComputeContour | null): ComputeContourDraft {
if (!contour) return emptyDraft();
return {
display_name: contour.display_name,
expected_node_id: contour.expected_node_id,
platform: contour.platform,
telemetry_mode: contour.telemetry_mode,
address: contour.address,
ssh_port: contour.ssh_port,
mqtt_host: contour.mqtt_host,
mqtt_port: contour.mqtt_port,
mqtt_bind_address: contour.mqtt_bind_address,
telemetry_poll_interval_seconds: contour.telemetry_poll_interval_seconds,
mqtt_publish_interval_seconds: contour.mqtt_publish_interval_seconds,
};
}
export function ComputeContourSettingsWindow({
open,
contour,
mode,
onClose,
onCreate,
onUpdate,
}: ComputeContourSettingsWindowProps) {
const [draft, setDraft] = useState<ComputeContourDraft>(() => draftFromContour(contour));
const [telemetryPollIntervalDraft, setTelemetryPollIntervalDraft] = useState(
() => String(draftFromContour(contour).telemetry_poll_interval_seconds),
);
const [mqttPublishIntervalDraft, setMqttPublishIntervalDraft] = useState(
() => String(draftFromContour(contour).mqtt_publish_interval_seconds),
);
const [activeSection, setActiveSection] = useState<"connection" | "agent">("connection");
const [install, setInstall] = useState<ComputeContourAgentInstall | null>(null);
const [network, setNetwork] = useState<ComputeContourNetworkStatus | null>(null);
const [networkAction, setNetworkAction] = useState<
"refresh" | "broker" | "worker" | null
>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!open) return;
const nextDraft = draftFromContour(mode === "edit" ? contour : null);
setDraft(nextDraft);
setTelemetryPollIntervalDraft(String(nextDraft.telemetry_poll_interval_seconds));
setMqttPublishIntervalDraft(String(nextDraft.mqtt_publish_interval_seconds));
setActiveSection("connection");
setInstall(null);
setNetwork(null);
setNetworkAction(null);
setError(null);
}, [contour, mode, open]);
useEffect(() => {
if (!open || mode !== "edit" || !contour) return;
const controller = new AbortController();
setNetworkAction("refresh");
void fetchComputeContourNetwork(contour.contour_id, controller.signal)
.then((document) => {
if (!controller.signal.aborted) setNetwork(document);
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) {
setError(reason instanceof Error ? reason.message : "Сетевая проверка недоступна.");
}
})
.finally(() => {
if (!controller.signal.aborted) setNetworkAction(null);
});
return () => controller.abort();
}, [contour, mode, open]);
useEffect(() => {
if (!open || mode !== "edit" || !contour) return;
const controller = new AbortController();
void fetchComputeContourAgentInstall(contour.contour_id, controller.signal)
.then((document) => {
if (!controller.signal.aborted) setInstall(document);
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) {
setError(reason instanceof Error ? reason.message : "Инструкция агента недоступна.");
}
});
return () => controller.abort();
}, [contour, mode, open]);
const telemetryPollIntervalSeconds = useMemo(
() => parseTelemetryPollIntervalDraft(telemetryPollIntervalDraft),
[telemetryPollIntervalDraft],
);
const mqttPublishIntervalSeconds = useMemo(
() => parseTelemetryPollIntervalDraft(mqttPublishIntervalDraft),
[mqttPublishIntervalDraft],
);
const valid = useMemo(() => (
Boolean(draft.display_name.trim())
&& Boolean(draft.expected_node_id.trim())
&& Boolean(draft.mqtt_host.trim())
&& Boolean(draft.mqtt_bind_address.trim())
&& Number.isInteger(draft.ssh_port)
&& draft.ssh_port > 0
&& Number.isInteger(draft.mqtt_port)
&& draft.mqtt_port > 0
&& telemetryPollIntervalSeconds !== null
&& mqttPublishIntervalSeconds !== null
), [draft, mqttPublishIntervalSeconds, telemetryPollIntervalSeconds]);
const networkProfileDirty = Boolean(
contour
&& (
draft.mqtt_host !== contour.mqtt_host
|| draft.mqtt_port !== contour.mqtt_port
|| draft.mqtt_bind_address !== contour.mqtt_bind_address
|| draft.mqtt_publish_interval_seconds !== contour.mqtt_publish_interval_seconds
),
);
const commitTelemetryPollInterval = () => {
const resolution = resolveTelemetryPollIntervalDraft(
telemetryPollIntervalDraft,
draft.telemetry_poll_interval_seconds,
);
setTelemetryPollIntervalDraft(resolution.draft);
if (!resolution.accepted) return;
setDraft((current) => (
current.telemetry_poll_interval_seconds === resolution.seconds
? current
: {
...current,
telemetry_poll_interval_seconds: resolution.seconds,
}
));
};
const commitMqttPublishInterval = () => {
const resolution = resolveTelemetryPollIntervalDraft(
mqttPublishIntervalDraft,
draft.mqtt_publish_interval_seconds,
);
setMqttPublishIntervalDraft(resolution.draft);
if (!resolution.accepted) return;
setDraft((current) => (
current.mqtt_publish_interval_seconds === resolution.seconds
? current
: {
...current,
mqtt_publish_interval_seconds: resolution.seconds,
}
));
};
const save = async () => {
if (
!valid
|| busy
|| telemetryPollIntervalSeconds === null
|| mqttPublishIntervalSeconds === null
) return;
const committedDraft = {
...draft,
telemetry_poll_interval_seconds: telemetryPollIntervalSeconds,
mqtt_publish_interval_seconds: mqttPublishIntervalSeconds,
};
setBusy(true);
setError(null);
try {
if (mode === "edit" && contour) {
await onUpdate(contour, committedDraft);
} else {
await onCreate(committedDraft);
}
onClose();
} catch (reason) {
setError(reason instanceof Error ? reason.message : "Контур не сохранён.");
} finally {
setBusy(false);
}
};
const refreshNetwork = async () => {
if (!contour || networkAction) return;
setNetworkAction("refresh");
setError(null);
try {
setNetwork(await fetchComputeContourNetwork(contour.contour_id));
} catch (reason) {
setError(reason instanceof Error ? reason.message : "Сетевая проверка недоступна.");
} finally {
setNetworkAction(null);
}
};
const applyNetwork = async (target: "broker" | "worker") => {
if (!contour || networkAction || networkProfileDirty) return;
setNetworkAction(target);
setError(null);
try {
await applyComputeContourNetwork(contour.contour_id, target);
setNetwork(await fetchComputeContourNetwork(contour.contour_id));
} catch (reason) {
setError(
reason instanceof Error ? reason.message : "Сетевой профиль не применён.",
);
} finally {
setNetworkAction(null);
}
};
return (
<FeatureSettingsWindow
open={open}
title={mode === "create" ? "Добавить вычислительный контур" : "Настройки контура"}
subtitle="Локальная переносимая конфигурация"
identity={{
title: contour?.display_name ?? "Новый контур",
subtitle: contour?.expected_node_id ?? "Node ID не назначен",
avatarLabel: contour?.display_name.slice(0, 2).toUpperCase() ?? "WC",
}}
sections={[
{
id: "connection",
label: "Подключение",
group: "ВЫЧИСЛИТЕЛЬНЫЙ КОНТУР",
icon: "network",
},
{
id: "agent",
label: "Агент",
group: "ТЕЛЕМЕТРИЯ",
icon: "activity",
disabled: mode === "create",
},
]}
activeSection={activeSection}
onSectionChange={setActiveSection}
onClose={onClose}
footer={(
<WindowFooterActions>
<Button variant="secondary" onClick={onClose}>Отмена</Button>
<Button variant="primary" disabled={!valid || busy} onClick={() => void save()}>
{busy ? "Сохраняем…" : mode === "create" ? "Добавить контур" : "Сохранить"}
</Button>
</WindowFooterActions>
)}
>
<div className="compute-contour-settings">
{activeSection === "connection" ? (
<>
<SettingsCard
eyebrow="КОНТУР"
title="Идентичность и локальная сеть"
description="Node ID проверяется независимо от IP-адреса. Адрес можно менять при переносе комплекта в другую локальную сеть."
>
<div className="compute-contour-settings__form">
<TextField
label="Название"
value={draft.display_name}
placeholder="Worker 006"
onChange={(event) => setDraft((current) => ({
...current,
display_name: event.currentTarget.value,
}))}
/>
<TextField
label="Ожидаемый Node ID"
value={draft.expected_node_id}
placeholder="DESKTOP-OPJ8J04"
onChange={(event) => setDraft((current) => ({
...current,
expected_node_id: event.currentTarget.value,
}))}
/>
<FieldFrame label="Операционная система">
<Select
label="Операционная система"
value={draft.platform}
options={platformOptions}
variant="split"
menuWidth="anchor"
onChange={(platform) => setDraft((current) => ({ ...current, platform }))}
/>
</FieldFrame>
<TextField
label="Адрес узла"
hint="IP или hostname в текущей LAN"
value={draft.address}
onChange={(event) => setDraft((current) => ({
...current,
address: event.currentTarget.value,
}))}
/>
<TextField
label="MQTT broker"
hint="Стабильный hostname рекомендуется вместо выдаваемого DHCP IP"
value={draft.mqtt_host}
onChange={(event) => setDraft((current) => ({
...current,
mqtt_host: event.currentTarget.value,
}))}
/>
<TextField
label="MQTT port"
type="number"
min={1}
max={65535}
value={String(draft.mqtt_port)}
onChange={(event) => setDraft((current) => ({
...current,
mqtt_port: Number(event.currentTarget.value),
}))}
/>
<TextField
label="Публикация broker"
hint="IP текущего Mac в разрешённой LAN · 0.0.0.0 запрещён"
value={draft.mqtt_bind_address}
onChange={(event) => setDraft((current) => ({
...current,
mqtt_bind_address: event.currentTarget.value,
}))}
/>
<TextField
label="Обновление интерфейса"
hint="1–60 с"
type="text"
inputMode="numeric"
autoComplete="off"
aria-invalid={telemetryPollIntervalSeconds === null}
value={telemetryPollIntervalDraft}
onChange={(event) => setTelemetryPollIntervalDraft(event.currentTarget.value)}
onBlur={commitTelemetryPollInterval}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
commitTelemetryPollInterval();
} else if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
setTelemetryPollIntervalDraft(
String(draft.telemetry_poll_interval_seconds),
);
}
}}
/>
<TextField
label="Интервал MQTT агента"
hint="1–60 с · применяется конфигурацией агента"
type="text"
inputMode="numeric"
autoComplete="off"
aria-invalid={mqttPublishIntervalSeconds === null}
value={mqttPublishIntervalDraft}
onChange={(event) => setMqttPublishIntervalDraft(event.currentTarget.value)}
onBlur={commitMqttPublishInterval}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
commitMqttPublishInterval();
} else if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
setMqttPublishIntervalDraft(
String(draft.mqtt_publish_interval_seconds),
);
}
}}
/>
{draft.telemetry_mode === "legacy-ssh" ? (
<TextField
label="SSH port"
type="number"
min={1}
max={65535}
value={String(draft.ssh_port)}
onChange={(event) => setDraft((current) => ({
...current,
ssh_port: Number(event.currentTarget.value),
}))}
/>
) : null}
</div>
</SettingsCard>
<SettingsCard
eyebrow="СЕТЕВОЙ ПРОФИЛЬ"
title="MQTT · Mac ↔ Worker"
description="Mesh-точки одной LAN не закрепляются по отдельности. Профиль хранит стабильное имя Mac и адрес публикации broker в текущей сети."
actions={(
<StatusBadge tone={network?.broker.ready ? "success" : "warning"}>
{network?.broker.ready ? "Broker доступен" : "Нужна проверка"}
</StatusBadge>
)}
>
<div className="compute-contour-settings__network">
<dl>
<div>
<dt>Endpoint Worker</dt>
<dd>{network
? `${network.broker.configured_host}:${network.broker.configured_port}`
: "—"}</dd>
</div>
<div>
<dt>Текущий IP</dt>
<dd>{network?.broker.resolved_addresses.join(", ") || "—"}</dd>
</div>
<div>
<dt>Публикация Mac</dt>
<dd>{network?.broker.bind_address ?? "—"}</dd>
</div>
<div>
<dt>{contour?.display_name ?? "Worker"}</dt>
<dd>{network?.worker.reachable
? `${network.worker.mqtt_host ?? "—"}:${network.worker.mqtt_port ?? "—"}`
: "Недоступен"}</dd>
</div>
</dl>
<div className="compute-contour-settings__network-statuses">
<StatusBadge tone={network?.broker.bind_reachable ? "success" : "danger"}>
{network?.broker.bind_reachable
? "Listener Mac доступен"
: "Listener Mac недоступен"}
</StatusBadge>
<StatusBadge tone={network?.worker.broker_reachable ? "success" : "danger"}>
{network?.worker.broker_reachable
? "Worker видит broker"
: "Worker не видит broker"}
</StatusBadge>
<StatusBadge tone={network?.worker.matches_profile ? "success" : "warning"}>
{network?.worker.matches_profile
? "Профиль синхронизирован"
: "Профиль отличается"}
</StatusBadge>
</div>
<div className="compute-contour-settings__network-actions">
<Button
size="compact"
variant="secondary"
disabled={Boolean(networkAction)}
icon={<Icon name="refresh" size={14} />}
onClick={() => void refreshNetwork()}
>
{networkAction === "refresh" ? "Проверяем…" : "Проверить"}
</Button>
<Button
size="compact"
variant="secondary"
disabled={Boolean(networkAction) || networkProfileDirty}
onClick={() => void applyNetwork("broker")}
>
{networkAction === "broker" ? "Применяем…" : "Применить на Mac"}
</Button>
<Button
size="compact"
variant="secondary"
disabled={Boolean(networkAction) || networkProfileDirty}
onClick={() => void applyNetwork("worker")}
>
{networkAction === "worker" ? "Применяем…" : "Применить на Worker"}
</Button>
</div>
{networkProfileDirty ? (
<p>Сначала сохраните изменённый сетевой профиль, затем примените его.</p>
) : null}
{error ? <StatusBadge tone="danger">{error}</StatusBadge> : null}
</div>
</SettingsCard>
</>
) : null}
{activeSection === "agent" ? (
<SettingsCard
eyebrow="АГЕНТ"
title="Telegraf · универсальный сборщик"
description="Hardware и runtime собирает готовый агент. Mission Core нормализует только контур, LAB/run и стадии обработки."
actions={(
<StatusBadge tone={install?.ready ? "success" : "warning"}>
{install?.ready ? "Готов к установке" : "Нужен scoped MQTT credential"}
</StatusBadge>
)}
>
{install ? (
<div className="compute-contour-settings__install">
<dl>
<div><dt>Шаблон</dt><dd>{install.agent.configuration_template}</dd></div>
<div><dt>Секрет</dt><dd>интерактивный ввод · не хранится в UI</dd></div>
</dl>
<code>{install.command}</code>
<Button
size="compact"
variant="secondary"
icon={<Icon name="copy" size={14} />}
onClick={() => void navigator.clipboard.writeText(install.command)}
>
Копировать команду
</Button>
{install.blocked_reason ? <p>{install.blocked_reason}</p> : null}
</div>
) : (
<p className="compute-contour-settings__empty">
Сохраните контур, чтобы получить платформенную инструкцию установки.
</p>
)}
{error ? <StatusBadge tone="danger">{error}</StatusBadge> : null}
</SettingsCard>
) : null}
</div>
</FeatureSettingsWindow>
);
}
@@ -0,0 +1,53 @@
import {useEffect, useRef, useState} from "react";
import {Button, Description, Icon, SettingsCard, StatusBadge} from "@nodedc/ui-react";
import {fleetRequest} from "../../core/fleet/useFleet";
import {connectionRequest, type ConnectionCatalog} from "../../core/system/workerConnections";
export function ImportNetworkProfile({onImported, disabled = false}: {onImported: () => Promise<unknown>; disabled?: boolean}) {
const input = useRef<HTMLInputElement>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
return <>
<input ref={input} type="file" accept=".json,application/json" hidden onChange={event => {
const file = event.currentTarget.files?.[0]; event.currentTarget.value = "";
if (!file || busy) return;
setBusy(true); setError(null);
void (async () => {
if (file.size > 16384) throw Error("Выберите файл подключения, выданный установщиком VPS.");
await fleetRequest("/network-profiles/import", "POST", {document: await file.text()}, 240000);
await onImported();
})().catch(e => setError(e instanceof Error ? e.message : "Не удалось добавить профиль."))
.finally(() => setBusy(false));
}}/>
<Button icon={<Icon name="upload"/>} disabled={disabled || busy} loading={busy} onClick={() => input.current?.click()}>
Импортировать подключение к серверу
</Button>
<Description>Файл mission-core-wireguard.json выдаёт установщик NODE.DC на вашем VPS. Получите его у администратора этого сервера и выберите здесь. Приглашение действует 24 часа; затем администратор выпускает новое. Экспорт туннеля из приложения WireGuard (.conf) не подходит.</Description>
{error && <p role="alert"><StatusBadge tone="warning">{error}</StatusBadge></p>}
</>;
}
export function SharedNetworkProfiles() {
const [catalog, setCatalog] = useState<ConnectionCatalog | null>(null);
const [error, setError] = useState<string | null>(null);
async function refresh(signal?: AbortSignal) {
const value = await connectionRequest<ConnectionCatalog>("", undefined, signal);
if (!signal?.aborted) {setCatalog(value); setError(null);}
}
useEffect(() => {
const controller = new AbortController();
void refresh(controller.signal).catch(e => {if (!controller.signal.aborted) setError(e.message);});
return () => controller.abort();
}, []);
return <SettingsCard eyebrow="ОБЩИЕ СЕТИ" title="Сетевые подключения"
description="Профили доступны всему парку. Активное подключение выбирается отдельно в настройках каждого устройства.">
{catalog?.profiles.map(profile => <p key={profile.id}>
<strong>{profile.name}</strong> · {profile.provider === "tailscale" ? "Tailscale" : "WireGuard"}
{profile.provider === "wireguard" ? " · подключение устройств настраивается отдельно" : " · сеть текущего клиента"}
</p>)}
<Description>Адреса WireGuard в списке — серверы VPN. Tailscale показывает текущую сеть приложения на этом компьютере.</Description>
<ImportNetworkProfile onImported={refresh}/>
{error && <p role="alert">{error}</p>}
{catalog?.notice && <Description>{catalog.notice}</Description>}
</SettingsCard>;
}
@@ -2,7 +2,7 @@ import { SegmentedControl } from "@nodedc/ui-react";
import { workspacesForRoot } from "../../productModel";
const systemWorkspaces = workspacesForRoot("system");
const systemWorkspaces = workspacesForRoot("system").filter(item => item.kind === "compute-modules" || item.kind === "network-monitor");
const compactLabels: Record<string, string> = {
modules: "Модули",
integrations: "Интеграции",
@@ -0,0 +1,26 @@
import {useState} from "react";
import {Button, Description, Icon} from "@nodedc/ui-react";
import {connectionRequest, type TailscaleClient} from "../../core/system/workerConnections";
export function TailscaleClientStatus({client, disabled, onOpened}: {
client: TailscaleClient; disabled: boolean; onOpened: () => Promise<unknown>;
}) {
const [opening, setOpening] = useState(false);
const [error, setError] = useState<string | null>(null);
if (client.state === "connected") return null;
return <>
<Description>{client.message}</Description>
{client.state === "not_installed" ? <Button icon={<Icon name="download"/>}
onClick={() => window.open("https://tailscale.com/download", "_blank", "noopener,noreferrer")}>
Скачать Tailscale
</Button> : client.can_open ? <Button disabled={disabled || opening} loading={opening}
onClick={() => {
setOpening(true); setError(null);
void connectionRequest("/tailscale/open", {}).then(onOpened)
.catch(reason => setError(reason instanceof Error ? reason.message : "Не удалось открыть Tailscale."))
.finally(() => setOpening(false));
}}>{client.state === "needs_login" ? "Авторизироваться" : "Открыть Tailscale"}</Button>
: <Description>Откройте установленный клиент Tailscale на этом компьютере и проверьте подключение.</Description>}
{error && <Description role="alert">{error}</Description>}
</>;
}
@@ -0,0 +1,146 @@
import {useEffect, useState} from "react";
import {Button, Description, FeatureSettingsWindow, FieldFrame, Icon, IconButton,
Select, SettingsCard, StatusBadge, TextField, WindowFooterActions} from "@nodedc/ui-react";
import {connectionRequest, keepAvailableSelection, workerCandidate, type ConnectionCheck} from "../../core/system/workerConnections";
import {useConnectionCatalog} from "../../core/system/useConnectionCatalog";
import type {ComputeContour, ComputeContourDraft} from "../../core/system/computeContours";
import {ImportNetworkProfile} from "./SharedNetworkProfiles";
import {TailscaleClientStatus} from "./TailscaleClientStatus";
interface Props {open: boolean; mode: "create" | "edit"; contour: ComputeContour | null;
onClose: () => void; onChanged: () => void;
onUpdate: (contour: ComputeContour, draft: ComputeContourDraft) => Promise<ComputeContour>}
export function WorkerConnectionSettings({open, mode, contour, onClose, onChanged, onUpdate}: Props) {
const [section, setSection] = useState("connections");
const [name, setName] = useState("");
const [poll, setPoll] = useState("3");
const [provider, setProvider] = useState("tailscale");
const [profileId, setProfileId] = useState("");
const [peerId, setPeerId] = useState("");
const [selectedPath, setSelectedPath] = useState("");
const [adding, setAdding] = useState(false);
const [acting, setBusy] = useState(false);
const {catalog, refresh, discoveryError, initializing} = useConnectionCatalog(open, acting);
const busy = acting || initializing;
const [error, setError] = useState<string | null>(null);
const [check, setCheck] = useState<ConnectionCheck | null>(null);
const worker = mode === "edit" ? catalog?.workers.find(x => x.contour_id === contour?.contour_id) : null;
const enroll = !worker;
const profiles = catalog?.profiles.filter(x => x.provider === provider
&& catalog.available_profile_ids.includes(x.id)
&& !worker?.connections.some(c => c.profile_id === x.id)) ?? [];
const profile = profiles.find(x => x.id === profileId);
const peers = catalog?.peers.filter(x => x.profile_id === profileId) ?? [];
const candidate = workerCandidate(catalog, profileId, peerId);
useEffect(() => {
if (!open) return;
setError(null); setCheck(null); setAdding(false); setSelectedPath("");
setSection("connections"); setName(contour?.display_name ?? "");
setPoll(String(contour?.telemetry_poll_interval_seconds ?? 3));
}, [open, contour?.contour_id, mode]);
useEffect(() => {setSelectedPath(worker?.active_connection_id ?? "");}, [worker?.active_connection_id]);
useEffect(() => {setProfileId(current => keepAvailableSelection(current, profiles.map(x => x.id), profiles[0]?.id));}, [provider, catalog, worker?.revision]);
useEffect(() => {setPeerId(current => keepAvailableSelection(current, peers.map(x => x.id)));}, [profileId, catalog]);
const availableNetworks = catalog?.available_profile_ids.join(",");
useEffect(() => {setCheck(null);}, [availableNetworks, catalog?.tailscale_client?.state]);
async function action(fn: () => Promise<void>) {
setBusy(true); setError(null);
try {await fn();} catch (e) {setError(e instanceof Error ? e.message : "Операция не выполнена.");}
finally {setBusy(false);}
}
async function add() {
if (!catalog || !profile || !peerId) return;
await connectionRequest(enroll ? "/enroll" : `/${worker!.contour_id}/attach`, {
profile_id: profile.id, peer_id: peerId, revision: enroll ? catalog.revision : worker!.revision,
...(enroll ? {binding_id: candidate.binding?.id} : {}),
});
await refresh(); onChanged(); setAdding(false); setCheck(null);
if (mode === "create") onClose();
}
return <FeatureSettingsWindow open={open} title={mode === "create" ? "Подключить воркер" : "Настройки воркера"}
subtitle="Сетевые подключения" identity={{title: contour?.display_name ?? "Новый воркер",
subtitle: contour?.expected_node_id ?? "Подключение к Mission Core", avatarLabel: "WC"}}
sections={[{id: "connections", label: "Подключения", icon: "network", group: "ВОРКЕР"},
...(mode === "edit" ? [{id: "agent", label: "Агент", icon: "activity" as const, group: "ВОРКЕР"}] : [])]}
activeSection={section} onSectionChange={setSection} onClose={busy ? () => {} : onClose}
headerActions={<IconButton label="Обновить подключения" disabled={busy} onClick={() => void action(async () => {await refresh(); setCheck(null);})}><Icon name="refresh"/></IconButton>}
footer={<WindowFooterActions><Button onClick={onClose} disabled={busy}>Готово</Button></WindowFooterActions>}>
<div className="compute-contour-settings">
{section === "agent" && contour && <SettingsCard title="Устройство и телеметрия"
description={`Идентичность: ${contour.expected_node_id}. Платформа: ${contour.platform}.`}>
<div className="compute-contour-settings__form">
<TextField label="Название" value={name} onChange={event => setName(event.currentTarget.value)}/>
<TextField label="Обновление интерфейса, с" type="number" min={1} max={60} value={poll} onChange={event => setPoll(event.currentTarget.value)}/>
</div>
<Button disabled={busy || !name.trim() || !Number.isInteger(Number(poll)) || Number(poll) < 1 || Number(poll) > 60}
onClick={() => void action(async () => {await onUpdate(contour, {
display_name: name, expected_node_id: contour.expected_node_id, platform: contour.platform,
telemetry_mode: contour.telemetry_mode, address: contour.address, ssh_port: contour.ssh_port,
mqtt_host: contour.mqtt_host, mqtt_port: contour.mqtt_port, mqtt_bind_address: contour.mqtt_bind_address,
mqtt_publish_interval_seconds: contour.mqtt_publish_interval_seconds,
telemetry_poll_interval_seconds: Number(poll),
});})}>Сохранить</Button>
</SettingsCard>}
{section === "connections" && worker && <SettingsCard eyebrow="ПОДКЛЮЧЕНИЯ" title="Активное подключение"
description="Выбор сети относится только к этому воркеру. Другие устройства сохраняют свои подключения.">
<div className="compute-contour-settings__form compute-contour-settings__connection-row">
<FieldFrame label="Подключение"><Select label="Подключение" value={selectedPath} disabled={busy}
options={worker.connections.map(x => ({value: x.id, label: catalog?.profiles.find(p => p.id === x.profile_id)?.name ?? x.profile_id,
description: x.id === worker.active_connection_id ? "Активное" : "Подготовлено"}))}
onChange={value => {setSelectedPath(value); setCheck(null);}}/></FieldFrame>
<div className="system-workspace__actions">
<Button disabled={busy || !selectedPath} onClick={() => void action(async () => {
setCheck(await connectionRequest<ConnectionCheck>(`/${worker.contour_id}/check`, {connection_id: selectedPath, revision: worker.revision}));
})}>Проверить</Button>
<Button disabled={busy || !selectedPath || selectedPath === worker.active_connection_id} onClick={() => void action(async () => {
await connectionRequest(`/${worker.contour_id}/activate`, {connection_id: selectedPath, revision: worker.revision});
await refresh(); onChanged(); setCheck(null);
})}>Использовать</Button>
<IconButton label="Добавить подключение" disabled={busy} onClick={() => setAdding(!adding)}><Icon name="plus"/></IconButton>
</div>
</div>
{catalog?.tailscale_client && worker.connections.some(path => path.id === selectedPath
&& catalog.profiles.some(p => p.id === path.profile_id && p.provider === "tailscale"))
&& <TailscaleClientStatus client={catalog.tailscale_client} disabled={busy} onOpened={refresh}/>}
{catalog?.tailscale_client?.state === "connected" && worker.connections.some(path => path.id === selectedPath
&& !catalog.available_profile_ids.includes(path.profile_id))
&& <Description>Выбранная сеть сейчас недоступна. Подключите её в VPN-клиенте.</Description>}
{check && <><StatusBadge tone="success">Устройство подтверждено · {check.identity.hostname}</StatusBadge>
{check.active && check.channels.map(x => <p key={x.id}><StatusBadge tone={x.connected ? "success" : "warning"}>{x.label} · {x.connected ? "соединение установлено" : "ожидает подключения"}</StatusBadge></p>)}
{check.active && <Description>Проверка подтверждает соединения. Свежие показатели и состояние сервисов отображаются в «Модулях».</Description>}
{check.active && check.channels.length === 0 && <Description>Рабочие каналы ещё не установлены.</Description>}</>}
</SettingsCard>}
{section === "connections" && catalog && (enroll || adding) && <SettingsCard eyebrow="НОВОЕ ПОДКЛЮЧЕНИЕ" title={enroll ? "Выберите устройство" : "Добавить резервную сеть"}
description="Выберите VPN, общую сеть и компьютер. Устройства в сети могут быть воркерами, бортами или другими компьютерами.">
<div className="compute-contour-settings__form">
<FieldFrame label="Тип VPN"><Select label="Тип VPN" value={provider} disabled={busy}
options={[{value: "tailscale", label: "Tailscale"}, {value: "wireguard", label: "WireGuard"}]} onChange={setProvider}/></FieldFrame>
<FieldFrame label="Сеть"><Select label="Сеть" value={profileId} disabled={busy || !profiles.length}
options={profiles.map(x => ({value: x.id, label: x.name}))} onChange={setProfileId}/></FieldFrame>
<FieldFrame label="Устройство в сети"><Select label="Устройство в сети" value={peerId} disabled={busy || !peers.length}
options={[{value: "", label: "Выберите устройство"}, ...peers.map(x => ({value: x.id, label: x.name,
description: workerCandidate(catalog, profileId, x.id).enrolled ? "Уже подключён к Mission Core" : x.online === false ? "Не в сети" : "Доступен в VPN"}))]} onChange={setPeerId}/></FieldFrame>
</div>
{provider === "tailscale" && catalog.tailscale_client
&& <TailscaleClientStatus client={catalog.tailscale_client} disabled={busy} onOpened={refresh}/>}
{enroll && candidate.enrolled && <Description>Этот воркер уже подключён. Его сети можно изменить через настройки в разделе «Система».</Description>}
{enroll && candidate.peer && !candidate.enrolled && !candidate.binding && <Description>Устройство найдено в VPN, но доступ Mission Core к нему ещё не настроен. Сначала требуется подготовка агента и доступа на самом компьютере. Одного подключения к VPN недостаточно.</Description>}
{enroll && candidate.binding && <Description>Доступ к {candidate.binding.name} подготовлен. При добавлении проверим устройство и его ключ.</Description>}
{provider === "tailscale" && <Description>Сеть берётся из приложения Tailscale на этом Mac. Чтобы увидеть новый компьютер, подключите его к той же сети Tailscale.</Description>}
{provider === "wireguard" && <Description>Здесь перечислены серверы WireGuard, добавленные в Mission Core. Адрес в названии относится к серверу VPN, а не к воркеру.</Description>}
{provider === "wireguard" && !peers.length && <Description>Сервер не сообщает о зарегистрированных воркерах. Здесь показан его реестр устройств; поиск остальных компьютеров в туннеле не выполняется.</Description>}
{provider === "wireguard" && <ImportNetworkProfile disabled={busy} onImported={refresh}/>}
{!profiles.length && <Description>Доступных новых профилей этого типа нет.</Description>}
<Button variant="primary" disabled={busy || !profile || !peerId || candidate.peer?.online === false || (enroll && (!candidate.binding || Boolean(candidate.enrolled)))} onClick={() => void action(add)}>
{busy ? "Проверяем…" : "Проверить и добавить"}</Button>
</SettingsCard>}
{busy && <Description>Проверяем подключение…</Description>}
{error && <p role="alert"><StatusBadge tone="warning">{error}</StatusBadge></p>}
{discoveryError && <Description role="alert">{discoveryError}</Description>}
{catalog?.notice && catalog.notice !== catalog.tailscale_client?.message && <Description>{catalog.notice}</Description>}
</div>
</FeatureSettingsWindow>;
}
@@ -2,7 +2,8 @@ import { useCallback, useMemo, useState, type ReactNode } from "react";
import type { ApplicationPanelUtilityAction } from "@nodedc/ui-react";
import { useComputeContours } from "../../core/system/ComputeContourContext";
import { ComputeContourSettingsWindow } from "./ComputeContourSettingsWindow";
import { WorkerConnectionSettings } from "./WorkerConnectionSettings";
import { useWorkerPower } from "./useWorkerPower";
interface ComputeContourSettingsController {
canEdit: boolean;
@@ -14,6 +15,7 @@ interface ComputeContourSettingsController {
export function useComputeContourSettings(): ComputeContourSettingsController {
const contours = useComputeContours();
const power = useWorkerPower(contours.selectedContour);
const [open, setOpen] = useState(false);
const [mode, setMode] = useState<"create" | "edit">("edit");
const openCreate = useCallback(() => {
@@ -47,16 +49,16 @@ export function useComputeContourSettings(): ComputeContourSettingsController {
canEdit: contours.selectedContour !== null,
openCreate,
openEdit,
utilityActions,
utilityActions: [...utilityActions, power.action],
window: (
<ComputeContourSettingsWindow
<><WorkerConnectionSettings
open={open}
mode={mode}
contour={contours.selectedContour}
contour={mode === "create" ? null : contours.selectedContour}
onClose={() => setOpen(false)}
onCreate={contours.createContour}
onChanged={() => {contours.refresh(); contours.refreshTelemetry();}}
onUpdate={contours.updateContour}
/>
/>{power.window}</>
),
};
}
@@ -0,0 +1,42 @@
import {useState} from "react";
import {Button, ConfirmationModal, Window, WindowFooterActions, type ApplicationPanelUtilityAction} from "@nodedc/ui-react";
import {connectionRequest} from "../../core/system/workerConnections";
import type {ComputeContour} from "../../core/system/computeContours";
export function useWorkerPower(contour: ComputeContour | null) {
const [busy, setBusy] = useState(false);
const [pending, setPending] = useState<{id: string; name: string; confirmation: string} | null>(null);
const [message, setMessage] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const action: ApplicationPanelUtilityAction = {
label: "Выключить воркер", icon: "power", disabled: !contour || busy,
onClick: () => {if (!contour) return; setBusy(true); setError(null);
const selected = contour;
void connectionRequest<{confirmation: string}>(`/${selected.contour_id}/power/prepare`, {})
.then(value => setPending({id: selected.contour_id, name: selected.display_name, confirmation: value.confirmation}))
.catch(e => setMessage(e instanceof Error ? e.message : "Воркер недоступен."))
.finally(() => setBusy(false));
},
};
const window = <>
<ConfirmationModal open={pending !== null} title="Выключить воркер?" danger
confirmLabel="Да, выключить" pendingLabel="Передаём команду…" onClose={() => {if (!busy) setPending(null);}}
description={<><p>Воркер «{pending?.name}» завершит работу. Выполняемые на нём задачи будут прерваны. Для включения потребуется доступ к компьютеру.</p>
{error && <p role="alert">{error}</p>}</>}
onConfirm={async () => {
if (!pending || busy) return;
setBusy(true); setError(null);
try {
const result = await connectionRequest<{message: string}>(`/${pending.id}/power/shutdown`, {confirmation: pending.confirmation});
setPending(null); setMessage(result.message);
} catch (e) {
setPending(null); setMessage(e instanceof Error ? e.message : "Ответ не получен. Автоматического повтора нет.");
} finally {setBusy(false);}
}}/>
<Window open={message !== null} title="Питание воркера" size="sm" onClose={() => setMessage(null)}
footer={<WindowFooterActions><Button onClick={() => setMessage(null)}>Понятно</Button></WindowFooterActions>}>
<p role="status">{message}</p>
</Window>
</>;
return {action, window};
}
@@ -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
@@ -16,6 +16,10 @@
gap: 0.75rem;
}
.compute-contour-settings__connection-row {
align-items: end;
}
.compute-contour-settings__install,
.compute-contour-settings__network {
display: grid;
@@ -171,8 +171,8 @@ export function ComputeModulesWorkspace() {
<h3>{node?.node_id ?? selectedContour?.expected_node_id ?? "Node ID не назначен"}</h3>
<p>{node?.os.caption ?? "Аппаратный профиль недоступен"}</p>
</div>
<StatusBadge tone={node?.node_id ? "success" : "danger"}>
{node?.node_id ? selectedContour?.display_name : "Нет данных"}
<StatusBadge tone={connectionStatus.tone}>
{connectionStatus.state === "online" ? selectedContour?.display_name : connectionStatus.label}
</StatusBadge>
</header>
<div className="worker-hardware__facts">
@@ -1,4 +1,5 @@
import {workerConnectionStatus} from '../../core/system/workerConnectionStatus';
import {SharedNetworkProfiles} from '../../components/system/SharedNetworkProfiles';
import {
GlassSurface,
StatusBadge,
@@ -57,6 +58,7 @@ export function NetworkWorkspace() {
</section>
{connectionStatus.detail && <p role="status">{connectionStatus.detail}</p>}
<SharedNetworkProfiles/>
{error ? (
<GlassSurface className="system-workspace__notice" padding="md" tone="soft">
<StatusBadge tone="warning">{error}</StatusBadge>
@@ -92,7 +94,7 @@ export function NetworkWorkspace() {
</div>
<div className="network-stat-card">
<span>Активные интерфейсы</span>
<strong>{telemetry?.network.interfaces.length ?? "—"}</strong>
<strong>{telemetry?.network.interfaces.length || "—"}</strong>
<small>{agentTelemetry ? "Telegraf net input" : "Windows network counters"}</small>
</div>
</section>
@@ -114,7 +116,7 @@ export function NetworkWorkspace() {
<i aria-hidden="true" data-state="online" />
<div data-state={connected ? "online" : "unknown"}>
<span>Telemetry plane</span>
<strong>{agentTelemetry ? "Mosquitto + Timescale" : "SSH diagnostic"}</strong>
<strong>{agentTelemetry ? "MQTT · текущая телеметрия" : "SSH diagnostic"}</strong>
<small>
{agentTelemetry
? `${selectedContour?.mqtt_host ?? "—"}:${selectedContour?.mqtt_port ?? "—"}`