feat(core): persist viewer state and integrate Cesium services and profiles

This commit is contained in:
DCCONSTRUCTIONS
2026-11-17 17:20:15 +03:00
parent 9cbdd4ea5c
commit 29ef038a43
52 changed files with 2943 additions and 72 deletions
@@ -1,5 +1,6 @@
import { EnvironmentSettingsWindow as SharedEnvironmentSettingsWindow } from "@nodedc/ui-react";
import { environmentSurfaceIds, type EnvironmentSettings, type EnvironmentSurfaceId, type UploadedEnvironmentMedia } from "../core/environment/environmentSettings";
import { CesiumServiceSettings } from "./map/CesiumServiceSettings";
import { useLabStorageSettings } from "./storage/LabStorageSettings";
import { roots, workspaces, workspacesForRoot } from "../productModel";
@@ -18,7 +19,7 @@ const surfaces = environmentSurfaceIds.map(id => ({
}));
export function EnvironmentSettingsWindow(props: Props) {
const storage = useLabStorageSettings(props.open);
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet" additionalSections={[storage]}
return <SharedEnvironmentSettingsWindow {...props} productName="Mission Core" surfaces={surfaces} initialSurfaceId="fleet" additionalSections={[storage, {id: "services", label: "Сервисы", icon: "key", content: props.open ? <CesiumServiceSettings/> : null}]}
onSave={draft => props.onSave({ ...draft, pages: Object.fromEntries(environmentSurfaceIds.map(id => [id, draft.pages[id]])) as EnvironmentSettings["pages"] })}
onUpload={(id, itemId, file) => {
if (!environmentSurfaceIds.includes(id as EnvironmentSurfaceId)) throw new Error("Страница окружения недоступна.");
@@ -0,0 +1,89 @@
import {useEffect, useState} from "react";
import {Description, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField} from "@nodedc/ui-react";
import {cesiumServiceMessage, cesiumTokenIndicator, readCesiumService, saveCesiumService, verifyCesiumService,
type CesiumRouteMode, type CesiumServiceSettings as Settings, type CesiumVerification} from "../../core/map/cesiumService";
import "./cesiumServiceSettings.css";
import {serverRequest, type Server} from "../../core/system/servers";
export function CesiumServiceSettings() {
const [service, setService] = useState("");
const [pending, setPending] = useState<"verify" | "save" | "remove" | null>(null);
const [settings, setSettings] = useState<Settings | null>(null);
const [mode, setMode] = useState<CesiumRouteMode>("auto");
const [egress, setEgress] = useState("");
const [servers, setServers] = useState<Server[]>([]);
const [routesError, setRoutesError] = useState("");
const [token, setToken] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [checking, setChecking] = useState(false);
const [checkError, setCheckError] = useState("");
const [showVerification, setShowVerification] = useState(false);
const [verification, setVerification] = useState<CesiumVerification | null>(null);
useEffect(() => {
let active = true;
void readCesiumService().then(value => {if (active) {setSettings(value); setMode(value.mode); setEgress(value.egress_id || "");}})
.catch(reason => {if (active) setError(reason.message);});
void serverRequest<{items:Server[]}>("").then(value => {if(active) setServers(value.items);})
.catch(reason => {if(active) setRoutesError(reason.message);});
return () => {active = false;};
}, []);
useEffect(() => {
let active = true;
setVerification(null); setCheckError(""); setShowVerification(false);
if (service !== "cesium" || !settings?.token_configured || token.trim() || egress !== (settings.egress_id || "")) {setChecking(false); return;}
setChecking(true);
void verifyCesiumService().then(value => {if (active) setVerification(value);})
.catch(reason => {if (active) setCheckError(reason instanceof Error ? reason.message : cesiumServiceMessage());})
.finally(() => {if (active) setChecking(false);});
return () => {active = false;};
}, [service, settings?.revision, settings?.token_configured, token, egress]);
const indicator = cesiumTokenIndicator({configured: !!settings?.token_configured, draft: !!token.trim(),
checking: checking || pending === "verify" || pending === "save", error: error || checkError, verification});
async function action(kind: "verify" | "save" | "remove") {
if (!settings || busy) return;
setBusy(true); setPending(kind); setError(""); setCheckError(""); setVerification(null); setShowVerification(kind === "verify");
try {
if (kind === "verify") setVerification(await verifyCesiumService(token.trim() || undefined, egress));
else {
const result = await saveCesiumService({revision: settings.revision, mode, egress_id: egress,
...(kind === "remove" ? {remove_token: true} : token.trim() ? {token: token.trim()} : {})});
setSettings(result); setToken("");
}
} catch (reason) {setError(reason instanceof Error ? reason.message : cesiumServiceMessage());}
finally {setBusy(false); setPending(null);}
}
return <SettingsCard title="Сервисы" actions={service === "cesium" && <>
<IconButton label="Проверить доступ" disabled={busy || checking || !settings || (!token.trim() && !settings.token_configured)}
loading={pending === "verify"} onClick={() => void action("verify")}><Icon name="activity"/></IconButton>
<IconButton label="Сохранить" disabled={busy || !settings} loading={pending === "save"}
onClick={() => void action("save")}><Icon name="save"/></IconButton>
{settings?.token_configured && <IconButton label="Удалить токен" disabled={busy} loading={pending === "remove"}
onClick={() => void action("remove")}><Icon name="trash"/></IconButton>}
</>}>
<Select label="Выберите сервис" value={service} disabled={busy} onChange={setService}
options={[{value: "", label: "Выберите сервис"}, {value: "cesium", label: "Cesium ion",
icon: <StatusBadge variant="indicator" tone={indicator.tone} pulse={indicator.pulse} title={indicator.label} aria-label={indicator.label}/>} ]}/>
{service === "cesium" && <>
<Description>Общий доступ к спутниковым картам, рельефу и зданиям во всех разделах Mission Core.</Description>
{!settings && !error && <Description role="status">Получаем настройки…</Description>}
{settings && <>
<Select label="Подключение" value={mode} disabled={busy} onChange={value => setMode(value as CesiumRouteMode)}
options={[{value: "auto", label: "Автоматически"}, {value: "direct", label: "Напрямую к источнику"},
{value: "gateway", label: "Сервер хранения локальных данных"}]}/>
<Description>{mode === "auto" ? "Карты используют сервер хранения локальных данных. Если сервер недоступен, подключение переключается на источник через интернет." :
mode === "direct" ? "Карты загружаются через интернет без сохранения тайлов на этом компьютере." : "Карты загружаются только через сервер хранения локальных данных. Если сервер недоступен, загрузка приостанавливается."}</Description>
<Select label="Маршрутизация" value={egress} disabled={busy} onChange={value=>{setEgress(value);setVerification(null);setError("");}}
options={[{value:"",label:"Текущий маршрут"},...servers.flatMap(server=>server.services.filter(item=>item.kind==='egress').map(item=>({value:item.id,label:`${server.name} · ${server.address}`})))]}/>
{routesError&&<Description role="alert">{routesError}</Description>}
<TextField label={settings.token_configured ? "Новый токен Cesium ion" : "Токен Cesium ion"} type="password" value={token}
disabled={busy} autoComplete="off" spellCheck={false} onChange={event => {setToken(event.target.value); setVerification(null); setError("");}}
placeholder={settings.token_configured ? "Токен сохранён; заполните для замены" : "Токен"}/>
<Description>Токен сохраняется только в Mission Core. Для прямого подключения нужен доступ к рельефу, спутниковой карте и зданиям Cesium ion.</Description>
{showVerification && verification && <div className="cesium-service-results" role="status">{Object.entries(verification.assets).map(([id, result]) =>
<Description key={id}>{({"1": "Рельеф", "2": "Спутниковая карта", "96188": "Здания"} as Record<string, string>)[id] ?? id}: {result.ok ? "доступ подтверждён" : cesiumServiceMessage(result.code)}</Description>)}</div>}
</>}
{error && <Description role="alert">{error}</Description>}
</>}
</SettingsCard>;
}
@@ -652,6 +652,7 @@ function CacheHealth({
);
}
const { cache } = health.snapshot;
if (!cache) return <ControlRow label="Подключение"><StatusBadge tone="neutral">Источник · без кэша</StatusBadge></ControlRow>;
return (
<dl className="mission-map__cache-health">
<div>
@@ -0,0 +1 @@
.cesium-service-results { display: grid; gap: var(--nodedc-space-2); }
@@ -2,7 +2,7 @@ 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,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'|'vps-librespeed'}){
export function InstallerCard({kind,connectionInstruction}:{connectionInstruction?:string;kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'|'vps-librespeed'|'vps-egress'}){
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((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.':'Получение установщика…'}>
@@ -1,3 +1,4 @@
import {useObservationView} from '../../core/observation/useObservationView';
import {roverModelID} from '../../core/roverScene/model';
import {lazy,Suspense,useCallback,useEffect,useRef,useState} from 'react';
import {createPortal} from 'react-dom';
@@ -15,6 +16,9 @@ const labels:Record<string,string>={observing:'Наблюдение',preparing:'
export function RoverView({vehicleID,name,controller:c,header,active,observation}:{vehicleID:string;name:string;controller:RoverController;header:ObservationHeaderTargets;active:boolean;observation?:RoverObservationStatus}){
const storage=`missioncore.rover-view.v1:${vehicleID}`;
const [settings,setSettings]=useState(()=>{try{return roverSettings(JSON.parse(localStorage.getItem(storage)??'null'));}catch{return roverSettings(null);}});
const presentation=useObservationView('rover-view',vehicleID,()=>({schema:'missioncore.rover-view/v1' as const,model:''}),async()=>{
try{const raw=localStorage.getItem(storage);return raw?{schema:'missioncore.rover-view/v1' as const,model:roverSettings(JSON.parse(raw)).model}:null;}catch{return null;}
});
const [open,setOpen]=useState(false),[held,setHeld]=useState<Set<string>>(new Set());
const [editing,setEditing]=useState(false);
const [modelState,setModelState]=useState<'loading'|'ready'|'error'>('loading');
@@ -57,7 +61,7 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
onKeyDown={e=>{if(!c.ready&&(c.armed||c.pending||c.recovering)&&e.isTrusted&&['Space','Escape'].includes(e.code)){e.preventDefault();stop();}}}
onBlur={e=>{if(c.armed&&!e.currentTarget.contains(e.relatedTarget as Node|null))c.pauseInput();}}>
<EditorWorkspace editing={editing&&active} title={`Ровер / ${name}`} subtitle="Редактирование сцены" onBack={()=>setEditing(false)}>
{settings.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
{!presentation.ready?<LoadingRegion loading label="Загрузка настроек вида"/>:presentation.document.model===roverModelID?<LoadingRegion className="rover-view__scene" loading={modelState==='loading'||c.recovering} label={c.recovering?'Восстанавливаем связь':'Загрузка модели ровера'}>
<Suspense fallback={null}><Scene key={vehicleID} vehicleID={vehicleID} editing={editing&&active} onModelState={setModelState}/></Suspense>
{modelState==='error'&&<p className="rover-view__empty">Не удалось загрузить модель ровера.</p>}
</LoadingRegion>:<div className="rover-view__empty"><Description>Выберите модель аппарата.</Description><Button onClick={showSettings}>Настройки вида</Button></div>}
@@ -75,8 +79,9 @@ export function RoverView({vehicleID,name,controller:c,header,active,observation
</EditorWorkspace>
</div>
<Window open={open} onClose={()=>setOpen(false)} title="Управление ровером" size="md"><div className="rover-settings">
{presentation.error&&<><Description>{presentation.error}</Description><Button onClick={presentation.retry}>Повторить сохранение вида</Button></>}
<Select label="Тип управления" value={settings.mode} options={[{value:'arcade',label:'Аркадный · W A S D'},{value:'tank',label:'Танковый · Q A / E D'}]} onChange={mode=>setSettings(v=>({...v,mode:mode as RoverMode}))}/>
<Select label="3D-модель" value={settings.model} options={[{value:'',label:'Не выбрана'},{value:roverModelID,label:'DCD-006 · сборка v022'}]} onChange={model=>setSettings(v=>({...v,model}))}/>
<Select label="3D-модель" disabled={!presentation.ready} value={presentation.document.model} options={[{value:'',label:'Не выбрана'},{value:roverModelID,label:'DCD-006 · сборка v022'}]} onChange={model=>presentation.update(v=>({...v,model}))}/>
{duty?<TextField label="Газ, %" hint="1–100" description="Доля полного газа пульта. Фактическая скорость зависит от нагрузки." type="number" min={1} max={100} step={1} value={Number.isFinite(settings.throttlePercent)?settings.throttlePercent:''} onChange={e=>setSettings(v=>({...v,throttlePercent:roverNumberInput(e.target.value)}))}/>:
<TextField label="Скорость, ERPM" hint="300–3000" description="Электрические обороты двигателя. Скорость по земле требует параметров трансмиссии." type="number" min={300} max={3000} step={100} value={Number.isFinite(settings.maxErpm)?settings.maxErpm:''} onChange={e=>setSettings(v=>({...v,maxErpm:roverNumberInput(e.target.value)}))}/>}
<TextField label="Предел тока каждого мотора, А" description={currentDescription} type="number" min={.5} step={.5} value={Number.isFinite(settings.currentA)?settings.currentA:''} onChange={e=>setSettings(v=>({...v,currentA:roverNumberInput(e.target.value)}))}/>
@@ -5,10 +5,10 @@ import {serverRequest,useServers,type Server} from '../../core/system/servers';
import {vpsRequest} from '../../core/fleet/vps';
export function ServerServiceSetup({server:initialServer,fixedKind,onClose,onSaved}:{server?:Server;fixedKind?:'librespeed';onClose:()=>void;onSaved:()=>void}) {
const [kind,setKind]=useState<'wireguard'|'arnavi'|'librespeed'>(fixedKind??'wireguard'),[document,setDocument]=useState(''),[filename,setFilename]=useState('');
const [kind,setKind]=useState<'wireguard'|'arnavi'|'librespeed'|'egress'>(fixedKind??'wireguard'),[document,setDocument]=useState(''),[filename,setFilename]=useState('');
const catalog=useServers();const [serverId,setServerId]=useState(initialServer?.id??'');
const server=initialServer??catalog.items?.find(s=>s.id===serverId);
const serviceName=kind==='librespeed'?'LibreSpeed':'WireGuard';
const serviceName=kind==='egress'?'Маршрутизация трафика':kind==='librespeed'?'LibreSpeed':'WireGuard';
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;};},[]);
@@ -22,14 +22,14 @@ export function ServerServiceSetup({server:initialServer,fixedKind,onClose,onSav
{!initialServer&&<Select label="VPS" value={serverId} disabled={busy} options={[{value:'',label:'Выберите VPS'},...(catalog.items??[]).map(s=>({value:s.id,label:`${s.name} · ${s.address}`}))]} onChange={id=>{setServerId(id);setDocument('');setFilename('');}}/>}
{!initialServer&&catalog.items?.length===0&&<Description>Сначала добавьте VPS в разделе «Система → VPS».</Description>}
{catalog.error&&!initialServer&&<Description>{catalog.error}</Description>}
<Select label="Служба" value={kind} disabled={busy||!!fixedKind} options={[{value:'wireguard',label:'WireGuard'},{value:'arnavi',label:'ARNavi'},{value:'librespeed',label:'LibreSpeed'}]} onChange={value=>{setKind(value as typeof kind);setDocument('');setFilename('');setError('');}}/>
<InstallerCard key={kind} connectionInstruction={kind==='librespeed'?undefined:"Вернитесь в это окно и подключите установленную службу с выданным приглашением."} kind={kind==='librespeed'?'vps-librespeed':kind==='wireguard'?'vps-wireguard':'vps-arnavi'}/>
<Select label="Служба" value={kind} disabled={busy||!!fixedKind} options={[{value:'wireguard',label:'WireGuard'},{value:'arnavi',label:'ARNavi'},{value:'librespeed',label:'LibreSpeed'},{value:'egress',label:'Маршрутизация трафика'}]} onChange={value=>{setKind(value as typeof kind);setDocument('');setFilename('');setError('');}}/>
<InstallerCard key={kind} connectionInstruction={kind==='librespeed'?undefined:"Вернитесь в это окно и подключите установленную службу с выданным приглашением."} kind={kind==='egress'?'vps-egress':kind==='librespeed'?'vps-librespeed':kind==='wireguard'?'vps-wireguard':'vps-arnavi'}/>
<SettingsCard title="Подключение установленной службы" description="Запустите установщик на выбранном VPS. Затем передайте выданное им приглашение — Mission Core проверит сервер и сохранит подключение.">
{kind!=='arnavi'?<>
<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(`Выберите файл приглашения ${serviceName} (до 16 КБ).`);setDocument(await chosen.text());setFilename(chosen.name);})().catch(e=>setError(e.message));}}/>
<Button icon={<Icon name="upload"/>} disabled={busy} onClick={()=>file.current?.click()}>Выбрать приглашение {serviceName}</Button>
{filename&&<Description>{filename}</Description>}
<Description>Файл на VPS: {kind==='librespeed'?'/var/lib/ndc-librespeed-vps/mission-core-librespeed.json':'/var/lib/ndc-wireguard-vps/mission-core-wireguard.json'}. Скопируйте его по защищённому соединению (например, SFTP). Приглашение действует 24 часа; новое выпускается командой connection того же установщика. {kind==='wireguard'?'Экспорт .conf из клиента WireGuard не подходит.':''}</Description>
<Description>Файл на VPS: {kind==='egress'?'/var/lib/ndc-egress-vps/mission-core-egress.json':kind==='librespeed'?'/var/lib/ndc-librespeed-vps/mission-core-librespeed.json':'/var/lib/ndc-wireguard-vps/mission-core-wireguard.json'}. Скопируйте его по защищённому соединению (например, SFTP). Приглашение действует 24 часа; новое выпускается командой connection того же установщика. {kind==='wireguard'?'Экспорт .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}/>}
@@ -0,0 +1,63 @@
export type CesiumRouteMode = "auto" | "direct" | "gateway";
export interface CesiumServiceSettings {
revision: number;
egress_id: string;
mode: CesiumRouteMode;
token_configured: boolean;
gateway_configured: boolean;
gateway_available: boolean | null;
active_route: "unknown" | "gateway" | "direct" | "unavailable";
}
export interface CesiumVerification { ok: boolean; assets: Record<string, {ok: boolean; code?: string}> }
const endpoint = "/api/v1/map/services/cesium-ion";
export const cesiumServiceChanged = "missioncore:cesium-service-changed";
const messages: Record<string, string> = {
cesium_egress_region_denied: "Источник карт блокирует страну исходящего IP выбранного VPS. Выберите другой маршрут.",
cesium_egress_invalid: "Выберите подключённую службу маршрутизации.",
cesium_egress_unavailable: "Служба маршрутизации недоступна. Проверьте подключение VPS.",
cesium_egress_gateway_not_ready: "Сервер хранения локальных данных ещё не подключён к выбранному маршруту. Настройки не изменены.",
cesium_token_required: "Добавьте токен Cesium ion для подключения к источнику.",
cesium_token_invalid: "Проверьте токен: он не должен содержать пробелы.",
cesium_provider_unauthorized: "Cesium ion отклонил токен. Проверьте срок действия, доступ к ресурсам и ограничения адресов.",
cesium_provider_unavailable: "Источник Cesium недоступен. Проверьте интернет и повторите попытку.",
cesium_provider_rate_limited: "Источник временно ограничил запросы. Повторите проверку позже.",
cesium_provider_contract_mismatch: "Источник вернул неподдерживаемый тип карты. Настройки не изменены.",
cesium_provider_invalid_response: "Не удалось прочитать ответ источника. Настройки не изменены.",
cesium_settings_conflict: "Настройки уже изменены в другом окне. Откройте этот раздел заново.",
cesium_settings_unreadable: "Не удалось прочитать сохранённые настройки сервиса.",
cesium_settings_unwritable: "Не удалось сохранить настройки сервиса. Проверьте доступ и свободное место.",
map_gateway_unavailable: "Сервер хранения локальных данных недоступен. Выберите автоматическое подключение или подключение к источнику.",
};
export function cesiumServiceMessage(code?: string) { return messages[code ?? ""] ?? "Не удалось выполнить запрос к сервису карт. Повторите попытку."; }
export function cesiumTokenIndicator(value: {configured: boolean; draft: boolean; checking: boolean; error: string; verification: CesiumVerification | null}) {
if (value.checking) return {tone: "warning" as const, pulse: true, label: "Проверка доступа Cesium ion"};
if (value.error) return {tone: "warning" as const, pulse: false, label: value.error};
if (value.verification?.ok) return {tone: "success" as const, pulse: false, label: "Cesium ion: доступ подтверждён"};
if (value.verification) {
const failed = Object.values(value.verification.assets).find(asset => !asset.ok);
return {tone: "warning" as const, pulse: false, label: cesiumServiceMessage(failed?.code)};
}
return {tone: "neutral" as const, pulse: false, label: value.draft ? "Новый токен ещё не проверен" :
value.configured ? "Токен сохранён; доступ ещё не проверен" : "Токен не задан"};
}
async function request<T>(path: string, method = "GET", body?: object): Promise<T> {
try {
const response = await fetch(endpoint + path, {method, credentials: "same-origin", cache: "no-store",
headers: {Accept: "application/json", ...(body ? {"Content-Type": "application/json"} : {})},
body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(30_000)});
const value = await response.json().catch(() => null);
if (!response.ok) throw new Error(cesiumServiceMessage(value?.code));
if (!value || typeof value !== "object") throw new Error(cesiumServiceMessage());
return value as T;
} catch (error) {
if (error instanceof Error && error.name === "Error") throw error;
throw new Error("Сервис карт не ответил. Проверьте соединение и повторите попытку.");
}
}
export const readCesiumService = () => request<CesiumServiceSettings>("");
export const verifyCesiumService = (token?: string, egress_id?: string) => request<CesiumVerification>("/verify", "POST", {...(token ? {token} : {}), ...(egress_id !== undefined ? {egress_id} : {})});
export async function saveCesiumService(value: {revision: number; mode: CesiumRouteMode; egress_id?: string; token?: string; remove_token?: boolean}) {
const result = await request<CesiumServiceSettings>("", "PUT", value);
window.dispatchEvent(new Event(cesiumServiceChanged));
return result;
}
@@ -11,7 +11,7 @@ export interface MapGatewayHealthSnapshot {
maxBytes: number | null;
atCapacity: boolean;
persistent: boolean;
};
} | null;
}
export interface MapGatewayHealth {
@@ -85,8 +85,11 @@ export function useMapGatewayHealth(active: boolean): MapGatewayHealth {
return health;
}
function decodeHealth(value: unknown): MapGatewayHealthSnapshot {
export function decodeHealth(value: unknown): MapGatewayHealthSnapshot {
const document = record(value, "gateway health");
if (document.ok === true && document.service === "missioncore-map-direct" && document.route === "direct") {
return {ionConfigured: true, assetAllowlist: [1, 2, 96188], cache: null};
}
if (document.ok !== true || document.service !== "nodedc-map-gateway") {
throw new Error("map_gateway_invalid_response");
}
@@ -1,8 +1,14 @@
import {useEffect,useRef} from 'react';
import {cesiumServiceChanged} from './cesiumService';
/** Recover the existing renderer only after its own gateway is reachable again. */
/** Recover the existing renderer after either admitted route becomes available. */
export function useMapRecovery(unavailable:boolean,retry:()=>void){
const callback=useRef(retry);callback.current=retry;
useEffect(()=>{
const changed=()=>callback.current();
window.addEventListener(cesiumServiceChanged,changed);
return()=>window.removeEventListener(cesiumServiceChanged,changed);
},[]);
useEffect(()=>{
if(!unavailable)return;
let active=true;let timer:ReturnType<typeof setTimeout>;
@@ -12,7 +18,7 @@ export function useMapRecovery(unavailable:boolean,retry:()=>void){
const response=await fetch('/api/v1/map/gateway/health',{credentials:'same-origin',cache:'no-store',signal:AbortSignal.any([abort.signal,AbortSignal.timeout(10000)])});
const value=response.ok?await response.json():null;
if(active&&value?.ok===true){callback.current();return;}
}catch{/* Retain the unavailable state; no public-provider fallback. */}
}catch{/* The server owns route selection; retry only when reachable. */}
if(active)timer=setTimeout(()=>void check(),30000);
}
timer=setTimeout(()=>void check(),30000);
@@ -0,0 +1,24 @@
import {useEffect,useRef,useState} from 'react';
import {observationViewProfile} from './viewProfile';
/** Operator presentation only. Never stores or restores control/arming state. */
export function useObservationView<T>(kind:'observation-map'|'rover-view',owner:string,defaults:()=>T,legacy:()=>Promise<T|null>){
const [document,setDocument]=useState(defaults),[ready,setReady]=useState(false),[error,setError]=useState(''),[reload,setReload]=useState(0);
const state=useRef({client:observationViewProfile<T>(kind,owner),document,ready:false,active:false,dirty:false});
useEffect(()=>{
const current={client:observationViewProfile<T>(kind,owner),document:defaults(),ready:false,active:true,dirty:false};state.current=current;setReady(false);setError('');
void current.client.read(legacy).then(value=>{if(!current.active)return;current.document=value??defaults();current.ready=true;setDocument(current.document);setReady(true);}).catch(cause=>{if(current.active)setError(cause instanceof Error?cause.message:'Не удалось прочитать настройки вида.');});
return()=>{current.active=false;};
},[kind,owner,reload]);
const save=()=>{
const current=state.current;if(!current.ready||!current.dirty)return;
const value=current.document;
void current.client.write(value).then(()=>{if(current.document===value)current.dirty=false;if(current.active)setError('');}).catch(cause=>{if(current.active)setError(cause instanceof Error?cause.message:'Не удалось сохранить настройки вида.');});
};
const update=(change:(value:T)=>T)=>{
const current=state.current;if(!current.ready)return;
const next=change(current.document);if(JSON.stringify(next)===JSON.stringify(current.document))return;
current.document=next;current.dirty=true;setDocument(next);save();
};
return {document,ready,error,update,retry:()=>{if(state.current.ready)save();else setReload(v=>v+1);}};
}
@@ -0,0 +1,14 @@
import {profileClient,type ProfileKind} from '../roverScene/profileClient';
// A newly mounted view must read after the previous view's acknowledged writes.
const pending=new Map<string,Promise<unknown>>();
export function observationViewProfile<T>(kind:ProfileKind,owner:string){
const key=JSON.stringify([kind,owner]),client=profileClient<T>(kind,owner);
function serial<R>(action:()=>Promise<R>):Promise<R>{
const next=(pending.get(key)??Promise.resolve()).catch(()=>{}).then(action);
pending.set(key,next);
void next.finally(()=>{if(pending.get(key)===next)pending.delete(key);}).catch(()=>{});
return next;
}
return {read:(legacy?:()=>Promise<T|null>)=>serial(()=>client.read(legacy)),write:(value:T)=>serial(()=>client.write(value))};
}
@@ -1,5 +1,5 @@
/** Durable JSON authority. A legacy browser record is only a one-time migration input. */
export type ProfileKind='battery'|'rover'|'battery-ui'|'battery-view'|'environments';
export type ProfileKind='battery'|'rover'|'battery-ui'|'battery-view'|'environments'|'observation-map'|'rover-view';
type Stored<T>={revision:number;document:T|null};
export function profileClient<T>(kind:ProfileKind,owner:string){
let revision:number|undefined;
@@ -2,7 +2,7 @@ import {useCallback, useEffect, useState} from 'react';
import type {VPSHost} from '../fleet/vps';
import {startSequentialPolling} from './sequentialPolling';
export type ServerService = {kind:'arnavi'|'wireguard'|'librespeed';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 ServerService = {kind:'arnavi'|'wireguard'|'librespeed'|'egress';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> {
@@ -1,5 +1,6 @@
import {useObservationView} from '../../../core/observation/useObservationView';
import {useEffect,useMemo,useRef,useState} from 'react';
import {CesiumMapRenderer,initialMapRuntimeState,type CesiumMapRendererHandle,type MapCamera,type MapGhostPinLayer} from '@nodedc/map-cesium-react';
import {CesiumMapRenderer,initialMapRuntimeState,type CesiumMapRendererHandle,type MapCamera,type MapLayerVisibility,type MapGhostPinLayer} from '@nodedc/map-cesium-react';
import { Description,Button,Icon,IconButton,Switch,Window} from '@nodedc/ui-react';
import {ObservationHeader} from '../../../../../../packages/sensor-ui/src/ObservationHeader';
import type {ObservationHeaderTargets} from '../../../../../../packages/sensor-ui/src/observation';
@@ -11,26 +12,30 @@ import {mapPresentation} from '../../../components/map/mapPresentation';
export function ObservationMap({vehicleID,header}:{vehicleID:string;header:ObservationHeaderTargets}){
const defaults=useMemo(()=>defaultMapViewDocument().view,[]),renderer=useRef<CesiumMapRendererHandle>(null);
const [settings,setSettings]=useState(false),[state,setState]=useState(initialMapRuntimeState),[generation,setGeneration]=useState(0);
const storageKey=`missioncore.observation-map.v1:${vehicleID}`;
const [camera,setCamera]=useState(()=>{try{const value=JSON.parse(localStorage.getItem(storageKey)??'null') as MapCamera|null;return value&&['longitude','latitude','height','heading','pitch','roll'].every(key=>Number.isFinite(value[key as keyof MapCamera]))?value:defaults.camera;}catch{return defaults.camera;}});
const [layers,setLayers]=useState({...defaults.layerVisibility,grid:false,targets:true});
const telemetry=useTrackerTelemetry(vehicleID),centered=useRef(false);
const view=useObservationView('observation-map',vehicleID,()=>({schema:'missioncore.observation-map/v1' as const,camera:null as MapCamera|null,layers:{...defaults.layerVisibility,grid:false,targets:true} as MapLayerVisibility}),async()=>{
try{const camera=JSON.parse(localStorage.getItem(`missioncore.observation-map.v1:${vehicleID}`)??'null') as MapCamera|null;
return camera&&['longitude','latitude','height','heading','pitch','roll'].every(key=>Number.isFinite(camera[key as keyof MapCamera]))?{schema:'missioncore.observation-map/v1' as const,camera,layers:{...defaults.layerVisibility,grid:false,targets:true}}:null;
}catch{return null;}
});
const {camera,layers}=view.document;
const telemetry=useTrackerTelemetry(vehicleID);
const pins=telemetry.items.flatMap(item=>item.position?[{id:item.instance_id,label:`${item.name} · ${item.position_fresh&&!telemetry.unavailable?item.position.source.toUpperCase():new Date(item.position.measured_at*1000).toLocaleTimeString('ru-RU')}`,longitude:item.position.longitude,latitude:item.position.latitude,heading_degrees:item.position.course,speed_meters_per_second:0}]:[]);
const presentation=useMemo(()=>(encodeMapViewPut(defaultMapViewDocument()) as {view:{ghost_pins:MapGhostPinLayer}}).view.ghost_pins.presentation,[]);
const markers:MapGhostPinLayer={anchor:null,radius_meters:0,simulation_enabled:false,pins,presentation:{...presentation,stem_height_meters:20,head_size_px:12,label_mode:'attributes',label_max_length:80}};
function center(){const pin=pins[0];if(pin){setCamera({longitude:pin.longitude,latitude:pin.latitude,height:1200,heading:0,pitch:-90,roll:0});setGeneration(v=>v+1);}}
useEffect(()=>{if(pins.length&&!centered.current){centered.current=true;center();}},[pins.length]);
function center(){const pin=pins[0];if(pin){view.update(value=>({...value,camera:{longitude:pin.longitude,latitude:pin.latitude,height:1200,heading:0,pitch:-90,roll:0}}));setGeneration(v=>v+1);}}
useEffect(()=>{if(view.ready&&pins.length&&!camera)center();},[view.ready,pins.length,camera]);
const latest=telemetry.items.find(item=>item.position);
const positionLabel=telemetry.unavailable?'Обновление координат недоступно':latest?.position?`${latest.position.latitude.toFixed(6)}, ${latest.position.longitude.toFixed(6)} · ${latest.position.source.toUpperCase()} · ${latest.position.satellites??'—'} спутников · ${new Date(latest.position.measured_at*1000).toLocaleTimeString('ru-RU')}`:'Ожидание координат трекера';
const available=state.phase==='ready'||Object.values(state.providers).some(provider=>provider.phase==='ready');
const unavailable=!available&&state.phase!=='loading';
useMapRecovery(unavailable,()=>setGeneration(v=>v+1));
return <div className="observation-source">
<ObservationHeader targets={header} live={!telemetry.unavailable&&telemetry.items.some(item=>item.online&&item.position_fresh)} label={positionLabel}><IconButton label="Показать аппарат на карте" disabled={!pins.length} onClick={center}><Icon name="globe"/></IconButton><IconButton label="Слои карты" onClick={()=>setSettings(true)}><Icon name="layers"/></IconButton></ObservationHeader>
<div className="observation-source__media observation-map" data-available={available}><CesiumMapRenderer key={generation} ref={renderer} runtimeConfigUrl="/api/v1/map/runtime-config" camera={camera} ghostPins={markers} layers={layers} settings={mapPresentation(defaults.visualSettings)} cacheIntent={{enabled:true,no_overwrite:true}} onRuntimeStateChange={setState} onCameraChange={value=>{try{localStorage.setItem(storageKey,JSON.stringify(value));}catch{/* Browser storage may be unavailable. */}}}/></div>
{unavailable&&<div className="observation-source__notice"><Description>Картографические слои недоступны. Проверяем связь с сервером карты.</Description><Description>{positionLabel}</Description><Button onClick={()=>setGeneration(v=>v+1)}>Повторить загрузку карты</Button></div>}
<ObservationHeader targets={header} live={!telemetry.unavailable&&telemetry.items.some(item=>item.online&&item.position_fresh)} label={positionLabel}><IconButton label="Показать аппарат на карте" disabled={!view.ready||!pins.length} onClick={center}><Icon name="globe"/></IconButton><IconButton label="Слои карты" onClick={()=>setSettings(true)}><Icon name="layers"/></IconButton></ObservationHeader>
<div className="observation-source__media observation-map" data-available={available}>{view.ready&&<CesiumMapRenderer key={generation} ref={renderer} runtimeConfigUrl="/api/v1/map/runtime-config" camera={camera??defaults.camera} ghostPins={markers} layers={layers} settings={mapPresentation(defaults.visualSettings)} cacheIntent={{enabled:true,no_overwrite:true}} onRuntimeStateChange={setState} onCameraChange={camera=>view.update(value=>({...value,camera}))}/> }</div>
{view.ready&&unavailable&&<div className="observation-source__notice"><Description>Картографические слои недоступны. Проверяем связь с сервером карты.</Description><Description>{positionLabel}</Description><Button onClick={()=>setGeneration(v=>v+1)}>Повторить загрузку карты</Button></div>}
{view.error&&<div className="observation-source__notice"><Description>{view.error}</Description><Button onClick={view.retry}>Повторить сохранение вида</Button></div>}
<Window open={settings} onClose={()=>setSettings(false)} title="Слои карты" size="sm">
<div className="observation-settings">{([{id:'imagery',name:'Спутниковые снимки'},{id:'terrain',name:'Рельеф'},{id:'buildings',name:'Здания OSM'}] as const).map(item=><Switch key={item.id} label={item.name} checked={layers[item.id]} onChange={value=>setLayers(current=>({...current,[item.id]:value}))}/>)}
<div className="observation-settings">{([{id:'imagery',name:'Спутниковые снимки'},{id:'terrain',name:'Рельеф'},{id:'buildings',name:'Здания OSM'}] as const).map(item=><Switch key={item.id} label={item.name} checked={layers[item.id]} disabled={!view.ready} onChange={value=>view.update(current=>({...current,layers:{...current.layers,[item.id]:value}}))}/>)}
</div>
</Window>
</div>;
@@ -56,6 +56,7 @@ export function ServersWorkspace({headerToolsHost}:{headerToolsHost?:HTMLElement
<Description>Подключено бортов: {'boards' in inspecting.details?inspecting.details.boards:0}</Description>
</SettingsCard>
</Window>}
{inspecting?.kind==='egress'&&<Window open title="Маршрутизация трафика" subtitle={inspecting.endpoint} size="md" onClose={()=>setInspecting(null)}><SettingsCard title="Подключение к источникам"><StatusBadge tone={liveState?.tone??'neutral'}>{liveState?.label??'Связь не проверена'}</StatusBadge><Description>Выберите этот VPS в настройках нужного сервиса. Доступность службы и доступность внешнего источника проверяются отдельно.</Description></SettingsCard></Window>}
{inspecting?.kind==='librespeed'&&<Window open title="LibreSpeed" subtitle={inspecting.endpoint} size="md" onClose={()=>setInspecting(null)}><SettingsCard title="Замер скорости" description="Служба для проверки соединения борта через роутер."><StatusBadge tone={liveState?.tone??'neutral'}>{liveState?.label??'Связь не проверена'}</StatusBadge><Description>Запускайте замер из вкладки «Замер скорости» в окне роутера. Одновременно выполняется один замер; результаты не сохраняются на VPS.</Description></SettingsCard></Window>}
{store.error&&<SettingsCard title="Не удалось получить VPS" description={store.error}/>}
</>;