From 7c0dbd4e0614917102909f1bb52df16a04d1fd05 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Mon, 16 Nov 2026 18:13:27 +0300 Subject: [PATCH] Make simulation imports background tasks with Worker-owned sources and durable deletion --- .../simulation/AiLocationCatalog.tsx | 34 ++-- .../components/simulation/AiWorldImport.tsx | 15 +- .../simulation/SimulationImports.tsx | 97 ++++++++++++ .../simulation/SimulationOriginalDownload.tsx | 23 +++ .../simulation/SimulationProjectWindow.tsx | 60 +++---- .../simulation/SimulationSourceImport.tsx | 42 +++-- .../src/core/simulation/locationDeletions.ts | 19 +++ .../core/simulation/locationImportQueue.ts | 82 ++++++++++ .../src/core/simulation/locationImports.ts | 18 +++ .../src/core/simulation/projects.ts | 2 + .../src/core/simulation/sourceFiles.ts | 35 ++++- .../core/simulation/useSimulationFileDrop.ts | 38 +++++ .../control-station/src/styles/ai-polygon.css | 8 +- .../simulation/AiPolygonWorkspace.tsx | 17 +- .../test/locationImportQueue.test.mjs | 101 ++++++++++++ .../test/simulationWorkspace.test.mjs | 4 +- docs/SIMULATION_IMPORT_STORAGE_20261116.md | 42 +++++ src/k1link/simulation/ai_polygon/originals.py | 75 +++++++++ .../simulation/ai_polygon/project_worlds.py | 6 +- .../simulation/gaussian_pipeline_gateway.py | 58 +++++-- src/k1link/simulation/project_deletions.py | 148 ++++++++++++++++++ src/k1link/simulation/projects.py | 65 ++++---- src/k1link/web/ai_polygon_api.py | 20 ++- src/k1link/web/simulation_originals_api.py | 97 ++++++++++++ src/k1link/web/simulation_projects_api.py | 20 ++- tests/test_simulation_deletions.py | 141 +++++++++++++++++ tests/test_simulation_originals.py | 141 +++++++++++++++++ tests/test_simulation_projects.py | 3 + 28 files changed, 1283 insertions(+), 128 deletions(-) create mode 100644 apps/control-station/src/components/simulation/SimulationImports.tsx create mode 100644 apps/control-station/src/components/simulation/SimulationOriginalDownload.tsx create mode 100644 apps/control-station/src/core/simulation/locationDeletions.ts create mode 100644 apps/control-station/src/core/simulation/locationImportQueue.ts create mode 100644 apps/control-station/src/core/simulation/locationImports.ts create mode 100644 apps/control-station/src/core/simulation/useSimulationFileDrop.ts create mode 100644 apps/control-station/test/locationImportQueue.test.mjs create mode 100644 docs/SIMULATION_IMPORT_STORAGE_20261116.md create mode 100644 src/k1link/simulation/ai_polygon/originals.py create mode 100644 src/k1link/simulation/project_deletions.py create mode 100644 src/k1link/web/simulation_originals_api.py create mode 100644 tests/test_simulation_deletions.py create mode 100644 tests/test_simulation_originals.py diff --git a/apps/control-station/src/components/simulation/AiLocationCatalog.tsx b/apps/control-station/src/components/simulation/AiLocationCatalog.tsx index 3c2aef77..861117fb 100644 --- a/apps/control-station/src/components/simulation/AiLocationCatalog.tsx +++ b/apps/control-station/src/components/simulation/AiLocationCatalog.tsx @@ -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; }) { 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(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 <> - {worlds.map(world => {const queued=queue.jobs.find(j=>j.world_id===world.world_id);return
  • + {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
  • } status={activeWorldId === world.world_id ? {paused ? "На паузе" : "Сцена открыта"} : queued ? {queue.unavailable?"Нет обновлений очереди":queued.cancel_requested?"Отмена расчёта":queued.status==="queued"?`В очереди · №${queued.queue?.position??"—"}`:queued.status==="running"?"Расчёт инфраструктуры":"Освобождение Worker"} : undefined} - actions={<> + actions={deletion?
    {deletion.error??"Удаление локации"}
    :<> onOpen(world)}> {canPlan&&world.status!=="uploading"&&world.settings.prepared? onPlan(world)}>:null} + {world.status!=="uploading"?:null} { setEditing(world); setName(world.name); setConfirming(false); setError(null); }}> @@ -44,7 +52,7 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused,
  • ;})}
    {removedWorlds.length ? <> + Скрытые локации · {removedWorlds.length} {showRemoved ? {removedWorlds.map(world =>
  • } actions={ + onClick={() => setConfirming(true)}>{editing?.local_scene?"Удалить локацию":"Скрыть локацию"} }> @@ -63,11 +71,17 @@ export function AiLocationCatalog({worlds, removedWorlds, activeWorldId, paused, onChange={event => setName(event.target.value)}/> {editing?.world_id === activeWorldId ? Удаление станет доступно после завершения симуляции. : null} - «{editing?.name}» исчезнет из доступных локаций. Исходный скан, разметка и задания сохранятся. - Восстановить её можно в списке удалённых локаций.} - confirmLabel="Удалить" pendingLabel="Удаляем" onClose={() => {if (!busy) setConfirming(false);}} - onConfirm={async () => {if (editing) await update(editing, {removed:true});}}/> + «{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 ? setError(null)}/> : null} ; diff --git a/apps/control-station/src/components/simulation/AiWorldImport.tsx b/apps/control-station/src/components/simulation/AiWorldImport.tsx index 474949c7..cb5756a2 100644 --- a/apps/control-station/src/components/simulation/AiWorldImport.tsx +++ b/apps/control-station/src/components/simulation/AiWorldImport.tsx @@ -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(source ?? { - name: "", author: "", license: "", source_url: "", + name: initialFile?.name.replace(/\.ply$/i, "") ?? "", author: "", license: "", source_url: "", }); - const [file, setFile] = useState(null); + const [file, setFile] = useState(initialFile ?? null); const [pending, setPending] = useState(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)); } diff --git a/apps/control-station/src/components/simulation/SimulationImports.tsx b/apps/control-station/src/components/simulation/SimulationImports.tsx new file mode 100644 index 00000000..4c17a4f4 --- /dev/null +++ b/apps/control-station/src/components/simulation/SimulationImports.tsx @@ -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([]), [error,setError]=useState(null); + const [target,setTarget]=useState(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; + 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)=>setTarget(item)}>; + return
    + + {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
  • + {failure&&!task.deleteRequested?(locationImports.canRetry(task.id)? + locationImports.retry(task.id)}>: + project?void retry(project)}>:null):null} + {failure&&!project&&!task.deleteRequested?locationImports.forget(task.id)}>: + trash({name:task.name,taskId:task.id})} + }/>
  • ; + })} + {pending.map(project=>{const progress=projectProgress(project);return
  • + {project.status==="failed"?void retry(project)}>:null}{trash({name:project.name,projectId:project.projectId})}}/> +
  • ;})} + {pendingDeletions.map(row=>
  • )} +
    + {error?{error}:null} + «{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:"Не удалось начать удаление.");} + }}/> +
    ; +} + +function ImportRow({name,label,value,failed,actions}:{name:string;label:string;value?:number;failed:boolean;actions?:React.ReactNode}){ + return } + status={{failed?"Ошибка импорта":"Импорт"}} + actions={<>
    + {!failed?:null}{label}{!failed&&value!==undefined?` · ${Math.floor(value*100)}%`:""} +
    {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={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}; +} diff --git a/apps/control-station/src/components/simulation/SimulationOriginalDownload.tsx b/apps/control-station/src/components/simulation/SimulationOriginalDownload.tsx new file mode 100644 index 00000000..a1688d6d --- /dev/null +++ b/apps/control-station/src/components/simulation/SimulationOriginalDownload.tsx @@ -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(null),[error,setError]=useState(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 <>void open()}> + setFiles(null)}> + Выберите файл для скачивания. + {files?.map(file=>)} + + {error?setError(null)}/>:null} + ; +} diff --git a/apps/control-station/src/components/simulation/SimulationProjectWindow.tsx b/apps/control-station/src/components/simulation/SimulationProjectWindow.tsx index fcf532b9..f7914870 100644 --- a/apps/control-station/src/components/simulation/SimulationProjectWindow.tsx +++ b/apps/control-station/src/components/simulation/SimulationProjectWindow.tsx @@ -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([]); const [dragging, setDragging] = useState(false); const [pending, setPending] = useState(false); - const [progress, setProgress] = useState(null); const [error, setError] = useState(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({ ) : null} - {progress ? ( -
    - -
    - - {formatBytes(progress.uploadedBytes)} / {formatBytes(progress.totalBytes)} - {" · "}{formatUploadEta(progress.estimatedSecondsRemaining)} - - {progress.currentPath} -
    -
    - ) : null} {error ?

    {error}

    : null} ); } -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 } { diff --git a/apps/control-station/src/components/simulation/SimulationSourceImport.tsx b/apps/control-station/src/components/simulation/SimulationSourceImport.tsx index 080626ed..c0b1ab60 100644 --- a/apps/control-station/src/components/simulation/SimulationSourceImport.tsx +++ b/apps/control-station/src/components/simulation/SimulationSourceImport.tsx @@ -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(null); + const [open,setOpen]=useState(false); + const [archive,setArchive]=useState<{candidates?:SimulationUploadCandidate[]}|null>(null), [project,setProject]=useState(null); const [error,setError]=useState(null); const [pending,setPending]=useState([]); + const drop=useSimulationFileDrop(importDroppedLocation,!disabled&&!open&&!archive&&!project); + const importAction=setOpen(true)}>; 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 <> -
    - - + return
    + {headerToolsHost?createPortal(importAction,headerToolsHost):
    {importAction}
    } + {children} + {drop.active? + Отпустите файл или папку, чтобы добавить локацию + {SIMULATION_IMPORT_FORMATS} + Одна локация за раз. Проверка и импорт начнутся автоматически. + :null} + setOpen(false)}>
    + +
    {pending.map(p=>
    {p.name} -
    )} +
    )} {error?{error}:null} - setArchive(false)} onSaved={p=>{setArchive(false);setProject(p);}} /> + setArchive(null)} onSaved={p=>{setArchive(null);setProject(p);}} /> {project?setProject(null)}> {error??project.error??'Локация появится в общей библиотеке после подготовки.'} {project.status==='failed'?:null} :null} - ; +
    ; } diff --git a/apps/control-station/src/core/simulation/locationDeletions.ts b/apps/control-station/src/core/simulation/locationDeletions.ts new file mode 100644 index 00000000..e66f6e25 --- /dev/null +++ b/apps/control-station/src/core/simulation/locationDeletions.ts @@ -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){ + const [rows,setRows]=useState([]); + useEffect(()=>{ + let stopped=false,timer:ReturnType;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; +} diff --git a/apps/control-station/src/core/simulation/locationImportQueue.ts b/apps/control-station/src/core/simulation/locationImportQueue.ts new file mode 100644 index 00000000..c91a6aba --- /dev/null +++ b/apps/control-station/src/core/simulation/locationImportQueue.ts @@ -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; + upload: (project:SimulationProject, source:SimulationImportSource, progress:(value:SimulationUploadProgress)=>void, signal:AbortSignal)=>Promise; + delete?: (project:SimulationProject)=>Promise; +} + +/** Owns browser File handles independently of any modal/workspace mount. */ +export function createLocationImportQueue(api:Dependencies) { + let rows:LocationImportTask[]=[], running=false; + const sources=new Map(), listeners=new Set<()=>void>(); + const controllers=new Map(), settled=new Map>(); + const publish=()=>{for(const listener of listeners)listener();}; + const change=(id:string,patch:Partial)=>{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(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,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();}, + }; +} diff --git a/apps/control-station/src/core/simulation/locationImports.ts b/apps/control-station/src/core/simulation/locationImports.ts new file mode 100644 index 00000000..46459e44 --- /dev/null +++ b/apps/control-station/src/core/simulation/locationImports.ts @@ -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); +} diff --git a/apps/control-station/src/core/simulation/projects.ts b/apps/control-station/src/core/simulation/projects.ts index 48d538d9..439a53d7 100644 --- a/apps/control-station/src/core/simulation/projects.ts +++ b/apps/control-station/src/core/simulation/projects.ts @@ -196,6 +196,7 @@ export async function createSimulationProject( name: string, sceneType: SimulationSceneType, candidates: SimulationUploadCandidate[], + attribution?: {author:string;license:string;source_url:string|null}, ): Promise { 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, diff --git a/apps/control-station/src/core/simulation/sourceFiles.ts b/apps/control-station/src/core/simulation/sourceFiles.ts index 9a23b853..cd7a8f2b 100644 --- a/apps/control-station/src/core/simulation/sourceFiles.ts +++ b/apps/control-station/src/core/simulation/sourceFiles.ts @@ -23,15 +23,21 @@ export async function candidatesFromDrop( transfer: DataTransfer, ): Promise { 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 { 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 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("Архив нужно загружать одним файлом."); diff --git a/apps/control-station/src/core/simulation/useSimulationFileDrop.ts b/apps/control-station/src/core/simulation/useSimulationFileDrop.ts new file mode 100644 index 00000000..4f2d0869 --- /dev/null +++ b/apps/control-station/src/core/simulation/useSimulationFileDrop.ts @@ -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) => event.currentTarget.contains(event.target as Node) && hasDroppedFiles(event.dataTransfer); + const handlers = { + onDragEnter(event: DragEvent) { + if (!accepts(event)) return; + event.preventDefault(); event.stopPropagation(); + if (enabled) {depth.current++; setActive(true);} + }, + onDragOver(event: DragEvent) { + if (!accepts(event)) return; + event.preventDefault(); event.stopPropagation(); event.dataTransfer.dropEffect = enabled ? "copy" : "none"; + if (enabled) setActive(true); + }, + onDragLeave(event: DragEvent) { + if (!accepts(event)) return; + event.stopPropagation(); if (--depth.current <= 0) reset(); + }, + onDrop(event: DragEvent) { + if (!accepts(event)) return; + event.preventDefault(); event.stopPropagation(); reset(); + if (enabled) onDrop(event.dataTransfer); + }, + }; + return {active, handlers}; +} diff --git a/apps/control-station/src/styles/ai-polygon.css b/apps/control-station/src/styles/ai-polygon.css index e8898413..e9dea68f 100644 --- a/apps/control-station/src/styles/ai-polygon.css +++ b/apps/control-station/src/styles/ai-polygon.css @@ -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; } diff --git a/apps/control-station/src/workspaces/simulation/AiPolygonWorkspace.tsx b/apps/control-station/src/workspaces/simulation/AiPolygonWorkspace.tsx index dae5582c..289f50a2 100644 --- a/apps/control-station/src/workspaces/simulation/AiPolygonWorkspace.tsx +++ b/apps/control-station/src/workspaces/simulation/AiPolygonWorkspace.tsx @@ -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(null); const [selectedId, setSelectedId] = useState(null); const [runId, setRunId] = useState(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(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
    + return setImporting({source:null,file})} onReady={id=>{void load();setSelectedId(id);}}>
    {selected && !planning ? @@ -234,11 +235,11 @@ export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLEleme
    {selected ? !planning&&!manual&&!running&&canEdit?start("planning")}>:null : <>{connection} - } + onClick={()=>start("planning")}>:null : connection}
    + world.world_id)??[]}/> {error ? setError(null)} /> : null} {removed.length? Удалено из списка: {removed.at(-1)?.name} @@ -297,9 +298,7 @@ export function AiPolygonWorkspace({headerToolsHost}:{headerToolsHost?:HTMLEleme }}/> : null} {saveOpen?setSaveOpen(false)} onSave={save}/>:null} - setImportChoice(false)} - onPly={()=>setImporting({source:null})} onReady={(id)=>{void load();setSelectedId(id);}} /> - {importing ? setImporting(null)} onImported={acceptWorld} /> : null} -
    ; + ; } diff --git a/apps/control-station/test/locationImportQueue.test.mjs b/apps/control-station/test/locationImportQueue.test.mjs new file mode 100644 index 00000000..e293598d --- /dev/null +++ b/apps/control-station/test/locationImportQueue.test.mjs @@ -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); +}); diff --git a/apps/control-station/test/simulationWorkspace.test.mjs b/apps/control-station/test/simulationWorkspace.test.mjs index 8b708d3a..89aa84b9 100644 --- a/apps/control-station/test/simulationWorkspace.test.mjs +++ b/apps/control-station/test/simulationWorkspace.test.mjs @@ -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"), diff --git a/docs/SIMULATION_IMPORT_STORAGE_20261116.md b/docs/SIMULATION_IMPORT_STORAGE_20261116.md new file mode 100644 index 00000000..5d83a67a --- /dev/null +++ b/docs/SIMULATION_IMPORT_STORAGE_20261116.md @@ -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. diff --git a/src/k1link/simulation/ai_polygon/originals.py b/src/k1link/simulation/ai_polygon/originals.py new file mode 100644 index 00000000..f2b14d72 --- /dev/null +++ b/src/k1link/simulation/ai_polygon/originals.py @@ -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"]} diff --git a/src/k1link/simulation/ai_polygon/project_worlds.py b/src/k1link/simulation/ai_polygon/project_worlds.py index fc378edf..66f5ca05 100644 --- a/src/k1link/simulation/ai_polygon/project_worlds.py +++ b/src/k1link/simulation/ai_polygon/project_worlds.py @@ -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", diff --git a/src/k1link/simulation/gaussian_pipeline_gateway.py b/src/k1link/simulation/gaussian_pipeline_gateway.py index 3b948a93..1c11159d 100644 --- a/src/k1link/simulation/gaussian_pipeline_gateway.py +++ b/src/k1link/simulation/gaussian_pipeline_gateway.py @@ -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( @@ -326,23 +326,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 +431,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 +624,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 +742,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 +822,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: diff --git a/src/k1link/simulation/project_deletions.py b/src/k1link/simulation/project_deletions.py new file mode 100644 index 00000000..da63a456 --- /dev/null +++ b/src/k1link/simulation/project_deletions.py @@ -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 diff --git a/src/k1link/simulation/projects.py b/src/k1link/simulation/projects.py index 70a69364..b435ad2f 100644 --- a/src/k1link/simulation/projects.py +++ b/src/k1link/simulation/projects.py @@ -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) diff --git a/src/k1link/web/ai_polygon_api.py b/src/k1link/web/ai_polygon_api.py index 19259d74..940ab08b 100644 --- a/src/k1link/web/ai_polygon_api.py +++ b/src/k1link/web/ai_polygon_api.py @@ -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", diff --git a/src/k1link/web/simulation_originals_api.py b/src/k1link/web/simulation_originals_api.py new file mode 100644 index 00000000..ddf42f82 --- /dev/null +++ b/src/k1link/web/simulation_originals_api.py @@ -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 diff --git a/src/k1link/web/simulation_projects_api.py b/src/k1link/web/simulation_projects_api.py index feee830a..51e3d60e 100644 --- a/src/k1link/web/simulation_projects_api.py +++ b/src/k1link/web/simulation_projects_api.py @@ -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: diff --git a/tests/test_simulation_deletions.py b/tests/test_simulation_deletions.py new file mode 100644 index 00000000..84fdcc63 --- /dev/null +++ b/tests/test_simulation_deletions.py @@ -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 diff --git a/tests/test_simulation_originals.py b/tests/test_simulation_originals.py new file mode 100644 index 00000000..417000a9 --- /dev/null +++ b/tests/test_simulation_originals.py @@ -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] diff --git a/tests/test_simulation_projects.py b/tests/test_simulation_projects.py index bead49ee..2b8016c9 100644 --- a/tests/test_simulation_projects.py +++ b/tests/test_simulation_projects.py @@ -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)