Compare commits

...
Author SHA1 Message Date
DCCONSTRUCTIONS bd8af772d9 Update BIM viewer with cursor-anchored navigation 2026-11-17 22:34:38 +03:00
DCCONSTRUCTIONS e26582fc75 feat(bim): ship unified scene settings and independent photo window layout 2026-11-17 21:53:01 +03:00
DCCONSTRUCTIONS e9527060f6 fix(bim): ship visible spatial note markers 2026-11-17 19:50:53 +03:00
DCCONSTRUCTIONS 56d89197a8 feat(bim): ship surface notes, photo galleries and favorites 2026-11-17 18:34:36 +03:00
DCCONSTRUCTIONS 29ef038a43 feat(core): persist viewer state and integrate Cesium services and profiles 2026-11-17 17:20:15 +03:00
DCCONSTRUCTIONS 9cbdd4ea5c fix(ui): consume shared borderless drag-handle focus 2026-11-17 02:06:23 +03:00
DCCONSTRUCTIONS b1533ce0ea fix(bim): retain Cesium inspector geometry and outline lock states 2026-11-17 01:45:33 +03:00
DCCONSTRUCTIONS f4b506d593 Integrate Cesium scan locks and persistent row ordering 2026-11-17 00:48:28 +03:00
DCCONSTRUCTIONS a3781bcf4b Pin Cesium import recovery and map editor corrections 2026-11-17 00:07:00 +03:00
DCCONSTRUCTIONS a3927ce846 Pin portable Cesium Gaussian inspector release 2026-11-16 22:52:25 +03:00
DCCONSTRUCTIONS 0a29522f2f Integrate Cesium Gaussian lifecycle and source-based cleanup rebuilds 2026-11-16 22:16:12 +03:00
DCCONSTRUCTIONS 7c0dbd4e06 Make simulation imports background tasks with Worker-owned sources and durable deletion 2026-11-16 18:13:27 +03:00
DCCONSTRUCTIONS 9871ae500f Upgrade Cesium runtime with versioned assets and verified cache-safe rollback 2026-11-16 16:18:59 +03:00
DCCONSTRUCTIONS a80e3a8ff5 Connect architectural project maps to the existing Cesium gateway 2026-11-16 15:24:11 +03:00
DCCONSTRUCTIONS a5e4fba807 Integrate compact BIM inspector, measurement editing and shared tooltips 2026-11-16 14:34:19 +03:00
DCCONSTRUCTIONS 996ce7efdf Update portable BIM viewer for concurrent flight and orbit 2026-11-16 00:47:22 +03:00
DCCONSTRUCTIONS 0f97f79216 Integrate layer notes, project views and resilient BIM uploads 2026-11-16 00:40:03 +03:00
DCCONSTRUCTIONS 8aeb5b3fd2 docs(ui): record shared collapsible navigation acceptance 2026-11-15 22:50:56 +03:00
DCCONSTRUCTIONS 958e9c396d fix(bim): record qualified legacy LAS worker correction 2026-11-15 22:20:30 +03:00
DCCONSTRUCTIONS 778a558a34 feat(bim): integrate version notes and verified photo intake fixes 2026-11-15 22:07:36 +03:00
118 changed files with 4741 additions and 232 deletions
+11 -10
View File
@@ -10,7 +10,7 @@
"hasInstallScript": true,
"dependencies": {
"@noble/hashes": "^2.2.0",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.22.tgz",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.86.tgz",
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
@@ -42,9 +42,9 @@
},
"../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react": {
"name": "@nodedc/map-cesium-react",
"version": "0.1.0",
"version": "0.1.4",
"dependencies": {
"cesium": "1.143.0"
"cesium": "1.147.0"
},
"devDependencies": {
"@types/react": "^19.1.0",
@@ -64,19 +64,19 @@
},
"../../../NODEDC_DESIGN_GUIDELINE/packages/ui-core": {
"name": "@nodedc/ui-core",
"version": "0.7.0",
"version": "0.7.4",
"dependencies": {
"@nodedc/tokens": "0.6.0"
}
},
"../../../NODEDC_DESIGN_GUIDELINE/packages/ui-react": {
"name": "@nodedc/ui-react",
"version": "0.7.0",
"version": "0.7.10",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@nodedc/ui-core": "0.7.0",
"@nodedc/ui-core": "0.7.4",
"lucide-react": "^0.468.0"
},
"devDependencies": {
@@ -884,11 +884,12 @@
}
},
"node_modules/@nodedc/bim-viewer": {
"version": "0.2.22",
"resolved": "file:../../vendor/bim/nodedc-bim-viewer-0.2.22.tgz",
"integrity": "sha512-Nl2PffhxaiSAdFZpHR5O2oYqxih/csC3fvIUl7EDnWWlDG7j1xKHtLo65suM9EaeAjx1GMUQsjTmF/I7VeI6Ow==",
"version": "0.2.86",
"resolved": "file:../../vendor/bim/nodedc-bim-viewer-0.2.86.tgz",
"integrity": "sha512-1yaWhAbEx3Y1V93b+T1HKfra7Z6hGpFL/Fhz/S6Bi+AzFMEJsQ4TpE32uVIARxN6EWJtAx3QuBlmaD8TP499IQ==",
"peerDependencies": {
"@nodedc/ui-react": "0.7.0",
"@nodedc/map-cesium-react": ">=0.1.4 <0.2",
"@nodedc/ui-react": ">=0.7.10 <0.8",
"react": ">=19 <20",
"react-dom": ">=19 <20"
}
+1 -1
View File
@@ -15,7 +15,7 @@
},
"dependencies": {
"@noble/hashes": "^2.2.0",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.22.tgz",
"@nodedc/bim-viewer": "file:../../vendor/bim/nodedc-bim-viewer-0.2.86.tgz",
"@nodedc/map-cesium-react": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/map-cesium-react",
"@nodedc/page-patterns": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/page-patterns",
"@nodedc/tokens": "file:../../../NODEDC_DESIGN_GUIDELINE/packages/tokens",
@@ -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)}))}/>
@@ -1,14 +1,21 @@
import { useState } from "react";
import { useInfrastructureQueue } from "../../core/simulation/infrastructureAnalysis";
import { Description, Button, ConfirmationModal, Icon, IconButton, ResourceList, ResourceRow,
StatusBadge, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
StatusBadge, ProgressBar, TextField, ToastStack, Window, WindowFooterActions } from "@nodedc/ui-react";
import { updateAiWorld, type AiWorld } from "../../core/simulation/aiPolygon";
import {useLocationImports} from "../../core/simulation/locationImports";
import {deleteLocation,useLocationDeletions} from "../../core/simulation/locationDeletions";
import {SimulationOriginalDownload} from "./SimulationOriginalDownload";
export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused, onOpen, onPlan, canPlan, onChanged}: {
worlds: AiWorld[]; removedWorlds: AiWorld[]; activeWorldId?: string; paused: boolean;
onOpen: (world: AiWorld) => void; onPlan: (world: AiWorld) => void; canPlan: boolean; onChanged: () => Promise<void>;
}) {
const queue=useInfrastructureQueue();
const deletions=useLocationDeletions(onChanged);
const imports=useLocationImports();
const uploadingWorlds=new Set(imports.map(task=>task.project?.projectId.replace("sim-","aiworld-")));
const [editing, setEditing] = useState<AiWorld | null>(null);
const [name, setName] = useState("");
const [confirming, setConfirming] = useState(false);
@@ -27,16 +34,17 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
} finally { setBusy(null); }
};
return <>
<ResourceList>{worlds.map(world => {const queued=queue.jobs.find(j=>j.world_id===world.world_id);return <li key={world.world_id}>
<ResourceList>{worlds.filter(world=>!uploadingWorlds.has(world.world_id)).map(world => {const queued=queue.jobs.find(j=>j.world_id===world.world_id);const deletion=deletions.find(d=>d.project_id===world.local_scene?.project_id);return <li key={world.world_id}>
<ResourceRow title={world.name} icon={<Icon name="globe"/>}
status={activeWorldId === world.world_id ? <StatusBadge tone="neutral">
{paused ? "На паузе" : "Сцена открыта"}</StatusBadge> : queued ? <StatusBadge tone={queue.unavailable?"neutral":"warning"}>
{queue.unavailable?"Нет обновлений очереди":queued.cancel_requested?"Отмена расчёта":queued.status==="queued"?`В очереди · №${queued.queue?.position??"—"}`:queued.status==="running"?"Расчёт инфраструктуры":"Освобождение Worker"}</StatusBadge> : undefined}
actions={<>
actions={deletion?<div className="simulation-imports__progress" role="status"><ProgressBar label="Удаление локации"/><Description>{deletion.error??"Удаление локации"}</Description></div>:<>
<IconButton label={world.status === "uploading" ? `Продолжить импорт ${world.name}` : `Открыть ${world.name}`}
onClick={() => onOpen(world)}><Icon name={world.status === "uploading" ? "upload" : "eye"}/></IconButton>
{canPlan&&world.status!=="uploading"&&world.settings.prepared?<IconButton label={`Подготовить маршрут · ${world.name}`}
onClick={() => onPlan(world)}><Icon name="plan"/></IconButton>:null}
{world.status!=="uploading"?<SimulationOriginalDownload worldId={world.world_id} name={world.name}/>:null}
<IconButton label={`Настройки ${world.name}`} onClick={() => {
setEditing(world); setName(world.name); setConfirming(false); setError(null);
}}><Icon name="settings"/></IconButton>
@@ -44,7 +52,7 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
</li>;})}</ResourceList>
{removedWorlds.length ? <>
<Button aria-expanded={showRemoved} onClick={() => setShowRemoved(!showRemoved)}>
Удалённые локации · {removedWorlds.length}</Button>
Скрытые локации · {removedWorlds.length}</Button>
{showRemoved ? <ResourceList>{removedWorlds.map(world => <li key={world.world_id}>
<ResourceRow title={world.name} icon={<Icon name="globe"/>} actions={
<Button disabled={busy !== null} loading={busy === world.world_id}
@@ -55,7 +63,7 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
onClose={() => {if (!busy) setEditing(null);}}
footer={<WindowFooterActions>
<Button icon={<Icon name="trash"/>} disabled={!!busy || editing?.world_id === activeWorldId}
onClick={() => setConfirming(true)}>Удалить локацию</Button>
onClick={() => setConfirming(true)}>{editing?.local_scene?"Удалить локацию":"Скрыть локацию"}</Button>
<Button variant="primary" loading={!!busy} disabled={!name.trim() || name.trim() === editing?.name}
onClick={() => {if (editing) void update(editing, {display_name:name.trim()});}}>Сохранить</Button>
</WindowFooterActions>}>
@@ -63,11 +71,17 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
onChange={event => setName(event.target.value)}/>
{editing?.world_id === activeWorldId ? <Description>Удаление станет доступно после завершения симуляции.</Description> : null}
</Window>
<ConfirmationModal open={!!editing && confirming} title="Удалить локацию?" danger
description={<>«{editing?.name}» исчезнет из доступных локаций. Исходный скан, разметка и задания сохранятся.
Восстановить её можно в списке удалённых локаций.</>}
confirmLabel="Удалить" pendingLabel="Удаляем" onClose={() => {if (!busy) setConfirming(false);}}
onConfirm={async () => {if (editing) await update(editing, {removed:true});}}/>
<ConfirmationModal open={!!editing && confirming} title={editing?.local_scene?"Удалить локацию полностью?":"Скрыть локацию?"} danger
description={editing?.local_scene?<>«{editing.name}»: обработка будет остановлена, исходные файлы и результаты удалены на Worker и на этом компьютере. Общие файлы других локаций сохранятся. Отменить удаление нельзя.</>:<>«{editing?.name}» будет скрыта из каталога. Эта старая локация хранит данные в отдельном контуре симулятора; скрытие не удаляет файлы. Восстановление доступно в списке скрытых локаций.</>}
confirmLabel={editing?.local_scene?"Удалить полностью":"Скрыть"} pendingLabel="Удаляем" onClose={() => {if (!busy) setConfirming(false);}}
onConfirm={async () => {
if(!editing)return;
if(!editing.local_scene){await update(editing,{removed:true});return;}
setBusy(editing.world_id);setError(null);
try{await deleteLocation(editing.local_scene.project_id);setConfirming(false);setEditing(null);await onChanged();}
catch(caught){setError(caught instanceof Error?caught.message:"Не удалось начать удаление.");}
finally{setBusy(null);}
}}/>
{error ? <ToastStack items={[{id:"location-settings",tone:"error",title:"Не удалось изменить локацию",description:error}]}
onDismiss={() => setError(null)}/> : null}
</>;
@@ -2,13 +2,16 @@ import { useEffect, useRef, useState } from "react";
import { Button, Icon, ProgressBar, TextField, ToastStack, Window } from "@nodedc/ui-react";
import { importAiWorld, type AiSource, type AiWorld } from "../../core/simulation/aiPolygon";
export function AiWorldImport({ source, resume, onClose, onImported }: {
source: AiSource | null; resume?: AiWorld; onClose: () => void; onImported: (world: AiWorld) => void;
import {locationImports} from "../../core/simulation/locationImports";
import {classifySimulationSource} from "../../core/simulation/sourceFiles";
export function AiWorldImport({ source, resume, initialFile, onClose, onImported }: {
source: AiSource | null; resume?: AiWorld; initialFile?: File; onClose: () => void; onImported: (world: AiWorld) => void;
}) {
const [draft, setDraft] = useState<AiSource>(source ?? {
name: "", author: "", license: "", source_url: "",
name: initialFile?.name.replace(/\.ply$/i, "") ?? "", author: "", license: "", source_url: "",
});
const [file, setFile] = useState<File | null>(null);
const [file, setFile] = useState<File | null>(initialFile ?? null);
const [pending, setPending] = useState<AiWorld | undefined>(resume);
const [progress, setProgress] = useState(0);
const [busy, setBusy] = useState(false);
@@ -18,6 +21,10 @@ export function AiWorldImport({ source, resume, onClose, onImported }: {
useEffect(() => () => controller.current?.abort(), []);
const submit = async () => {
if (!file || busy) return;
if (!resume) {
locationImports.enqueue(draft.name.trim(), Promise.resolve().then(()=>({...classifySimulationSource([{file,logicalPath:file.name}]), attribution:{author:draft.author,license:draft.license,source_url:draft.source_url}})));
onClose(); return;
}
setBusy(true); setError(null);
const abort = new AbortController(); controller.current = abort;
try { onImported(await importAiWorld(file, draft, setProgress, abort.signal, pending, setPending)); }
@@ -45,8 +45,8 @@ export function PlannerExperience({worldId,worldSha,runtime,viewport,onVisibilit
{visible&&memory?createPortal(<svg className="ai-local-editor__markers" viewBox="0 0 1280 720" preserveAspectRatio="none" aria-label="Память проездов">
{memory.attempts.map((attempt,i)=>{const p=projected[i];if(!p)return null;
const label=attemptLabel(attempt),color=URBAN_COLORS[attempt.status==="unresolved"?"attempt":"revisited"];
return <g key={attempt.id} role="img" aria-label={label} tabIndex={0} style={{pointerEvents:"auto"}}>
<title>{label}</title><circle cx={p[0]*1280} cy={p[1]*720} r="7" fill={`rgb(${color.join(",")})`}/>
return <g key={attempt.id} role="img" data-nodedc-tooltip={label} aria-label={label} tabIndex={0} style={{pointerEvents:"auto"}}>
<circle cx={p[0]*1280} cy={p[1]*720} r="7" fill={`rgb(${color.join(",")})`}/>
</g>;
})}
</svg>,viewport):null}
@@ -38,21 +38,20 @@ export function SemanticEditOverlay(props:SemanticOverlayProps) {
{props.editing&&!props.blocked&&base&&g?<g aria-label="Пивот перемещения">
{(["x","y","z"] as const).map(axis=>{const end=g[axis];if(!end)return null;const p=[end[0]*rect.width,end[1]*rect.height],d=Math.hypot(p[0]-base[0],p[1]-base[1]);if(d<12)return null;
const ux=(p[0]-base[0])/d,uy=(p[1]-base[1])/d;
return <g key={axis} data-semantic-axis={axis} style={{pointerEvents:"stroke",cursor:"move"}}>
<title>{`Переместить по ${axis.toUpperCase()}`}</title>
return <g key={axis} data-nodedc-tooltip={`Переместить по ${axis.toUpperCase()}`} aria-label={`Переместить по ${axis.toUpperCase()}`} data-semantic-axis={axis} style={{pointerEvents:"stroke",cursor:"move"}}>
<line x1={base[0]} y1={base[1]} x2={p[0]} y2={p[1]} stroke="transparent" strokeWidth={18}/>
<line x1={base[0]} y1={base[1]} x2={p[0]} y2={p[1]} stroke={g.colors[axis]} strokeWidth={3}/>
<path d={`M${p[0]},${p[1]} L${p[0]-ux*12-uy*5},${p[1]-uy*12+ux*5} L${p[0]-ux*12+uy*5},${p[1]-uy*12-ux*5} Z`} fill={g.colors[axis]}/>
<text x={p[0]+7} y={p[1]-7} fill={g.colors[axis]} fontSize={12}>{axis.toUpperCase()}</text>
</g>;
})}
<rect data-semantic-axis={props.axis} x={base[0]-7} y={base[1]-7} width={14} height={14} fill={color} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}><title>{`Переместить: ${props.axis.toUpperCase()}`}</title></rect>
{chosen[0]&&(isRigidMarking(chosen[0])||selected?.object)?<circle data-semantic-axis="rotate" cx={base[0]} cy={base[1]} r={48} fill="none" stroke={color} strokeWidth={3} style={{pointerEvents:"stroke",cursor:"grab"}}><title>Повернуть элемент в плоскости</title></circle>:null}
<rect data-nodedc-tooltip={`Переместить: ${props.axis.toUpperCase()}`} aria-label={`Переместить: ${props.axis.toUpperCase()}`} data-semantic-axis={props.axis} x={base[0]-7} y={base[1]-7} width={14} height={14} fill={color} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}/>
{chosen[0]&&(isRigidMarking(chosen[0])||selected?.object)?<circle data-nodedc-tooltip="Повернуть элемент в плоскости" aria-label="Повернуть элемент в плоскости" data-semantic-axis="rotate" cx={base[0]} cy={base[1]} r={48} fill="none" stroke={color} strokeWidth={3} style={{pointerEvents:"stroke",cursor:"grab"}}/>:null}
</g>:null}
{props.editing&&node&&props.selection.length===1?(["incoming","outgoing"] as const).map(key=>{
const a=project(node.point),b=project(curveControlPoint(node,key,handleScale));
if(!a||!b||!node[key].some(Boolean))return null;
return <g key={key} data-semantic-handle-scale={handleScale}><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={4}/><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke={color} strokeWidth={1.5}/><circle data-semantic-handle={key} cx={b[0]} cy={b[1]} r={6} fill="var(--nodedc-text-primary)" stroke={color} strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}><title>Ручка кривой</title></circle></g>;
return <g key={key} data-semantic-handle-scale={handleScale}><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke="var(--nodedc-glass-panel-bg)" strokeWidth={4}/><line x1={a[0]} y1={a[1]} x2={b[0]} y2={b[1]} stroke={color} strokeWidth={1.5}/><circle data-nodedc-tooltip="Ручка кривой" aria-label="Ручка кривой" data-semantic-handle={key} cx={b[0]} cy={b[1]} r={6} fill="var(--nodedc-text-primary)" stroke={color} strokeWidth={2} style={{pointerEvents:"all",cursor:"move"}}/></g>;
}):null}
</svg>,viewport);
}
@@ -0,0 +1,97 @@
import {useCallback, useEffect, useState} from "react";
import {ConfirmationModal, Description, Icon, IconButton, ProgressBar, ResourceList, ResourceRow, StatusBadge} from "@nodedc/ui-react";
import {locationImports, useLocationImports} from "../../core/simulation/locationImports";
import {deleteLocation, useLocationDeletions} from "../../core/simulation/locationDeletions";
import {estimateSimulationProcessing, fetchSimulationProjects, retrySimulationProject, type SimulationProject} from "../../core/simulation/projects";
type DeletionTarget={name:string;taskId?:string;projectId?:string};
/** Pending source rows stay visible before the world is admitted to the location catalog. */
export function SimulationImports({worldIds}:{worldIds:string[]}) {
const tasks=useLocationImports();
const [projects,setProjects]=useState<SimulationProject[]>([]), [error,setError]=useState<string|null>(null);
const [target,setTarget]=useState<DeletionTarget|null>(null);
const refresh=useCallback(async()=>{
const started=performance.now(),rows=await fetchSimulationProjects();
setProjects(rows);locationImports.reconcile(rows.map(row=>row.projectId),started);
},[]);
const deletions=useLocationDeletions(refresh);
useEffect(()=>{
const abort=new AbortController();let timer:ReturnType<typeof setTimeout>;
const poll=async()=>{
try {const started=performance.now(),rows=await fetchSimulationProjects(abort.signal);
if(!abort.signal.aborted){setProjects(rows);locationImports.reconcile(rows.map(row=>row.projectId),started);setError(null);}}
catch(caught){if(!abort.signal.aborted)setError(caught instanceof Error?caught.message:"Нет обновлений импорта.");}
if(!abort.signal.aborted)timer=setTimeout(()=>void poll(),2000);
};
void poll();return()=>{abort.abort();clearTimeout(timer);};
},[]);
useEffect(()=>{
for(const task of tasks)if(task.phase==="submitted" && worldIds.includes(task.project?.projectId.replace("sim-","aiworld-")??""))locationImports.forget(task.id);
},[tasks,worldIds]);
const taskProjects=new Set(tasks.map(task=>task.project?.projectId));
const deletingIds=new Set(deletions.map(row=>row.project_id));
const pending=projects.filter(project=>project.status!=="ready"&&!taskProjects.has(project.projectId)&&!deletingIds.has(project.projectId));
const pendingDeletions=deletions.filter(row=>!taskProjects.has(row.project_id)&&!worldIds.includes(row.project_id.replace("sim-","aiworld-")));
if(!tasks.length&&!pending.length&&!pendingDeletions.length&&!error)return null;
const retry=async(project:SimulationProject)=>{
try {await retrySimulationProject(project.projectId);setProjects(await fetchSimulationProjects());}
catch(caught){setError(caught instanceof Error?caught.message:"Не удалось продолжить обработку.");}
};
const trash=(item:DeletionTarget)=><IconButton label={"Удалить импорт "+item.name} onClick={()=>setTarget(item)}><Icon name="trash"/></IconButton>;
return <section className="simulation-imports" aria-label="Импорт локаций">
<ResourceList>
{tasks.map(task=>{
const project=projects.find(row=>row.projectId===task.project?.projectId)??task.project;
const serverPhase=task.phase==="submitted"&&project?projectProgress(project):null;
const failure=task.error??serverPhase?.error;
const label=failure??(task.phase==="deleting"?(deletions.find(row=>row.project_id===task.project?.projectId)?.error??"Удаление импорта"):task.phase==="checking"?"Проверка файла":task.phase==="waiting"?"В очереди загрузки":task.phase==="uploading"?
(task.progress===1?"Проверка и сохранение исходного файла":"Загрузка"):serverPhase?.label??"Обновление каталога");
return <li key={task.id}><ImportRow name={task.name} label={label} value={task.deleteRequested?undefined:serverPhase?.value??task.progress} failed={!!failure}
actions={task.phase==="deleting"?undefined:<>
{failure&&!task.deleteRequested?(locationImports.canRetry(task.id)?
<IconButton label={"Повторить импорт "+task.name} onClick={()=>locationImports.retry(task.id)}><Icon name="refresh"/></IconButton>:
project?<IconButton label={"Повторить обработку "+task.name} onClick={()=>void retry(project)}><Icon name="refresh"/></IconButton>:null):null}
{failure&&!project&&!task.deleteRequested?<IconButton label={"Убрать ошибку "+task.name} onClick={()=>locationImports.forget(task.id)}><Icon name="close"/></IconButton>:
trash({name:task.name,taskId:task.id})}
</>}/></li>;
})}
{pending.map(project=>{const progress=projectProgress(project);return <li key={project.projectId}>
<ImportRow name={project.name} {...progress} failed={!!progress.error} label={progress.error??progress.label}
actions={<>{project.status==="failed"?<IconButton label={`Повторить обработку ${project.name}`} onClick={()=>void retry(project)}><Icon name="refresh"/></IconButton>:null}{trash({name:project.name,projectId:project.projectId})}</>}/>
</li>;})}
{pendingDeletions.map(row=><li key={row.project_id}><ImportRow name={row.name} label={row.error??"Удаление локации"} failed={false}/></li>)}
</ResourceList>
{error?<Description role="alert">{error}</Description>:null}
<ConfirmationModal open={!!target} title="Удалить импорт полностью?" danger confirmLabel="Удалить полностью" pendingLabel="Останавливаем импорт"
description={<>«{target?.name}»: загрузка и обработка будут остановлены. Исходные файлы и результаты этой локации будут удалены на Worker и на этом компьютере. Общие файлы других локаций сохранятся.</>}
onClose={()=>setTarget(null)} onConfirm={async()=>{
if(!target)return;
try {
if(target.taskId)await locationImports.remove(target.taskId);
else if(target.projectId)await deleteLocation(target.projectId);
setTarget(null);await refresh();
} catch(caught){setError(caught instanceof Error?caught.message:"Не удалось начать удаление.");}
}}/>
</section>;
}
function ImportRow({name,label,value,failed,actions}:{name:string;label:string;value?:number;failed:boolean;actions?:React.ReactNode}){
return <ResourceRow title={name} icon={<Icon name="globe"/>}
status={<StatusBadge tone={failed?"danger":"warning"} pulse={!failed}>{failed?"Ошибка импорта":"Импорт"}</StatusBadge>}
actions={<><div className="simulation-imports__progress" role={failed?"alert":"status"}>
{!failed?<ProgressBar label={label} value={value}/>:null}<Description>{label}{!failed&&value!==undefined?` · ${Math.floor(value*100)}%`:""}</Description>
</div>{actions}</>}/>;
}
function projectProgress(project:SimulationProject):{label:string;value?:number;error?:string}{
if(project.status==="failed")return {label:"Ошибка обработки",error:project.error??"Обработка не завершена."};
if(project.status==="uploading")return {label:"Загрузка исходника не завершена",value:project.source.uploadedByteLength/project.source.totalByteLength};
if(project.status==="queued")return {label:"Ожидание обработки"};
if(project.status==="ready")return {label:"Готово",value:1};
if(project.status==="importing")return {label:"Получение готовой локации"};
const label:Record<string,string>={verifying_source:"Проверка исходника",inspecting:"Анализ локации",building_preview:"Конвертация превью",building_streamed_sog:"Конвертация уровней детализации",building_collision:"Подготовка коллизий"};
const estimate=estimateSimulationProcessing(project);
const eta=estimate?.estimatedSecondsRemaining;
return {label:(label[project.provider.state??""]??"Обработка локации")+(eta?` · осталось ≈ ${Math.max(1,Math.ceil(eta/60))} мин`:""),value:estimate?estimate.percent/100:undefined};
}
@@ -0,0 +1,23 @@
import {useState} from "react";
import {Button, Description, Icon, IconButton, ToastStack, Window} from "@nodedc/ui-react";
import {polygonRequest} from "../../core/simulation/aiPolygon";
type OriginalFile={name:string;byte_length:number;url:string};
export function SimulationOriginalDownload({worldId,name}:{worldId:string;name:string}){
const [files,setFiles]=useState<OriginalFile[]|null>(null),[error,setError]=useState<string|null>(null),[busy,setBusy]=useState(false);
const download=(file:OriginalFile)=>{window.location.assign(file.url);setFiles(null);};
const open=async()=>{
setBusy(true);setError(null);
try {const result=await polygonRequest<{files:OriginalFile[]}>(`/worlds/${worldId}/originals`);
if(result.files.length===1)download(result.files[0]);else setFiles(result.files);
}catch(caught){setError(caught instanceof Error?caught.message:"Исходник недоступен.");}
finally{setBusy(false);}
};
return <><IconButton label={`Скачать исходник ${name}`} disabled={busy} onClick={()=>void open()}><Icon name="download"/></IconButton>
<Window open={!!files} title={`Исходные файлы · ${name}`} onClose={()=>setFiles(null)}>
<Description>Выберите файл для скачивания.</Description>
{files?.map(file=><Button key={file.url} onClick={()=>download(file)}>{file.name}</Button>)}
</Window>
{error?<ToastStack items={[{id:"original-download",tone:"error",title:"Исходник недоступен",description:error}]} onDismiss={()=>setError(null)}/>:null}
</>;
}
@@ -11,26 +11,29 @@ import {
} from "@nodedc/ui-react";
import {
createAndUploadSimulationProject,
updateSimulationProject,
type SimulationProject,
type SimulationSceneType,
type SimulationUploadCandidate,
type SimulationUploadProgress,
} from "../../core/simulation/projects";
import {
candidatesFromDrop,
validateSimulationCandidates,
classifySimulationSource,
} from "../../core/simulation/sourceFiles";
import { locationImports } from "../../core/simulation/locationImports";
export function SimulationProjectWindow({
open,
project,
initialCandidates,
onClose,
onSaved,
}: {
open: boolean;
project: SimulationProject | null;
initialCandidates?: SimulationUploadCandidate[];
onClose: () => void;
onSaved: (project: SimulationProject) => void;
}) {
@@ -41,7 +44,6 @@ export function SimulationProjectWindow({
const [candidates, setCandidates] = useState<SimulationUploadCandidate[]>([]);
const [dragging, setDragging] = useState(false);
const [pending, setPending] = useState(false);
const [progress, setProgress] = useState<SimulationUploadProgress | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
@@ -49,10 +51,16 @@ export function SimulationProjectWindow({
setName(project?.name ?? "");
setSceneType(project?.sceneType ?? "outdoor");
setCandidates([]);
setProgress(null);
setPending(false);
setError(null);
}, [open, project]);
if (!project && initialCandidates?.length) {
try {
validateSimulationCandidates(initialCandidates);
setCandidates(initialCandidates);
setName(candidateName(initialCandidates));
} catch (caught) {setError(caught instanceof Error ? caught.message : "Источник не принят.");}
}
}, [open, project, initialCandidates]);
const sourceSummary = useMemo(() => summarizeCandidates(candidates), [candidates]);
const canSubmit = name.trim().length > 0 && (project !== null || candidates.length > 0) && !pending;
@@ -63,9 +71,7 @@ export function SimulationProjectWindow({
setCandidates(next);
setError(null);
if (!name.trim() && next.length) {
const named = next.find((candidate) => /\.lcc2?$/i.test(candidate.logicalPath)) ?? next[0];
const first = named?.logicalPath.split("/").filter(Boolean).at(-1) ?? "Новая сцена";
setName(first.replace(/\.(lcc2?|zip|rar|7z)$/i, ""));
setName(candidateName(next));
}
} catch (caught) {
setCandidates([]);
@@ -75,17 +81,15 @@ export function SimulationProjectWindow({
const submit = async () => {
if (!canSubmit) return;
if (!project) {
locationImports.enqueue(name, Promise.resolve({...classifySimulationSource(candidates), sceneType}));
onClose();
return;
}
setPending(true);
setError(null);
try {
const saved = project
? await updateSimulationProject(project.projectId, name, sceneType)
: await createAndUploadSimulationProject(
name,
sceneType,
candidates,
setProgress,
);
const saved = await updateSimulationProject(project.projectId, name, sceneType);
onSaved(saved);
} catch (caught) {
setError(caught instanceof Error ? caught.message : "Не удалось сохранить проект.");
@@ -213,33 +217,15 @@ export function SimulationProjectWindow({
</div>
</FieldFrame>
) : null}
{progress ? (
<div className="simulation-upload-progress" role="status">
<span><i style={{ width: `${Math.min(100, progress.totalBytes ? progress.uploadedBytes / progress.totalBytes * 100 : 0)}%` }} /></span>
<div>
<strong>
{formatBytes(progress.uploadedBytes)} / {formatBytes(progress.totalBytes)}
{" · "}{formatUploadEta(progress.estimatedSecondsRemaining)}
</strong>
<small>{progress.currentPath}</small>
</div>
</div>
) : null}
{error ? <p className="simulation-project-window__error" role="alert">{error}</p> : null}
</div>
</Window>
);
}
function formatUploadEta(seconds: number | null): string {
if (seconds === 0) return "загружено";
if (seconds === null) return "считаем время";
if (seconds < 60) return `осталось ≈ ${Math.max(1, seconds)} сек`;
const minutes = Math.ceil(seconds / 60);
if (minutes < 60) return `осталось ≈ ${minutes} мин`;
const hours = Math.floor(minutes / 60);
const remainder = minutes % 60;
return `осталось ≈ ${hours} ч${remainder ? ` ${remainder} мин` : ""}`;
function candidateName(candidates: SimulationUploadCandidate[]): string {
const named = candidates.find(candidate => /\.lcc2?$/i.test(candidate.logicalPath)) ?? candidates[0];
return (named?.logicalPath.split("/").filter(Boolean).at(-1) ?? "Новая сцена").replace(/\.(lcc2?|zip|rar|7z)$/i, "");
}
function summarizeCandidates(candidates: SimulationUploadCandidate[]): { title: string; detail: string } {
@@ -1,15 +1,24 @@
import { useEffect, useState } from "react";
import { Description, Button, LoadingRegion, Window } from "@nodedc/ui-react";
import { fetchSimulationProjects, retrySimulationProject, type SimulationProject } from "../../core/simulation/projects";
import { useEffect, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { Description, Button, GlassMaterialSurface, Icon, IconButton, LoadingRegion, Window } from "@nodedc/ui-react";
import { fetchSimulationProjects, retrySimulationProject, type SimulationProject, type SimulationUploadCandidate } from "../../core/simulation/projects";
import { SIMULATION_IMPORT_FORMATS } from "../../core/simulation/sourceFiles";
import { useSimulationFileDrop } from "../../core/simulation/useSimulationFileDrop";
import { importDroppedLocation } from "../../core/simulation/locationImports";
import { SimulationProjectWindow } from "./SimulationProjectWindow";
/** Reuses the existing resumable Gaussian Pipeline admission workflow. */
export function SimulationSourceImport({open,onClose,onPly,onReady}: {
open:boolean; onClose:()=>void; onPly:()=>void; onReady:(worldId:string)=>void;
export function SimulationSourceImport({children,headerToolsHost,disabled=false,onPly,onReady}: {
children:ReactNode; headerToolsHost?:HTMLElement|null; disabled?:boolean;
onPly:(file?:File)=>void; onReady:(worldId:string)=>void;
}) {
const [archive,setArchive]=useState(false), [project,setProject]=useState<SimulationProject|null>(null);
const [open,setOpen]=useState(false);
const [archive,setArchive]=useState<{candidates?:SimulationUploadCandidate[]}|null>(null), [project,setProject]=useState<SimulationProject|null>(null);
const [error,setError]=useState<string|null>(null);
const [pending,setPending]=useState<SimulationProject[]>([]);
const drop=useSimulationFileDrop(importDroppedLocation,!disabled&&!open&&!archive&&!project);
const importAction=<IconButton label="Импорт локации" disabled={disabled||!!archive||open}
onClick={()=>setOpen(true)}><Icon name="plus"/></IconButton>;
useEffect(()=>{
if(!open)return;
const abort=new AbortController();setError(null);
@@ -33,21 +42,28 @@ export function SimulationSourceImport({open,onClose,onPly,onReady}: {
};
void poll();return()=>{abort.abort();clearTimeout(timer);};
},[project?.projectId,project?.status]);
return <>
<Window open={open} title="Импорт локации" onClose={onClose}><div className="ai-polygon__actions">
<Button onClick={()=>{onClose();onPly();}}>Gaussian PLY</Button>
<Button onClick={()=>{onClose();setArchive(true);}}>Архив или папка LCC</Button>
return <div className="ai-polygon" {...drop.handlers}>
{headerToolsHost?createPortal(importAction,headerToolsHost):<div className="ai-polygon__import-action">{importAction}</div>}
{children}
{drop.active?<GlassMaterialSurface context="floating" radius="panel" className="simulation-import-overlay" role="status">
<Icon name="upload"/><strong>Отпустите файл или папку, чтобы добавить локацию</strong>
<Description>{SIMULATION_IMPORT_FORMATS}</Description>
<Description>Одна локация за раз. Проверка и импорт начнутся автоматически.</Description>
</GlassMaterialSurface>:null}
<Window open={open} title="Импорт локации" onClose={()=>setOpen(false)}><div className="ai-polygon__actions">
<Button onClick={()=>{setOpen(false);onPly();}}>Gaussian PLY</Button>
<Button onClick={()=>{setOpen(false);setArchive({});}}>Архив или папка LCC</Button>
</div>
{pending.map(p=><div key={p.projectId} className="ai-polygon__row"><Description>{p.name}</Description>
<Button onClick={()=>{onClose();setError(null);setProject(p);}}>Подготовка локации</Button></div>)}
<Button onClick={()=>{setOpen(false);setError(null);setProject(p);}}>Подготовка локации</Button></div>)}
{error?<Description role="alert">{error}</Description>:null}
</Window>
<SimulationProjectWindow open={archive} project={null} onClose={()=>setArchive(false)} onSaved={p=>{setArchive(false);setProject(p);}} />
<SimulationProjectWindow open={!!archive} initialCandidates={archive?.candidates} project={null} onClose={()=>setArchive(null)} onSaved={p=>{setArchive(null);setProject(p);}} />
{project?<Window open title={`Подготовка ${project.name}`} onClose={()=>setProject(null)}>
<LoadingRegion loading={project.status!=='failed'&&!error} label="Подготовка локации">
<Description>{error??project.error??'Локация появится в общей библиотеке после подготовки.'}</Description>
{project.status==='failed'?<Button onClick={()=>void retrySimulationProject(project.projectId).then(setProject).catch(e=>setError(e.message))}>Повторить подготовку</Button>:null}
</LoadingRegion>
</Window>:null}
</>;
</div>;
}
@@ -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;
@@ -0,0 +1,19 @@
import {useEffect,useState} from "react";
import {deleteSimulationProject} from "./projects";
export interface LocationDeletion {project_id:string;name:string;state:"deleting"|"waiting";error:string|null}
export const deleteLocation=deleteSimulationProject;
export function useLocationDeletions(onChanged:()=>Promise<void>){
const [rows,setRows]=useState<LocationDeletion[]>([]);
useEffect(()=>{
let stopped=false,timer:ReturnType<typeof setTimeout>;let previous="";
const poll=async()=>{
try{const response=await fetch("/api/v1/simulation-worlds/deletions");if(!response.ok)throw Error();
const data=await response.json() as {deletions:LocationDeletion[]};
if(!stopped){setRows(data.deletions);const key=JSON.stringify(data.deletions);if(key!==previous){previous=key;await onChanged();}}}
catch{/* Keep acknowledged deletion visible while disconnected. */}
if(!stopped)timer=setTimeout(()=>void poll(),1500);
};
void poll();return()=>{stopped=true;clearTimeout(timer);};
},[onChanged]);
return rows;
}
@@ -0,0 +1,82 @@
import type {SimulationImportSource} from "./sourceFiles";
import type {SimulationProject, SimulationUploadProgress} from "./projects";
export interface LocationImportTask {
id: string; name: string; phase: "checking" | "waiting" | "uploading" | "submitted" | "failed" | "deleting";
project?: SimulationProject; progress?: number; error?: string; deleteRequested?: boolean; deletionAcknowledgedAt?: number;
}
interface Dependencies {
create: (name:string, source:SimulationImportSource)=>Promise<SimulationProject>;
upload: (project:SimulationProject, source:SimulationImportSource, progress:(value:SimulationUploadProgress)=>void, signal:AbortSignal)=>Promise<SimulationProject>;
delete?: (project:SimulationProject)=>Promise<void>;
}
/** Owns browser File handles independently of any modal/workspace mount. */
export function createLocationImportQueue(api:Dependencies) {
let rows:LocationImportTask[]=[], running=false;
const sources=new Map<string,SimulationImportSource>(), listeners=new Set<()=>void>();
const controllers=new Map<string,AbortController>(), settled=new Map<string,Promise<void>>();
const publish=()=>{for(const listener of listeners)listener();};
const change=(id:string,patch:Partial<LocationImportTask>)=>{rows=rows.map(row=>row.id===id?{...row,...patch}:row);publish();};
const fail=(id:string,caught:unknown)=>change(id,{phase:"failed",error:caught instanceof Error?caught.message:"Импорт не завершён."});
const next=()=>[...rows].reverse().find(item=>item.phase==="waiting");
const pump=async()=>{
if(running)return;
running=true;
try {
for(let row=next();row;row=next()) {
const {id}=row, source=sources.get(id)!;
const controller=new AbortController();controllers.set(id,controller);
let finish!:()=>void;settled.set(id,new Promise<void>(resolve=>{finish=resolve;}));
change(id,{phase:"uploading",progress:undefined,error:undefined});
try {
const project=row.project??await api.create(row.name,source);
change(id,{project});
controller.signal.throwIfAborted();
const submitted=await api.upload(project,source,value=>change(id,{progress:value.totalBytes?value.uploadedBytes/value.totalBytes:0}),controller.signal);
controller.signal.throwIfAborted();
change(id,{project:submitted,phase:"submitted",progress:undefined});
sources.delete(id);
} catch(caught) {if(!controller.signal.aborted)fail(id,caught);}
finally {controllers.delete(id);settled.delete(id);finish();}
}
} finally {running=false;}
};
return {
getSnapshot:()=>rows,
subscribe(listener:()=>void){listeners.add(listener);return()=>{listeners.delete(listener);};},
enqueue(name:string,source:Promise<SimulationImportSource>,resume?:SimulationProject) {
const id=crypto.randomUUID();
rows=[{id,name,phase:"checking",project:resume},...rows];publish();
void source.then(value=>{
if(!rows.some(row=>row.id===id&&!row.deleteRequested))return;
sources.set(id,value);change(id,{phase:"waiting"});void pump();
}).catch(caught=>fail(id,caught));
return id;
},
async remove(id:string){
const row=rows.find(item=>item.id===id);if(!row)return;
change(id,{phase:"deleting",deleteRequested:true,error:undefined});
controllers.get(id)?.abort();
// Creation is deliberately not aborted: retain its server identity for cleanup.
await settled.get(id);
try {
const project=rows.find(item=>item.id===id)?.project;
if(project){
if(!api.delete)throw new Error("Удаление импорта недоступно.");
await api.delete(project);sources.delete(id);
change(id,{deletionAcknowledgedAt:performance.now()});
} else {sources.delete(id);rows=rows.filter(item=>item.id!==id);publish();}
} catch(caught){fail(id,caught);throw caught;}
},
reconcile(projectIds:string[],requestStartedAt:number){
const retained=rows.filter(row=>!(row.deletionAcknowledgedAt!==undefined &&
requestStartedAt>=row.deletionAcknowledgedAt && !projectIds.includes(row.project!.projectId)));
if(retained.length!==rows.length){rows=retained;publish();}
},
retry(id:string){if(sources.has(id)&&!rows.find(row=>row.id===id)?.deleteRequested){change(id,{phase:"waiting",error:undefined});void pump();}},
canRetry:(id:string)=>sources.has(id),
forget(id:string){const row=rows.find(item=>item.id===id);if(!row||!["failed","submitted"].includes(row.phase))return;
sources.delete(id);rows=rows.filter(item=>item.id!==id);publish();},
};
}
@@ -0,0 +1,18 @@
import {useSyncExternalStore} from "react";
import {createLocationImportQueue} from "./locationImportQueue";
import {createSimulationProject, deleteSimulationProject, uploadSimulationProjectSource} from "./projects";
import {candidatesFromDrop, classifySimulationSource} from "./sourceFiles";
export const locationImports=createLocationImportQueue({
create:(name,source)=>createSimulationProject(name,source.sceneType??"outdoor",source.candidates,source.attribution),
upload:(project,source,progress,signal)=>uploadSimulationProjectSource(project,source.candidates,progress,signal),
delete:project=>deleteSimulationProject(project.projectId),
});
export function useLocationImports(){return useSyncExternalStore(locationImports.subscribe,locationImports.getSnapshot);}
export function importDroppedLocation(transfer:DataTransfer){
const name=transfer.files[0]?.name.replace(/\.(zip|rar|7z|ply)$/i,"")??"Новая локация";
// Capture drop entries synchronously; the row exists before directory checks finish.
const source=candidatesFromDrop(transfer).then(classifySimulationSource);
locationImports.enqueue(name,source);
}
@@ -196,6 +196,7 @@ export async function createSimulationProject(
name: string,
sceneType: SimulationSceneType,
candidates: SimulationUploadCandidate[],
attribution?: {author:string;license:string;source_url:string|null},
): Promise<SimulationProject> {
const sourceKind = sourceKindFor(candidates);
const createdResponse = await fetch(API_ROOT, {
@@ -206,6 +207,7 @@ export async function createSimulationProject(
name,
scene_type: sceneType,
source_kind: sourceKind,
attribution,
files: candidates.map((candidate) => ({
logical_path: candidate.logicalPath,
byte_length: candidate.file.size,
@@ -23,15 +23,21 @@ export async function candidatesFromDrop(
transfer: DataTransfer,
): Promise<SimulationUploadCandidate[]> {
const candidates: SimulationUploadCandidate[] = [];
for (const item of Array.from(transfer.items)) {
// The browser revokes DataTransfer access after the drop callback returns.
// Capture every entry/file before awaiting directory enumeration.
const fallbackFiles = Array.from(transfer.files);
const entries = Array.from(transfer.items).map(item => {
const file = item.getAsFile();
const entry = (item as DataTransferItem & {
webkitGetAsEntry?: () => LegacyFileEntry | null;
}).webkitGetAsEntry?.();
return {entry, file};
});
for (const {entry, file} of entries) {
if (entry?.isDirectory) {
await collectEntry(entry, candidates);
continue;
}
const file = item.getAsFile();
if (file) {
candidates.push({ file, logicalPath: file.name });
continue;
@@ -39,13 +45,33 @@ export async function candidatesFromDrop(
if (entry) await collectEntry(entry, candidates);
}
if (!candidates.length) {
for (const file of Array.from(transfer.files)) {
for (const file of fallbackFiles) {
candidates.push({ file, logicalPath: file.name });
}
}
return candidates;
}
export type SimulationImportSource = ({sceneType?: import("./projects").SimulationSceneType; attribution?:{author:string;license:string;source_url:string|null}} & (
| {kind: "ply"; file: File; candidates: SimulationUploadCandidate[]}
| {kind: "lcc"; candidates: SimulationUploadCandidate[]}));
export const SIMULATION_IMPORT_FORMATS = "Gaussian PLY · ZIP, RAR, 7z или папка с LCC/LCC2";
export function classifySimulationSource(candidates: SimulationUploadCandidate[]): SimulationImportSource {
if (candidates.length === 1 && /\.ply$/i.test(candidates[0].logicalPath)) {
const file = candidates[0].file;
if (!file.size) throw new Error("Выбранный файл пуст.");
if (file.size > 8 * 1024 ** 3) throw new Error("Gaussian PLY превышает лимит 8 ГБ.");
return {kind: "ply", file, candidates};
}
if (candidates.length === 1 && !/\.(zip|rar|7z|lcc2?)$/i.test(candidates[0].logicalPath)) {
throw new Error(`Формат не поддерживается. Доступны: ${SIMULATION_IMPORT_FORMATS}.`);
}
validateSimulationCandidates(candidates);
return {kind: "lcc", candidates};
}
export async function archivesFromDrop(transfer: DataTransfer): Promise<File[]> {
const candidates = await candidatesFromDrop(transfer);
const invalid = candidates.filter((candidate) => !ARCHIVE_PATTERN.test(candidate.logicalPath));
@@ -71,6 +97,9 @@ export async function archivesFromDrop(transfer: DataTransfer): Promise<File[]>
export function validateSimulationCandidates(candidates: SimulationUploadCandidate[]): void {
if (!candidates.length) throw new Error("Выберите архив или папку с результатом LCC/LCC2.");
if (candidates.length === 1 && /\.ply$/i.test(candidates[0].logicalPath)) {
classifySimulationSource(candidates); return;
}
const archives = candidates.filter((candidate) => ARCHIVE_PATTERN.test(candidate.logicalPath));
if (archives.length) {
if (candidates.length !== 1) throw new Error("Архив нужно загружать одним файлом.");
@@ -0,0 +1,38 @@
import {useEffect, useRef, useState, type DragEvent} from "react";
import {hasDroppedFiles} from "./sourceFiles";
/** External files only; native window/tree dragging and portal forms are independent. */
export function useSimulationFileDrop(onDrop: (transfer: DataTransfer) => void, enabled: boolean) {
const [active, setActive] = useState(false);
const depth = useRef(0);
const reset = () => {depth.current = 0; setActive(false);};
useEffect(() => {
const escape = (event: KeyboardEvent) => {if (event.key === "Escape") reset();};
window.addEventListener("dragend", reset); window.addEventListener("blur", reset); window.addEventListener("keydown", escape);
return () => {window.removeEventListener("dragend", reset); window.removeEventListener("blur", reset); window.removeEventListener("keydown", escape);};
}, []);
useEffect(() => {if (!enabled) reset();}, [enabled]);
const accepts = (event: DragEvent<HTMLElement>) => event.currentTarget.contains(event.target as Node) && hasDroppedFiles(event.dataTransfer);
const handlers = {
onDragEnter(event: DragEvent<HTMLElement>) {
if (!accepts(event)) return;
event.preventDefault(); event.stopPropagation();
if (enabled) {depth.current++; setActive(true);}
},
onDragOver(event: DragEvent<HTMLElement>) {
if (!accepts(event)) return;
event.preventDefault(); event.stopPropagation(); event.dataTransfer.dropEffect = enabled ? "copy" : "none";
if (enabled) setActive(true);
},
onDragLeave(event: DragEvent<HTMLElement>) {
if (!accepts(event)) return;
event.stopPropagation(); if (--depth.current <= 0) reset();
},
onDrop(event: DragEvent<HTMLElement>) {
if (!accepts(event)) return;
event.preventDefault(); event.stopPropagation(); reset();
if (enabled) onDrop(event.dataTransfer);
},
};
return {active, handlers};
}
@@ -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> {
+3 -2
View File
@@ -1,3 +1,4 @@
import { TooltipProvider } from "@nodedc/ui-react";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { applyNodedcTheme } from "@nodedc/ui-core";
@@ -23,11 +24,11 @@ rootElement.dataset.nodedcUi = "";
applyNodedcTheme(rootElement, { theme: "dark" });
createRoot(rootElement).render(
<StrictMode>
<StrictMode><TooltipProvider>
<DevicePluginHostProvider plugins={installedDevicePlugins} nodeSensorContributions={installedNodeSensorContributions}>
<ComputeContourProvider>
<PlanningTestProvider><App /></PlanningTestProvider>
</ComputeContourProvider>
</DevicePluginHostProvider>
</StrictMode>,
</TooltipProvider></StrictMode>,
);
@@ -1,6 +1,12 @@
.simulation-profiles { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 1rem; height: 100%; min-height: 0; }
.simulation-profiles > .nodedc-select-anchor { justify-self: start; }
.ai-polygon { display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 1rem; height: 100%; min-width: 0; min-height: 0; overflow: hidden; }
.ai-polygon { position: relative; display: grid; grid-template-rows: auto minmax(0, 1fr); gap: 1rem; height: 100%; min-width: 0; min-height: 0; overflow: hidden; }
.ai-polygon__import-action { position: absolute; top: 0; right: 0; }
.simulation-import-overlay.nodedc-glass-material { position: absolute; inset: 0; z-index: 100; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--nodedc-space-3); padding: var(--nodedc-space-5); text-align: center; pointer-events: none; border-radius: var(--nodedc-radius-panel); }
.simulation-imports { flex: 0 0 auto; margin-bottom: var(--nodedc-space-3); }
.simulation-imports__progress { display: flex; align-items: center; gap: var(--nodedc-space-3); width: clamp(14rem, 35vw, 32rem); max-width: 100%; min-width: 0; }
.simulation-imports__progress .nodedc-progress-bar { flex: 1 1 45%; min-width: 3rem; }
.simulation-imports__progress .nodedc-description { flex: 1 1 55%; min-width: 0; }
.ai-polygon__content { min-height: 0; overflow: auto; overscroll-behavior: contain; padding-bottom: 1rem; }
.ai-polygon__head, .ai-polygon__row { display: flex; justify-content: space-between; align-items: center; gap: 1rem; flex-wrap: wrap; }
.ai-polygon__actions, .ai-polygon__facts { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; }
@@ -1,3 +1,5 @@
import {defaultMapViewDocument} from '../../core/map/mapView';
import {mapPresentation} from '../../components/map/mapPresentation';
import {lazy, Suspense, useCallback, useMemo, useState, type ComponentProps} from 'react';
import {Description, ToastStack} from '@nodedc/ui-react';
import type {BimHost, Notice} from '@nodedc/bim-viewer';
@@ -19,6 +21,7 @@ export function ArchitecturalProjectsWorkspace({headerToolsHost,headerTitleHost}
}, []);
const host = useMemo<BimHost>(() => ({
apiBase: '/api/v1/bim', assets: {fragmentsWorker, mapWorker}, notify,
cesium:{runtimeConfigUrl:'/api/v1/map/runtime-config',settings:mapPresentation(defaultMapViewDocument().view.visualSettings),cacheIntent:{enabled:true,no_overwrite:true}},
}), [notify]);
return <>
<Suspense fallback={<Description role="status">Открываем архитектурные проекты…</Description>}>
@@ -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>;
@@ -4,6 +4,7 @@ import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react"
import { Description, Button, GlassSurface, Icon, IconButton, LoadingRegion, InspectorSelectField, StatusBadge, ToastStack } from "@nodedc/ui-react";
import { AiLocationCatalog } from "../../components/simulation/AiLocationCatalog";
import { SimulationSourceImport } from "../../components/simulation/SimulationSourceImport";
import { SimulationImports } from "../../components/simulation/SimulationImports";
import { AiWorldImport } from "../../components/simulation/AiWorldImport";
import { AiWorldStream } from "../../components/simulation/AiWorldStream";
import { AiWorldSetup } from "../../components/simulation/AiWorldSetup";
@@ -33,7 +34,6 @@ const EMPTY_POINTS:AiWaypoint[]=[];
export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLElement|null}) {
const [mode,setMode] = useState<"manual"|"inference">("inference");
const [manual,setManual] = useState(false);
const [importChoice,setImportChoice] = useState(false);
const [planning, setPlanning] = useState(false);
const [layout,updateLayout]=useSimulationLayout();
const sceneMode=layout.mode, setSceneMode=(mode:typeof sceneMode)=>updateLayout({mode});
@@ -41,7 +41,7 @@ export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLEleme
const [catalog, setCatalog] = useState<AiCatalog | null>(null);
const [selectedId, setSelectedId] = useState<string | null>(null);
const [runId, setRunId] = useState<string | null>(null);
const [importing, setImporting] = useState<{ source: AiSource | null; resume?: AiWorld } | null>(null);
const [importing, setImporting] = useState<{ source: AiSource | null; resume?: AiWorld; file?: File } | null>(null);
const [error, setError] = useState<string | null>(null);
const [starting, setStarting] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
@@ -224,7 +224,8 @@ export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLEleme
{taskSelector}
{routeActions}
</> : null;
return <div className="ai-polygon">
return <SimulationSourceImport headerToolsHost={headerToolsHost} disabled={!!importing}
onPly={file=>setImporting({source:null,file})} onReady={id=>{void load();setSelectedId(id);}}>
<header className="ai-polygon__head">
<div className="ai-polygon__title">
{selected && !planning ? <IconButton label="Назад к локациям" onClick={returnToLocations}>
@@ -234,11 +235,11 @@ export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLEleme
</div>
<div className="ai-polygon__actions ai-polygon__location-actions" ref={setActionsHost}>
{selected ? !planning&&!manual&&!running&&canEdit?<IconButton label="Подготовить маршрут"
onClick={()=>start("planning")}><Icon name="plan"/></IconButton>:null : <>{connection}
<Button icon={<Icon name="upload" />} onClick={() => setImportChoice(true)}>Импорт локации</Button></>}
onClick={()=>start("planning")}><Icon name="plan"/></IconButton>:null : connection}
</div>
</header>
<LoadingRegion className={`ai-polygon__content${manual||planning?" ai-polygon__content--local":""}`} loading={!catalog && !error} label="Загрузка локаций">
<SimulationImports worldIds={catalog?.worlds.map(world=>world.world_id)??[]}/>
{error ? <ToastStack items={[{ id: "error", tone: "error", title: "Не удалось выполнить действие", description: error }]} onDismiss={() => setError(null)} /> : null}
{removed.length?<GlassSurface padding="sm" className="ai-polygon__row">
<span>Удалено из списка: {removed.at(-1)?.name}</span>
@@ -297,9 +298,7 @@ export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLEleme
}}/> : null}
{saveOpen?<AiPlanSaveWindow error={saveError} name={planName} onName={setPlanName} busy={saving}
launch={launchAfterSave} onClose={()=>setSaveOpen(false)} onSave={save}/>:null}
<SimulationSourceImport open={importChoice} onClose={()=>setImportChoice(false)}
onPly={()=>setImporting({source:null})} onReady={(id)=>{void load();setSelectedId(id);}} />
{importing ? <AiWorldImport source={importing.source} resume={importing.resume}
{importing ? <AiWorldImport source={importing.source} resume={importing.resume} initialFile={importing.file}
onClose={() => setImporting(null)} onImported={acceptWorld} /> : null}
</div>;
</SimulationSourceImport>;
}
@@ -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}/>}
</>;
@@ -0,0 +1,55 @@
import assert from "node:assert/strict";
import {after, before, test} from "node:test";
import {createServer} from "./support/vite-server.mjs";
let server, service, health;
const fetchOriginal = globalThis.fetch;
before(async () => {
server = await createServer({appType: "custom", logLevel: "silent", server: {middlewareMode: true}});
service = await server.ssrLoadModule("/src/core/map/cesiumService.ts");
health = await server.ssrLoadModule("/src/core/map/useMapGatewayHealth.ts");
});
after(async () => {globalThis.fetch = fetchOriginal; await server?.close();});
test("health distinguishes direct provider from an actual NAS cache", () => {
const value = health.decodeHealth({ok: true, service: "missioncore-map-direct", route: "direct", cache: null});
assert.equal(value.cache, null);
assert.equal(value.ionConfigured, true);
assert.throws(() => health.decodeHealth({ok: false, service: "missioncore-map-direct", route: "direct"}));
const nas = health.decodeHealth({ok: true, service: "nodedc-map-gateway", ionConfigured: true, assetAllowlist: [1, 2, 96188],
cache: {mode: "online", writePolicy: "read-through", entries: 12, bytes: 30, maxBytes: null, atCapacity: false, persistent: true}});
assert.equal(nas.cache.entries, 12);
});
test("settings save uses body-only token and revision, then refreshes maps", async () => {
const previousWindow = globalThis.window;
const events = [];
globalThis.window = {dispatchEvent: event => events.push(event.type)};
globalThis.fetch = async (url, options) => {
assert.equal(url, "/api/v1/map/services/cesium-ion");
assert.equal(options.method, "PUT");
assert.equal(options.cache, "no-store");
assert.deepEqual(JSON.parse(options.body), {revision: 7, mode: "auto", token: "candidate"});
return new Response(JSON.stringify({revision: 8, mode: "auto", token_configured: true}));
};
try {
const value = await service.saveCesiumService({revision: 7, mode: "auto", token: "candidate"});
assert.equal(value.revision, 8);
assert.deepEqual(events, [service.cesiumServiceChanged]);
} finally {globalThis.window = previousWindow;}
});
test("failed settings write neither exposes upstream body nor announces success", async () => {
globalThis.fetch = async () => new Response(JSON.stringify({code: "cesium_provider_unauthorized", detail: "private-credential"}), {status: 401});
await assert.rejects(service.saveCesiumService({revision: 7, mode: "auto", token: "candidate"}), error =>
/отклонил токен/.test(error.message) && !error.message.includes("private-credential"));
});
test("token lamp distinguishes saved, pending, verified, rejected and new draft", () => {
const base = {configured: false, draft: false, checking: false, error: "", verification: null};
assert.equal(service.cesiumTokenIndicator(base).tone, "neutral");
assert.equal(service.cesiumTokenIndicator({...base, configured: true}).tone, "neutral");
assert.deepEqual(service.cesiumTokenIndicator({...base, checking: true}), {
tone: "warning", pulse: true, label: "Проверка доступа Cesium ion",
});
assert.equal(service.cesiumTokenIndicator({...base, verification: {ok: true, assets: {}}}).tone, "success");
assert.match(service.cesiumTokenIndicator({...base, verification: {ok: false,
assets: {"1": {ok: false, code: "cesium_provider_unauthorized"}}}}).label, /отклонил токен/);
assert.equal(service.cesiumTokenIndicator({...base, error: "Нет соединения"}).tone, "warning");
assert.match(service.cesiumTokenIndicator({...base, configured: true, draft: true}).label, /ещё не проверен/);
});
@@ -0,0 +1,101 @@
import assert from 'node:assert/strict';
import {readFileSync} from 'node:fs';
import {test} from 'node:test';
import ts from 'typescript';
async function load(name){
const code=ts.transpileModule(readFileSync(new URL(`../src/core/simulation/${name}.ts`,import.meta.url),'utf8'),{compilerOptions:{module:ts.ModuleKind.ESNext}}).outputText;
return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
}
const {createLocationImportQueue}=await load('locationImportQueue');
const {classifySimulationSource,candidatesFromDrop}=await load('sourceFiles');
const tick=()=>new Promise(resolve=>setImmediate(resolve));
const deferred=()=>{let resolve;const promise=new Promise(r=>{resolve=r;});return {promise,resolve};};
const archive={kind:'lcc',candidates:[{logicalPath:'scene.zip',file:new File(['source'],'scene.zip')}]};
test('row precedes validation; unsupported input never creates a server project',async()=>{
let created=0;const queue=createLocationImportQueue({create:()=>{created++;}});
const input=deferred(),id=queue.enqueue('bad.las',input.promise.then(classifySimulationSource));
assert.equal(queue.getSnapshot()[0].phase,'checking');
input.resolve([{logicalPath:'bad.las',file:new File(['x'],'bad.las')}]);await tick();
assert.equal(created,0);assert.match(queue.getSnapshot()[0].error,/Формат не поддерживается/);
queue.forget(id);assert.equal(queue.getSnapshot().length,0);
});
test('background upload survives loss of all UI subscribers; queued files run sequentially',async()=>{
const release=deferred(),order=[];let active=0,maxActive=0;
const queue=createLocationImportQueue({create:async name=>({projectId:name}),upload:async project=>{
active++;maxActive=Math.max(maxActive,active);order.push(project.projectId);
if(project.projectId==='first')await release.promise;active--;return {...project,status:'queued'};
}});
const unsubscribe=queue.subscribe(()=>{});
queue.enqueue('first',Promise.resolve(archive));await tick();unsubscribe();
queue.enqueue('second',Promise.resolve(archive));queue.enqueue('third',Promise.resolve(archive));await tick();
assert.equal(queue.getSnapshot().find(row=>row.name==='second').phase,'waiting');
release.resolve();await tick();await tick();
assert.deepEqual(order,['first','second','third']);assert.equal(maxActive,1);
assert.ok(queue.getSnapshot().every(row=>row.phase==='submitted'));
});
test('retry after transfer failure reuses the created project instead of making a duplicate',async()=>{
let creates=0,attempts=0;
const queue=createLocationImportQueue({create:async()=>{creates++;return {projectId:'same'};},upload:async project=>{
if(!attempts++)throw new Error('Связь прервана');return {...project,status:'queued'};
}});
const id=queue.enqueue('scene',Promise.resolve(archive));await tick();
assert.equal(queue.getSnapshot()[0].phase,'failed');queue.retry(id);await tick();
assert.equal(creates,1);assert.equal(queue.getSnapshot()[0].phase,'submitted');
});
test('drop captures file references before asynchronous directory enumeration revokes DataTransfer',async()=>{
let live=true;const file=new File(['x'],'scene.lcc');
const entry={isDirectory:true,createReader:()=>{let done=false;return {readEntries:callback=>{
setImmediate(()=>{callback(done?[]:[{isFile:true,fullPath:'/scan/scene.lcc',file:callback=>callback(file)}]);done=true;});
}};}};
const second=new File(['mesh'],'mesh.ply');
const transfer={files:[],items:[{getAsFile:()=>null,webkitGetAsEntry:()=>entry},{getAsFile:()=>live?second:null}]};
const result=candidatesFromDrop(transfer);live=false;
assert.deepEqual((await result).map(row=>row.logicalPath),['scan/scene.lcc','mesh.ply']);
});
test('format dispatch checks emptiness, PLY size limit, archive multiplicity and LCC descriptor count',()=>{
const candidate=(name,size=1)=>({logicalPath:name,file:{name,size}});
assert.equal(classifySimulationSource([candidate('SCAN.PLY')]).kind,'ply');
assert.equal(classifySimulationSource([candidate('scene.7z')]).kind,'lcc');
assert.throws(()=>classifySimulationSource([candidate('scene.ply',0)]),/пуст/);
assert.throws(()=>classifySimulationSource([candidate('scene.ply',9*1024**3)]),/8 ГБ/);
assert.throws(()=>classifySimulationSource([candidate('a.zip'),candidate('b.zip')]),/одним файлом/);
assert.throws(()=>classifySimulationSource([candidate('folder/a.lcc'),candidate('folder/b.lcc2')]),/ровно одна/);
});
test('PLY and archive forms share durable project upload and preserve source options',async()=>{
const calls=[];
const queue=createLocationImportQueue({create:async(name,source)=>{calls.push(source);return {projectId:name};},upload:async project=>({...project,status:'queued'})});
const source={...classifySimulationSource([{logicalPath:'world.ply',file:new File(['ply'],'world.ply')}]),sceneType:'interior',attribution:{author:'Owner',license:'Private',source_url:null}};
queue.enqueue('ply',Promise.resolve(source));await tick();
assert.equal(calls.length,1);assert.equal(calls[0].kind,'ply');assert.equal(calls[0].sceneType,'interior');
assert.equal(calls[0].attribution.author,'Owner');assert.equal(queue.getSnapshot()[0].phase,'submitted');
});
test('delete during creation waits for server identity and never starts its upload',async()=>{
const created=deferred(),events=[];
const queue=createLocationImportQueue({create:()=>created.promise,upload:async()=>events.push('upload'),delete:async p=>events.push('delete:'+p.projectId)});
const id=queue.enqueue('late',Promise.resolve(archive));await tick();
const removal=queue.remove(id);await tick();assert.equal(queue.getSnapshot()[0].phase,'deleting');
created.resolve({projectId:'late'});await removal;
assert.deepEqual(events,['delete:late']);assert.equal(queue.getSnapshot()[0].phase,'deleting');
queue.reconcile([],0);assert.equal(queue.getSnapshot().length,1);
queue.reconcile(['late'],Infinity);assert.equal(queue.getSnapshot().length,1);
queue.reconcile([],Infinity);assert.equal(queue.getSnapshot().length,0);
});
test('delete aborts active upload; failed delete remains retryable without restarting upload',async()=>{
let attempts=0,aborted=false,uploads=0;
const queue=createLocationImportQueue({create:async()=>({projectId:'active'}),upload:async(p,s,progress,signal)=>{
uploads++;await new Promise((resolve,reject)=>signal.addEventListener('abort',()=>{aborted=true;reject(new Error('abort'));}));
},delete:async()=>{if(!attempts++)throw new Error('offline');}});
const id=queue.enqueue('active',Promise.resolve(archive));await tick();
await assert.rejects(queue.remove(id),/offline/);assert.equal(aborted,true);
assert.equal(queue.getSnapshot()[0].deleteRequested,true);queue.retry(id);await tick();
assert.equal(uploads,1);await queue.remove(id);queue.reconcile([],Infinity);assert.equal(queue.getSnapshot().length,0);
});
test('deleting a checking row prevents a late validation result from admitting a project',async()=>{
const checked=deferred();let creates=0;
const queue=createLocationImportQueue({create:async()=>{creates++;}});
const id=queue.enqueue('checking',checked.promise);await queue.remove(id);checked.resolve(archive);await tick();
assert.equal(creates,0);assert.equal(queue.getSnapshot().length,0);
});
@@ -0,0 +1,51 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {build} from 'esbuild';
const b=await build({entryPoints:['src/workspaces/fleet/observation/ObservationMap.tsx'],bundle:true,write:false,platform:'node',format:'esm',jsx:'automatic',plugins:[{name:'fixture',setup(b){
const fixtures={
react:'export const useState=v=>globalThis.viewUI.state(v),useRef=v=>globalThis.viewUI.ref(v),useEffect=(f,d)=>globalThis.viewUI.effect(f,d),useMemo=(f,d)=>globalThis.viewUI.memo(f,d);',
'react/jsx-runtime':'export const jsx=(type,props)=>({type,props}),jsxs=jsx;',
'@nodedc/map-cesium-react':'export const CesiumMapRenderer="Map",initialMapRuntimeState={phase:"ready",providers:{}};',
'@nodedc/ui-react':'export const Description="Description",Button="Button",Icon="Icon",IconButton="IconButton",Switch="Switch",Window="Window";',
'../../../core/fleet/vps':'export const useTrackerTelemetry=()=>globalThis.viewUI.telemetry;',
'../../../core/map/mapView':'export const defaultMapViewDocument=()=>({view:{camera:{longitude:0,latitude:0,height:40000,heading:0,pitch:-50,roll:0},layerVisibility:{imagery:true,terrain:true,buildings:true,grid:false,targets:true},visualSettings:{}}}),encodeMapViewPut=()=>({view:{ghost_pins:{presentation:{}}}});',
'../../../core/map/useMapRecovery':'export const useMapRecovery=()=>{};',
'../../../components/map/mapPresentation':'export const mapPresentation=v=>v;',
'../../../../../../packages/sensor-ui/src/ObservationHeader':'export const ObservationHeader="Header";',
};
b.onResolve({filter:/.*/},a=>fixtures[a.path]?{path:a.path,namespace:'fixture'}:undefined);
b.onLoad({filter:/.*/,namespace:'fixture'},a=>({contents:fixtures[a.path]}));
}}]});
const {ObservationMap}=await import('data:text/javascript;base64,'+Buffer.from(b.outputFiles[0].contents).toString('base64'));
const camera={longitude:37,latitude:55,height:600,heading:137,pitch:-28,roll:3};
const layers={imagery:true,terrain:true,buildings:false,grid:false,targets:true};
const doc=(value=camera)=>({schema:'missioncore.observation-map/v1',camera:value,layers});
function find(v,type){if(!v||typeof v!=='object')return null;if(Array.isArray(v)){for(const item of v){const hit=find(item,type);if(hit)return hit;}return null;}return v.type===type?v:find(v.props?.children,type);}
async function fixture(initial,run){
const old=new Map(['viewUI','localStorage','fetch'].map(k=>[k,globalThis[k]]));let slots=[],effects=[],queue=[],cursor=0,dirty=true,closed=false;
const h={value:{revision:initial?1:0,document:initial},puts:[],tree:null,gate:null,fail:false,
telemetry:{items:[{instance_id:'b2',name:'Arnavi',position_fresh:true,online:true,position:{longitude:38,latitude:56,measured_at:1,source:'gnss'}}]},
state(v){const i=cursor++;if(!(i in slots))slots[i]=typeof v==='function'?v():v;return[slots[i],v=>{slots[i]=typeof v==='function'?v(slots[i]):v;dirty=true;}];},
ref(v){const i=cursor++;return slots[i]??={current:v};},
memo(f,d){const i=cursor++;if(!slots[i]||d.some((v,j)=>v!==slots[i].d[j]))slots[i]={d,v:f()};return slots[i].v;},
effect(f,d){const i=cursor++;if(!effects[i]||d.some((v,j)=>v!==effects[i].d[j])){const before=effects[i];effects[i]={d};queue.push(()=>{before?.cleanup?.();effects[i].cleanup=f();});}},
async settle(){for(let i=0;i<100;i++){await Promise.resolve();if(dirty&&!closed){dirty=false;cursor=0;h.tree=ObservationMap({vehicleID:'fixture',header:{}});for(const f of queue.splice(0))f();}}},
close(){closed=true;effects.forEach(e=>e?.cleanup?.());},
reopen(){h.close();slots=[];effects=[];queue=[];closed=false;dirty=true;},
};
globalThis.viewUI=h;globalThis.localStorage={getItem:()=>null};
globalThis.fetch=async(_url,o)=>{if(h.fail)return new Response('{}',{status:503});if(o.method==='PUT'){const v=JSON.parse(o.body);h.puts.push(v);if(h.gate)await h.gate;if(v.expected_revision!==h.value.revision)return new Response('{"detail":"conflict"}',{status:409});h.value={revision:h.value.revision+1,document:v.document};}return new Response(JSON.stringify(h.value));};
try{await run(h);}finally{h.close();await h.settle();for(const[k,v]of old){if(v===undefined)delete globalThis[k];else globalThis[k]=v;}}
}
test('saved Cesium tilt wins over tracker arrival and browser cache; reopen waits for camera write',()=>fixture(doc(),async h=>{
await h.settle();assert.deepEqual(find(h.tree,'Map').props.camera,camera);assert.equal(h.puts.length,0);assert.deepEqual(find(h.tree,'Map').props.layers,layers);
let release;h.gate=new Promise(r=>release=r);const moved={...camera,heading:220,pitch:-17};find(h.tree,'Map').props.onCameraChange(moved);await h.settle();h.reopen();await h.settle();assert.equal(find(h.tree,'Map'),null);
release();h.gate=null;await h.settle();assert.deepEqual(find(h.tree,'Map').props.camera,moved);assert.deepEqual(h.value.document.camera,moved);
}));
test('new map centers once; later telemetry and renderer recovery do not reset its angle',()=>fixture(null,async h=>{
await h.settle();assert.equal(find(h.tree,'Map').props.camera.latitude,56);assert.equal(h.puts.length,1);
find(h.tree,'Map').props.onCameraChange(camera);await h.settle();h.telemetry.items[0].position.latitude=58;h.reopen();await h.settle();assert.deepEqual(find(h.tree,'Map').props.camera,camera);assert.equal(h.puts.length,2);
}));
test('failed map profile read cannot render or overwrite defaults',()=>fixture(doc(),async h=>{
h.fail=true;await h.settle();assert.equal(find(h.tree,'Map'),null);assert.equal(h.puts.length,0);assert.deepEqual(h.value.document,doc());
}));
@@ -40,6 +40,7 @@ const {BoardObservationCenter}=await component('../src/workspaces/fleet/observat
'../../../components/rover/RoverTelemetry':'export const RoverTelemetry="RoverTelemetry",roverTelemetryMinimum=()=>({width:1,height:1});',
});
const {RoverView}=await component('../src/components/rover/RoverView.tsx',{
'../../core/observation/useObservationView':'export const useObservationView=()=>({ready:true,document:{model:""},update:()=>{},retry:()=>{},error:null});',
'../../core/fleet/roverObservation':'export const roverObservationStatus=()=>({label:null,pulse:false});',
'../../core/fleet/roverInput':'export const keysFor=()=>[],roverSettings=()=>({mode:"tank",model:"",currentA:34.5,throttlePercent:20}),persistableRoverSettings=()=>false,roverNumberInput=Number;',
'../../core/fleet/roverDevEvents':'export const roverDevEvent=()=>{};',
@@ -65,10 +65,10 @@ test("browser upload remains same-origin, resumable and token-free", async () =>
assert.match(sourceFiles, /ровно одна сцена \.lcc или \.lcc2/);
assert.match(sourceFiles, /отдельные архивы ZIP, RAR или 7z/);
assert.doesNotMatch(window, /Загружаем источник/);
assert.match(window, /считаем время/);
assert.match(window, /locationImports\.enqueue[\s\S]*onClose\(\)/);
});
test("failed simulation can restart from its retained Mission Core source", async () => {
test("failed simulation can request restart from its retained source", async () => {
const [core, workspace] = await Promise.all([
read("core/simulation/projects.ts"),
read("components/simulation/SimulationSourceImport.tsx"),
+6 -3
View File
@@ -1,4 +1,4 @@
import { createReadStream, cpSync, existsSync, statSync } from "node:fs";
import { createReadStream, cpSync, existsSync, readFileSync, statSync } from "node:fs";
import { createRequire } from "node:module";
import { dirname, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
@@ -9,6 +9,8 @@ import wasm from "vite-plugin-wasm";
const mapAdapterEntry = fileURLToPath(import.meta.resolve("@nodedc/map-cesium-react"));
const cesiumPackageJson = createRequire(mapAdapterEntry).resolve("cesium/package.json");
const cesiumRuntimeVersion = JSON.parse(readFileSync(cesiumPackageJson, "utf8")).version as string;
const cesiumAssetBase = `/cesium/${cesiumRuntimeVersion}`;
const cesiumBuildRoot = resolve(
dirname(cesiumPackageJson),
"Build",
@@ -21,11 +23,11 @@ function cesiumRuntimeAssets(): Plugin {
name: "mission-core-cesium-runtime-assets",
config: () => ({
define: {
CESIUM_BASE_URL: JSON.stringify("/cesium"),
CESIUM_BASE_URL: JSON.stringify(cesiumAssetBase),
},
}),
configureServer(server) {
server.middlewares.use("/cesium", (request, response, next) => {
server.middlewares.use(cesiumAssetBase, (request, response, next) => {
const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
const target = resolve(cesiumBuildRoot, `.${decodeURIComponent(pathname)}`);
if (!target.startsWith(`${cesiumBuildRoot}${sep}`) || !existsSync(target)) {
@@ -54,6 +56,7 @@ function cesiumRuntimeAssets(): Plugin {
process.cwd(),
typeof options.dir === "string" ? options.dir : "dist",
"cesium",
cesiumRuntimeVersion,
);
cesiumRuntimeDirectories.forEach((directory) => {
cpSync(
@@ -0,0 +1,45 @@
# Collapsible application navigation
Owner request: 2026-11-15. This is shared application chrome, applying to Park,
Control, Missions, Data, System and LAB. The operator collapses the left navigation
to gain workspace width while keeping direct route access.
## Composition and ownership
Use the Design Guideline `ApplicationShell` + `AdminNavigationPanel` contract.
The shell owns a single collapse state and synchronizes column width with the
workspace offset. Individual roots, including SystemNavigationPanel, consume the
same provider. No BIM-specific sidebar or application-local control CSS is added.
A separate BIM implementation was rejected because all application roots need
identical behavior; hiding the whole navigation was rejected because routes must
remain directly accessible.
Expanded: a circular left chevron beside the existing close control.
Collapsed: a 4.55rem icon rail, a right chevron, no title, text or close control.
Icon routes retain their names, active state and keyboard/hover tooltips. Escape
closes a tooltip, not the navigation. Context selectors and secondary header
controls return when expanded. Keyboard focus colors only the icon circle.
The 440ms shell easing animates the navigation width and workspace position
together. Reduced-motion mode disables the animation. Workspace content remains
mounted; renderer geometry follows its existing resize observer. The right
application panel keeps its original width. Existing mobile single-panel
presentation remains in effect.
Collapse state persists between roots and workspace closes/reopens in the mounted
shell. The shared component does not write browser storage. It exposes controlled
state callbacks for a host-owned persistent preference if needed.
## Acceptance
- Shared DOM interaction check: controlled and standalone use, collapse/expand,
route changes, close/reopen, hidden actions, accessible names, tooltip Escape,
retained workspace instance and unsaved input.
- Registry, theme and typography checks; all Design Guideline workspace types and
catalog production build.
- Mission Core architecture gate, full TypeScript, 1,605 frontend tests and
production build.
- Canonical 127.0.0.1:8000 browser: all six roots retain compact navigation;
expanded and compact layouts, Enter/Tab/Escape and real project/fleet navigation.
At 1440px: rail width 72.8px, workspace left edge 112.8px (20px outer pad +
rail + 20px gap). Temporary browser viewport override reset after QA.
+177 -2
View File
@@ -1,7 +1,153 @@
# Portable BIM module in Mission Core
## Current delivery · Cesium Gaussian cleanup · 16 November 2026
## Current cloud slice · 15 November 2026
Portable client **0.2.57**, host **0.2.18**; the separate BIM conversion Worker
remains **0.2.12**. Gaussian Pipeline Worker is **6afbf43**, deployed into the
existing container with the existing native GPU executor. Cesium stays 1.147.0;
provider routes and Synology tile caches are unchanged.
Project settings now expose Gaussian processing settings: curved trajectory
corridor (15 m per side), optional vertical limits, conservative floater cleanup
and **Пересчитать**. Originals and prepared source remain shared by SHA-256 with
LAB. A durable replacement intent survives closing the form. Only verified ready
artifacts replace the current scene, preserving the exact geographic pose and
placement origin; then Worker acknowledges old-owner deletion and Core retires
its old ready copy. First drop/import uses the same settings form.
Live Novinskiy result: **16,901,217 splats**, 7.17% fewer; corridor removed
1,275,353 and the floater filter another 29,436. Core has 1,386,147,270 bytes of
Cesium artifacts plus its 397,648-byte manifest. Old result absent on both hosts,
work/staging empty; LAB still owns the same physical archive. Settings close /
reopen, ready rendering and exact pose preservation passed. See
`outputs/cesium-cleanup-20261116/RESULT.md` for private execution evidence and
module `docs/cesium-gaussians.md` for lifecycle and qualification limits.
Validation: 90 Pipeline, 182 client, 175 module server and 29 Core simulation/adapter tests;
client types and integrated production build passed. Real LCC2, fused trajectory
frames, native fullscreen and physical power-loss acceptance remain unqualified.
## Earlier delivery · Cesium project map · 16 November 2026
Portable client **0.2.47**, host **0.2.15**, Worker unchanged **0.2.12**.
Exact source identities and artifact hashes are in `vendor/bim/*release.json`.
The map Layers menu now selects **Libre / Cesium**. Cesium uses the existing
`@nodedc/map-cesium-react` adapter (0.1.2), CesiumJS **1.147.0**, runtime BFF and
Map Gateway. Terrain, imagery and buildings retain their existing server/cache
ownership. No browser credentials, separate Viewer service or new cache.
The 1.143 → 1.147 upgrade, cache-byte verification and exercised runtime rollback
are recorded in [CESIUM_UPGRADE.md](CESIUM_UPGRADE.md).
All configured project markers remain available. Multiple nearby ready BIM
previews are admitted by distance and memory budgets, independently of catalog
selection. Settings support terrain click/drag, view-center placement, heading
and terrain-relative/ellipsoid height. The renderer draws verified ready
Fragments; Worker sources and conversions are unchanged. Map provider, camera
and provider visibility persist in the BIM workspace document.
172 BIM client / 168 Python / 8 shared adapter checks passed; Core frontend
1608, focused BIM/Map API 15, architecture, typography, types and production
build passed. Live BUH geometry, terrain placement and Cancel were checked on
canonical :8000. Detailed residency is bounded to 8 nearby models / 128 MiB live
geometry; millions of complete IFC meshes and NAS Internet-outage failover are
not newly qualified. See the module's `docs/project-map.md` for contracts/limits.
Previous compact inspector/selection changes were committed and pushed before
this delivery. Existing user uploads were not interrupted during UI validation.
## Notes, project state and upload delivery · 16 November 2026
Portable client **0.2.32**, host and single BIM Worker **0.2.12**. The current
release identities and artifact hashes are in `vendor/bim/*release.json`.
The sections below are dated earlier qualifications, not the current package pins.
Each material root in Hierarchy opens its own dockable Notes window. Notes have
list/tiles views, prepared thumbnails, same-version photo navigation, a separate
camera-view action, editing and deletion. File/storage actions remain with the
material in Hierarchy; active/error transfers use a separate temporary Uploads
window. Original photos remain on Worker; display/thumbnail WebP and the bounded
Core preview cache are unchanged. No new photos were admitted.
Each project owns a durable `project-views/<id>/meta.json`: camera, projection,
loaded/hidden layers, viewport preferences and docked/floating windows. KU Leuven
→ another project → KU Leuven preserved every viewer field exactly. Concurrent
conflicting edits showed a visible conflict and retained the newer document.
Project roots now have full-deletion confirmation and a durable retirement
outbox. Worker confirmation and local cleanup precede removal of the row;
shared data is retained for remaining owners. Only open/cancel was exercised
live; destructive/restart paths were covered with synthetic regression cases.
Interrupted chunk transfers reappear after reload. Reselecting a matching file
checks its full SHA-256 and resumes its acknowledged Worker offset without a
new version. No original file is cached on Core. Transient failures reconcile
Worker acknowledgement before bounded retries. SSH cleanup cannot leak a
capacity slot, and photo preview concurrency leaves capacity for source uploads.
Browser restart still requires file reselection; autonomous access to an old
File handle is not claimed. See the module's `docs/upload-recovery.md`.
Keyboard flight and mouse orbit now run together: movement key repeats do not
release the orbit pointer, and surface-pivot picking no longer clears held flight
keys. The actual-controller regression covers WASD/QE/arrows and changing heading.
Large-file acceptance: the Sadovaya LAS (7,448,522,823 bytes) resumed the existing
2 GiB partial upload after exact reselection, retained all 219,074,194 points,
and produced 1,944,796,856 bytes of ready Potree data. The complete product was
verified in Core and rendered in the viewport, including a fresh-page reopening
regression. Worker retains the source; staging and job scratch are empty.
The accepted source SHA-256 and conversion details are in the module's upload
recovery document. Native multi-GB intake across arbitrary browser termination
still requires reselecting the file; a disconnected browser cannot read it alone.
Validation: 107 module client, 161 module server, 2 Core adapter and 1608 Core
frontend tests passed; architecture, typography, types and production build
passed. Live notes list/tiles, gallery next/previous, keyboard and Escape passed.
IAB rejected native fullscreen, so that action is not newly accepted here.
Complete multiuser authorization and physical power-loss qualification remain open.
## LAS normalization correction · 15 November 2026
Only Worker advanced to module 0.2.10 / source 5029a39; host 0.2.9 and client
0.2.27 remain as installed below. A LAS 1.1 export using point format 3 now gets
a compatible 1.2 working header during conversion, without changing its archived
bytes. Nineteen targeted checks passed. Existing Novinskiy Boulevard intake was
retried through UI, converted (18,289,361 points), downloaded (202,335,776 bytes)
and rendered. Its original SHA-256 is unchanged and scratch is empty. No new
source upload, duplicate material or Core restart was needed.
## Notes and photo fixes · 15 November 2026
The preceding notes delivery used portable client 0.2.27 / host and single BIM Worker
0.2.9, from module source `60b88af9e84496191451819dd3ef19e9ec9b1c81`.
The Layers panel owns text/photo/camera notes beneath each material version.
Worker retains immutable originals and prepares bounded WebP images; Core keeps
metadata and a 64 MiB preview LRU. Originals stream only on explicit download.
Camera JPEGs carrying an MPF auxiliary frame now pass the same upload path as
ordinary JPEGs; viewing uses the primary frame and preserves every original byte.
Worker error codes survive the host/client boundary. Marker placement takes
priority over viewport gestures; camera viewpoint activation restores perspective.
Repeated archive admission preserves deleted-note tombstones and serializes each
archive batch. A retained project photo archive is an independent owner; deleting
a note does not implicitly destroy that archive.
The operator stopped further image downloads/imports. Final UI inventory is 1970
photographs (week17: 412, week18: 639, week20: 919) and one week21 text note.
1895 camera notes have source poses, 75 photos remain explicitly unplaced.
All original/display/thumbnail members exist. Incomplete download parts and photo
staging are empty; 6790 completed archive members remain on Worker, independently
of the smaller UI inventory. No more imports are queued.
Final live UI reupload of DSC_1777.JPG preserved SHA-256
`46539b1eeee91014ef8503b0d362c8c04c18c3994223fa2225e662484ea5e091` and
the shared archive inode, with the same 1971 notes before/after. The 14,806,653-byte
original renders through a 311,534-byte WebP. 13 focused notes/photo regressions,
93 module client checks, 1605 Core frontend baseline checks and the final
architecture/typecheck/production build passed. No claim of exact photo
reprojection, full multiuser/crash qualification or newly verified live deletion/
native fullscreen is made. Core :8000 and the qualified Worker remain running.
## Previous cloud slice · 15 November 2026
Host package 0.2.6 / Worker 0.2.3, portable viewer 0.2.22. PTS/LAS/LAZ are converted on the single isolated BIM Worker into immutable Potree 2 products. The actual Bridge_2 1.pts was uploaded through the LivingBIM Dataset UI: 85,515,903 points, 3,323,939,155 source bytes, 897,877,195 ready bytes. Only the verified ready set enters Core; source/CAS remain on Worker and owned staging/scratch are empty.
@@ -344,7 +490,7 @@ The trash action is full version retirement after explicit confirmation, separat
Worker remains one container on the same named volume, with the same CPU/RAM/PID/network boundary. All 22 unrelated containers present at deployment kept their identities. The six pre-existing source/product records were inventoried before replacement and verified afterward, including manifests, file lengths and SHA-256. The destructive qualification removed only its separately approved additional public fixture. No raw source is stored in Core.
Deletion-phase validation: 77 module Python tests, 14 browser contracts, 2 Core adapter tests, 1,596 Core frontend tests, typography/typecheck and production build. The deletion tests include a real forced process exit followed by queue/journal/scratch recovery, active-process cancellation, lost acknowledgement and partial unlink. Detailed current UI/Worker evidence is in the module's entry qualification; initial IFC facts above remain dated evidence.
Deletion-phase validation: 77 module Python tests, 14 browser contracts, 29 Core simulation/adapter tests, 1,596 Core frontend tests, typography/typecheck and production build. The deletion tests include a real forced process exit followed by queue/journal/scratch recovery, active-process cancellation, lost acknowledgement and partial unlink. Detailed current UI/Worker evidence is in the module's entry qualification; initial IFC facts above remain dated evidence.
Live UI fault qualification: with Worker stopped, confirmation enqueued the temporary version deletion and the row retained its central progress/status. Core restarted while Worker remained offline; the durable task and row returned. Starting the same Worker completed deletion automatically, then the row disappeared. Worker acknowledgement, removal of temporary source/product paths and local copy, empty scratch and preservation of all six previous materials were verified. Browser 0.1.7 also restores viewer admission after Core restart (three regressions plus live open-model restart); it does not readmit retired products. Final 1280/700 px layout and individual Glass V4 controls with transparent rails were checked. Design Guideline source `3d4c4aaa082d75de8e1a3a63abfa19b863f674c9`. See the module entry qualification and compact deletion evidence for scope.
@@ -398,6 +544,14 @@ buttons share individual Glass V4, with no common capsule. Tree rows have both
visibility eyes and plain `i` actions. Visibility applies to complete IFC
subtrees without repeating a spatial traversal for each already known ID.
2026-11-17 visibility persistence: client 0.2.74 / host 0.2.30 stores sparse
`viewer.hidden_nodes` in the per-project workspace. Project/category/product/IFC
branch eyes are independent masks; turning a parent back on preserves children.
Absent/null masks migrate legacy `hidden_layers`; explicit `[]` means all gates
open. Eye intent writes before React unmount and is reapplied as models load.
Temporary isolation does not overwrite the saved choices. Previously unsaved
IFC choices cannot be reconstructed. Acceptance: `outputs/view-visibility-20261117/RESULT.md`.
Navigation Cube settings include face/edge colors and independent transparency,
text and hover colors; selection color is configurable. Host 0.1.4 validates and
merges nested preferences, preserving new fields when old clients save.
@@ -443,3 +597,24 @@ gaps; no claim of full crash or multiuser readiness. Installed Worker source fil
match the audited archive/queue/deletion/API code; live staging/scratch have no files.
No operational Worker mutation was performed. See the
[full audit](https://git.dcserve.ru/dctouch/NODEDC_BIM_MOD/src/branch/feat/portable-bim-ifc/docs/ifc-lifecycle-audit-20261115.md).
## Notes workflow qualification — 2026-11-17
The portable viewer 0.2.76 / host 0.2.33 adds surface-first notes with multiple image
attachments, per-layer list/tile filters and favorites. A click fixes the anchor before
the editor opens. Photo previews remain open while the scene moves to their viewpoint.
Marker appearance and tile preferences live in the project workspace; favorite state is
versioned note metadata on Worker. Design Guideline 0.7.6 supplies the canonical star
and glyph-only action surface.
Worker runs BIM 0.2.32 (e314f1e), with unchanged named data volume and no new ports.
The host-only 0.2.33 cleanup removes derived previews after Worker acknowledgement,
retains shared attachments across notes/projects, and retries after local disk failure.
No original image is admitted into the Core preview cache.
Validation: 215 BIM Python tests, 212 client tests, Core adapter tests (2), frontend
build/typecheck/typography and live Chrome acceptance. The two synthetic JPEGs and their
temporary note were removed; all 1971 baseline notes remain. Native Finder-to-editor drag
was not separately automated; its rendered drop handler has regression coverage.
Detailed evidence: `outputs/bim-notes-20261117/RESULT.md` on the operator workspace.
+186
View File
@@ -0,0 +1,186 @@
# Cesium services and NAS outage routing
Implemented 2026-11-17. Cesium remains at 1.147.0. This change does not migrate,
reindex, clear or copy Synology tiles. Existing cache identity and upgrade rules
remain in [CESIUM_UPGRADE.md](CESIUM_UPGRADE.md).
## Operator surface
Profile → Settings → Services contains a service selector. Select **Cesium ion**
to reveal its connection mode and token field. Check access and Save are canonical
circular icon buttons at the top right of the service card. Saved credentials are
never filled back into the browser. Clear-token appears only when configured.
Product copy names the cache host **Сервер хранения локальных данных**; Synology is
an infrastructure detail. Persistent missing-token, last-route and saved-success
lines are intentionally absent. Explicit verification results and actionable
errors are retained. A canonical StatusBadge indicator precedes Cesium ion in the
selector: neutral for absent/unverified credentials, pulsing yellow while checking,
yellow for a failed check, green for confirmed asset permissions. Selecting Cesium
or saving credentials checks access automatically; details appear only after an
explicit Check access. The tooltip explains the state. This is token permission
status, not a claim that every provider tile is reachable.
This is installation-wide service configuration, not a per-map/project setting
or a hardware entry in System. The admitted composition uses Environment Settings,
SettingsCard, Select, TextField, Description, IconButton and registry icons. An
individual map settings panel was rejected because it would duplicate credentials
and leave Fleet, Observation Center and architectural maps with divergent routes.
The state grammar is: no service selected, loading, editable, checking/saving,
success, missing token, explicit safe error, revision conflict. No token means the
existing NAS route still works; it cannot enable the independent online route.
## Routing contract
All consumers retain the existing Core `/api/v1/map/gateway/*` URLs and endpoint
contract (`credentialMode: gateway`). `MapServiceRoutes` chooses the backend:
| Mode | Behavior |
| --- | --- |
| auto | Probe NAS, use it while reachable; otherwise use the original provider through Core. |
| direct | Use the original provider through Core, without the NAS cache. |
| gateway | Use NAS only; unavailable NAS remains an explicit error. |
NAS health has a two-second timeout and a single shared probe with a 15-second
cooldown. Successful NAS recovery returns subsequent requests to its existing
route. A transport failure opens the fallback cooldown. An upstream HTTP 502/503
falls back for that request without marking the cache server unavailable: warm
tiles must remain usable when only its internet exit is down. NAS 401, 403,
404 and 504 are preserved: these can represent authorization, absent data or an
offline-cache policy refusal, not a broken NAS connection. Existing tile URLs and
cache query parameters are forwarded unchanged. No administrative cache endpoint
is called. Response header `x-nodedc-map-route` identifies the chosen transport.
Direct transport resolves ion assets 1 (terrain), 2 (Bing imagery) and 96188
(buildings). Only metadata and short-lived credentials are retained in RAM.
Binary tiles stream to the browser; Core creates no persistent tile store and
returns `Cache-Control: no-store`. Range and HEAD requests remain supported.
Provider URLs are allowlisted and ion credentials are restricted to their asset
directory. Redirects are refused. Credentials stay on the server, including the
Bing query key; HTTPX provider URL logging is redacted.
Provider contract changes, unavailable assets and rejected credentials are
reported explicitly. This is not a fallback for private imported Gaussian
products: their existing local ready-product lifecycle is unchanged.
## Secret storage and activation
Core owns `data_dir/services/cesium-ion/settings.json` (0600 file, 0700 service
directory), outside Git and browser profile JSON. Writes use an atomic replace,
fsync and revision checks. Corrupt configuration fails closed instead of silently
replacing it with defaults. API reads expose only configuration status, not the
token. Mutations require a loopback caller and same-origin JSON requests.
The operator enters the token directly in the UI. Check access verifies the three
asset endpoint permissions. Saving a new token repeats this validation before
replacing a working token. It does not prove every tile can be downloaded. URL-
restricted ion tokens must permit the canonical operator origin
`http://127.0.0.1:8000/`, which Core sends as a fixed provider Referer.
The Core token supplies the independent online route for every Core map. Existing
NAS credentials remain owned by Map Gateway and are **not** remotely replaced by
this form. When NAS is available it uses its current credential/cache policy.
There is no dependency on Ops, SMB or Synology for reading/saving Core settings.
After a save, subsequent requests use the new policy. Observation maps with the
recovery hook are notified; an already failed map may need reopening/retry. Do
not forcibly remount an architectural editor with unsaved placement edits.
## Original token/outage acceptance · 17 November 2026
- 30 backend tests: old BFF contract, NAS outage/recovery, unchanged cache URLs,
concurrent single-probe behavior, credential redaction, path/host restrictions,
private storage, revision conflicts and same-origin API boundaries.
- Four focused frontend adapter/indicator tests, existing 1619 frontend tests, application
architecture checks, typecheck, Ruff, focused mypy and production build passed.
- Final selector/header-button adjustment passed the production build/typecheck
and typography gate; UI selection and saving were exercised on port 8000.
- With the real NAS off and no configured Core token, the real service returns
`cesium_token_required` promptly. The Settings UI is usable without NAS.
- The operator saved a valid token (revision 4). With NAS off, real health and
all three asset endpoints succeed via `direct`; terrain layer.json, Bing imagery
metadata and buildings tileset.json return 200. A quantized-mesh terrain tile
returns 200 (15,069 bytes). No test tile was retained on disk.
- UI acceptance confirms the green token indicator and existing local Gaussian
rendering. Full satellite rendering is **not accepted**: the Bing tile host
`ecn.t0.tiles.virtualearth.net` is unreachable from this Mac (direct HTTPS
reports `No route to host`; Core reports `cesium_provider_unavailable`, 503).
Metadata/token success does not establish satellite tile connectivity. No VPN,
DNS or route changes were made to bypass this failure.
- Real NAS recovery/cache reuse has not been tested while the owner's NAS is off.
## Real acceptance after token/NAS availability
1. Save a valid token; with NAS off, inspect imagery, terrain and buildings in
architectural maps and Observation Center. Confirm `x-nodedc-map-route: direct`
and absence of new Core tile storage.
2. Turn NAS on. Allow the 15-second probe cooldown to expire, then move the map.
Confirm `x-nodedc-map-route: gateway` and the existing NAS cache-hit headers.
3. Compare a bounded set of previously cached physical files and existing cache
counters before/after a repeat view; inspect only, do not request a refresh,
purge, import or full cache walk. Confirm a new area follows the NAS's existing
read-through write policy.
4. Disable NAS again and verify recovery with the same map open. No cache rebuild
is an acceptable substitute for diagnosing a routing regression.
## Rollback
Selecting **Сервер хранения локальных данных** disables the new direct transport without
altering cache contents or deleting the saved token. For a source rollback, revert
only the Cesium services changes (especially the `settings_path` wiring in
`web/app.py`), preserving unrelated work in shared files. `MapGatewayProxy`
without `settings_path` retains its previous NAS-only behavior. Never reset the
whole dirty checkout or touch NAS storage as part of this rollback.
## Selectable VPS transport · 17 November 2026
System → VPS can install and pair **Маршрутизация трафика** alongside the existing
services. Profile → Settings → Services → Cesium ion → Routing selects a connected
service or **Текущий маршрут**. The choice is installation-wide, shared by Fleet,
Observation Center and architectural maps. It does not change the machine's
default route, VPN, DNS or application URLs. The initial transport profile only
allows Cesium/Bing GET/HEAD; unrelated external services require their own scoped
profile and client integration.
The independent `egress_vps` package lives in `NODEDC_MISSION_CORE_ARNAVI-VPS`;
its operating contract is `docs/EGRESS_SERVICE.md` in that repository. Core stores
paired credentials in the private Fleet `egress.sqlite3`. TLS 1.3 and an exact
certificate fingerprint are checked before sending credentials. Provider and
relay credentials are separate. Binary responses stream without a Core/VPS tile
store. Disconnecting a route used by Cesium is guarded.
For direct mode the selected relay carries Core's provider requests. For NAS
cache mode the prepared Gateway adapter accepts a separately signed, short-lived
`nodedc.map-egress/v1` request binding. Cache lookup still precedes external fetch;
canonical URLs, keys and physical objects remain unchanged. Gateway deployment
and private signing-key provisioning are required before selecting this mode.
Missing signing material blocks activation even while NAS is offline, preventing
a route that works only until the cache server returns. The prepared adapter is
documented in `platform/services/map-gateway/EGRESS.md`.
**Live state:** routing service 0.1.0 is installed on McHost at port 19446 and
paired with the canonical Core on port 8000. The installer is published in the
Fleet catalog. The NAS adapter is prepared and tested but **not deployed**;
no delegation key has been provisioned. Cesium's selected route remains unchanged.
Real authenticated checks from McHost received CloudFront country-block 403 for
assets 1, 2 and 96188. Core reports `cesium_egress_region_denied`, rather than an
invalid-token error. An attempted save returns 422 and leaves both saved route
and revision unchanged. UI acceptance exercised the route selector, yellow
indicator and explicit per-asset errors, then discarded the draft selection.
The owner has no other VPS. A working external exit channel remains a prerequisite;
installing a relay on the same blocked public IP cannot supply it. No automatic
switch to an unqualified transport is allowed.
Validation: 24 VPS tests; 58 focused Core tests followed by 8 focused egress tests
after the stream-cleanup regression fix; 4 frontend Cesium tests, typography
gate, typecheck and production build. Gateway delegation tests and the existing
credential-boundary, live-cache-fallback and streaming-cache-fill smoke checks
passed. Live wrong relay credential returns 403, private target returns 400, and
wrong certificate pin is rejected. All five McHost services remain active; the
new unit reports zero restarts. These checks do not constitute live NAS-to-VPS or
successful Cesium tile acceptance.
Activation requires a reachable provider exit, real asset and representative
tile checks, then canonical Gateway plan/apply deployment and secret provisioning.
Recheck warm hits, a bounded cold fill, NAS outage/recovery and unchanged cache
objects. The current route remains the rollback until those checks pass.
+181
View File
@@ -0,0 +1,181 @@
# Cesium upgrade and cache-preserving rollback
## Delivered on 16 November 2026
The canonical Mission Core service on `127.0.0.1:8000` now uses **CesiumJS
1.147.0**, supplied by Design Guideline `@nodedc/map-cesium-react` **0.1.2**.
The prior release was CesiumJS 1.143.0 / adapter 0.1.1. BIM client 0.2.47,
host 0.2.15 and Worker 0.2.12 did not require new distributions.
Latest stable was checked against the official
[release history](https://github.com/CesiumGS/cesium/releases),
[1.147 package](https://raw.githubusercontent.com/CesiumGS/cesium/1.147/package.json)
and [changelog](https://raw.githubusercontent.com/CesiumGS/cesium/1.147/CHANGES.md).
It was released on 2 November 2026. Pin the exact version; do not resolve a future
release implicitly when reproducing this delivery.
Only the shared client dependency, matching BFF version declaration, runtime
asset paths, tests and documentation changed. The NAS Gateway was **not deployed
or reconfigured**. Updating the DG catalog diagnostic in source does not establish
that the separately deployed Foundry application has upgraded.
## Preserve this boundary
```text
Mission Core / BIM map
-> /api/v1/map/runtime-config
-> /api/v1/map/gateway/ion/assets/{id}/endpoint
-> /api/v1/map/gateway/cache?url=...
-> existing Map Gateway on Synology
-> existing persistent TileCache / upstream on a real miss
```
At acceptance the Core internal Gateway URL was `http://127.0.0.1:18103`, an
existing SSH tunnel to DC_1221RP (`100.109.216.21:18103`). The operator identity,
asset allowlist (terrain 1, imagery 2, buildings 96188) and credential boundary
are unchanged. Credentials remain server-side.
Live cache host path:
`/volume1/docker/nodedc-platform/map-gateway/live-tile-cache`, mounted at
`/var/lib/nodedc-map-live-cache`. The sibling offline snapshot is read-only and
reported zero entries at this acceptance. The live cache reports persistence,
append-only/no-eviction writes and a 20 GiB quota. These are Gateway/runtime
observations and the existing deployment contract; root-level NAS filesystem
inventory was not available to the operator account.
The index remains v1. Objects retain their content-key paths. Credential-free
canonical URL hashing, sorted query parameters, Bing host normalization and
removal of client revision/cache-intent parameters remain Gateway responsibilities.
Do not inject a Cesium version into tile URLs, replace provider revisions, change
mounts, delete the index or switch to an empty cache to make an upgrade appear
healthy. A changed resource URL must first be compared with its previous
canonical identity. Fix the binding or roll back the client before considering
any separate data migration.
Client **code assets** now use `/cesium/1.147.0/{Workers,Assets,Widgets,ThirdParty}`.
This prevents a stale tab from mixing an old JS bundle with new workers. It is
independent of tile identities. During this transition, the existing unversioned
1.143 assets and previous hashed frontend chunks were retained in the live dist
without overwriting new files. Only one previous generation is retained; retire
it after old tabs have reloaded and the rollback retention decision is made.
## Pipeline used
1. Record clean committed source baselines and inspect unrelated work in the
shared checkouts. Do not reset another task's changes or create a second Core.
2. Record BFF runtime configuration, Gateway health/counts and representative
cached metadata/binary hashes before changing the client. Check available disk
and active imports before restarting the canonical Core process.
3. Pin the previous built interface with a hash manifest. Keep the previous lock
files and version declaration. No tile archive, NAS snapshot or new cache is
required for this client-only rollback.
4. Update the shared adapter dependency and version contract together; refresh
exact lock files. Core continues importing this adapter. Review upstream API,
Resource/proxy behavior and Camera changes; do not introduce a second viewer.
5. Build/test DG, Core frontend and Map BFF; publish the matched frontend and
server declaration on the existing service. Retain previous code assets for
already-open tabs. Never interrupt active uploads to run a smoke test.
6. Check Libre/Cesium switching, existing terrain/imagery/buildings, project focus,
restored camera and the browser console. Compare warmed resource bytes and
Gateway counters; an ordinary cache miss may append data but is not a reason
to rebuild the cache.
7. Actually restore the old interface and BFF declaration, restart the same Core,
verify 1.143 from HTTP and render the map. Then reapply the matched 1.147 pair,
restart and verify again. This rehearsal was completed successfully.
8. Preserve the bounded rollback archive and compact evidence; remove only the
task's extracted duplicate builds/npm scratch. Commit only owned paths and
record current delivery, limitations and rollback in Ops.
## Acceptance evidence
Evidence directory (local, not a second checkout):
`.runtime/cesium-upgrade-20261116/`.
- Initial Gateway cache: **72,624 entries / 1,694,493,925 bytes**.
- After normal missing-resource reads: **72,627 / 1,694,980,798 bytes**.
There was no reset or decrease. Further UI exploration can append more tiles.
- Six warmed resources before/after activation had identical SHA-256 values:
terrain `layer.json`, building `tileset.json`, child metadata, terrain binary,
building `.b3dm` and Bing imagery. The first four were already cached at the
initial probe; the last two were first warmed before client activation.
- During the controlled six-read comparison: egress **774 -> 774**, upstream
**774 -> 774**, misses **323 -> 323**, refreshes **0 -> 0**; hit +3 and stale-hit
+3. Responses were `live-cache-hit` / `live-cache-stale`.
- `cache-verification.json` retains exact public resource identities, hashes and
before/after counters. `rollback-runtime-verified.json` records the old runtime
declaration after the real rollback. The pinned manifest verifies old artifacts.
- Shared adapter: **12 tests**; Gateway/cache Resource contract: **2 tests**;
registry valid. Core frontend: **1,608 tests**, typecheck and production build;
focused Python Map checks passed. New tests exercise actual Cesium Resource
derived URLs, incompatible runtime rejection and Camera focus/persistence.
- UI rendered existing imagery, terrain and buildings. Libre/Cesium switching
and project focus were exercised. Both old and new runtime worker URLs returned
JavaScript successfully. A one-off too-close camera transition was observed;
controlled repeats on old and new versions both focused correctly. No proven
root cause or camera fix is claimed.
Limits: no NAS-wide Internet interruption, expired-Ion-endpoint/new-session
offline test or complete filesystem hash inventory was performed. Warm cached
reads without additional egress are established; uncached coverage still requires
the upstream. At final UI verification all current projects had `map_product_id`
unset, so project markers were checked; ready BIM mesh placement acceptance
remains the earlier dated qualification in `docs/BIM_MODULE.md`, not a fresh
1.147 mesh rendering claim. Do not mark the separately deployed Foundry upgraded.
## Rollback artifact and procedure
Pinned directory:
`.runtime/cesium-upgrade-20261116/rollback-1.143.0/`.
`control-station-dist.tar.gz` is **120,787,409 bytes** (about 121 MB), containing
the previous built `dist/`, with SHA-256:
```text
5eae647f1e326936428851f9ae2cff8e53b711d928d67018fbe69cffb32bf049
```
`manifest.json` contains hashes of the archive, old DG/Core locks, adapter
package and old `map_api.py`. This is a copy of client code, **not tile data**.
Keep it pinned until explicitly superseded by another qualified rollback.
Source baselines already published before the upgrade:
| Repository | Baseline |
| --- | --- |
| Mission Core | `a80e3a8ff53b6d351d05bd1381a2f8033de6a202` |
| Design Guideline | `f4e7369eeccc9745c30ddf6476810ddc1efd523d` |
| BIM Mod | `581666957ed3855906be34081f5ebdfe04307b1a` |
For an immediate runtime rollback:
1. Verify the archive hash against `manifest.json`; confirm there are no active
browser uploads before the managed Core restart. Record the current matched
version and retain its built dist temporarily for reapplication.
2. Extract the archive into a **new empty task scratch directory**, using safe
tar extraction. Rename the current `apps/control-station/dist` to a bounded
candidate path, then rename the extracted `dist` into that canonical location.
Do not overlay files from two bundles or touch `.runtime/mission-core` data.
3. Change only `CESIUM_RENDERER_VERSION` in `src/k1link/web/map_api.py` back to
`1.143.0`. Do not replace the entire source file if it has newer unrelated
changes. The built old frontend already contains the matched adapter.
4. Restart the existing managed service (operator Mac):
```sh
launchctl kickstart -k gui/$(id -u)/com.nodedc.mission-core.local
```
5. Verify `/api/v1/map/runtime-config` reports 1.143.0; reload the map and verify
known cached imagery/terrain/buildings through the unchanged Gateway. A stale
incompatible tab must reload, not bypass the version check.
6. To reapply, restore the saved 1.147 dist, set the BFF declaration to 1.147.0,
restart the same service and repeat HTTP/UI checks. Retire extracted duplicate
directories only after verifying the pinned rollback archive remains intact.
An archive rollback changes the served runtime only. Before a subsequent source
build, either reapply the matching source release or revert the **owned upgrade
commits** in DG/Core and reinstall their matching locks. Never reset the shared
checkouts wholesale. No rollback step modifies NAS cache mounts/index/objects,
provider metadata, project JSON, Worker sources or prepared BIM products.
Ops records: [MISSIONCOR-100](https://ops.nodedc.ru/nodedc/browse/MISSIONCOR-100)
and [DCPLATFORM-61](https://ops.nodedc.ru/nodedc/browse/DCPLATFORM-61).
@@ -0,0 +1,42 @@
# Simulation import and storage acceptance — 2026-11-16
## Current import contract
LAB → Simulations uses the shared window-header plus button. The plus opens the import form; dropping a supported PLY or LCC/LCC2 archive/folder into the main workspace admits a background import directly. The whole workspace displays the supported-input overlay. The import queue is independent of the modal and workspace lifetime. File handles still belong to the browser session: browser reload is not resumable-file-handle acceptance.
Core stages upload bytes only until the Worker retains the original and returns a verified receipt. Worker runs the conversion; Core publishes the verified SOG/streamed rendering product. Original downloads stream from Worker. The old raw-PLY local import endpoint returns 410. Missing Worker does not enable a local conversion fallback.
LCC/LCC2 follows upload → retained original → ingest/extracted-source receipt → build → verified ready artifacts. The original and extracted-source receipts have separate deletion lifecycles. Gaussian PLY currently produces visual products, not a collision mesh; opening the viewer does not qualify rover simulation.
## Physical source cleanup
Two legacy local PLY originals (Bamboo Trail and Forest Scan) were retained on Worker and checked by byte count and SHA-256 before local retirement. Their ready render assets were verified and both scenes opened in the actual UI afterward. Freed 831,479,037 bytes (about 793 MiB). Riverside already had a Worker-side original; its independent AI simulator cache remains owned by that runtime.
The twelve pre-existing LCC projects had no remaining local originals. Ready scenes, collision products, manual edits, maps, saved runs, settings and rollback data were retained. Missing catalog entries alone are not cleanup evidence.
## Explicit full deletion
New simulation projects use a durable Core deletion intent, persisted before API acknowledgement. The UI keeps the row with deleting/waiting status; Worker failure retries automatically and Core restart resumes the journal. Processing is cancelled and its local writer stops before cleanup. Worker job, prepared source receipt and original source receipt are removed before local products and catalog metadata. Shared job/source owners are preserved until the last owner is deleted. Existing independent saved runs/maps/edits block deletion with an explanation.
Worker serializes upload ownership admission and deletion, tracks active original/result readers, persists job/source deletion journals and resumes partially completed cleanup. Native executor requests belonging to the job are cancelled; their running/queued records must disappear before removing working files. Small completed tombstones remain as idempotency receipts, not as retained input/output payloads.
Native startup reconciles records provably older than the current OS boot before accepting work. Interrupted responses release the waiting deletion; a previously published completion is preserved. Current-boot orphaned native records still fail closed for process reconciliation rather than deleting under a possibly live child. Physical power loss was not exercised. The three old PLY worlds still have a distinct, explicitly labelled “Hide location” action. This is not full deletion of their independent simulator-owned data.
## Qualified runtime and rollback
Gaussian Pipeline deployed revision 277f4b20d011bf0fde2f4b178cfed042449b8dc5, image ndc/gaussian-pipeline:277f4b2, digest sha256:393b20ebf9d58784cbf419a895632f83b8b8c0f89002300989a2bdc43e94573c. Only the existing pipeline service was replaced; gateway, terrain executor, SplatTransform 3.3.3 and persistent data remain in their original contour. The separate native executor is updated independently as described below.
Rollback image: ndc/gaussian-pipeline:1ae2088, revision 1ae2088693ecda3f1bcc92a4159d7c45aa74fe79, digest sha256:3aa6c1c4b6619244d84de51ba386a63b14433dc540f830d17e3c54fa5e30f7c9. Rollback stops new admissions first; source/deletion journal compatibility must be reviewed before serving deletions from an older image.
Native executor is installed at D:/NDC_GAUSSIAN_PIPELINE/runtimes/5a40af071c6295c7db5872f804c03f6c0b569ff4. The existing NODEDC Gaussian Pipeline Executor scheduled task now points there. Its previous runtime 932877ac55b379a0686a6299aafeb494ff5a43a6 remains the rollback and dependency owner: the new runtime junction reuses its node_modules only after matching package-lock SHA-256 690da6bf015ad71a634ac93eb5a44526448bc59c80923086a42753d43e5d28ef. Do not delete that dependency owner while the junction is in use. Previous task XML is retained under staging/native-before-5a40af0.xml. No second executor or GPU environment was added.
The ready-scene UI check exposed that the prior native runtime did not yet consume cancellation requests even though the API did. The versioned native update closes that gap. Pending browser imports also offer full deletion: wait for an in-flight project creation to return its identity, abort upload, persist the server deletion intent, then keep the server row until cleanup completes. A late file-check result cannot recreate a cancelled import; deleting projects cannot be requeued.
## Validation
- Gaussian Pipeline: 73 tests pass (8 native executor tests also pass on Windows Worker), including shared sources, partial cleanup recovery, active build cancellation and detached native request handling.
- Core: 53 focused backend tests passed before the final dependency fix; 8 deletion tests pass after it, including durable deletion recovery, shared owners, saved-dependency refusal and HTTP 202 intent persistence.
- Frontend: TypeScript project check, 17 focused architecture/import tests, typography gate and production build pass. Final full frontend suite: 1,619 tests pass. Browser queue tests cover deletion during validation, server creation, active upload, failed delete retry, and retention of the row until a fresh server listing confirms removal.
- Actual UI: plus/import of the synthetic temporary PLY continued after workspace close/reopen; ready scene and original download verified by SHA-256. External native drag/drop is covered by event tests, not claimed as live desktop QA.
- Actual UI full deletion completed at 2026-11-16T14:52:34Z for the synthetic temporary scene after owner confirmation. Physical SSH checks found no job directory, retained source receipt, source upload bytes, upload metadata or pin. Core project, deletion intent, catalog entry and editor cache were absent. All 22 protected metadata files of other scenes retained their exact SHA-256. Small completed job/source tombstones remain for idempotency.
- Live UI exposed an overbroad 8 MiB dependency guard: an unrelated large geometry JSON blocked deletion. Replaced with bounded streaming identity scanning; tests cover an unrelated 9 MiB file and identity crossing a 64 KiB boundary. No user scene was deleted.
@@ -17,6 +17,68 @@ Do not start a second backend on another port. Do not use
`launchctl kickstart -k` for this service: it combines termination and restart
without proving that the old process group has released the singleton lease.
## Local HTTPS operator address
The operator-facing alias is `https://nodedc.missioncore`. The canonical
application remains the single backend on `127.0.0.1:8000`; no second Core
process is launched and Worker/provider routes keep their existing endpoints.
The macOS-only installer is `scripts/local_https/install.py`. It uses the
system Apache, a loopback-only listener on ports 80/443, one hosts entry and a
single-host SSL leaf certificate. Administrator authorization is required.
The single-host certificate is trusted for SSL in the operator login keychain
and cannot sign other certificates. It expires after 365 days. `receipt.json` records
its exact validity/fingerprint. Renewal needs explicit administrator action;
the installer refuses to silently replace a certificate nearing expiry.
After the administrator installer prepares the certificate, configure trust
from the operator login session (macOS may show its authorization dialog):
```bash
security add-trusted-cert -r trustRoot -p ssl \
-k "$HOME/Library/Keychains/login.keychain-db" \
"/Library/Application Support/NODE.DC/MissionCoreHTTPS/server.crt"
```
Do not add a policy-string (`-s`) constraint: native certificate verification
accepted it, but curl and Chromium rejected that trust record during qualification.
The leaf itself has exactly one DNS SAN and `CA:FALSE`. Do not run the trust step
inside a background root AppleScript; macOS refuses the interactive authorization
there. The installed gateway's own acceptance pins the certificate; final operator
acceptance must use the login trust store without `--cacert` or insecure flags.
Installed ownership:
- `/Library/Application Support/NODE.DC/MissionCoreHTTPS`: root-owned
configuration, private key, certificate and compact install receipt.
- `/Library/LaunchDaemons/com.nodedc.mission-core.https.plist`: durable
HTTPS gateway; Apache workers drop to `_www`.
- `/Library/Logs/NODE.DC/MissionCoreHTTPS`: bounded two-file 1 MiB error log.
- `/private/etc/hosts`: only the marked `nodedc.missioncore` loopback entry.
The gateway validates the public Host and Origin before mapping them to
Core's existing local boundary. It strips caller-supplied forwarding headers,
rejects foreign origins/cross-site API calls, streams uploads/responses, and
supports Range and WebSocket upgrades. It has no body-size cap or disk cache;
Core retains its own validation/quotas. HTTP redirects to HTTPS. The system
Apache build supports TLS 1.2; no weakened browser security flags are used.
Qualification: `python scripts/local_https/qualify.py` runs a small isolated
transport fixture, verifies forwarded-header stripping, host/origin rejection,
upload hash, Range, a WebSocket frame and redirect. It removes its exact
scratch/processes on exit. It never uploads production files or mutates Core.
Acceptance: `/usr/bin/curl --noproxy '*' https://nodedc.missioncore/api/health`
must pass without insecure flags, and a browser must report a secure context.
Do not restart Core to repair the HTTPS entry. Inspect only
`launchctl print system/com.nodedc.mission-core.https` and its bounded logs.
Rollback is limited to this gateway: boot out that exact system label, remove
its exact plist and marked hosts line, and remove trust for the exact certificate
fingerprint in the receipt. Keep the existing Core listener/data and unrelated
hosts/certificates intact. Never restore the complete hosts backup over later
changes. This alias is local to the configured Mac, not public DNS.
## Recovery contract
The installed LaunchAgent and application form one bounded recovery ladder:
@@ -0,0 +1,12 @@
# Observation view persistence
The operator's map camera/layer choices and selected rover model belong to Core presentation, not the vehicle's control authority. They use the existing scene profile store (`scene-profiles/<kind>/<owner hash>/meta.json`) with the vehicle ID as owner:
- `observation-map`: camera longitude/latitude/height/heading/pitch/roll and five layer visibility flags.
- `rover-view`: chosen model ID only.
The browser record is only a one-time migration input after an acknowledged empty profile read. Reopening waits for writes queued by the previous view. Atomic revisioned writes retain meta.previous.json; read errors cannot publish defaults. Browser cache clearing does not erase these profiles.
Tracker centering is automatic only when no camera has been saved or chosen. “Показать аппарат на карте” deliberately recenters. Renderer recovery uses the latest camera, not the mount-time value.
PlayCanvas scene materials, layout and its own camera remain in the separate existing `rover` profile. Arming and input ownership are never restored by either presentation profile.
+2 -2
View File
@@ -18,7 +18,7 @@ dependencies = [
"httpx>=0.28,<1",
"lz4>=4.4,<5",
"missioncore-plugin-sdk",
"nodedc-bim-module==0.2.6",
"nodedc-bim-module==0.2.36",
"paho-mqtt>=2.1,<3",
"pillow>=12,<13",
"pyyaml>=6.0,<7",
@@ -29,7 +29,7 @@ dependencies = [
]
[tool.uv.sources]
nodedc-bim-module = { path = "vendor/bim/nodedc_bim_module-0.2.6-py3-none-any.whl" }
nodedc-bim-module = { path = "vendor/bim/nodedc_bim_module-0.2.36-py3-none-any.whl" }
missioncore-plugin-sdk = { path = "packages/plugin-sdk", editable = true }
[project.optional-dependencies]
+291
View File
@@ -0,0 +1,291 @@
#!/usr/bin/env python3
"""Install the operator's loopback HTTPS name using macOS's own Apache.
Run with administrator authorization. This never restarts or replaces Core.
The certificate is a single-host leaf, not a general-purpose signing CA.
"""
import hashlib
import json
import os
import pathlib
import plistlib
import socket
import subprocess
import sys
import tempfile
import time
import urllib.request
DOMAIN = "nodedc.missioncore"
ORIGIN = "https://" + DOMAIN
LABEL = "com.nodedc.mission-core.https"
ROOT = pathlib.Path("/Library/Application Support/NODE.DC/MissionCoreHTTPS")
LOGS = pathlib.Path("/Library/Logs/NODE.DC/MissionCoreHTTPS")
PLIST = pathlib.Path("/Library/LaunchDaemons") / (LABEL + ".plist")
HOSTS = pathlib.Path("/private/etc/hosts")
HOST_LINE = "127.0.0.1 nodedc.missioncore # NODE.DC Mission Core HTTPS"
def config(root=ROOT, logs=LOGS, https_port=443, http_port=80, upstream_port=8000):
"""Ports/paths can be overridden for an isolated transport qualification."""
proxy_route = (
f"http://127.0.0.1:{upstream_port}/ nocanon "
"connectiontimeout=3 timeout=3600 upgrade=websocket"
)
return f'''ServerRoot "/usr"
ServerName {DOMAIN}
Listen 127.0.0.1:{http_port}
Listen 127.0.0.1:{https_port}
LoadModule mpm_event_module libexec/apache2/mod_mpm_event.so
LoadModule unixd_module libexec/apache2/mod_unixd.so
LoadModule authz_core_module libexec/apache2/mod_authz_core.so
LoadModule ssl_module libexec/apache2/mod_ssl.so
LoadModule proxy_module libexec/apache2/mod_proxy.so
LoadModule proxy_http_module libexec/apache2/mod_proxy_http.so
LoadModule headers_module libexec/apache2/mod_headers.so
LoadModule rewrite_module libexec/apache2/mod_rewrite.so
User _www
Group _www
PidFile "{root}/httpd.pid"
DefaultRuntimeDir "{root}"
Mutex "file:{root}" default
ErrorLog "|/usr/sbin/rotatelogs -n 2 '{logs}/error.log' 1M"
LogLevel warn
ServerTokens Prod
ServerSignature Off
TraceEnable Off
StartServers 1
ServerLimit 2
ThreadLimit 32
ThreadsPerChild 32
MinSpareThreads 16
MaxSpareThreads 32
MaxRequestWorkers 64
MaxConnectionsPerChild 10000
Timeout 600
KeepAlive On
KeepAliveTimeout 5
LimitRequestBody 0
AllowEncodedSlashes NoDecode
<Directory />
Require all denied
</Directory>
<VirtualHost 127.0.0.1:{http_port}>
ServerName {DOMAIN}
RewriteEngine On
RewriteCond %{{HTTP_HOST}} !^{DOMAIN.replace(".", "[.]")}(:{http_port})?$ [NC]
RewriteRule ^ - [F,L]
RewriteRule ^/(.*)$ {ORIGIN}/$1 [R=308,NE,L]
</VirtualHost>
<VirtualHost 127.0.0.1:{https_port}>
ServerName {DOMAIN}
SSLEngine On
SSLProtocol -all +TLSv1.2
SSLCipherSuite HIGH:!aNULL:!MD5:!3DES
SSLCertificateFile "{root}/server.crt"
SSLCertificateKeyFile "{root}/server.key"
RewriteEngine On
RewriteCond %{{HTTP_HOST}} !^{DOMAIN.replace(".", "[.]")}(:{https_port})?$ [NC]
RewriteRule ^ - [F,L]
# Validate the public browser origin BEFORE mapping it to Core's origin.
RewriteCond %{{HTTP:Origin}} !^$
RewriteCond %{{HTTP:Origin}} !^{ORIGIN.replace(".", "[.]")}(:{https_port})?$
RewriteRule ^ - [F,L]
# External links may navigate to the UI; cross-site API calls remain blocked.
RewriteCond %{{HTTP:Sec-Fetch-Site}} ^cross-site$ [NC]
RewriteCond %{{HTTP:Sec-Fetch-Mode}} !^navigate$ [NC,OR]
RewriteCond %{{REQUEST_URI}} ^/(api|ws)(/|$) [NC]
RewriteRule ^ - [F,L]
ProxyRequests Off
ProxyPreserveHost Off
ProxyAddHeaders Off
RequestHeader unset Forwarded
RequestHeader unset X-Forwarded-For
RequestHeader unset X-Forwarded-Host
RequestHeader unset X-Forwarded-Proto
RequestHeader unset X-Forwarded-Port
RequestHeader unset X-Real-IP
RequestHeader edit Origin "^{ORIGIN.replace(".", "[.]")}(:{https_port})?$" "http://127.0.0.1:{upstream_port}"
ProxyPass / {proxy_route}
ProxyPassReverse / http://127.0.0.1:{upstream_port}/
<Location />
Require all granted
</Location>
</VirtualHost>
'''
def run(*args):
result = subprocess.run(args, capture_output=True, text=True)
if result.returncode:
raise RuntimeError(f"{args[0]}: {result.stderr.strip()}")
return result.stdout.strip()
def atomic(path, content, mode=0o600):
fd, name = tempfile.mkstemp(dir=path.parent, prefix=".https-")
try:
with os.fdopen(fd, "wb") as stream:
stream.write(content)
stream.flush()
os.fsync(stream.fileno())
os.chmod(name, mode)
os.replace(name, path)
finally:
if os.path.exists(name):
os.unlink(name)
def create_certificate(root):
key, cert = root / "server.key", root / "server.crt"
if key.exists() and cert.exists():
run("/usr/bin/openssl", "x509", "-in", str(cert), "-checkend", "2592000", "-noout")
return
if key.exists() or cert.exists():
raise RuntimeError("Incomplete HTTPS certificate; inspect before replacing it")
spec = root / "certificate.conf"
atomic(
spec,
f"""[req]
prompt=no
distinguished_name=dn
x509_extensions=server
[dn]
CN={DOMAIN}
O=NODE.DC Local Mission Core
[server]
subjectAltName=DNS:{DOMAIN}
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
extendedKeyUsage=serverAuth
""".encode(),
)
run(
"/usr/bin/openssl",
"req",
"-new",
"-x509",
"-newkey",
"rsa:2048",
"-nodes",
"-sha256",
"-days",
"365",
"-config",
str(spec),
"-keyout",
str(key),
"-out",
str(cert),
)
os.chmod(key, 0o600)
os.chmod(cert, 0o644)
spec.unlink()
def install():
if sys.platform != "darwin" or os.geteuid() != 0:
raise RuntimeError("Use macOS administrator authorization for this installer")
op = urllib.request.build_opener(urllib.request.ProxyHandler({}))
with op.open("http://127.0.0.1:8000/api/health", timeout=10) as response:
health = json.load(response)
if health.get("service") != "mission-core-control-plane" or not health.get("ok"):
raise RuntimeError("Canonical Mission Core is not healthy")
before = HOSTS.read_bytes()
for line in before.decode().splitlines():
fields = line.split("#", 1)[0].split()
if DOMAIN in fields[1:] and fields[0] != "127.0.0.1":
raise RuntimeError("The requested name already resolves elsewhere in hosts")
existing = (
subprocess.run(
["/bin/launchctl", "print", "system/" + LABEL], capture_output=True
).returncode
== 0
)
if not existing:
for port in (80, 443):
with socket.socket() as probe:
probe.bind(("127.0.0.1", port))
for directory in (ROOT, LOGS):
directory.mkdir(parents=True, exist_ok=True)
os.chmod(directory, 0o755)
create_certificate(ROOT)
conf = config().encode()
conf_path = ROOT / "httpd.conf"
if existing and conf_path.read_bytes() != conf:
raise RuntimeError("Existing HTTPS configuration differs; review before restarting")
atomic(conf_path, conf, 0o644)
run("/usr/sbin/httpd", "-t", "-f", str(conf_path))
# Trust is configured separately in the operator's login session. macOS
# refuses interactive trust authorization from this background root process.
# Never install a general signing CA or disable browser certificate checks.
if not any(
DOMAIN in line.split("#", 1)[0].split()[1:] for line in before.decode().splitlines()
):
if not (ROOT / "hosts.before").exists():
atomic(ROOT / "hosts.before", before)
atomic(HOSTS, before.rstrip(b"\n") + b"\n" + HOST_LINE.encode() + b"\n", 0o644)
run("/usr/bin/dscacheutil", "-flushcache")
declaration = plistlib.dumps(
{
"Label": LABEL,
"ProgramArguments": ["/usr/sbin/httpd", "-f", str(conf_path), "-D", "FOREGROUND"],
"RunAtLoad": True,
"KeepAlive": True,
"ThrottleInterval": 5,
"AbandonProcessGroup": False,
"ExitTimeOut": 15,
}
)
if PLIST.exists() and PLIST.read_bytes() != declaration:
raise RuntimeError("Existing HTTPS launch declaration differs; review it first")
atomic(PLIST, declaration, 0o644)
if not existing:
run("/bin/launchctl", "bootstrap", "system", str(PLIST))
for _attempt in range(20):
check = subprocess.run(
[
"/usr/bin/curl",
"--noproxy",
"*",
"--silent",
"--show-error",
"--fail",
"--max-time",
"5",
"--cacert",
str(ROOT / "server.crt"),
ORIGIN + "/api/health",
],
capture_output=True,
text=True,
)
if check.returncode == 0 and json.loads(check.stdout).get("ok"):
receipt = {
"url": ORIGIN,
"upstream": "http://127.0.0.1:8000",
"config_sha256": hashlib.sha256(conf).hexdigest(),
"certificate": run(
"/usr/bin/openssl",
"x509",
"-in",
str(ROOT / "server.crt"),
"-noout",
"-dates",
"-fingerprint",
"-sha256",
),
"core_restarted": False,
"https_health": "verified_exact_certificate",
"browser_trust": "verify_in_operator_login_session",
}
atomic(ROOT / "receipt.json", (json.dumps(receipt, indent=2) + "\n").encode())
print(json.dumps(receipt, indent=2))
return
time.sleep(0.5)
raise RuntimeError("HTTPS health failed: " + check.stderr[-500:])
if __name__ == "__main__":
install()
+196
View File
@@ -0,0 +1,196 @@
"""Bounded Apache transport qualification; no production data is modified."""
import base64
import hashlib
import http.client
import http.server
import json
import os
import pathlib
import shutil
import signal
import socket
import ssl
import subprocess
import tempfile
import threading
import time
from install import DOMAIN, config, create_certificate
class Echo(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *args):
pass
def do_GET(self):
if self.headers.get("Upgrade", "").lower() == "websocket":
value = self.headers["Sec-WebSocket-Key"] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
self.send_response(101)
self.send_header("Upgrade", "websocket")
self.send_header("Connection", "Upgrade")
self.send_header(
"Sec-WebSocket-Accept",
base64.b64encode(hashlib.sha1(value.encode()).digest()).decode(),
)
self.end_headers()
self.wfile.write(b"\x81\x02ok")
self.wfile.flush()
self.close_connection = True
return
body = json.dumps(dict(self.headers)).encode()
self.send_response(206 if self.headers.get("Range") else 200)
if self.headers.get("Range"):
self.send_header("Content-Range", "bytes 0-1/2")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
digest = hashlib.sha256()
left = int(self.headers["Content-Length"])
while left:
chunk = self.rfile.read(min(left, 65536))
if not chunk:
raise RuntimeError("Truncated stream")
digest.update(chunk)
left -= len(chunk)
body = digest.hexdigest().encode()
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def free_port():
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
return probe.getsockname()[1]
def main():
# macOS's Apache cannot read an operator's protected Downloads directory.
scratch = pathlib.Path(tempfile.mkdtemp(prefix="missioncore-https-transport-"))
upstream = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Echo)
threading.Thread(target=upstream.serve_forever, daemon=True).start()
process = None
try:
create_certificate(scratch)
tls_port, redirect_port = free_port(), free_port()
(scratch / "httpd.conf").write_text(
config(scratch, scratch, tls_port, redirect_port, upstream.server_port)
)
subprocess.run(
["/usr/sbin/httpd", "-t", "-f", str(scratch / "httpd.conf")],
check=True,
capture_output=True,
)
process = subprocess.Popen(
["/usr/sbin/httpd", "-f", str(scratch / "httpd.conf"), "-D", "FOREGROUND"],
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
start_new_session=True,
)
context = ssl.create_default_context(cafile=str(scratch / "server.crt"))
context.check_hostname = (
False # Test socket uses loopback; trusted test certificate still verified.
)
def call(path="/", method="GET", headers=None, body=None):
connection = http.client.HTTPSConnection(
"127.0.0.1", tls_port, context=context, timeout=10
)
connection.request(
method, path, body=body, headers={"Host": f"{DOMAIN}:{tls_port}", **(headers or {})}
)
response = connection.getresponse()
result = response.status, dict(response.headers), response.read()
connection.close()
return result
for _ in range(50):
try:
call()
break
except OSError:
if process.poll() is not None:
errors = "\n".join(p.read_text() for p in scratch.glob("error.log*"))
raise RuntimeError(process.stderr.read().decode() + errors) from None
time.sleep(0.1)
status, _, body = call(
"/api/check",
headers={
"Origin": f"https://{DOMAIN}:{tls_port}",
"Sec-Fetch-Site": "same-origin",
"X-Forwarded-For": "8.8.8.8",
"X-Forwarded-Proto": "https",
},
)
mapped = {k.lower(): v for k, v in json.loads(body).items()}
assert status == 200 and mapped["host"] == f"127.0.0.1:{upstream.server_port}"
assert mapped["origin"] == f"http://127.0.0.1:{upstream.server_port}"
assert "x-forwarded-for" not in mapped and "x-forwarded-proto" not in mapped
assert call(headers={"Host": "evil.example"})[0] == 403
assert call(headers={"Origin": "https://evil.example"})[0] == 403
assert call(headers={"Origin": "null"})[0] == 403
assert (
call(
"/api/check", headers={"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "navigate"}
)[0]
== 403
)
assert (
call("/", headers={"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "navigate"})[0]
== 200
)
assert call("/api/check", headers={"Range": "bytes=0-1"})[0] == 206
payload = b"NODE.DC-stream-test" * 65536
assert (
call("/upload", "POST", body=payload)[2].decode() == hashlib.sha256(payload).hexdigest()
)
with (
socket.create_connection(("127.0.0.1", tls_port), timeout=5) as tcp,
context.wrap_socket(tcp, server_hostname=DOMAIN) as stream,
):
key = base64.b64encode(os.urandom(16)).decode()
stream.sendall(
(
f"GET /socket HTTP/1.1\r\nHost: {DOMAIN}:{tls_port}\r\n"
f"Origin: https://{DOMAIN}:{tls_port}\r\n"
"Upgrade: websocket\r\nConnection: Upgrade\r\n"
f"Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: {key}\r\n\r\n"
).encode()
)
data = b""
while b"\r\n\r\n" not in data or not data.endswith(b"\x81\x02ok"):
part = stream.recv(4096)
if not part:
break
data += part
assert b"101 Switching Protocols" in data and data.endswith(b"\x81\x02ok")
connection = http.client.HTTPConnection("127.0.0.1", redirect_port, timeout=5)
connection.request("GET", "/path?q=1", headers={"Host": f"{DOMAIN}:{redirect_port}"})
response = connection.getresponse()
assert (
response.status == 308
and response.headers["Location"] == "https://nodedc.missioncore/path?q=1"
)
response.read()
connection.close()
print(
"PASS: origin/host boundary, forwarded-header stripping, range, "
"upload hash, WebSocket frame, HTTP redirect"
)
finally:
if process is not None and process.poll() is None:
os.killpg(process.pid, signal.SIGTERM)
process.wait(timeout=10)
upstream.shutdown()
upstream.server_close()
shutil.rmtree(scratch)
if __name__ == "__main__":
main()
+11 -1
View File
@@ -18,7 +18,7 @@ def main():
parser.add_argument("--version", required=True)
parser.add_argument(
"--kind",
choices=("node", "vps-arnavi", "vps-wireguard", "vps-netbird", "vps-librespeed"),
choices=("node", "vps-arnavi", "vps-wireguard", "vps-netbird", "vps-librespeed", "vps-egress"),
required=True,
)
args = parser.parse_args()
@@ -88,6 +88,16 @@ def main():
"Скопируйте с VPS файл /var/lib/ndc-librespeed-vps/mission-core-librespeed.json и выберите его в этом окне. Затем нажмите «Подключить службу».",
],
)
if args.kind == "vps-egress":
value.update(
label="Маршрутизация трафика",
os="Ubuntu Server 24.04 LTS · x86-64",
instructions=[
"Скопируйте установщик на VPS: sudo python3 mission-core-egress-vps.pyz plan --host АДРЕС",
"Примените проверенный план: sudo python3 mission-core-egress-vps.pyz apply --host АДРЕС --expect ХЕШ_ПЛАНА",
"Подключите службу файлом /var/lib/ndc-egress-vps/mission-core-egress.json.",
],
)
temporary = root / (args.kind + ".json.new")
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
temporary.chmod(0o600)
+133
View File
@@ -0,0 +1,133 @@
"""Durable ownership and private credentials for portable egress services."""
import json
import re
import secrets
import sqlite3
import threading
import time
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from typing import Any
from . import vps_transport
from .trust import PairingError
Document = dict[str, Any]
lock = threading.RLock()
def invitation(document: str) -> Document:
try:
value = json.loads(document)
if set(value) != {
"schema",
"server_id",
"endpoint",
"fingerprint",
"bootstrap",
"expires_at",
}:
raise ValueError
if value["schema"] != "missioncore.egress-connect/v1":
raise ValueError
for key, pattern in (
("server_id", r"eg_[a-f0-9]{32}"),
("fingerprint", r"[a-f0-9]{64}"),
("bootstrap", r"[A-Za-z0-9_-]{43}"),
):
if not isinstance(value[key], str) or not re.fullmatch(pattern, value[key]):
raise ValueError
if not time.time() < value["expires_at"] <= time.time() + 86500:
raise PairingError("Приглашение службы маршрутизации просрочено. Скачайте новое с VPS.")
vps_transport.destination(value["endpoint"])
return dict(value)
except (ValueError, TypeError, KeyError):
raise PairingError("Файл приглашения Egress повреждён или просрочен.") from None
class Egress:
def __init__(self, root: Path):
self.path = root / "egress.sqlite3"
root.mkdir(parents=True, exist_ok=True)
with self.db() as db:
db.execute(
"CREATE TABLE IF NOT EXISTS services (id TEXT PRIMARY KEY, body TEXT NOT NULL)"
)
self.path.chmod(0o600)
@contextmanager
def db(self) -> Iterator[sqlite3.Connection]:
connection = sqlite3.connect(self.path)
try:
with connection:
yield connection
finally:
connection.close()
def rows(self) -> list[Document]:
with lock, self.db() as db:
return [json.loads(r[0]) for r in db.execute("SELECT body FROM services")]
def listing(self) -> list[Document]:
return [
{k: r[k] for k in ("id", "endpoint", "state", "fingerprint")}
for r in self.rows()
if r["state"] == "connected"
]
def save(self, row: Document) -> None:
with self.db() as db:
db.execute("INSERT OR REPLACE INTO services VALUES (?,?)", (row["id"], json.dumps(row)))
def find(self, identifier: str) -> Document:
row = next(
(r for r in self.rows() if r["id"] == identifier and r["state"] == "connected"), None
)
if not row:
raise PairingError("Подключите службу маршрутизации на VPS.")
return row
def pair(self, document: str, network_interface: str | None = None) -> Document:
value = invitation(document)
vps_transport.validate_interface(network_interface)
with lock:
row = next((r for r in self.rows() if r["id"] == value["server_id"]), None)
if row and (
row["fingerprint"] != value["fingerprint"] or row["endpoint"] != value["endpoint"]
):
raise PairingError("Идентичность службы маршрутизации изменилась.")
if row is None:
row = {
"id": value["server_id"],
"endpoint": value["endpoint"],
"fingerprint": value["fingerprint"],
"token": secrets.token_urlsafe(32),
"core_id": "core_" + secrets.token_hex(16),
"state": "pending",
}
row["network_interface"] = network_interface
self.save(row) # Retry a lost claim reply using the same controller identity.
result = vps_transport.request(
row,
"POST",
"/v1/claim",
{
"core_id": row["core_id"],
"bootstrap": value["bootstrap"],
"credential": row["token"],
},
)
if (
result.get("server_id") != row["id"]
or result.get("schema") != "missioncore.egress/v1"
):
raise PairingError("VPS вернул другую службу.")
row["state"] = "connected"
self.save(row)
return {"id": row["id"], "state": "connected"}
def forget(self, identifiers: set[str]) -> None:
with lock, self.db() as db:
db.executemany("DELETE FROM services WHERE id=?", [(i,) for i in identifiers])
+137
View File
@@ -0,0 +1,137 @@
"""Pinned streaming transport shared by service clients; no persistent payloads."""
from __future__ import annotations
import asyncio
import hashlib
import http.client
import socket
import ssl
from collections.abc import AsyncIterator
from contextlib import suppress
from typing import Any
from urllib.parse import urlencode
import httpx
from . import vps_transport
from .trust import PairingError
def open_response(
binding: dict[str, Any], method: str, target: str, headers: dict[str, str], profile: str
) -> tuple[http.client.HTTPConnection, http.client.HTTPResponse]:
if profile != "cesium" or method not in {"GET", "HEAD"}:
raise ValueError("Unsupported egress profile")
name, port, address = vps_transport.destination(binding["endpoint"])
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.check_hostname = False
context.verify_mode = (
ssl.CERT_NONE
) # Mandatory certificate pin checked BEFORE sending any bytes.
context.minimum_version = ssl.TLSVersion.TLSv1_3
connection = http.client.HTTPConnection(name, port, timeout=30)
raw = vps_transport.connect(address, port, binding.get("network_interface"))
try:
connection.sock = context.wrap_socket(raw, server_hostname=name)
if (
hashlib.sha256(connection.sock.getpeercert(binary_form=True) or b"").hexdigest()
!= binding["fingerprint"]
):
raise PairingError("Идентичность службы маршрутизации изменилась.")
connection.sock.settimeout(30)
forwarded = {
k: v
for k, v in headers.items()
if k.lower() in {"accept", "range", "if-none-match", "if-modified-since"}
}
for key, value in headers.items():
if key.lower() == "authorization":
forwarded["X-Nodedc-Upstream-Authorization"] = value
elif key.lower() == "referer":
forwarded["X-Nodedc-Upstream-Referer"] = value
forwarded["Authorization"] = "Bearer " + binding["token"]
connection.request(
method, "/v1/fetch/" + profile + "?" + urlencode({"url": target}), headers=forwarded
)
return connection, connection.getresponse()
except BaseException:
raw.close()
connection.close()
raise
class RelayStream(httpx.AsyncByteStream):
def __init__(
self,
connection: http.client.HTTPConnection,
response: http.client.HTTPResponse,
slots: asyncio.Semaphore,
) -> None:
self.connection, self.response, self.slots = connection, response, slots
self.closed = False
async def __aiter__(self) -> AsyncIterator[bytes]:
try:
while data := await asyncio.to_thread(self.response.read, 65536):
yield data
if self.response.length not in (None, 0):
raise http.client.IncompleteRead(b"", self.response.length)
except (OSError, http.client.HTTPException) as exc:
raise httpx.ReadError("Routing service stream interrupted") from exc
finally:
await self.aclose()
async def aclose(self) -> None:
if not self.closed:
self.closed = True
try:
if self.connection.sock is not None:
with suppress(OSError):
self.connection.sock.shutdown(socket.SHUT_RDWR)
self.connection.close()
await asyncio.to_thread(self.response.close)
finally:
self.slots.release()
class EgressTransport:
def __init__(self) -> None:
self.slots = asyncio.Semaphore(16)
async def request(
self,
binding: dict[str, Any],
method: str,
target: str,
headers: dict[str, str],
profile: str = "cesium",
) -> httpx.Response:
await self.slots.acquire()
task = asyncio.create_task(
asyncio.to_thread(open_response, binding, method, target, headers, profile)
)
try:
connection, response = await asyncio.shield(task)
except asyncio.CancelledError:
def finish(done: asyncio.Task[Any]) -> None:
try:
conn, result = done.result()
conn.close()
result.close()
except Exception:
pass
finally:
self.slots.release()
task.add_done_callback(finish)
raise
except (OSError, ValueError, http.client.HTTPException) as exc:
self.slots.release()
raise httpx.ConnectError("Routing service unavailable") from exc
return httpx.Response(
response.status,
headers=response.getheaders(),
stream=RelayStream(connection, response, self.slots),
)
+34 -1
View File
@@ -11,9 +11,12 @@ from typing import Any
from k1link.compute_connections.store import ConnectionStore, Registry, WorkerBinding
from k1link.fleet import network_client
from k1link.fleet.egress import Egress
from k1link.fleet.egress import lock as egress_lock
from k1link.fleet.librespeed import LibreSpeed
from k1link.fleet.librespeed import lock as speed_lock
from k1link.fleet.server_catalog import Document, ServerCatalog, endpoint_address
from k1link.maps.settings import CesiumSettingsStore, MapServiceError
class ServerRemoval:
@@ -30,6 +33,7 @@ class ServerRemoval:
# cannot race retirement; fleet/connection revisions invalidate stale tabs.
with (
speed_lock,
egress_lock,
self.networks.import_lock,
self.hosts.lock,
self.networks.sync_lock,
@@ -104,7 +108,28 @@ class ServerRemoval:
for e in self.fleet.routers.pending.values()
):
blocked.append("Остановите замер скорости перед отключением VPS.")
egress = [
r
for r in Egress(self.fleet.root).rows()
if endpoint_address(r["endpoint"]) == host["address"]
]
if egress:
try:
selected = (
CesiumSettingsStore(
self.fleet.root.parent / "services" / "cesium-ion" / "settings.json"
)
.read()
.egress_id
)
if selected in {r["id"] for r in egress}:
blocked.append("Сначала выберите другой маршрут в настройках Cesium ion.")
except MapServiceError:
blocked.append("Не удалось проверить настройки маршрутизации Cesium ion.")
signature = {
"egress": [
{k: r[k] for k in ("id", "endpoint", "fingerprint", "state")} for r in egress
],
"librespeed": [
{k: r[k] for k in ("id", "endpoint", "fingerprint", "state")} for r in speed
],
@@ -138,7 +163,8 @@ class ServerRemoval:
"blocked": blocked,
"services": ["ARNavi"] * len(arnavi)
+ ["WireGuard"] * len(wg)
+ ["LibreSpeed"] * len(speed),
+ ["LibreSpeed"] * len(speed)
+ ["Маршрутизация трафика"] * len(egress),
"vehicle_connections": len(affected),
"worker_connections": sum(
c.profile_id in profiles for w in registry.workers for c in w.connections
@@ -235,5 +261,12 @@ class ServerRemoval:
if endpoint_address(r["endpoint"]) == host["address"]
}
)
Egress(self.fleet.root).forget(
{
r["id"]
for r in Egress(self.fleet.root).rows()
if endpoint_address(r["endpoint"]) == host["address"]
}
)
self.catalog.remove(host["id"])
return {"removed": True, "id": host["id"]}
+1
View File
@@ -0,0 +1 @@
"""Shared map service configuration and optional, diskless provider transport."""
+316
View File
@@ -0,0 +1,316 @@
from __future__ import annotations
import asyncio
import base64
import json
import re
import time
from collections.abc import AsyncIterator, Awaitable, Callable
from dataclasses import dataclass, field
from typing import Any
from urllib.parse import parse_qsl, unquote, urlencode, urlsplit, urlunsplit
import httpx
from .settings import MapServiceError
ASSETS = {1: "TERRAIN", 2: "IMAGERY", 96188: "3DTILES"}
BING_HOSTS = {
"dev.virtualearth.net",
"ecn.tiles.virtualearth.net",
*(f"ecn.t{n}.tiles.virtualearth.net" for n in range(4)),
}
ION_HOSTS = {"assets.ion.cesium.com", "assets.cesium.com"}
SECRET_KEYS = {"key", "access_token", "token", "authorization", "signature", "sig"}
MAX_JSON = 2 * 1024 * 1024
class JsonStream(httpx.AsyncByteStream):
def __init__(self, payload: bytes) -> None:
self.payload = payload
async def __aiter__(self) -> AsyncIterator[bytes]:
yield self.payload
def json_response(document: dict[str, Any], status: int = 200) -> httpx.Response:
return httpx.Response(
status,
headers={"content-type": "application/json", "cache-control": "no-store"},
stream=JsonStream(json.dumps(document).encode()),
)
def safe_url(raw: str) -> str:
try:
url = urlsplit(raw)
if (
url.scheme != "https"
or url.hostname not in ION_HOSTS | BING_HOSTS
or url.port not in (None, 443)
or url.username
or url.password
or url.fragment
or len(raw) > 8192
):
raise ValueError
decoded = unquote(url.path)
if "\\" in decoded or any(part in (".", "..") for part in decoded.split("/")):
raise ValueError
# Encoded separators must not broaden the credential scope downstream.
if re.search(r"%2f|%5c|%25", url.path, re.I):
raise ValueError
return urlunsplit(
(
url.scheme,
url.netloc,
url.path,
urlencode(
[
(k, v)
for k, v in parse_qsl(url.query, keep_blank_values=True)
if k.lower() not in SECRET_KEYS
and not k.lower().startswith("nodedc_cache_")
]
),
"",
)
)
except ValueError as exc:
raise MapServiceError("cesium_resource_not_allowed", 403) from exc
def in_scope(target: str, root: str) -> bool:
url, base = urlsplit(target), urlsplit(root)
if (url.scheme, url.netloc) != (base.scheme, base.netloc):
return False
if url.path == base.path:
return True
directory = base.path.rsplit("/", 1)[0] + "/"
return directory != "/" and url.path.startswith(directory)
async def read_json(response: httpx.Response) -> dict[str, Any]:
try:
payload = bytearray()
async for chunk in response.aiter_bytes():
payload.extend(chunk)
if len(payload) > MAX_JSON:
raise ValueError
document = json.loads(payload)
if not isinstance(document, dict):
raise ValueError
return document
except (ValueError, UnicodeError) as exc:
raise MapServiceError("cesium_provider_invalid_response", 502) from exc
except httpx.HTTPError as exc:
raise MapServiceError("cesium_provider_unavailable", 503) from exc
finally:
await response.aclose()
@dataclass
class Endpoint:
public: dict[str, Any]
root: str
credential: str = field(repr=False)
expires: float = 0
class DirectCesium:
"""Official providers through Core. Only three credentials/metadata live in RAM.
No tile cache, private token in a browser URL, alternate renderer or NAS mutation.
Endpoint-derived credentials are scoped to the exact provider asset directory.
"""
def __init__(
self,
token: str,
client: httpx.AsyncClient,
provider_request: Callable[..., Awaitable[httpx.Response]] | None = None,
) -> None:
self.provider_request = provider_request
self._token = token
self.client = client
self.endpoints: dict[int, Endpoint] = {}
self.locks = {asset: asyncio.Lock() for asset in ASSETS}
async def endpoint(self, asset: int, *, refresh: bool = False) -> Endpoint:
if asset not in ASSETS:
raise MapServiceError("cesium_asset_not_allowed", 404)
if not self._token:
raise MapServiceError("cesium_token_required", 503)
async with self.locks[asset]:
cached = self.endpoints.get(asset)
if not refresh and cached and cached.expires > time.time():
return cached
response = await self._request(
"GET",
f"https://api.cesium.com/v1/assets/{asset}/endpoint",
headers={"Authorization": f"Bearer {self._token}"},
)
await self._require_success(response)
body = await read_json(response)
if body.get("type") != ASSETS[asset]:
raise MapServiceError("cesium_provider_contract_mismatch", 502)
public: dict[str, Any] = {
"assetId": str(asset),
"type": ASSETS[asset],
"credentialMode": "gateway",
"attributions": self._attributions(body.get("attributions")),
}
if asset == 2:
options = body.get("options")
if body.get("externalType") != "BING" or not isinstance(options, dict):
raise MapServiceError("cesium_provider_contract_mismatch", 502)
root = safe_url(str(options.get("url", "")))
if urlsplit(root).hostname != "dev.virtualearth.net":
raise MapServiceError("cesium_provider_contract_mismatch", 502)
credential = options.get("key")
public.update(
externalType="BING",
options={"url": root, "mapStyle": str(options.get("mapStyle", "Aerial"))},
)
else:
root = safe_url(str(body.get("url", "")))
if urlsplit(root).hostname not in ION_HOSTS:
raise MapServiceError("cesium_provider_contract_mismatch", 502)
credential = body.get("accessToken")
public["url"] = root
if not isinstance(credential, str) or not credential or len(credential) > 16384:
raise MapServiceError("cesium_provider_contract_mismatch", 502)
expiry = time.time() + 900
if asset != 2:
try:
segment = credential.split(".")[1]
jwt = json.loads(base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4)))
expiry = min(expiry, float(jwt["exp"]) - 60)
except (ValueError, KeyError, IndexError, TypeError):
pass
result = Endpoint(public, root, credential, expiry)
self.endpoints[asset] = result
return result
async def verify(self) -> dict[str, Any]:
async def check(asset: int) -> tuple[str, dict[str, Any]]:
try:
await self.endpoint(asset)
return str(asset), {"ok": True}
except MapServiceError as exc:
return str(asset), {"ok": False, "code": exc.code}
results = dict(await asyncio.gather(*(check(asset) for asset in ASSETS)))
return {"ok": all(value["ok"] for value in results.values()), "assets": results}
async def resource(self, method: str, target: str, headers: dict[str, str]) -> httpx.Response:
target = safe_url(target)
is_bing = urlsplit(target).hostname in BING_HOSTS
# A page can have been initialized through NAS before its outage. Resolve
# only the relevant asset(s); failure of imagery cannot block terrain.
asset_ids = (2,) if is_bing else (1, 96188)
endpoint = None
matched_asset = None
last_error = None
for asset in asset_ids:
try:
candidate = await self.endpoint(asset)
except MapServiceError as exc:
last_error = exc
continue
if is_bing or in_scope(target, candidate.root):
endpoint, matched_asset = candidate, asset
break
if endpoint is None or matched_asset is None:
raise last_error or MapServiceError("cesium_resource_outside_asset", 403)
for attempt in range(2):
outgoing = dict(headers)
outgoing["accept-encoding"] = "identity"
url = target
if is_bing:
# httpx request logging must not emit this URL (see transport).
url += ("&" if urlsplit(url).query else "?") + urlencode(
{"key": endpoint.credential}
)
else:
outgoing["authorization"] = f"Bearer {endpoint.credential}"
response = await self._request(method, url, headers=outgoing)
if response.status_code in (401, 403) and attempt == 0:
await response.aclose()
endpoint = await self.endpoint(matched_asset, refresh=True)
if not is_bing and not in_scope(target, endpoint.root):
raise MapServiceError("cesium_endpoint_changed", 409)
continue
await self._require_success(response)
response.headers["cache-control"] = "no-store"
response.headers["x-nodedc-map-route"] = "direct"
if (
method != "HEAD"
and response.status_code not in (204, 304)
and (
"json" in response.headers.get("content-type", "")
or urlsplit(target).path.endswith(".json")
)
):
document = self._sanitize(await read_json(response), endpoint.credential)
result = json_response(document, response.status_code)
result.headers["x-nodedc-map-route"] = "direct"
return result
return response
raise MapServiceError("cesium_provider_unauthorized", 401)
async def _request(self, method: str, url: str, *, headers: dict[str, str]) -> httpx.Response:
try:
# Core has one canonical operator origin. Keep URL-restricted ion
# tokens usable without accepting a caller-supplied provider origin.
headers = {**headers, "referer": "http://127.0.0.1:8000/"}
if self.provider_request is not None:
return await self.provider_request(method, url, headers=headers)
request = self.client.build_request(
method, url, headers=headers, timeout=httpx.Timeout(20, connect=4)
)
return await self.client.send(request, stream=True, follow_redirects=False)
except httpx.HTTPError as exc:
raise MapServiceError("cesium_provider_unavailable", 503) from exc
@staticmethod
async def _require_success(response: httpx.Response) -> None:
if response.status_code in (200, 206, 204, 304):
return
status = response.status_code
code = response.headers.get("x-nodedc-egress-error")
await response.aclose()
if code == "upstream_region_denied":
raise MapServiceError("cesium_egress_region_denied", 403)
if code:
raise MapServiceError("cesium_egress_unavailable", 503)
if status in (401, 403):
raise MapServiceError("cesium_provider_unauthorized", status)
if status == 429:
raise MapServiceError("cesium_provider_rate_limited", 429)
raise MapServiceError("cesium_provider_unavailable", 502)
@staticmethod
def _attributions(value: object) -> list[dict[str, Any]]:
if not isinstance(value, list):
return []
return [
{"html": str(item.get("html", "")), "collapsible": bool(item.get("collapsible"))}
for item in value[:100]
if isinstance(item, dict)
]
@classmethod
def _sanitize(cls, value: Any, credential: str) -> Any:
if isinstance(value, dict):
return {
key: cls._sanitize(item, credential)
for key, item in value.items()
if key.lower().replace("_", "")
not in {"key", "token", "accesstoken", "authorization"}
}
if isinstance(value, list):
return [cls._sanitize(item, credential) for item in value]
if isinstance(value, str):
return value.replace(credential, "nodedc-gateway")
return value
+37
View File
@@ -0,0 +1,37 @@
"""Signed request-scoped cache egress. Secrets stay between Core and Gateway."""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import re
import time
from pathlib import Path
from typing import Any
from .settings import MapServiceError
def gateway_headers(
key_path: Path, binding: dict[str, Any], method: str, path: str
) -> dict[str, str]:
try:
if key_path.is_symlink() or key_path.stat().st_size > 128:
raise ValueError()
key = key_path.read_text().strip()
if not re.fullmatch(r"[a-f0-9]{64}", key):
raise ValueError()
except (OSError, ValueError) as exc:
raise MapServiceError("cesium_egress_gateway_not_ready", 503) from exc
value = {k: binding[k] for k in ("endpoint", "fingerprint", "token")}
value.update(schema="nodedc.map-egress/v1", timestamp=int(time.time()), profile="cesium")
payload = (
base64.urlsafe_b64encode(json.dumps(value, separators=(",", ":")).encode())
.decode()
.rstrip("=")
)
message = f"nodedc.map-egress/v1\n{method}\n{path}\n{payload}"
signature = hmac.new(bytes.fromhex(key), message.encode(), hashlib.sha256).hexdigest()
return {"x-nodedc-map-egress": payload, "x-nodedc-map-egress-signature": signature}
+269
View File
@@ -0,0 +1,269 @@
from __future__ import annotations
import asyncio
import logging
import re
import time
from collections.abc import Callable
from pathlib import Path
from typing import Any, cast
import httpx
from k1link.fleet.egress import Egress
from k1link.fleet.egress import lock as egress_lock
from k1link.fleet.egress_transport import EgressTransport
from k1link.fleet.trust import PairingError
from .direct import DirectCesium, json_response, read_json
from .egress import gateway_headers
from .settings import CesiumSettings, CesiumSettingsStore, MapServiceError, RouteMode
class _ProviderLogFilter(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
# Bing requires a query credential. Never put provider URLs into HTTP
# client diagnostic logs, including when another feature enables INFO.
message = record.getMessage()
if "virtualearth.net" in message or "cesium.com" in message:
record.msg = "Map provider HTTP request (URL omitted)"
record.args = ()
return True
class MapServiceRoutes:
def __init__(
self,
store: CesiumSettingsStore,
gateway_url: str | None,
client: httpx.AsyncClient,
*,
fleet_root: Path | None = None,
clock: Callable[[], float] = time.monotonic,
) -> None:
self.store, self.gateway_url, self.client, self.clock = store, gateway_url, client, clock
self.fleet_root = fleet_root
self.egress_transport = EgressTransport()
self.gateway_egress = False
self.commit_lock = asyncio.Lock()
self.probe_lock = asyncio.Lock()
self.gateway_available: bool | None = None
self.next_probe = 0.0
self.active_route = "unknown"
self._direct: DirectCesium | None = None
self._revision = -1
self._settings: CesiumSettings | None = None
logger = logging.getLogger("httpx")
if not any(isinstance(item, _ProviderLogFilter) for item in logger.filters):
logger.addFilter(_ProviderLogFilter())
@property
def settings(self) -> CesiumSettings:
if self._settings is None:
self._settings = self.store.read()
return self._settings
@property
def configured(self) -> bool:
try:
return bool(self.settings.token) or bool(self.gateway_url)
except MapServiceError:
return bool(self.gateway_url)
def binding(self, identifier: str) -> dict[str, Any]:
try:
if not self.fleet_root:
raise PairingError("not configured")
return Egress(self.fleet_root).find(identifier)
except PairingError as exc:
raise MapServiceError("cesium_egress_unavailable", 503) from exc
def provider(self, token: str, identifier: str) -> DirectCesium:
if not identifier:
return DirectCesium(token, self.client)
binding = self.binding(identifier)
async def request(method: str, target: str, *, headers: dict[str, str]) -> httpx.Response:
return await self.egress_transport.request(binding, method, target, headers)
return DirectCesium(token, self.client, request)
def direct(self) -> DirectCesium:
settings = self.settings
if self._direct is None or self._revision != settings.revision:
self._direct = self.provider(settings.token, settings.egress_id)
self._revision = settings.revision
return self._direct
def status(self) -> dict[str, Any]:
return {
"schema_version": "missioncore.cesium-service/v1",
**self.settings.public(),
"gateway_configured": bool(self.gateway_url),
"gateway_available": self.gateway_available,
"active_route": self.active_route,
}
async def gateway_ready(self) -> bool:
if not self.gateway_url:
self.gateway_available = False
return False
if self.clock() < self.next_probe:
return self.gateway_available is True
async with self.probe_lock:
if self.clock() < self.next_probe:
return self.gateway_available is True
try:
response = await self.client.send(
self.client.build_request(
"GET",
f"{self.gateway_url}/healthz",
timeout=2.0,
headers={"x-nodedc-user-id": "mission-core-loopback-operator"},
),
stream=True,
)
if response.status_code != 200:
await response.aclose()
raise MapServiceError("map_gateway_unavailable")
value = await read_json(response)
self.gateway_egress = value.get("egressContract") == "nodedc.map-egress/v1"
self.gateway_available = (
value.get("ok") is True and value.get("service") == "nodedc-map-gateway"
)
except (httpx.HTTPError, MapServiceError):
self.gateway_available = False
self.next_probe = self.clock() + 15.0
return self.gateway_available
async def send(
self, method: str, path: str, query: dict[str, str] | None, headers: dict[str, str]
) -> httpx.Response:
mode = self.settings.mode
if mode != "direct" and await self.gateway_ready():
forwarded = dict(headers)
if self.settings.egress_id:
if not self.gateway_egress:
raise MapServiceError("cesium_egress_gateway_not_ready", 503)
forwarded.update(
gateway_headers(
self.store.path.parent / "egress-signing.key",
self.binding(self.settings.egress_id),
method,
path,
)
)
try:
response = await self.client.send(
self.client.build_request(
method,
f"{self.gateway_url}{path}",
params=query,
headers=forwarded,
timeout=httpx.Timeout(30.0, connect=2.0),
),
stream=True,
)
# A cache-policy refusal, auth failure or absent resource is not
# evidence that NAS is down. Preserve that server's decision.
if response.status_code not in (502, 503):
self.active_route = "gateway"
response.headers["x-nodedc-map-route"] = "gateway"
return response
await response.aclose()
except httpx.HTTPError:
self.gateway_available = False
self.next_probe = self.clock() + 15.0
# An upstream 502/503 is not an outage of the cache server.
# Other requests must still be able to read its warm tiles.
if mode == "gateway":
self.active_route = "unavailable"
raise MapServiceError("map_gateway_unavailable")
direct = self.direct()
if not self.settings.token:
self.active_route = "unavailable"
raise MapServiceError("cesium_token_required")
if path == "/healthz":
verification = await direct.verify()
self.active_route = "direct" if verification["ok"] else "unavailable"
return json_response(
{
"service": "missioncore-map-direct",
**verification,
"route": "direct",
"cache": None,
},
200 if verification["ok"] else 503,
)
match = re.fullmatch(r"/api/map/ion/assets/(\d+)/endpoint", path)
if match:
endpoint = await direct.endpoint(int(match[1]))
self.active_route = "direct"
response = json_response(endpoint.public)
elif path == "/api/map/cache" and query:
forwarded = {
key: value
for key, value in headers.items()
if key.lower() in {"accept", "range", "if-none-match", "if-modified-since"}
}
response = await direct.resource(method, query["url"], forwarded)
self.active_route = "direct"
else:
raise MapServiceError("map_route_not_allowed", 404)
response.headers["x-nodedc-map-route"] = "direct"
return response
async def verify(
self, token: str | None = None, egress_id: str | None = None
) -> dict[str, Any]:
candidate = self.provider(
token if token is not None else self.settings.token,
self.settings.egress_id if egress_id is None else egress_id,
)
return await candidate.verify()
async def save(
self,
expected: int,
mode: str,
token: str | None,
*,
remove: bool = False,
egress_id: str | None = None,
) -> dict[str, Any]:
# Validate without replacing the working token. Check revision again
# after awaited provider I/O; a stale tab cannot overwrite newer settings.
candidate = None
selected = self.settings.egress_id if egress_id is None else egress_id
if not remove and (token is not None or selected != self.settings.egress_id):
candidate = self.provider(token if token is not None else self.settings.token, selected)
result = await candidate.verify()
if not result["ok"]:
first = next(item["code"] for item in result["assets"].values() if not item["ok"])
raise MapServiceError(first, 422)
async with self.commit_lock:
if selected and mode != "direct" and self.gateway_url:
if await self.gateway_ready() and not self.gateway_egress:
raise MapServiceError("cesium_egress_gateway_not_ready", 503)
gateway_headers(
self.store.path.parent / "egress-signing.key",
self.binding(selected),
"GET",
"/healthz",
)
previous = self.store.read()
next_settings = CesiumSettings(
expected,
cast(RouteMode, mode),
"" if remove else (previous.token if token is None else token),
selected,
)
with egress_lock:
if selected:
self.binding(selected)
self._settings = self.store.save(next_settings, expected)
self._direct = candidate
self._revision = self._settings.revision
self.next_probe = 0
self.active_route = "unknown"
return self.status()
+123
View File
@@ -0,0 +1,123 @@
from __future__ import annotations
import json
import os
import re
import tempfile
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Literal
RouteMode = Literal["auto", "direct", "gateway"]
MODES = {"auto", "direct", "gateway"}
class MapServiceError(Exception):
def __init__(self, code: str, status: int = 503) -> None:
self.code = code
self.status = status
super().__init__(code)
@dataclass(frozen=True)
class CesiumSettings:
revision: int = 0
mode: RouteMode = "auto"
token: str = field(default="", repr=False)
egress_id: str = ""
def public(self) -> dict[str, Any]:
return {
"revision": self.revision,
"mode": self.mode,
"token_configured": bool(self.token),
"egress_id": self.egress_id,
}
def validate_egress(value: object) -> str:
if not isinstance(value, str) or (value and not re.fullmatch(r"eg_[a-f0-9]{32}", value)):
raise MapServiceError("cesium_egress_invalid", 422)
return value
def validate_token(value: object) -> str:
if not isinstance(value, str) or not 1 <= len(value.strip()) <= 8192:
raise MapServiceError("cesium_token_invalid", 422)
token = value.strip()
if not token.isascii() or any(character.isspace() for character in token):
raise MapServiceError("cesium_token_invalid", 422)
return token
class CesiumSettingsStore:
"""One installation-owned secret document; never exposed as a profile or cache."""
def __init__(self, path: Path) -> None:
self.path = path
def read(self) -> CesiumSettings:
try:
if self.path.is_symlink() or self.path.stat().st_size > 16384:
raise ValueError
value = json.loads(self.path.read_text())
if (
value.get("schema_version") != "missioncore.cesium-service/v1"
or type(value.get("revision")) is not int
or value["revision"] < 1
or value.get("mode") not in MODES
):
raise ValueError
token = validate_token(value["token"]) if value.get("token") else ""
return CesiumSettings(
value["revision"], value["mode"], token, validate_egress(value.get("egress_id", ""))
)
except FileNotFoundError:
return CesiumSettings()
except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
raise MapServiceError("cesium_settings_unreadable", 503) from exc
def save(self, settings: CesiumSettings, expected_revision: int) -> CesiumSettings:
# The owner serializes commits, including the revision check, in one lock.
if self.read().revision != expected_revision:
raise MapServiceError("cesium_settings_conflict", 409)
directory = self.path.parent
try:
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
if directory.resolve() != directory or self.path.is_symlink():
raise MapServiceError("cesium_settings_unwritable", 503)
os.chmod(directory, 0o700)
descriptor, temporary = tempfile.mkstemp(prefix=".cesium-", dir=directory)
except OSError as exc:
raise MapServiceError("cesium_settings_unwritable", 503) from exc
next_value = CesiumSettings(
expected_revision + 1,
settings.mode,
settings.token,
validate_egress(settings.egress_id),
)
payload = {
"schema_version": "missioncore.cesium-service/v1",
"revision": next_value.revision,
"mode": next_value.mode,
"token": next_value.token,
"egress_id": next_value.egress_id,
}
try:
with os.fdopen(descriptor, "w") as output:
os.fchmod(output.fileno(), 0o600)
json.dump(payload, output)
output.flush()
os.fsync(output.fileno())
os.replace(temporary, self.path)
directory_fd = os.open(directory, os.O_RDONLY)
try:
os.fsync(directory_fd)
finally:
os.close(directory_fd)
except OSError as exc:
raise MapServiceError("cesium_settings_unwritable", 503) from exc
finally:
Path(temporary).unlink(missing_ok=True)
return next_value
+25
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import fcntl
import hashlib
import json
import math
import os
from contextlib import contextmanager
from datetime import UTC, datetime
@@ -19,6 +20,8 @@ KINDS = {
"battery-ui": "missioncore.battery-ui/v1",
"battery-view": "missioncore.battery-view/v1",
"environments": "missioncore.environment-library/v1",
"observation-map": "missioncore.observation-map/v1",
"rover-view": "missioncore.rover-view/v1",
}
_lock = RLock()
@@ -44,6 +47,28 @@ def validate_document(kind: str, document: Any) -> None:
height = document.get("height")
if type(height) not in (int, float) or not 360 <= height <= 2160:
raise ValueError("Неверная высота окна.")
elif kind == "observation-map":
camera, layers = document.get("camera"), document.get("layers")
limits = {"longitude": (-180, 180), "latitude": (-90, 90),
"height": (-100_000, 1_000_000_000), "heading": (-360, 360),
"pitch": (-90, 90), "roll": (-360, 360)}
if set(document) != {"schema", "camera", "layers"} or (
camera is not None and (
not isinstance(camera, dict) or set(camera) != set(limits)
or any(type(camera[k]) not in (float, int) or not math.isfinite(camera[k])
or not low <= camera[k] <= high for k, (low, high) in limits.items())
)
):
raise ValueError("Неверное положение камеры карты.")
if not isinstance(layers, dict) or set(layers) != {
"imagery", "terrain", "buildings", "grid", "targets"
} or any(type(v) is not bool for v in layers.values()):
raise ValueError("Неверная видимость слоёв карты.")
elif kind == "rover-view":
if set(document) != {"schema", "model"} or document.get("model") not in (
"", "dcd006-v022"
):
raise ValueError("Неверная модель аппарата.")
else:
profiles = document.get("profiles")
if not isinstance(profiles, list) or len(profiles) > 64:
@@ -0,0 +1,75 @@
"""Worker-owned originals for legacy PLY worlds and simulation projects."""
import hashlib
from k1link.simulation.gaussian_pipeline_gateway import GaussianPipelineIntegrityError
from k1link.simulation.source_retention import receipt_files
from .worlds import write_json
def original_receipt(worlds, world_id):
world = worlds.get(world_id)
if world.get("storage", {}).get("kind") == "project":
project = worlds.projects.projects.get(world["storage"]["project_id"])
storage = project["source"].get("storage", {})
else:
storage = world.get("original_storage", {})
receipt = storage.get("receipt")
if not receipt:
raise ValueError(
"Исходник ещё не подтверждён в хранилище. Повторите после завершения импорта."
)
return world, storage, receipt
def retain_legacy_original(worlds, world_id, provider, editor):
"""A receipt and usable render result must survive before an exact source unlink."""
with worlds.lock:
world = worlds.get(world_id)
cache = editor.get(editor.request(world_id)["key"])
if cache["status"] != "ready":
raise ValueError("Сначала дождитесь готового материала для просмотра.")
for name in cache["files"]:
path, expected = editor.asset(cache["key"], name)
with path.open("rb") as stream:
if hashlib.file_digest(stream, "sha256").hexdigest() != expected:
raise GaussianPipelineIntegrityError("Render asset changed; original retained")
source = worlds.directory(world_id) / "source.ply"
storage = world.get("original_storage")
if storage:
if storage["provider_endpoint"] != provider.endpoint:
raise GaussianPipelineIntegrityError("Original provider changed")
receipt = provider.retained_source(storage["receipt"], verify=True)
else:
provider.require_source_retention()
if source.is_symlink() or not source.is_file():
raise GaussianPipelineIntegrityError("Local original missing")
with source.open("rb") as stream:
if hashlib.file_digest(stream, "sha256").hexdigest() != world["sha256"]:
raise GaussianPipelineIntegrityError("Local original changed")
bundle = provider.upload_source_bundle(
source.parent, entrypoint="source.ply", source_format="ply"
)
receipt = provider.retain_source({"kind": "folder", "source": bundle.to_dict()})
provider.retained_source(receipt, verify=True)
if receipt_files(receipt) != {"source.ply": (world["byte_length"], world["sha256"])}:
raise GaussianPipelineIntegrityError("Worker did not retain this exact PLY")
world["original_storage"] = {
"provider_endpoint": provider.endpoint,
"receipt": receipt,
"local_state": "retiring",
}
write_json(worlds.directory(world_id) / "world.json", world)
removed = 0
if source.exists():
if source.is_symlink() or source.stat().st_size != world["byte_length"]:
raise GaussianPipelineIntegrityError("Source changed before removal")
with source.open("rb") as stream:
if hashlib.file_digest(stream, "sha256").hexdigest() != world["sha256"]:
raise GaussianPipelineIntegrityError("Source changed before removal")
removed = source.stat().st_size
source.unlink()
world["original_storage"]["local_state"] = "remote"
write_json(worlds.directory(world_id) / "world.json", world)
return {"world_id": world_id, "removed_bytes": removed, "source_id": receipt["source_id"]}
@@ -54,9 +54,9 @@ class ProjectWorlds:
"schema_version": "missioncore.ai-polygon-world/v1",
"world_id": project["project_id"].replace("sim-", "aiworld-", 1),
"name": project["name"],
"author": "",
"license": "",
"source_url": None,
"author": project.get("attribution", {}).get("author", ""),
"license": project.get("attribution", {}).get("license", ""),
"source_url": project.get("attribution", {}).get("source_url"),
"filename": "lod-meta.json",
"byte_length": sum(a["byte_length"] for a in project["artifacts"]),
"status": "available",
@@ -174,8 +174,8 @@ class GaussianPipelineGateway:
source_format: str,
additional_paths: list[str] | None = None,
) -> GaussianSourceBundleUpload:
if source_format not in {"lcc", "lcc2"}:
raise GaussianPipelineIntegrityError("Gaussian source format must be lcc or lcc2")
if source_format not in {"lcc", "lcc2", "ply"}:
raise GaussianPipelineIntegrityError("Gaussian source format must be lcc, lcc2 or Gaussian ply")
logical_entrypoint = _logical_path(entrypoint, "entrypoint")
if not logical_entrypoint.lower().endswith(f".{source_format}"):
raise GaussianPipelineIntegrityError(
@@ -237,7 +237,7 @@ class GaussianPipelineGateway:
members=members,
)
def upload_source_archive(self, archive_path: Path) -> GaussianArchiveUpload:
def upload_source_archive(self, archive_path: Path, *, owner_id: str | None = None) -> GaussianArchiveUpload:
source_candidate = archive_path.expanduser().absolute()
if source_candidate.is_symlink() or not source_candidate.is_file():
raise GaussianPipelineIntegrityError(
@@ -266,6 +266,24 @@ class GaussianPipelineGateway:
raise GaussianPipelineIntegrityError(
"Gaussian source archive exceeds provider byte admission"
)
if owner_id is not None:
self.require_shared_source_retention(capabilities)
claimed = self._json("POST", "/v1/sources/claim", document={
"owner_id": owner_id,
"archive": {"archive_name": archive_name, "format": archive_format,
"sha256": digest, "byte_length": byte_length},
}, timeout_seconds=self.ingest_timeout_seconds).get("receipt")
if claimed is not None:
from k1link.simulation.source_retention import validate_receipt
validate_receipt(claimed)
original = claimed["input"]
if (claimed.get("owner_id") != owner_id or original["kind"] != "archive"
or {k: v for k, v in original["archive"].items() if k != "upload_id"} != {
"archive_name": archive_name, "format": archive_format,
"sha256": digest, "byte_length": byte_length,
}):
raise GaussianPipelineIntegrityError("Worker claimed different source bytes or owner")
return GaussianArchiveUpload(**original["archive"])
upload_id = self._upload_file(
source,
{"archive_name": archive_name, "sha256": digest},
@@ -304,11 +322,32 @@ class GaussianPipelineGateway:
"Worker не поддерживает постоянное хранение исходников. Обновите Gaussian Pipeline."
)
def retain_source(self, original: dict[str, Any]) -> dict[str, Any]:
@staticmethod
def require_shared_source_retention(capabilities: dict[str, Any]) -> None:
if capabilities.get("source_deduplication") != "owned-archive-sha256/v1":
raise GaussianPipelineGatewayError(
"Worker не поддерживает общий дедуп исходников. Обновите Gaussian Pipeline."
)
def retain_source(self, original: dict[str, Any], *, owner_id: str | None = None) -> dict[str, Any]:
from k1link.simulation.source_retention import validate_receipt
receipt = self._json("POST", "/v1/sources", document=original,
timeout_seconds=self.ingest_timeout_seconds)
validate_receipt(receipt, expected=original)
if owner_id is None:
receipt = self._json("POST", "/v1/sources", document=original,
timeout_seconds=self.ingest_timeout_seconds)
validate_receipt(receipt, expected=original)
return receipt
self.require_shared_source_retention(self.capabilities())
receipt = self._json("POST", "/v1/sources/retain",
document={"owner_id": owner_id, "input": original},
timeout_seconds=self.ingest_timeout_seconds).get("receipt")
validate_receipt(receipt)
expected = original
if original["kind"] == "archive" and receipt["input"]["kind"] == "archive":
expected = {"kind": "archive", "archive": {**original["archive"],
"upload_id": receipt["input"]["archive"]["upload_id"]}}
validate_receipt(receipt, expected=expected)
if receipt.get("owner_id") != owner_id:
raise GaussianPipelineIntegrityError("Worker retained source for a different owner")
return receipt
def retained_source(self, receipt: dict[str, Any], *, verify: bool = False) -> dict[str, Any]:
@@ -326,23 +365,31 @@ class GaussianPipelineGateway:
return self._json("GET", f"/v1/jobs/{quote(job_id, safe='')}/source")
def stream_retained_archive(self, receipt: dict[str, Any]) -> Iterator[bytes]:
"""Compatibility transport for existing analysis clients; no disk staging."""
import hashlib
return self.stream_retained_file(receipt, receipt["input"]["archive"]["archive_name"])
def stream_retained_file(self, receipt: dict[str, Any], logical_path: str) -> Iterator[bytes]:
"""Bounded original download, without creating a Core cache or staging file."""
from k1link.simulation.source_retention import receipt_files
self.retained_source(receipt)
archive = receipt["input"]["archive"]
with self._client.stream("GET", f"/v1/sources/{receipt['source_id']}/archive",
files = receipt_files(receipt)
if logical_path not in files:
raise GaussianPipelineIntegrityError("File is not part of this retained source")
size, expected_hash = files[logical_path]
suffix = "archive" if receipt["input"]["kind"] == "archive" else "member?path=" + quote(logical_path, safe="")
with self._client.stream("GET", f"/v1/sources/{receipt['source_id']}/{suffix}",
timeout=self.ingest_timeout_seconds) as response:
response.raise_for_status()
digest = hashlib.sha256()
length = 0
if int(response.headers.get("Content-Length", "-1")) != size:
raise GaussianPipelineIntegrityError("Worker original size changed")
digest, length = hashlib.sha256(), 0
for chunk in response.iter_bytes(1024 * 1024):
length += len(chunk)
if length > archive["byte_length"]:
raise GaussianPipelineIntegrityError("Worker archive size changed")
if length > size:
raise GaussianPipelineIntegrityError("Worker original size changed")
digest.update(chunk)
yield chunk
if length != archive["byte_length"] or digest.hexdigest() != archive["sha256"]:
raise GaussianPipelineIntegrityError("Worker archive integrity mismatch")
if length != size or digest.hexdigest() != expected_hash:
raise GaussianPipelineIntegrityError("Worker original integrity mismatch")
def _upload_member(
self,
@@ -423,10 +470,22 @@ class GaussianPipelineGateway:
_safe_id(job_id, "job id")
try:
response = self._client.delete(f"/v1/jobs/{quote(job_id, safe='')}")
response.raise_for_status()
if response.status_code != 404:
response.raise_for_status()
except httpx.HTTPError as exc:
raise _unavailable("Gaussian job deletion failed", exc) from exc
def delete_retained_source(self, receipt: dict[str, Any]) -> None:
from k1link.simulation.source_retention import validate_receipt
validate_receipt(receipt)
try:
response = self._client.delete(f"/v1/sources/{receipt['source_id']}")
# Missing endpoint/source is not an acknowledgement. A durable Worker
# tombstone returns 204 after retries, including a restarted process.
response.raise_for_status()
except httpx.HTTPError as exc:
raise _unavailable("Не удалось удалить исходные файлы на Worker", exc) from exc
def download_artifact(
self,
job_id: str,
@@ -604,6 +663,12 @@ def discover_gaussian_source_bundle(root_path: Path) -> tuple[str, str]:
suffix = candidate.suffix.lower()
if suffix in {".lcc", ".lcc2"}:
descriptors.append(candidate.relative_to(root).as_posix())
if not descriptors:
files = [p for p in root.rglob("*") if p.is_file()]
if len(files) == 1 and files[0].suffix.lower() == ".ply":
entrypoint = files[0].relative_to(root).as_posix()
_discover_bundle_members(root, entrypoint, "ply")
return entrypoint, "ply"
descriptors.sort(key=lambda value: value.encode("utf-8"))
if len(descriptors) != 1:
raise GaussianPipelineIntegrityError(
@@ -716,7 +781,7 @@ def _source_bundle_upload(value: object) -> GaussianSourceBundleUpload:
total_byte_length = value.get("total_byte_length")
raw_members = value.get("members")
if (
source_format not in {"lcc", "lcc2"}
source_format not in {"lcc", "lcc2", "ply"}
or not isinstance(entrypoint, str)
or not entrypoint.lower().endswith(f".{source_format}")
or not isinstance(bundle_sha256, str)
@@ -796,6 +861,10 @@ def _source_bundle_upload(value: object) -> GaussianSourceBundleUpload:
def _discover_bundle_members(root: Path, entrypoint: str, source_format: str) -> set[str]:
descriptor = _bundle_member(root, entrypoint)
if source_format == "ply":
from k1link.simulation.ai_polygon.worlds import inspect_gaussian_ply
inspect_gaussian_ply(descriptor)
return {entrypoint}
if descriptor.stat().st_size > 16 * 1024 * 1024:
raise GaussianPipelineIntegrityError("Gaussian source descriptor is too large")
try:
+148
View File
@@ -0,0 +1,148 @@
"""Durable explicit deletion: retain the catalog until Worker acknowledges cleanup."""
from __future__ import annotations
import json
import os
import shutil
import threading
from k1link.artifacts import utc_now_iso
def write_json(path, value):
from k1link.simulation.ai_polygon.worlds import write_json as persist
persist(path, value)
descriptor = os.open(path.parent, os.O_RDONLY)
try:
os.fsync(descriptor)
finally:
os.close(descriptor)
class ProjectDeletions:
def __init__(self, service):
self.service = service
self.root = service.store.root / "deletions"
self.root.mkdir(parents=True, exist_ok=True)
self.lock = threading.RLock()
self.thread = None
self.wake = threading.Event()
def path(self, project_id):
self.service.store._project_root(project_id) # Canonical identity validation.
return self.root / f"{project_id}.json"
def contains(self, project_id):
return self.path(project_id).exists()
def list(self):
return [json.loads(p.read_text()) for p in sorted(self.root.glob("sim-*.json"))]
def request(self, project_id):
with self.lock:
if not self.contains(project_id):
project = self.service.store.get(project_id)
self.check_dependencies(project_id)
write_json(
self.path(project_id),
dict(
project_id=project_id,
name=project["name"],
requested_at=utc_now_iso(),
state="deleting",
error=None,
),
)
self.start()
self.wake.set()
def start(self):
with self.lock:
if self.thread is not None and self.thread.is_alive():
return
self.thread = threading.Thread(
target=self._run, name="simulation-deletions", daemon=True
)
self.thread.start()
def _run(self):
while True:
with self.lock:
rows = self.list()
if not rows:
self.thread = None
return
for row in rows:
self.attempt(row)
self.wake.wait(5)
self.wake.clear()
def attempt(self, row):
from k1link.simulation.projects import SimulationProjectNotFoundError
try:
try:
self.service.store.get(row["project_id"])
except SimulationProjectNotFoundError:
# Local deletion is the last step, after all remote acknowledgements.
self.path(row["project_id"]).unlink(missing_ok=True)
return
self.service.delete(row["project_id"])
self.path(row["project_id"]).unlink(missing_ok=True)
except Exception as exc:
write_json(self.path(row["project_id"]), {**row, "state": "waiting", "error": str(exc)})
def check_dependencies(self, project_id):
from k1link.simulation.projects import SimulationProjectConflictError
world_id = project_id.replace("sim-", "aiworld-", 1)
ai = self.service.store.root.parent / "ai-polygon"
# These are independent durable records, never disposable render caches.
# Refuse instead of silently orphaning a run or deleting shared evidence.
for folder in (
"runs",
"plans",
"infrastructure-jobs",
"route-preparations",
"semantic-edits",
"spatial-experience",
"urban-maps",
):
root = ai / folder
for path in root.rglob("*.json"):
if path.is_symlink():
raise SimulationProjectConflictError(
"Не удалось проверить связанные данные локации."
)
if contains_identity(path, world_id, project_id):
raise SimulationProjectConflictError(
"Локация используется в сохранённых заданиях или разметке. "
"Сначала удалите связанные задания; файлы локации сохранены."
)
def clean_local_views(self, project_id):
world_id = project_id.replace("sim-", "aiworld-", 1)
ai = self.service.store.root.parent / "ai-polygon"
for manifest in (ai / "editor-cache").glob("*/manifest.json"):
if manifest.is_symlink() or manifest.parent.is_symlink():
raise ValueError("Небезопасный путь кэша локации.")
row = json.loads(manifest.read_text())
if row.get("identity", {}).get("world_id") == world_id:
shutil.rmtree(manifest.parent)
(ai / "world-library" / f"{world_id}.json").unlink(missing_ok=True)
def contains_identity(path, *identities):
"""Scan large evidence JSON without loading geometry arrays into Core RAM."""
needles = [identity.encode("ascii") for identity in identities]
overlap = max(map(len, needles)) - 1
tail = b""
with path.open("rb") as stream:
while chunk := stream.read(64 * 1024):
window = tail + chunk
if any(needle in window for needle in needles):
return True
tail = window[-overlap:] if overlap else b""
return False
+37 -28
View File
@@ -87,6 +87,7 @@ class SimulationProjectStore:
scene_type: str,
source_kind: str,
files: list[dict[str, object]],
attribution: dict[str, str | None] | None = None,
) -> dict[str, Any]:
display_name = _project_name(name)
if scene_type not in {"interior", "outdoor", "object"}:
@@ -140,6 +141,7 @@ class SimulationProjectStore:
"schema_version": PROJECT_SCHEMA,
"project_id": project_id,
"name": display_name,
"attribution": attribution or {},
"scene_type": scene_type,
"status": "uploading",
"source": {
@@ -489,10 +491,13 @@ class SimulationProjectService:
self._worker: threading.Thread | None = None
self._cancel_events: dict[str, threading.Event] = {}
self._inflight_jobs: dict[str, str] = {}
from k1link.simulation.project_deletions import ProjectDeletions
self.deletions = ProjectDeletions(self)
def recover_pending(self) -> int:
self.deletions.start()
pending = sorted(
[project for project in self.store.list() if project.get("status") in ACTIVE_STATES],
[project for project in self.store.list() if project.get("status") in ACTIVE_STATES and not self.deletions.contains(project["project_id"])],
key=lambda project: (
str(project.get("created_at_utc")),
str(project.get("project_id")),
@@ -509,6 +514,8 @@ class SimulationProjectService:
"simulation project is not ready for queued processing"
)
with self._condition:
if self.deletions.contains(project_id):
raise SimulationProjectConflictError("Удаление локации уже начато.")
if project_id in self._queued_ids or project_id == self._active_project_id:
return
event = self._cancel_events.setdefault(project_id, threading.Event())
@@ -585,6 +592,8 @@ class SimulationProjectService:
provider.close()
def begin_build(self, project_id: str) -> dict[str, Any]:
if self.deletions.contains(project_id):
raise SimulationProjectConflictError("Локация удаляется.")
project = self.store.get(project_id)
if project.get("status") == "failed":
job_id = project["provider"].get("job_id")
@@ -689,7 +698,6 @@ class SimulationProjectService:
job_id = submitted.get("job_id")
if not isinstance(job_id, str):
raise SimulationProjectError("Gaussian Pipeline не вернул job id.")
self._register_inflight_job(project_id, job_id, provider)
self.store.update_processing(
project_id,
status="processing",
@@ -704,6 +712,7 @@ class SimulationProjectService:
progress=submitted.get("progress"),
bundle_sha256=source.bundle_sha256,
)
self._register_inflight_job(project_id, job_id, provider)
deadline = time.monotonic() + PROVIDER_POLL_TIMEOUT_SECONDS
while True:
self._raise_if_cancelled(project_id)
@@ -813,42 +822,42 @@ class SimulationProjectService:
)
def delete(self, project_id: str) -> None:
self.deletions.check_dependencies(project_id)
project = self.store.get(project_id)
with self._condition:
cancel = self._cancel_events.setdefault(project_id, threading.Event())
cancel.set()
if project_id in self._queued_ids:
self._queue = deque(item for item in self._queue if item != project_id)
self._queued_ids.discard(project_id)
job_id = self._inflight_jobs.pop(
project_id,
project["provider"].get("job_id"),
)
self._queue = deque(item for item in self._queue if item != project_id)
self._queued_ids.discard(project_id)
self._condition.notify_all()
if isinstance(job_id, str):
# Do not remove source/artifact directories under a live writer. The
# persisted deletion intent survives while this producer stops.
if not self._condition.wait_for(lambda: self._active_project_id != project_id, timeout=10):
raise SimulationProjectConflictError("Остановка обработки локации.")
project = self.store.get(project_id)
job_id = project["provider"].get("job_id")
receipts = [r for r in [project["source"].get("prepared_receipt"),
project["source"].get("storage", {}).get("receipt")] if r]
others = [p for p in self.store.list() if p["project_id"] != project_id]
shared_jobs = {p["provider"].get("job_id") for p in others}
shared_sources = {r["source_id"] for p in others for r in
[p["source"].get("prepared_receipt"), p["source"].get("storage", {}).get("receipt")] if r}
if job_id or receipts:
provider = self.provider_factory()
if provider is None:
with suppress(SimulationProjectError):
self.store.fail(
project_id,
"Gaussian Pipeline недоступен для удаления серверных артефактов.",
)
raise SimulationProjectConflictError(
"Gaussian Pipeline недоступен для удаления серверных артефактов."
)
raise GaussianPipelineUnavailableError("Worker недоступен. Удаление продолжится после подключения.")
try:
if project["source"].get("storage"):
provider.require_source_retention()
provider.delete_job(job_id)
except GaussianPipelineGatewayError:
with suppress(SimulationProjectError):
self.store.fail(
project_id,
"Не удалось удалить активную сборку на Worker 006.",
)
raise
endpoint = project["source"].get("storage", {}).get("provider_endpoint")
if endpoint and endpoint != provider.endpoint:
raise SimulationProjectConflictError("Изменился сервер исходников. Проверьте подключение.")
if job_id and job_id not in shared_jobs:
provider.delete_job(job_id)
for receipt in receipts:
if receipt["source_id"] not in shared_sources:
provider.delete_retained_source(receipt)
finally:
provider.close()
self.deletions.clean_local_views(project_id)
self.store.delete(project_id, allow_active=True)
with self._condition:
self._cancel_events.pop(project_id, None)
+4 -3
View File
@@ -196,7 +196,7 @@ def prepare_source(
root = store.source_root(project_id)
if project["source"]["kind"] == "archive":
item = project["source"]["files"][0]
archive = provider.upload_source_archive(root / item["logical_path"])
archive = provider.upload_source_archive(root / item["logical_path"], owner_id=f"simulation/{project_id}/original")
original = {"kind": "archive", "archive": archive.to_dict()}
else:
entrypoint, source_format = discover_gaussian_source_bundle(root)
@@ -207,7 +207,7 @@ def prepare_source(
additional_paths=[f["logical_path"] for f in project["source"]["files"]],
)
original = {"kind": "folder", "source": bundle.to_dict()}
receipt = provider.retain_source(original)
receipt = provider.retain_source(original, owner_id=f"simulation/{project_id}/original")
confirm_storage(store, project_id, provider, receipt)
retire_local_source(store, project_id, provider)
original = receipt["input"]
@@ -217,7 +217,8 @@ def prepare_source(
if prepared:
return _source_bundle_upload(provider.retained_source(prepared)["input"]["source"])
bundle = provider.normalize_archive(GaussianArchiveUpload(**original["archive"]))
prepared = provider.retain_source({"kind": "folder", "source": bundle.to_dict()})
prepared = provider.retain_source({"kind": "folder", "source": bundle.to_dict()},
owner_id=f"simulation/{project_id}/prepared")
store.update_source_storage(project_id, prepared_receipt=prepared)
return bundle
+19 -1
View File
@@ -49,6 +49,8 @@ def build_ai_polygon_router(
editor = EditorCache(data_dir, worlds)
routes = RoutePreparationStore(data_dir)
router = APIRouter(prefix="/api/v1/ai-polygon", tags=["ai-polygon"])
from k1link.web.simulation_originals_api import build_simulation_originals_router
router.include_router(build_simulation_originals_router(worlds))
adapters = Path(__file__).resolve().parents[3] / "simulation/ai-polygon"
from k1link.web.ai_profile_api import build_ai_profile_router
@@ -142,7 +144,7 @@ def build_ai_polygon_router(
@router.post("/worlds", status_code=201)
def create_world(body: WorldCreate):
return invoke(worlds.create, body)
raise HTTPException(410, "Импорт PLY перенесён в серверную обработку локаций. Обновите приложение.")
@router.get("/worlds/{world_id}")
def get_world(world_id: str):
@@ -187,6 +189,22 @@ def build_ai_polygon_router(
raise HTTPException(409, "Импорт не завершён.")
if row.get("storage", {}).get("kind") == "worker":
raise HTTPException(409, "Исходник локации хранится на Worker.")
if row.get("original_storage"):
from k1link.simulation.gaussian_pipeline_gateway import configured_gaussian_pipeline_gateway
provider = configured_gaussian_pipeline_gateway()
if provider is None:
raise HTTPException(503, "Сервер исходников недоступен.")
storage = row["original_storage"]
if provider.endpoint != storage["provider_endpoint"]:
provider.close()
raise HTTPException(503, "Хранилище исходника изменилось.")
def original_stream():
try:
yield from provider.stream_retained_file(storage["receipt"], "source.ply")
finally:
provider.close()
return StreamingResponse(original_stream(), media_type="application/octet-stream",
headers={"Content-Length": str(row["byte_length"]), "Cache-Control": "no-store"})
return FileResponse(
worlds.directory(world_id) / "source.ply",
media_type="application/octet-stream",
+5 -1
View File
@@ -540,7 +540,11 @@ try:
except (OSError, ValueError):
lab_gateway_configuration = None
laboratory_worker_gateway = LaboratoryWorkerGateway(lab_gateway_configuration)
map_gateway_proxy = MapGatewayProxy(MapGatewayConfiguration.from_environment())
map_gateway_proxy = MapGatewayProxy(
MapGatewayConfiguration.from_environment(),
settings_path=session_store.data_dir / "services" / "cesium-ion" / "settings.json",
fleet_root=session_store.data_dir / "fleet",
)
recording_reconciler_readiness = BackgroundReconcilerReadiness()
+6 -1
View File
@@ -82,8 +82,13 @@ class BimModuleSurface:
)
services = None
try:
from k1link.simulation.gaussian_pipeline_gateway import configured_gaussian_pipeline_gateway
gaussian = configured_gaussian_pipeline_gateway()
services = HostServices(
ProjectStore(root / "documents"), copies, BoundWorker(binding)
ProjectStore(root / "documents"), copies, BoundWorker(binding),
gaussian_endpoint=gaussian.endpoint if gaussian else None,
gaussian_token_file=gaussian.token_file if gaussian else None,
)
application = create_host_app(services, authorize_operator)
except BaseException:
+2 -1
View File
@@ -14,8 +14,9 @@ from k1link.web.fleet_api import local_operator
router = APIRouter(prefix="/api/v1/fleet/installers", tags=["installers"])
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
KINDS = {"node", "vps-arnavi", "vps-wireguard", "vps-netbird", "vps-librespeed"}
KINDS = {"node", "vps-arnavi", "vps-wireguard", "vps-netbird", "vps-librespeed", "vps-egress"}
DOWNLOAD_NAMES = {
"vps-egress": "mission-core-egress-vps.pyz",
"vps-librespeed": "mission-core-librespeed-vps.pyz",
"node": "mission-core-node-install.pyz",
"vps-arnavi": "mission-core-vps-install.pyz",
+26 -2
View File
@@ -5,6 +5,7 @@ import re
from collections.abc import AsyncIterator, Mapping
from dataclasses import dataclass
from ipaddress import ip_address
from pathlib import Path as FilePath
from typing import Annotated, Any, Final
from urllib.parse import parse_qsl, urlsplit
@@ -12,12 +13,17 @@ import httpx
from fastapi import APIRouter, HTTPException, Path, Query, Request
from fastapi.responses import JSONResponse, Response, StreamingResponse
from k1link.maps.direct import json_response
from k1link.maps.routing import MapServiceRoutes
from k1link.maps.settings import CesiumSettingsStore, MapServiceError
from k1link.web.map_services_api import build_map_services_router
MAP_GATEWAY_URL_ENV: Final = "MISSIONCORE_MAP_GATEWAY_INTERNAL_URL"
MAP_SANDBOX_HIDE_CREDITS_ENV: Final = "MISSIONCORE_MAP_SANDBOX_HIDE_CREDITS"
MAP_SCHEMA_VERSION: Final = "missioncore.map-gateway/v1"
MAP_RUNTIME_SCHEMA_VERSION: Final = "missioncore.map-runtime/v1"
MAP_PAGE_VERSION: Final = "0.1.0"
CESIUM_RENDERER_VERSION: Final = "1.143.0"
CESIUM_RENDERER_VERSION: Final = "1.147.0"
MAP_GATEWAY_SUBJECT: Final = "mission-core-loopback-operator"
ALLOWED_ION_ASSET_IDS: Final = frozenset({1, 2, 96188})
SAFE_ERROR_CODE = re.compile(r"^[a-z][a-z0-9_]{0,95}$")
@@ -46,6 +52,7 @@ RESPONSE_HEADER_ALLOWLIST: Final = frozenset(
"expires",
"last-modified",
"vary",
"x-nodedc-map-route",
}
)
SENSITIVE_JSON_KEYS: Final = frozenset(
@@ -100,6 +107,8 @@ class MapGatewayProxy:
configuration: MapGatewayConfiguration,
*,
client: httpx.AsyncClient | None = None,
settings_path: FilePath | None = None,
fleet_root: FilePath | None = None,
) -> None:
self._configuration = configuration
self._owns_client = client is None
@@ -117,10 +126,14 @@ class MapGatewayProxy:
keepalive_expiry=30.0,
),
)
self.routes = (MapServiceRoutes(CesiumSettingsStore(settings_path),
configuration.internal_url, self._client, fleet_root=fleet_root)
if settings_path is not None else None)
@property
def configured(self) -> bool:
return self._configuration.internal_url is not None
return (self.routes.configured if self.routes is not None
else self._configuration.internal_url is not None)
def runtime_configuration(self) -> Response:
if not self.configured:
@@ -249,6 +262,15 @@ class MapGatewayProxy:
query: Mapping[str, str] | None = None,
) -> httpx.Response:
_require_loopback_request(request)
if self.routes is not None:
headers = {name: value for name, value in request.headers.items()
if name.lower() in REQUEST_HEADER_ALLOWLIST}
headers["x-nodedc-user-id"] = MAP_GATEWAY_SUBJECT
try:
return await self.routes.send(request.method, upstream_path,
dict(query) if query else None, headers)
except MapServiceError as exc:
return json_response({"code": exc.code, "retryable": exc.status >= 500}, exc.status)
base_url = self._configuration.internal_url
if base_url is None:
raise HTTPException(
@@ -452,6 +474,8 @@ def _filtered_response_headers(headers: httpx.Headers) -> dict[str, str]:
def build_map_router(service: MapGatewayProxy) -> APIRouter:
router = APIRouter(prefix="/api/v1/map", tags=["map"])
if service.routes is not None:
router.include_router(build_map_services_router(service.routes, _require_loopback_request))
@router.get("/runtime-config")
async def runtime_config(request: Request) -> Response:
+102
View File
@@ -0,0 +1,102 @@
from __future__ import annotations
import json
from collections.abc import Callable
from typing import Any
from urllib.parse import urlsplit
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from k1link.maps.routing import MapServiceRoutes
from k1link.maps.settings import MODES, MapServiceError, validate_egress, validate_token
def reply(value: dict[str, Any], status: int = 200) -> JSONResponse:
return JSONResponse(value, status_code=status, headers={"Cache-Control": "no-store"})
async def payload(request: Request) -> dict[str, Any]:
host = urlsplit(str(request.url)).hostname
origin = request.headers.get("origin")
if (
host not in {"127.0.0.1", "localhost", "::1"}
or request.headers.get("sec-fetch-site") == "cross-site"
or (origin is not None and origin != str(request.base_url).rstrip("/"))
):
raise MapServiceError("cesium_settings_local_only", 403)
if request.headers.get("content-type", "").split(";", 1)[0] != "application/json":
raise MapServiceError("cesium_settings_invalid_request", 415)
body = bytearray()
async for chunk in request.stream():
body.extend(chunk)
if len(body) > 16384:
raise MapServiceError("cesium_settings_invalid_request", 413)
try:
value = json.loads(body)
if not isinstance(value, dict):
raise ValueError
return value
except (ValueError, UnicodeError) as exc:
raise MapServiceError("cesium_settings_invalid_request", 422) from exc
def build_map_services_router(
service: MapServiceRoutes, require_local: Callable[[Request], None]
) -> APIRouter:
router = APIRouter(prefix="/services/cesium-ion")
@router.get("")
async def status(request: Request) -> JSONResponse:
require_local(request)
try:
return reply(service.status())
except MapServiceError as exc:
return reply({"code": exc.code}, exc.status)
@router.post("/verify")
async def verify(request: Request) -> JSONResponse:
require_local(request)
try:
value = await payload(request)
if set(value) - {"token", "egress_id"}:
raise MapServiceError("cesium_settings_invalid_request", 422)
token = validate_token(value["token"]) if "token" in value else None
return reply(
await service.verify(
token, validate_egress(value["egress_id"]) if "egress_id" in value else None
)
)
except MapServiceError as exc:
return reply({"code": exc.code}, exc.status)
@router.put("")
async def save(request: Request) -> JSONResponse:
require_local(request)
try:
value = await payload(request)
if (
set(value) - {"revision", "mode", "token", "remove_token", "egress_id"}
or type(value.get("revision")) is not int
or value["revision"] < 0
or not isinstance(value.get("mode"), str)
or value["mode"] not in MODES
or type(value.get("remove_token", False)) is not bool
or (value.get("remove_token") and "token" in value)
):
raise MapServiceError("cesium_settings_invalid_request", 422)
token = validate_token(value["token"]) if "token" in value else None
return reply(
await service.save(
value["revision"],
value["mode"],
token,
remove=value.get("remove_token", False),
egress_id=validate_egress(value["egress_id"]) if "egress_id" in value else None,
)
)
except MapServiceError as exc:
# Never reflect upstream bodies, validation input or secret values.
return reply({"code": exc.code}, exc.status)
return router
+26 -1
View File
@@ -11,6 +11,8 @@ from typing import Annotated, Literal
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from pydantic import BaseModel, ConfigDict, Field
from k1link.fleet.egress import Egress
from k1link.fleet.egress import invitation as egress_invitation
from k1link.fleet.librespeed import LibreSpeed
from k1link.fleet.librespeed import invitation as speed_invitation
from k1link.fleet.network_profiles import parse_file
@@ -40,7 +42,7 @@ class Update(Details):
class ServiceImport(BaseModel):
model_config = ConfigDict(extra="forbid")
kind: Literal["arnavi", "wireguard", "librespeed"]
kind: Literal["arnavi", "wireguard", "librespeed", "egress"]
document: str = Field(min_length=1, max_length=16384)
network_interface: str | None = Field(default=None, max_length=20)
expected_revision: int = Field(ge=1, strict=True)
@@ -94,6 +96,23 @@ def services(fleet: FleetRegistry) -> list[Document]:
details={**item, "name": "LibreSpeed", "boards": 0, "last_verified": None},
)
)
for item in Egress(fleet.root).listing():
result.append(
dict(
kind="egress",
id=item["id"],
endpoint=item["endpoint"],
name="Маршрутизация трафика",
state=item["state"],
last_seen=None,
details={
**item,
"name": "Маршрутизация трафика",
"boards": 0,
"last_verified": None,
},
)
)
return result
@@ -133,6 +152,8 @@ async def health(key: str, request: Request, response: Response, fleet: Fleet) -
("librespeed", r) for r in LibreSpeed(fleet.root).rows() if ("librespeed", r["id"]) in known
]
rows += [("egress", r) for r in Egress(fleet.root).rows() if ("egress", r["id"]) in known]
async def inspect(kind: str, row: Document) -> Document:
observed = await observer.observe(kind, row, fleet.network_profiles.verify_status)
return {"kind": kind, "id": row.get("id", row.get("server_id")), **observed}
@@ -189,6 +210,8 @@ def connect_service(key: str, body: ServiceImport, fleet: Fleet) -> Document:
parsed = (
parse_file(body.document) # type: ignore[no-untyped-call] # existing invitation validator
if body.kind == "wireguard"
else egress_invitation(body.document)
if body.kind == "egress"
else speed_invitation(body.document)
if body.kind == "librespeed"
else invitation(body.document.strip())
@@ -199,6 +222,8 @@ def connect_service(key: str, body: ServiceImport, fleet: Fleet) -> Document:
fleet.network_profiles.import_file( # type: ignore[no-untyped-call] # existing admission authority
body.document, host["name"], body.network_interface
)
elif body.kind == "egress":
Egress(fleet.root).pair(body.document, body.network_interface)
elif body.kind == "librespeed":
LibreSpeed(fleet.root).pair(body.document, body.network_interface)
else:
+2 -2
View File
@@ -14,9 +14,9 @@ def probe(kind: str, row: Document, verify: Callable[[Document, Document], Docum
value = request(row, "GET", "/v1/status")
if kind == "wireguard":
verify(row, value)
elif kind == "librespeed":
elif kind in {"librespeed", "egress"}:
if (
value.get("schema") != "missioncore.librespeed/v1"
value.get("schema") != f"missioncore.{kind}/v1"
or value.get("server_id") != row["id"]
):
raise ValueError("Service identity mismatch")
@@ -0,0 +1,97 @@
"""Explicit original downloads. No source staging or render fallback on Core."""
from pathlib import PurePosixPath
from urllib.parse import quote
from fastapi import APIRouter, HTTPException
from fastapi.responses import StreamingResponse
from k1link.simulation.ai_polygon.originals import original_receipt
from k1link.simulation.gaussian_pipeline_gateway import (
GaussianPipelineGatewayError,
configured_gaussian_pipeline_gateway,
)
from k1link.simulation.source_retention import receipt_files
def build_simulation_originals_router(
worlds, provider_factory=configured_gaussian_pipeline_gateway
):
router = APIRouter()
def resolve(world_id):
provider = provider_factory()
if provider is None:
raise HTTPException(503, "Сервер исходников недоступен. Обратитесь к администратору.")
try:
world, storage, receipt = original_receipt(worlds, world_id)
if storage["provider_endpoint"] != provider.endpoint:
raise ValueError("Хранилище исходника изменилось. Обратитесь к администратору.")
provider.retained_source(receipt)
return provider, world, receipt
except (ValueError, FileNotFoundError, GaussianPipelineGatewayError) as exc:
provider.close()
raise HTTPException(503, str(exc)) from exc
@router.get("/worlds/{world_id}/originals")
def originals(world_id: str):
provider, world, receipt = resolve(world_id)
try:
return {
"files": [
{
"name": world.get("filename", path)
if world.get("original_storage")
else path,
"byte_length": size,
"sha256": digest,
"url": (f"/api/v1/ai-polygon/worlds/{world_id}/original"
f"?path={quote(path, safe='')}"),
}
for path, (size, digest) in receipt_files(receipt).items()
]
}
finally:
provider.close()
@router.get("/worlds/{world_id}/original")
def original(world_id: str, path: str):
provider, world, receipt = resolve(world_id)
files = receipt_files(receipt)
if path not in files:
provider.close()
raise HTTPException(404, "Исходный файл не найден.")
iterator = provider.stream_retained_file(receipt, path)
try:
first = next(iterator)
except Exception as exc:
iterator.close()
provider.close()
raise HTTPException(
503, "Не удалось получить оригинал с сервера. Повторите попытку."
) from exc
def stream():
try:
yield first
yield from iterator
finally:
iterator.close()
provider.close()
name = (
world.get("filename", path)
if world.get("original_storage")
else PurePosixPath(path).name
)
return StreamingResponse(
stream(),
media_type="application/octet-stream",
headers={
"Content-Length": str(files[path][0]),
"Cache-Control": "no-store",
"Content-Disposition": "attachment; filename*=UTF-8''" + quote(name, safe=""),
},
)
return router
+17 -3
View File
@@ -28,6 +28,13 @@ class SimulationSourceFileCreate(BaseModel):
byte_length: int = Field(gt=0)
class SimulationSourceAttribution(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
author: str = Field(default="", max_length=500)
license: str = Field(default="", max_length=500)
source_url: str | None = Field(default=None, max_length=2048)
class SimulationProjectCreate(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
@@ -36,6 +43,7 @@ class SimulationProjectCreate(BaseModel):
scene_type: Literal["interior", "outdoor", "object"]
source_kind: Literal["archive", "folder"]
files: list[SimulationSourceFileCreate] = Field(min_length=1, max_length=10_000)
attribution: SimulationSourceAttribution | None = None
class SimulationProjectUpdate(BaseModel):
@@ -107,6 +115,7 @@ class SimulationProjectDocument(BaseModel):
scene_type: Literal["interior", "outdoor", "object"]
status: Literal["uploading", "queued", "processing", "importing", "ready", "failed"]
source: dict[str, Any]
attribution: dict[str, str | None] = Field(default_factory=dict, exclude=True)
provider: dict[str, Any]
artifacts: list[dict[str, Any]]
world_manifest: dict[str, Any] | None
@@ -153,6 +162,7 @@ def build_simulation_projects_router(
scene_type=request.scene_type,
source_kind=request.source_kind,
files=[item.model_dump() for item in request.files],
attribution=request.attribution.model_dump() if request.attribution else None,
)
except SimulationProjectError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -278,11 +288,15 @@ def build_simulation_projects_router(
except GaussianPipelineGatewayError as exc:
raise HTTPException(status_code=503, detail=str(exc)) from exc
@router.delete("/projects/{project_id}", status_code=204)
@router.get("/deletions")
def list_deletions():
return {"deletions": service.deletions.list()}
@router.delete("/projects/{project_id}", status_code=202)
def delete_project(project_id: str) -> Response:
try:
service.delete(project_id)
return Response(status_code=204, headers={"Cache-Control": "no-store"})
service.deletions.request(project_id)
return Response(status_code=202, headers={"Cache-Control": "no-store"})
except SimulationProjectNotFoundError as exc:
raise HTTPException(status_code=404, detail="Проект симуляции не найден.") from exc
except SimulationProjectConflictError as exc:
+211
View File
@@ -0,0 +1,211 @@
import asyncio
import base64
import hashlib
import hmac
import json
import httpx
import pytest
from k1link.fleet.egress import Egress
from k1link.fleet.egress_transport import RelayStream
from k1link.maps.direct import DirectCesium, json_response
from k1link.maps.egress import gateway_headers
from k1link.maps.routing import MapServiceRoutes
from k1link.maps.settings import CesiumSettings, CesiumSettingsStore, MapServiceError
IDENTIFIER = "eg_" + "a" * 32
BINDING = {
"id": IDENTIFIER,
"endpoint": "https://1.1.1.1:19446",
"fingerprint": "b" * 64,
"token": "c" * 43,
"state": "connected",
}
def test_signed_gateway_binding_is_method_and_path_scoped(tmp_path):
key = tmp_path / "key"
key.write_text("ab" * 32)
headers = gateway_headers(key, BINDING, "GET", "/api/map/cache")
payload = headers["x-nodedc-map-egress"]
raw = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
assert raw["token"] == BINDING["token"]
expected = hmac.new(
bytes.fromhex("ab" * 32),
("nodedc.map-egress/v1\nGET\n/api/map/cache\n" + payload).encode(),
hashlib.sha256,
).hexdigest()
assert headers["x-nodedc-map-egress-signature"] == expected
with pytest.raises(MapServiceError, match="gateway_not_ready"):
gateway_headers(tmp_path / "absent", BINDING, "GET", "/healthz")
def test_legacy_settings_keep_route_and_new_id_is_durable(tmp_path):
store = CesiumSettingsStore(tmp_path / "settings.json")
store.save(CesiumSettings(token="private-token"), 0)
document = json.loads(store.path.read_text())
document.pop("egress_id")
store.path.write_text(json.dumps(document))
assert store.read().egress_id == ""
saved = store.save(CesiumSettings(token="private-token", egress_id=IDENTIFIER), 1)
assert store.read().egress_id == IDENTIFIER
assert "private-token" not in repr(saved)
assert "private-token" not in json.dumps(saved.public())
def test_region_refusal_is_not_invalid_token():
async def scenario():
async def relay(*args, **kwargs):
return httpx.Response(403, headers={"x-nodedc-egress-error": "upstream_region_denied"})
async with httpx.AsyncClient() as client:
result = await DirectCesium("private-token", client, relay).verify()
assert not result["ok"]
assert {x["code"] for x in result["assets"].values()} == {"cesium_egress_region_denied"}
asyncio.run(scenario())
def test_unreachable_provider_does_not_disable_warm_cache(tmp_path):
async def scenario():
requests = []
def gateway(request):
requests.append(request.url.path)
if request.url.path == "/healthz":
return json_response({"ok": True, "service": "nodedc-map-gateway"})
if request.url.params.get("url", "").endswith("cold"):
return json_response({"error": "map_egress_upstream_unavailable"}, 503)
return json_response({"warm": True})
async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:
service = MapServiceRoutes(
CesiumSettingsStore(tmp_path / "settings.json"), "http://nas.test", client
)
with pytest.raises(MapServiceError, match="token_required"):
await service.send("GET", "/api/map/cache", {"url": "cold"}, {})
assert service.gateway_available is True
response = await service.send("GET", "/api/map/cache", {"url": "warm"}, {})
assert json.loads(await response.aread())["warm"]
assert requests.count("/healthz") == 1
asyncio.run(scenario())
def test_failed_route_admission_keeps_working_settings(tmp_path):
async def scenario():
fleet = tmp_path / "fleet"
Egress(fleet).save(BINDING)
store = CesiumSettingsStore(tmp_path / "services" / "cesium-ion" / "settings.json")
store.save(CesiumSettings(token="private-token"), 0)
async with httpx.AsyncClient() as client:
routes = MapServiceRoutes(store, None, client, fleet_root=fleet)
async def relay(*args, **kwargs):
return httpx.Response(
403, headers={"x-nodedc-egress-error": "upstream_region_denied"}
)
routes.egress_transport.request = relay
with pytest.raises(MapServiceError, match="cesium_egress_region_denied"):
await routes.save(1, "auto", None, egress_id=IDENTIFIER)
assert store.read().egress_id == ""
assert store.read().revision == 1
asyncio.run(scenario())
def test_nas_down_uses_selected_relay_without_direct_leak(tmp_path):
async def scenario():
fleet = tmp_path / "fleet"
Egress(fleet).save(BINDING)
store = CesiumSettingsStore(tmp_path / "settings.json")
store.save(CesiumSettings(token="private-token", egress_id=IDENTIFIER), 0)
def network(request):
assert request.url.host == "nas.test", "Provider request bypassed selected VPS"
raise httpx.ConnectError("offline")
async with httpx.AsyncClient(transport=httpx.MockTransport(network)) as client:
routes = MapServiceRoutes(store, "http://nas.test", client, fleet_root=fleet)
calls = []
async def relay(binding, method, target, headers):
calls.append(target)
assert binding["id"] == IDENTIFIER
return json_response(
{
"type": "TERRAIN",
"url": "https://assets.ion.cesium.com/1/",
"accessToken": "scoped-secret",
}
)
routes.egress_transport.request = relay
response = await routes.send("GET", "/api/map/ion/assets/1/endpoint", None, {})
body = await response.aread()
assert calls == ["https://api.cesium.com/v1/assets/1/endpoint"]
assert b"private-token" not in body and b"scoped-secret" not in body
assert not list(tmp_path.rglob("*.terrain"))
asyncio.run(scenario())
def test_offline_nas_cannot_bypass_gateway_setup_on_route_save(tmp_path):
async def scenario():
fleet = tmp_path / "fleet"
Egress(fleet).save(BINDING)
store = CesiumSettingsStore(tmp_path / "settings.json")
store.save(CesiumSettings(token="private-token"), 0)
def offline(request):
raise httpx.ConnectError("offline")
class VerifiedProvider:
async def verify(self):
return {"ok": True}
async with httpx.AsyncClient(transport=httpx.MockTransport(offline)) as client:
routes = MapServiceRoutes(store, "http://nas.test", client, fleet_root=fleet)
routes.provider = lambda *_: VerifiedProvider()
with pytest.raises(MapServiceError, match="gateway_not_ready"):
await routes.save(1, "auto", None, egress_id=IDENTIFIER)
assert store.read().egress_id == ""
assert store.read().revision == 1
asyncio.run(scenario())
def test_truncated_relay_stream_is_not_accepted_and_releases_slot():
class Connection:
sock = None
closed = False
def close(self):
self.closed = True
class Truncated:
length = 3
closed = False
def read(self, _):
return b""
def close(self):
self.closed = True
async def scenario():
connection, response = Connection(), Truncated()
slots = asyncio.Semaphore(1)
await slots.acquire()
stream = RelayStream(connection, response, slots)
with pytest.raises(httpx.ReadError):
async for _ in stream:
pass
assert connection.closed and response.closed
await asyncio.wait_for(slots.acquire(), 0.1)
await stream.aclose()
assert slots.locked(), "Repeated close must not release another caller's slot"
asyncio.run(scenario())
+312
View File
@@ -0,0 +1,312 @@
from __future__ import annotations
import asyncio
import json
import httpx
import pytest
from fastapi import FastAPI
from k1link.maps.direct import JsonStream, json_response
from k1link.maps.routing import MapServiceRoutes
from k1link.maps.settings import CesiumSettings, CesiumSettingsStore, MapServiceError
from k1link.web.map_api import MapGatewayConfiguration, MapGatewayProxy, build_map_router
MASTER = "test-master-secret"
ASSET = "test-scoped-secret"
BING = "test-bing-secret"
class Providers:
def __init__(self):
self.requests = []
self.nas = False
self.nas_status = 200
self.authorized = True
self.asset_status = 200
def __call__(self, request):
self.requests.append(request)
if request.url.host == "nas.test":
if not self.nas:
raise httpx.ConnectError("offline", request=request)
if request.url.path == "/healthz":
return json_response({"ok": True, "service": "nodedc-map-gateway"})
return json_response({"code": "offline_cache_miss", "nas": True}, self.nas_status)
if request.url.host == "api.cesium.com":
assert request.headers["authorization"] == f"Bearer {MASTER}"
if not self.authorized:
return json_response({"secret": MASTER}, 401)
asset = int(request.url.path.split("/")[-2])
if asset == 2:
return json_response(
{
"type": "IMAGERY",
"externalType": "BING",
"options": {
"url": "https://dev.virtualearth.net",
"key": BING,
"mapStyle": "Aerial",
},
}
)
return json_response(
{
"type": "TERRAIN" if asset == 1 else "3DTILES",
"url": f"https://assets.ion.cesium.com/{asset}/",
"accessToken": ASSET,
}
)
if request.url.host == "dev.virtualearth.net":
assert request.url.params["key"] == BING
return json_response(
{
"imageUrl": f"https://ecn.t0.tiles.virtualearth.net/tiles/a.jpg?key={BING}",
"accessToken": ASSET,
}
)
if request.url.host == "assets.ion.cesium.com":
assert request.headers["authorization"] == f"Bearer {ASSET}"
assert not any(key.startswith("nodedc_cache_") for key in request.url.params)
return httpx.Response(
self.asset_status,
stream=JsonStream(b"tile-data"),
headers={
"content-type": "application/octet-stream",
"content-range": "bytes 0-8/9",
},
)
raise AssertionError("Unexpected request")
def routes(tmp_path, providers, clock=lambda: 0):
store = CesiumSettingsStore(tmp_path / "services" / "cesium-ion" / "settings.json")
store.save(CesiumSettings(token=MASTER), 0)
return MapServiceRoutes(
store,
"http://nas.test",
httpx.AsyncClient(transport=httpx.MockTransport(providers)),
clock=clock,
)
def test_private_atomic_store_and_revision(tmp_path):
store = CesiumSettingsStore(tmp_path / "private" / "settings.json")
saved = store.save(CesiumSettings(token=MASTER), 0)
assert store.path.stat().st_mode & 0o777 == 0o600
assert store.path.parent.stat().st_mode & 0o777 == 0o700
assert MASTER not in repr(saved)
assert MASTER not in json.dumps(saved.public())
with pytest.raises(MapServiceError, match="conflict"):
store.save(CesiumSettings(token="other"), 0)
assert store.read().token == MASTER
assert len(list(store.path.parent.iterdir())) == 1
def test_nas_down_then_returns_without_new_cache_or_changed_query(tmp_path):
async def scenario():
upstream = Providers()
now = [0]
service = routes(tmp_path, upstream, lambda: now[0])
url = "https://assets.ion.cesium.com/1/tile.terrain?v=4&nodedc_cache_profile=live"
first = await service.send("GET", "/api/map/cache", {"url": url}, {})
assert await first.aread() == b"tile-data"
assert first.headers["x-nodedc-map-route"] == "direct"
await service.send("GET", "/api/map/cache", {"url": url}, {})
assert sum(r.url.host == "nas.test" for r in upstream.requests) == 1
upstream.nas = True
now[0] = 16
second = await service.send("GET", "/api/map/cache", {"url": url}, {})
assert second.headers["x-nodedc-map-route"] == "gateway"
assert upstream.requests[-1].url.params["url"] == url
assert list(tmp_path.rglob("*.*")) == [service.store.path]
await service.client.aclose()
asyncio.run(scenario())
def test_concurrent_tiles_share_probe_and_endpoint_resolution(tmp_path):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
responses = await asyncio.gather(
*(
service.send(
"GET",
"/api/map/cache",
{"url": f"https://assets.ion.cesium.com/1/{index}.terrain"},
{},
)
for index in range(12)
)
)
for response in responses:
await response.aclose()
assert sum(r.url.host == "nas.test" for r in upstream.requests) == 1
assert sum(r.url.host == "api.cesium.com" for r in upstream.requests) == 1
await service.client.aclose()
asyncio.run(scenario())
def test_redirect_is_not_followed_and_missing_token_has_explicit_reason(tmp_path):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
upstream.asset_status = 302
with pytest.raises(MapServiceError, match="unavailable"):
await service.direct().resource("GET", "https://assets.ion.cesium.com/1/a", {})
assert len(upstream.requests) == 2
await service.save(1, "auto", None, remove=True)
with pytest.raises(MapServiceError, match="token_required"):
await service.send("GET", "/healthz", None, {})
await service.client.aclose()
asyncio.run(scenario())
def test_bing_query_credential_not_written_to_http_log(tmp_path, caplog):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
with caplog.at_level("INFO", logger="httpx"):
response = await service.direct().resource(
"GET", "https://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial", {}
)
await response.aclose()
assert BING not in caplog.text and MASTER not in caplog.text
assert all(r.headers.get("referer") == "http://127.0.0.1:8000/" for r in upstream.requests)
await service.client.aclose()
asyncio.run(scenario())
@pytest.mark.parametrize("status", [401, 403, 404, 504])
def test_nas_cache_policy_is_never_bypassed(tmp_path, status):
async def scenario():
upstream = Providers()
upstream.nas, upstream.nas_status = True, status
service = routes(tmp_path, upstream)
response = await service.send(
"GET", "/api/map/cache", {"url": "https://assets.ion.cesium.com/1/x"}, {}
)
assert response.status_code == status
assert all(r.url.host == "nas.test" for r in upstream.requests)
await response.aclose()
await service.client.aclose()
asyncio.run(scenario())
def test_endpoint_and_bing_metadata_never_expose_credentials(tmp_path):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
for asset in (1, 2, 96188):
response = await service.send("GET", f"/api/map/ion/assets/{asset}/endpoint", None, {})
payload = await response.aread()
assert all(secret.encode() not in payload for secret in (MASTER, ASSET, BING))
response = await service.send(
"GET",
"/api/map/cache",
{
"url": "https://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial?key=nodedc-gateway"
},
{},
)
payload = await response.aread()
assert BING.encode() not in payload and ASSET.encode() not in payload
assert b"nodedc-gateway" in payload
await service.client.aclose()
asyncio.run(scenario())
@pytest.mark.parametrize(
"target",
[
"https://localhost/x",
"https://evil.test/x",
"https://assets.ion.cesium.com:123/1/x",
"https://assets.ion.cesium.com/1/../9/x",
"https://assets.ion.cesium.com/1/%2e%2e/9/x",
"https://assets.ion.cesium.com/1%2fx",
"https://assets.ion.cesium.com/999/x",
"https://user@assets.ion.cesium.com/1/x",
],
)
def test_no_arbitrary_proxy_or_credential_scope_escape(tmp_path, target):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
with pytest.raises(MapServiceError):
await service.direct().resource("GET", target, {})
assert all(r.url.host == "api.cesium.com" for r in upstream.requests)
await service.client.aclose()
asyncio.run(scenario())
def test_invalid_candidate_does_not_replace_saved_token(tmp_path):
async def scenario():
upstream = Providers()
service = routes(tmp_path, upstream)
upstream.authorized = False
with pytest.raises(MapServiceError, match="unauthorized"):
await service.save(1, "direct", MASTER)
assert service.store.read() == CesiumSettings(1, "auto", MASTER)
await service.save(1, "gateway", None, remove=True)
assert service.store.read().token == ""
assert MASTER not in service.store.path.read_text()
await service.client.aclose()
asyncio.run(scenario())
def test_api_secret_redaction_csrf_ranges_and_recovery(tmp_path):
async def scenario():
upstream = Providers()
state = routes(tmp_path, upstream)
app = FastAPI()
proxy = MapGatewayProxy(
MapGatewayConfiguration("http://nas.test"),
client=state.client,
settings_path=state.store.path,
)
app.include_router(build_map_router(proxy))
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app, client=("127.0.0.1", 9000)),
base_url="http://127.0.0.1:8000",
) as client:
base = "/api/v1/map/services/cesium-ion"
status = await client.get(base)
assert status.json()["token_configured"] is True
assert MASTER not in status.text
forbidden = await client.put(
base, json={"revision": 1, "mode": "auto"}, headers={"Origin": "https://evil.test"}
)
assert forbidden.status_code == 403
invalid = await client.put(base, json={"revision": 1, "mode": [], "token": MASTER})
assert invalid.status_code == 422 and MASTER not in invalid.text
health = await client.get("/api/v1/map/gateway/health")
assert health.json()["service"] == "missioncore-map-direct"
assert health.json()["cache"] is None
endpoint = await client.get("/api/v1/map/gateway/ion/assets/1/endpoint")
assert endpoint.status_code == 200 and ASSET not in endpoint.text
upstream.asset_status = 206
binary = await client.get(
"/api/v1/map/gateway/cache",
params={"url": "https://assets.ion.cesium.com/1/a.terrain"},
headers={"Range": "bytes=0-8"},
)
assert binary.status_code == 206 and binary.content == b"tile-data"
assert binary.headers["content-range"] == "bytes 0-8/9"
assert binary.headers["cache-control"] == "no-store"
assert upstream.requests[-1].headers["range"] == "bytes=0-8"
saved = await client.put(base, json={"revision": 1, "mode": "auto"})
assert saved.status_code == 200
conflict = await client.put(base, json={"revision": 1, "mode": "direct"})
assert conflict.status_code == 409
await state.client.aclose()
asyncio.run(scenario())
+2 -2
View File
@@ -117,7 +117,7 @@ def test_runtime_config_exposes_only_same_origin_contract_and_hides_internal_ori
lambda request: httpx.Response(
200,
headers={"content-type": "application/json"},
json={"ok": True, "rendererVersion": "1.143.0"},
json={"ok": True, "rendererVersion": "1.147.0"},
)
)
router = build_map_router(service)
@@ -130,7 +130,7 @@ def test_runtime_config_exposes_only_same_origin_contract_and_hides_internal_ori
document = json.loads(_response_body(response))
assert document["schema_version"] == "missioncore.map-runtime/v1"
assert document["map_page_version"] == "0.1.0"
assert document["renderer"] == {"id": "cesium", "version": "1.143.0"}
assert document["renderer"] == {"id": "cesium", "version": "1.147.0"}
assert document["gateway"]["cache_proxy_prefix"].startswith("/api/v1/map/")
assert document["assets"] == {
"imagery": 2,
+31
View File
@@ -126,3 +126,34 @@ def test_api_cross_browser_read_and_stale_write(tmp_path):
== 403
)
assert a.get(url, headers={"Sec-Fetch-Site": "cross-site"}).status_code == 403
def test_observation_views_survive_new_clients_without_browser_storage(tmp_path):
camera = dict(longitude=37, latitude=55, height=600, heading=137, pitch=-28, roll=3)
document = {"schema": "missioncore.observation-map/v1", "camera": camera,
"layers": dict(imagery=True, terrain=True, buildings=False,
grid=False, targets=True)}
a = client(tmp_path)
url = "/api/v1/scene-profiles/observation-map?owner=rover-006"
assert a.put(url, json={"document": document, "expected_revision": 0}).status_code == 200
assert client(tmp_path).get(url).json()["document"] == document
assert client(tmp_path).get(url.replace("rover-006", "other")).json()["document"] is None
model = {"schema": "missioncore.rover-view/v1", "model": "dcd006-v022"}
url = "/api/v1/scene-profiles/rover-view?owner=rover-006"
assert a.put(url, json={"document": model, "expected_revision": 0}).status_code == 200
assert client(tmp_path).get(url).json()["document"] == model
model["armed"] = True
assert a.put(url, json={"document": model, "expected_revision": 1}).status_code == 422
@pytest.mark.parametrize("field,value", [("pitch", -100), ("height", True),
("longitude", 200), ("heading", "30")])
def test_observation_map_rejects_bad_pose(tmp_path, field, value):
camera = dict(longitude=37, latitude=55, height=600, heading=137, pitch=-28, roll=3)
camera[field] = value
document = {"schema": "missioncore.observation-map/v1", "camera": camera,
"layers": dict(imagery=True, terrain=True, buildings=False,
grid=False, targets=True)}
with pytest.raises(ValueError):
SceneProfileStore(tmp_path).save("observation-map", "rover", document, 0)
assert not SceneProfileStore(tmp_path).path("observation-map", "rover").exists()
+141
View File
@@ -0,0 +1,141 @@
import json
from types import SimpleNamespace
import pytest
from k1link.simulation.gaussian_pipeline_gateway import GaussianPipelineGatewayError
from k1link.simulation.projects import (
SimulationProjectNotFoundError,
SimulationProjectService,
SimulationProjectStore,
)
def fixture(tmp_path):
store = SimulationProjectStore(tmp_path)
row = store.create(
name="Disposable",
scene_type="outdoor",
source_kind="folder",
files=[dict(logical_path="a.ply", byte_length=8)],
)
receipt = dict(source_id="src-" + "a" * 64)
store.update_source_storage(
row["project_id"],
storage=dict(provider_endpoint="http://worker", receipt=receipt, local_state="remote"),
)
store.update_processing(
row["project_id"], status="processing", provider_job_id="gsp-20261116000000-1234abcd"
)
calls = []
provider = SimpleNamespace(
endpoint="http://worker",
close=lambda: None,
delete_job=lambda id: calls.append(("job", id)),
delete_retained_source=lambda r: calls.append(("source", r["source_id"])),
)
service = SimulationProjectService(store, lambda: provider)
service.deletions.start = lambda: None
return store, row["project_id"], provider, service, calls
def test_source_failure_keeps_row_and_recovery_completes_after_restart(tmp_path):
store, pid, provider, service, calls = fixture(tmp_path)
good = provider.delete_retained_source
def offline(_):
raise GaussianPipelineGatewayError("Worker offline")
provider.delete_retained_source = offline
service.deletions.request(pid)
service.deletions.attempt(service.deletions.list()[0])
assert store.get(pid) and service.deletions.list()[0]["state"] == "waiting"
assert calls[0][0] == "job"
provider.delete_retained_source = good
recovered = SimulationProjectService(store, lambda: provider)
recovered.deletions.attempt(recovered.deletions.list()[0])
assert not recovered.deletions.list()
with pytest.raises(SimulationProjectNotFoundError):
store.get(pid)
assert calls[-1][0] == "source"
def test_shared_source_and_job_survive_until_last_project_owner(tmp_path):
store, pid, provider, service, calls = fixture(tmp_path)
second = store.create(
name="Second",
scene_type="outdoor",
source_kind="folder",
files=[dict(logical_path="a.ply", byte_length=8)],
)
first = store.get(pid)
store.update_source_storage(second["project_id"], storage=first["source"]["storage"])
store.update_processing(
second["project_id"], status="processing", provider_job_id=first["provider"]["job_id"]
)
service.delete(pid)
assert calls == [] and store.get(second["project_id"])
service.delete(second["project_id"])
assert [call[0] for call in calls] == ["job", "source"]
def test_dependency_blocks_deletion_instead_of_orphaning_run(tmp_path):
store, pid, provider, service, calls = fixture(tmp_path)
run = tmp_path / "ai-polygon/runs/run"
run.mkdir(parents=True)
(run / "run.json").write_text(json.dumps({"world_id": pid.replace("sim-", "aiworld-")}))
with pytest.raises(RuntimeError, match="сохранённых заданиях"):
service.deletions.request(pid)
assert not calls and store.get(pid)
def test_ui_delete_endpoint_persists_intent_without_waiting_for_worker(tmp_path):
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.web.simulation_projects_api import build_simulation_projects_router
store, pid, provider, service, calls = fixture(tmp_path)
app = FastAPI()
app.include_router(build_simulation_projects_router(store=store, service=service))
client = TestClient(app)
assert client.delete("/api/v1/simulation-worlds/projects/" + pid).status_code == 202
assert (
client.get("/api/v1/simulation-worlds/deletions").json()["deletions"][0]["project_id"]
== pid
)
assert store.get(pid) and not calls
def test_prepared_archive_members_and_original_are_both_removed(tmp_path):
store, pid, provider, service, calls = fixture(tmp_path)
store.update_source_storage(pid, prepared_receipt=dict(source_id="src-" + "b" * 64))
service.delete(pid)
assert [call[0] for call in calls] == ["job", "source", "source"]
assert calls[1][1] == "src-" + "b" * 64
def test_large_unrelated_evidence_does_not_block_deletion(tmp_path):
store, pid, provider, service, calls = fixture(tmp_path)
evidence = tmp_path / "ai-polygon/urban-maps/other.json"
evidence.parent.mkdir(parents=True)
evidence.write_text('{"geometry":"' + 'x' * (9 * 1024**2) + '"}')
service.delete(pid)
assert [call[0] for call in calls] == ["job", "source"]
def test_dependency_scan_finds_identity_across_chunk_boundary(tmp_path):
from k1link.simulation.project_deletions import contains_identity
identity = "aiworld-" + "f" * 32
evidence = tmp_path / "large.json"
evidence.write_bytes(b"x" * (64 * 1024 - 10) + identity.encode() + b"x")
assert contains_identity(evidence, identity, "sim-" + "f" * 32)
def test_deleting_project_cannot_be_requeued(tmp_path):
store, pid, provider, service, calls = fixture(tmp_path)
service.deletions.request(pid)
with pytest.raises(RuntimeError, match="Удаление локации уже начато"):
service.enqueue(pid)
assert not calls
+141
View File
@@ -0,0 +1,141 @@
import hashlib
from types import SimpleNamespace
import pytest
from k1link.simulation.ai_polygon.originals import retain_legacy_original
from k1link.simulation.ai_polygon.worlds import WorldStore, write_json
from k1link.simulation.gaussian_pipeline_gateway import GaussianPipelineIntegrityError
def setup(tmp_path):
worlds = WorldStore(tmp_path)
wid = "aiworld-" + "a" * 32
root = worlds.root / wid
root.mkdir()
raw = b"original"
(root / "source.ply").write_bytes(raw)
sha = hashlib.sha256(raw).hexdigest()
write_json(
root / "world.json",
dict(world_id=wid, status="available", byte_length=len(raw), sha256=sha),
)
output = root / "render.sog"
output.write_bytes(b"optimized")
editor = SimpleNamespace(
request=lambda _: dict(key="cache"),
get=lambda _: dict(key="cache", status="ready", files={"scene.sog": {}}),
asset=lambda *_: (output, hashlib.sha256(b"optimized").hexdigest()),
)
source = dict(
format="ply",
entrypoint="source.ply",
total_byte_length=8,
bundle_sha256="",
members=[dict(upload_id="x", logical_path="source.ply", byte_length=8, sha256=sha)],
)
import json
# Real connector computes this exact canonical manifest; test uses its serializer.
from k1link.simulation.gaussian_pipeline_gateway import _source_bundle_upload
# key ordering is format/entrypoint/members, each member logical_path/sha256/byte_length.
identity = dict(
format="ply",
entrypoint="source.ply",
members=[dict(logical_path="source.ply", sha256=sha, byte_length=8)],
)
source["bundle_sha256"] = hashlib.sha256(
json.dumps(identity, separators=(",", ":")).encode()
).hexdigest()
bundle = _source_bundle_upload(source)
receipt = dict(
schema_version="gaussian-pipeline.source-receipt/v1",
retention="independent-of-jobs",
source_id="src-" + "b" * 64,
verified_at_utc="2026-11-16T00:00:00Z",
input=dict(kind="folder", source=source),
)
provider = SimpleNamespace(
endpoint="http://worker",
require_source_retention=lambda: None,
upload_source_bundle=lambda *_a, **_k: bundle,
retain_source=lambda _: receipt,
retained_source=lambda r, **_k: r,
)
return worlds, wid, root, editor, provider
def test_cleanup_requires_verified_original_and_keeps_result_identity(tmp_path):
worlds, wid, root, editor, provider = setup(tmp_path)
result = retain_legacy_original(worlds, wid, provider, editor)
assert result["removed_bytes"] == 8 and not (root / "source.ply").exists()
assert (root / "render.sog").read_bytes() == b"optimized"
assert worlds.get(wid)["original_storage"]["local_state"] == "remote"
assert retain_legacy_original(worlds, wid, provider, editor)["removed_bytes"] == 0
def test_worker_failure_never_removes_only_local_original(tmp_path):
worlds, wid, root, editor, provider = setup(tmp_path)
def unavailable(*_a, **_k):
raise RuntimeError("offline")
provider.retained_source = unavailable
with pytest.raises(RuntimeError, match="offline"):
retain_legacy_original(worlds, wid, provider, editor)
assert (root / "source.ply").read_bytes() == b"original"
def test_render_corruption_blocks_source_cleanup(tmp_path):
worlds, wid, root, editor, provider = setup(tmp_path)
(root / "render.sog").write_bytes(b"corrupt")
with pytest.raises(GaussianPipelineIntegrityError):
retain_legacy_original(worlds, wid, provider, editor)
assert (root / "source.ply").exists()
def test_original_download_streams_worker_bytes_without_local_source(tmp_path):
from fastapi import FastAPI
from fastapi.testclient import TestClient
from k1link.web.simulation_originals_api import build_simulation_originals_router
worlds, wid, root, editor, provider = setup(tmp_path)
retain_legacy_original(worlds, wid, provider, editor)
closed = []
provider.close = lambda: closed.append(True)
provider.stream_retained_file = lambda *_: (chunk for chunk in [b"ori", b"ginal"])
app = FastAPI()
app.include_router(build_simulation_originals_router(worlds, lambda: provider))
client = TestClient(app)
response = client.get(f"/worlds/{wid}/originals")
assert response.status_code == 200
assert response.json()["files"][0]["sha256"] == worlds.get(wid)["sha256"]
response = client.get(f"/worlds/{wid}/original", params={"path": "source.ply"})
assert response.content == b"original"
assert response.headers["content-disposition"].startswith("attachment;")
assert not (root / "source.ply").exists() and closed
assert (
client.get(f"/worlds/{wid}/original", params={"path": "../world.json"}).status_code == 404
)
offline = FastAPI()
offline.include_router(build_simulation_originals_router(worlds, lambda: None))
assert TestClient(offline).get(f"/worlds/{wid}/originals").status_code == 503
def test_source_attribution_does_not_expand_closed_project_v1_response(tmp_path):
from k1link.simulation.projects import SimulationProjectStore
from k1link.web.simulation_projects_api import SimulationProjectDocument, SimulationProjectPage
store = SimulationProjectStore(tmp_path)
row = store.create(
name="Test",
scene_type="outdoor",
source_kind="folder",
files=[{"logical_path": "scene.ply", "byte_length": 8}],
attribution={"author": "Owner", "license": "Private", "source_url": None},
)
assert store.get(row["project_id"])["attribution"]["author"] == "Owner"
assert "attribution" not in SimulationProjectDocument.model_validate(row).model_dump()
assert "attribution" not in SimulationProjectPage(projects=[row]).model_dump()["projects"][0]
+6 -3
View File
@@ -165,7 +165,7 @@ class _ReadyProvider:
def require_source_retention(self):
pass
def retain_source(self, original):
def retain_source(self, original, *, owner_id=None):
return {"schema_version": "gaussian-pipeline.source-receipt/v1",
"source_id": "src-" + "a" * 64, "retention": "independent-of-jobs",
"verified_at_utc": "2026-11-07T00:00:00Z", "input": copy.deepcopy(original)}
@@ -288,6 +288,9 @@ class _ReadyProvider:
destination.write_bytes(payload)
return destination
def delete_retained_source(self, receipt) -> None:
self.deleted_sources = getattr(self, "deleted_sources", []) + [receipt["source_id"]]
def delete_job(self, job_id: str) -> None:
self.deleted.append(job_id)
@@ -969,7 +972,7 @@ def test_wrong_or_incomplete_worker_receipt_never_removes_local_files(tmp_path):
from k1link.simulation.source_retention import prepare_source
store, project_id, provider = _retention_fixture(tmp_path)
original = provider.retain_source
def wrong_receipt(value):
def wrong_receipt(value, *, owner_id=None):
receipt = original(value)
receipt["input"]["source"]["members"][0]["sha256"] = "0" * 64
return receipt
@@ -1030,7 +1033,7 @@ def test_archive_is_retained_before_normalization_failure(tmp_path):
offset=0, payload=b"test")
store.begin_build(project["project_id"])
provider = _ReadyProvider()
provider.upload_source_archive = lambda path: GaussianArchiveUpload(
provider.upload_source_archive = lambda path, **kwargs: GaussianArchiveUpload(
"archive-id", "scene.zip", "zip", hashlib.sha256(b"test").hexdigest(), 4)
def failed(_archive):
assert not (store.source_root(project["project_id"]) / "scene.zip").exists()
Generated
+5 -4
View File
@@ -479,8 +479,8 @@ wheels = [
[[package]]
name = "nodedc-bim-module"
version = "0.2.6"
source = { path = "vendor/bim/nodedc_bim_module-0.2.6-py3-none-any.whl" }
version = "0.2.36"
source = { path = "vendor/bim/nodedc_bim_module-0.2.36-py3-none-any.whl" }
dependencies = [
{ name = "fastapi" },
{ name = "httpx" },
@@ -488,7 +488,7 @@ dependencies = [
{ name = "uvicorn" },
]
wheels = [
{ filename = "nodedc_bim_module-0.2.6-py3-none-any.whl", hash = "sha256:0f7f8e5764b2881fd28c02956c4de743b9b75de40544b23f31f6bbeb584df537" },
{ filename = "nodedc_bim_module-0.2.36-py3-none-any.whl", hash = "sha256:eaaef709abae33d04e8d7a731f95d4b7ad9ce996ffe791b320dff807ac0f58ed" },
]
[package.metadata]
@@ -498,6 +498,7 @@ requires-dist = [
{ name = "laspy", marker = "extra == 'worker'", specifier = "==2.7.0" },
{ name = "lazrs", marker = "extra == 'worker'", specifier = "==0.8.2" },
{ name = "numpy", marker = "extra == 'worker'", specifier = "==2.2.6" },
{ name = "pillow", marker = "extra == 'worker'", specifier = "==13.0.0" },
{ name = "pydantic", specifier = ">=2.11,<3" },
{ name = "uvicorn", specifier = ">=0.35,<1" },
]
@@ -560,7 +561,7 @@ requires-dist = [
{ name = "httpx", specifier = ">=0.28,<1" },
{ name = "lz4", specifier = ">=4.4,<5" },
{ name = "missioncore-plugin-sdk", editable = "packages/plugin-sdk" },
{ name = "nodedc-bim-module", path = "vendor/bim/nodedc_bim_module-0.2.6-py3-none-any.whl" },
{ name = "nodedc-bim-module", path = "vendor/bim/nodedc_bim_module-0.2.36-py3-none-any.whl" },
{ name = "paho-mqtt", specifier = ">=2.1,<3" },
{ name = "pillow", specifier = ">=12,<13" },
{ name = "pyyaml", specifier = ">=6.0,<7" },
+4 -2
View File
@@ -2,8 +2,8 @@
Immutable packages from the independent [NODEDC_BIM_MOD](https://git.dcserve.ru/dctouch/NODEDC_BIM_MOD) repository:
- Python host services 0.1.4: `release.json`, wheel, `uv.lock` integrity.
- Browser workspace 0.1.9: `client-release.json`, npm tarball, Control Station lockfile integrity. Runtime workers and third-party notices are included in the tarball.
- Python host services 0.2.36: `release.json`, wheel, `uv.lock` integrity.
- Browser workspace 0.2.86: `client-release.json`, npm tarball, Control Station lockfile integrity. Runtime workers and third-party notices are included in the tarball.
Core consumes these versioned artifacts without importing a sibling checkout or copying the domain implementation. Update through a new module release, identity review and host qualification. The Worker image and durable data volume remain on Worker 006. Private connection settings and service tokens are never part of these releases.
@@ -14,3 +14,5 @@ The retained 0.1.0/0.1.1 artifacts identify the previous qualified release. New
Full-version deletion requires Worker 0.1.2 or later. Do not roll back to an implementation without deletion journals while retirement is pending; retain the durable journals and deploy a compatible forward fix. Local-copy eviction is still separate.
Viewer preferences include new fields; host 0.1.3 cannot parse the new cube fields. Keep host 0.1.4 when reverting a client instead of discarding durable meta.json. Worker remains 0.1.2.
Current release uses host 0.2.36 and UI 0.2.86 with Design Guideline UI React 0.7.10 / UI Core 0.7.4. Worker remains on 0.2.32. Scene settings and note/camera appearance share one project-header settings window. Normal and enlarged note-window rectangles persist separately; cursor zoom stays anchored to the visible surface during navigation and marker editing, including after keyboard flight. Whole-layer and per-IFC-item transforms are scene metadata, never modifications to original files. UI tool window is named «Инспектор»; compact axis fields and shared glass tooltips are shipped by the portable module. The module and Design Guideline changes are committed; see release manifests for exact provenance and qualification limits.
+39 -13
View File
@@ -1,18 +1,18 @@
{
"schema_version": "missioncore.bim-client-release/v1",
"repository": "https://git.dcserve.ru/dctouch/NODEDC_BIM_MOD",
"source_commit": "3ff31ddc66b2528cc39a2b2b68c985e94389b23f",
"package": "nodedc-bim-viewer-0.2.22.tgz",
"sha256": "e32c21e151901a108761b7d5ee2856e9e1a8ee98f4e3ac818fd89b3d83b7139d",
"source_commit": "322788f33e42b553a4fd3b32690fb373480796ff",
"package": "nodedc-bim-viewer-0.2.86.tgz",
"sha256": "6e732cbad7ee20170f52c6ac67cad5449691fa734abe8a45d3fe91b6f4040a01",
"types": "pass",
"contract_tests": 93,
"visual_acceptance": "LivingBIM: native scene cloud selection highlights its hierarchy row; whole BIM root and IFC element selection checked. Thin speed rail without enclosing surface shown in normal/fullscreen viewport, native keyboard adjustment, ten-second auto-hide and brief-key reappearance verified. Narrow viewport hints no longer overlap rail. Existing placement and source data preserved; host and Worker unchanged.",
"evidence": "docs/BIM_MODULE.md",
"qualification_date": "2026-11-15",
"design_guideline_commit": "d0648014f58daf9b94b6bf8ba681ef0aa82c1e82",
"core_frontend_tests": 1604,
"contract_tests": 222,
"visual_acceptance": "Chrome at nodedc.missioncore, ЖК Academie. Starting from the project view, scroll toward a concrete column left of center, then toward a different column on the right. Each stayed beneath the cursor while enlarging. Original project view restored.",
"evidence": "client/test/cursorZoom.test.ts and client/test/notePosition.test.ts in NODEDC_BIM_MOD at source_commit",
"qualification_date": "2026-11-17",
"design_guideline_commit": "bcc121e7b2fbb924e1c2b10532057f482155f258",
"core_frontend_tests": 1626,
"core_frontend_failures": 0,
"validation_context": "shared canonical working checkout; unrelated concurrent edits preserved",
"validation_context": "222 client tests passed, including off-center wheel gestures with OrbitControls in both projections. BIM client and Core production builds passed. Core frontend test counts are from the preceding release.",
"visual_limits": [
"Native RMB drag not independently automated; actual OrbitControls pan regression passed",
"Native OS layout switch not exercised; physical code fixtures cover Cyrillic/IME labels",
@@ -20,7 +20,33 @@
"Pivot samples currently rendered depth/LOD with a two-CSS-pixel neighbour fallback; not exhaustive GPU/material qualification",
"Preflight File handles remain browser-session resources; full reload/browser shutdown does not resume local checks or unsubmitted drafts.",
"Native Ctrl+drag was not independently automated; actual gesture/runtime tests cover both configured rotation modes.",
"Manual whole-material placement supports translation and vertical-axis rotation; no scale, roll/pitch or automatic scan registration.",
"Thin range variant uses canonical theme tokens; light theme and every accent palette were not independently visually qualified."
]
"Thin range variant uses canonical theme tokens; light theme and every accent palette were not independently visually qualified.",
"Live note deletion and native fullscreen were not newly qualified; note deletion/recovery is covered by focused tests.",
"1895 imported camera notes have source poses; 75 photographs remain explicitly unplaced. Exact pixel reprojection, lens distortion and roll are not qualified.",
"The operator stopped further photo admission at 1970 photographs plus one text note. No additional image imports are pending.",
"IFC sub-element pointer transforms preview the shared frame; geometry updates on release. Transform history is session-local.",
"Detailed map previews are bounded to 8 nearby models / 128 MiB live geometry, not millions of IFC meshes; multi-model residency has unit qualification, no large live load benchmark.",
"Existing gateway/cache path retained; NAS failover during a real Internet outage was not newly qualified.",
"0.2.58: full native drag coverage for every gizmo axis and dock/reopen layout roundtrip were not newly qualified; operator resumed live editing. Actual Cesium Gaussian transform redraw can still rebuild its snapshot and sort data. History is session-local.",
"0.2.63: preflight local File handles survive dialog close but not browser shutdown; accepted jobs remain server-owned. Legacy rows without admission time use original server insertion order. Native fullscreen was not requalified in IAB.",
"0.2.64: native pointer row sorting and lock roundtrip qualified in normal project settings; native fullscreen and full GPU gizmo axis coverage were not repeated. Multi-tab lock/move races covered by regression tests, not simultaneous live browser gestures.",
"0.2.65: IAB denied native fullscreen even while visible. Normal/reopened/reloaded Inspector and narrow/normal viewport adaptation were verified. No object transforms exercised.",
"0.2.66: common header pointer/keyboard focus qualified on actual Cesium Inspector and all three shared window components. Native fullscreen was not requalified. Existing project transforms, locks, uploads and capture were not modified.",
"0.2.70: native fullscreen and nested Escape qualified for Cesium appearance settings. AO is gated by GPU support; not every GPU/postprocessing combination or all other Cesium consumers was visually requalified. No Worker, network route or tile-cache changes.",
"0.2.72: IAB rejected native fullscreen even while visible; normal/floating settings and final Default label verified. Physical-layout mapping covered by KeyZ/KeyY fixtures; actual OS layout switching not performed. Save confirmation branch verified with real rendered components. Appearance history is session-local.",
"0.2.74: browser cache clearing was represented by a fresh profile client regression; live full-page reload/reopen was verified. Observation tilted-camera fixture was seeded through the revisioned API, then restored by the real renderer; pointer pan and layer changes were exercised in UI. No hardware control was enabled.",
"0.2.76: multi-file selection/upload exercised through native chooser; whole-editor drag/drop covered by rendered-component regression, not native Finder drag. Native OS keyboard layout switching and all GPU variants not requalified.",
"0.2.85: no new Finder drag/drop, native OS keyboard-layout switching, every GPU or every gizmo axis qualification. Whole-note file drop and physical KeyZ mappings are regression-tested; existing stored notes/photos/coordinates were preserved. Separate point-edit/settings shortcut ownership is a rendered-component regression, not an additional native UI pass."
],
"source_state": "committed",
"design_guideline_version": "0.7.10",
"design_guideline_source_state": "UI React 0.7.10 and UI Core 0.7.4 committed. BIM vendors a clean committed DG package; unrelated existing live host DG changes preserved.",
"inspector_evidence": "inspector-compact-axes.jpg (operator Codex workspace)",
"map_cesium_adapter_version": "0.1.4",
"cesium_version": "1.147.0",
"map_evidence": "docs/project-map.md in NODEDC_BIM_MOD; cesium-project-map.png and cesium-bim-placement.png in operator task workspace",
"earlier_visual_acceptance": "KU layer notes list/tiles/gallery and exact per-project view roundtrip passed; project deletion confirmation open/cancel only; 219074194-point LAS rendered and reopened after full page reload; IAB held W and mouse drag changed heading and displayed flight speed, then Fit restored cloud overview; 2026-11-16: individual IFC translation/rotation/scale, group translation and Ctrl/Command undo checked; compact inspector has nine editable fields and no caption/section plates; window and toolbar read «Инспектор»; single shared tooltip verified in viewer and main navigation: radius 14px, blur 18px, border/outline 0, 12px text.; 0.2.46: background click cleared whole cloud and BIM group selected through tree in navigate mode; inspector and selected rows removed. Compact axis headings align on one line (verified equal top coordinate), units hidden in headings. Regression covers geometry/modifier clicks and orbit returning to its starting point.; 0.2.47: existing Cesium runtime rendered prepared BUH geometry; terrain click, marker drag and center placement changed draft coordinates, Cancel preserved project. Libre/Cesium switching and saved Cesium camera survived reload.",
"previous_visual_acceptance": "Default is present in the final live UI; native visuals applied and inspected. Command Z/Shift Z changed 100→101→100→101; fixed unsaved-close confirmation, cancel/discard and floating scene glass verified. Saved MCMAP - GAUSS TILESET and both profile definitions restored after QA.",
"scope": "Cursor-anchored BIM and point cloud navigation after flight, including marker editing",
"previous_marker_visual_acceptance": "Real Chrome UI at nodedc.missioncore: existing text notes 1237 and 1333 render red camera-facing spatial glyphs; each marker opens its corresponding note on click. Marker remains attached to its position and faces the camera during orbit. Existing note coordinates, visibility and appearance preserved."
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More