feat(core): persist viewer state and integrate Cesium services and profiles
This commit is contained in:
@@ -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> {
|
||||
|
||||
Reference in New Issue
Block a user