Make simulation imports background tasks with Worker-owned sources and durable deletion
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
import {useEffect,useState} from "react";
|
||||
import {deleteSimulationProject} from "./projects";
|
||||
export interface LocationDeletion {project_id:string;name:string;state:"deleting"|"waiting";error:string|null}
|
||||
export const deleteLocation=deleteSimulationProject;
|
||||
export function useLocationDeletions(onChanged:()=>Promise<void>){
|
||||
const [rows,setRows]=useState<LocationDeletion[]>([]);
|
||||
useEffect(()=>{
|
||||
let stopped=false,timer:ReturnType<typeof setTimeout>;let previous="";
|
||||
const poll=async()=>{
|
||||
try{const response=await fetch("/api/v1/simulation-worlds/deletions");if(!response.ok)throw Error();
|
||||
const data=await response.json() as {deletions:LocationDeletion[]};
|
||||
if(!stopped){setRows(data.deletions);const key=JSON.stringify(data.deletions);if(key!==previous){previous=key;await onChanged();}}}
|
||||
catch{/* Keep acknowledged deletion visible while disconnected. */}
|
||||
if(!stopped)timer=setTimeout(()=>void poll(),1500);
|
||||
};
|
||||
void poll();return()=>{stopped=true;clearTimeout(timer);};
|
||||
},[onChanged]);
|
||||
return rows;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type {SimulationImportSource} from "./sourceFiles";
|
||||
import type {SimulationProject, SimulationUploadProgress} from "./projects";
|
||||
|
||||
export interface LocationImportTask {
|
||||
id: string; name: string; phase: "checking" | "waiting" | "uploading" | "submitted" | "failed" | "deleting";
|
||||
project?: SimulationProject; progress?: number; error?: string; deleteRequested?: boolean; deletionAcknowledgedAt?: number;
|
||||
}
|
||||
interface Dependencies {
|
||||
create: (name:string, source:SimulationImportSource)=>Promise<SimulationProject>;
|
||||
upload: (project:SimulationProject, source:SimulationImportSource, progress:(value:SimulationUploadProgress)=>void, signal:AbortSignal)=>Promise<SimulationProject>;
|
||||
delete?: (project:SimulationProject)=>Promise<void>;
|
||||
}
|
||||
|
||||
/** Owns browser File handles independently of any modal/workspace mount. */
|
||||
export function createLocationImportQueue(api:Dependencies) {
|
||||
let rows:LocationImportTask[]=[], running=false;
|
||||
const sources=new Map<string,SimulationImportSource>(), listeners=new Set<()=>void>();
|
||||
const controllers=new Map<string,AbortController>(), settled=new Map<string,Promise<void>>();
|
||||
const publish=()=>{for(const listener of listeners)listener();};
|
||||
const change=(id:string,patch:Partial<LocationImportTask>)=>{rows=rows.map(row=>row.id===id?{...row,...patch}:row);publish();};
|
||||
const fail=(id:string,caught:unknown)=>change(id,{phase:"failed",error:caught instanceof Error?caught.message:"Импорт не завершён."});
|
||||
const next=()=>[...rows].reverse().find(item=>item.phase==="waiting");
|
||||
const pump=async()=>{
|
||||
if(running)return;
|
||||
running=true;
|
||||
try {
|
||||
for(let row=next();row;row=next()) {
|
||||
const {id}=row, source=sources.get(id)!;
|
||||
const controller=new AbortController();controllers.set(id,controller);
|
||||
let finish!:()=>void;settled.set(id,new Promise<void>(resolve=>{finish=resolve;}));
|
||||
change(id,{phase:"uploading",progress:undefined,error:undefined});
|
||||
try {
|
||||
const project=row.project??await api.create(row.name,source);
|
||||
change(id,{project});
|
||||
controller.signal.throwIfAborted();
|
||||
const submitted=await api.upload(project,source,value=>change(id,{progress:value.totalBytes?value.uploadedBytes/value.totalBytes:0}),controller.signal);
|
||||
controller.signal.throwIfAborted();
|
||||
change(id,{project:submitted,phase:"submitted",progress:undefined});
|
||||
sources.delete(id);
|
||||
} catch(caught) {if(!controller.signal.aborted)fail(id,caught);}
|
||||
finally {controllers.delete(id);settled.delete(id);finish();}
|
||||
}
|
||||
} finally {running=false;}
|
||||
};
|
||||
return {
|
||||
getSnapshot:()=>rows,
|
||||
subscribe(listener:()=>void){listeners.add(listener);return()=>{listeners.delete(listener);};},
|
||||
enqueue(name:string,source:Promise<SimulationImportSource>,resume?:SimulationProject) {
|
||||
const id=crypto.randomUUID();
|
||||
rows=[{id,name,phase:"checking",project:resume},...rows];publish();
|
||||
void source.then(value=>{
|
||||
if(!rows.some(row=>row.id===id&&!row.deleteRequested))return;
|
||||
sources.set(id,value);change(id,{phase:"waiting"});void pump();
|
||||
}).catch(caught=>fail(id,caught));
|
||||
return id;
|
||||
},
|
||||
async remove(id:string){
|
||||
const row=rows.find(item=>item.id===id);if(!row)return;
|
||||
change(id,{phase:"deleting",deleteRequested:true,error:undefined});
|
||||
controllers.get(id)?.abort();
|
||||
// Creation is deliberately not aborted: retain its server identity for cleanup.
|
||||
await settled.get(id);
|
||||
try {
|
||||
const project=rows.find(item=>item.id===id)?.project;
|
||||
if(project){
|
||||
if(!api.delete)throw new Error("Удаление импорта недоступно.");
|
||||
await api.delete(project);sources.delete(id);
|
||||
change(id,{deletionAcknowledgedAt:performance.now()});
|
||||
} else {sources.delete(id);rows=rows.filter(item=>item.id!==id);publish();}
|
||||
} catch(caught){fail(id,caught);throw caught;}
|
||||
},
|
||||
reconcile(projectIds:string[],requestStartedAt:number){
|
||||
const retained=rows.filter(row=>!(row.deletionAcknowledgedAt!==undefined &&
|
||||
requestStartedAt>=row.deletionAcknowledgedAt && !projectIds.includes(row.project!.projectId)));
|
||||
if(retained.length!==rows.length){rows=retained;publish();}
|
||||
},
|
||||
retry(id:string){if(sources.has(id)&&!rows.find(row=>row.id===id)?.deleteRequested){change(id,{phase:"waiting",error:undefined});void pump();}},
|
||||
canRetry:(id:string)=>sources.has(id),
|
||||
forget(id:string){const row=rows.find(item=>item.id===id);if(!row||!["failed","submitted"].includes(row.phase))return;
|
||||
sources.delete(id);rows=rows.filter(item=>item.id!==id);publish();},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import {useSyncExternalStore} from "react";
|
||||
import {createLocationImportQueue} from "./locationImportQueue";
|
||||
import {createSimulationProject, deleteSimulationProject, uploadSimulationProjectSource} from "./projects";
|
||||
import {candidatesFromDrop, classifySimulationSource} from "./sourceFiles";
|
||||
|
||||
export const locationImports=createLocationImportQueue({
|
||||
create:(name,source)=>createSimulationProject(name,source.sceneType??"outdoor",source.candidates,source.attribution),
|
||||
upload:(project,source,progress,signal)=>uploadSimulationProjectSource(project,source.candidates,progress,signal),
|
||||
delete:project=>deleteSimulationProject(project.projectId),
|
||||
|
||||
});
|
||||
export function useLocationImports(){return useSyncExternalStore(locationImports.subscribe,locationImports.getSnapshot);}
|
||||
export function importDroppedLocation(transfer:DataTransfer){
|
||||
const name=transfer.files[0]?.name.replace(/\.(zip|rar|7z|ply)$/i,"")??"Новая локация";
|
||||
// Capture drop entries synchronously; the row exists before directory checks finish.
|
||||
const source=candidatesFromDrop(transfer).then(classifySimulationSource);
|
||||
locationImports.enqueue(name,source);
|
||||
}
|
||||
@@ -196,6 +196,7 @@ export async function createSimulationProject(
|
||||
name: string,
|
||||
sceneType: SimulationSceneType,
|
||||
candidates: SimulationUploadCandidate[],
|
||||
attribution?: {author:string;license:string;source_url:string|null},
|
||||
): Promise<SimulationProject> {
|
||||
const sourceKind = sourceKindFor(candidates);
|
||||
const createdResponse = await fetch(API_ROOT, {
|
||||
@@ -206,6 +207,7 @@ export async function createSimulationProject(
|
||||
name,
|
||||
scene_type: sceneType,
|
||||
source_kind: sourceKind,
|
||||
attribution,
|
||||
files: candidates.map((candidate) => ({
|
||||
logical_path: candidate.logicalPath,
|
||||
byte_length: candidate.file.size,
|
||||
|
||||
@@ -23,15 +23,21 @@ export async function candidatesFromDrop(
|
||||
transfer: DataTransfer,
|
||||
): Promise<SimulationUploadCandidate[]> {
|
||||
const candidates: SimulationUploadCandidate[] = [];
|
||||
for (const item of Array.from(transfer.items)) {
|
||||
// The browser revokes DataTransfer access after the drop callback returns.
|
||||
// Capture every entry/file before awaiting directory enumeration.
|
||||
const fallbackFiles = Array.from(transfer.files);
|
||||
const entries = Array.from(transfer.items).map(item => {
|
||||
const file = item.getAsFile();
|
||||
const entry = (item as DataTransferItem & {
|
||||
webkitGetAsEntry?: () => LegacyFileEntry | null;
|
||||
}).webkitGetAsEntry?.();
|
||||
return {entry, file};
|
||||
});
|
||||
for (const {entry, file} of entries) {
|
||||
if (entry?.isDirectory) {
|
||||
await collectEntry(entry, candidates);
|
||||
continue;
|
||||
}
|
||||
const file = item.getAsFile();
|
||||
if (file) {
|
||||
candidates.push({ file, logicalPath: file.name });
|
||||
continue;
|
||||
@@ -39,13 +45,33 @@ export async function candidatesFromDrop(
|
||||
if (entry) await collectEntry(entry, candidates);
|
||||
}
|
||||
if (!candidates.length) {
|
||||
for (const file of Array.from(transfer.files)) {
|
||||
for (const file of fallbackFiles) {
|
||||
candidates.push({ file, logicalPath: file.name });
|
||||
}
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
export type SimulationImportSource = ({sceneType?: import("./projects").SimulationSceneType; attribution?:{author:string;license:string;source_url:string|null}} & (
|
||||
| {kind: "ply"; file: File; candidates: SimulationUploadCandidate[]}
|
||||
| {kind: "lcc"; candidates: SimulationUploadCandidate[]}));
|
||||
|
||||
export const SIMULATION_IMPORT_FORMATS = "Gaussian PLY · ZIP, RAR, 7z или папка с LCC/LCC2";
|
||||
|
||||
export function classifySimulationSource(candidates: SimulationUploadCandidate[]): SimulationImportSource {
|
||||
if (candidates.length === 1 && /\.ply$/i.test(candidates[0].logicalPath)) {
|
||||
const file = candidates[0].file;
|
||||
if (!file.size) throw new Error("Выбранный файл пуст.");
|
||||
if (file.size > 8 * 1024 ** 3) throw new Error("Gaussian PLY превышает лимит 8 ГБ.");
|
||||
return {kind: "ply", file, candidates};
|
||||
}
|
||||
if (candidates.length === 1 && !/\.(zip|rar|7z|lcc2?)$/i.test(candidates[0].logicalPath)) {
|
||||
throw new Error(`Формат не поддерживается. Доступны: ${SIMULATION_IMPORT_FORMATS}.`);
|
||||
}
|
||||
validateSimulationCandidates(candidates);
|
||||
return {kind: "lcc", candidates};
|
||||
}
|
||||
|
||||
export async function archivesFromDrop(transfer: DataTransfer): Promise<File[]> {
|
||||
const candidates = await candidatesFromDrop(transfer);
|
||||
const invalid = candidates.filter((candidate) => !ARCHIVE_PATTERN.test(candidate.logicalPath));
|
||||
@@ -71,6 +97,9 @@ export async function archivesFromDrop(transfer: DataTransfer): Promise<File[]>
|
||||
|
||||
export function validateSimulationCandidates(candidates: SimulationUploadCandidate[]): void {
|
||||
if (!candidates.length) throw new Error("Выберите архив или папку с результатом LCC/LCC2.");
|
||||
if (candidates.length === 1 && /\.ply$/i.test(candidates[0].logicalPath)) {
|
||||
classifySimulationSource(candidates); return;
|
||||
}
|
||||
const archives = candidates.filter((candidate) => ARCHIVE_PATTERN.test(candidate.logicalPath));
|
||||
if (archives.length) {
|
||||
if (candidates.length !== 1) throw new Error("Архив нужно загружать одним файлом.");
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import {useEffect, useRef, useState, type DragEvent} from "react";
|
||||
import {hasDroppedFiles} from "./sourceFiles";
|
||||
|
||||
/** External files only; native window/tree dragging and portal forms are independent. */
|
||||
export function useSimulationFileDrop(onDrop: (transfer: DataTransfer) => void, enabled: boolean) {
|
||||
const [active, setActive] = useState(false);
|
||||
const depth = useRef(0);
|
||||
const reset = () => {depth.current = 0; setActive(false);};
|
||||
useEffect(() => {
|
||||
const escape = (event: KeyboardEvent) => {if (event.key === "Escape") reset();};
|
||||
window.addEventListener("dragend", reset); window.addEventListener("blur", reset); window.addEventListener("keydown", escape);
|
||||
return () => {window.removeEventListener("dragend", reset); window.removeEventListener("blur", reset); window.removeEventListener("keydown", escape);};
|
||||
}, []);
|
||||
useEffect(() => {if (!enabled) reset();}, [enabled]);
|
||||
const accepts = (event: DragEvent<HTMLElement>) => event.currentTarget.contains(event.target as Node) && hasDroppedFiles(event.dataTransfer);
|
||||
const handlers = {
|
||||
onDragEnter(event: DragEvent<HTMLElement>) {
|
||||
if (!accepts(event)) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (enabled) {depth.current++; setActive(true);}
|
||||
},
|
||||
onDragOver(event: DragEvent<HTMLElement>) {
|
||||
if (!accepts(event)) return;
|
||||
event.preventDefault(); event.stopPropagation(); event.dataTransfer.dropEffect = enabled ? "copy" : "none";
|
||||
if (enabled) setActive(true);
|
||||
},
|
||||
onDragLeave(event: DragEvent<HTMLElement>) {
|
||||
if (!accepts(event)) return;
|
||||
event.stopPropagation(); if (--depth.current <= 0) reset();
|
||||
},
|
||||
onDrop(event: DragEvent<HTMLElement>) {
|
||||
if (!accepts(event)) return;
|
||||
event.preventDefault(); event.stopPropagation(); reset();
|
||||
if (enabled) onDrop(event.dataTransfer);
|
||||
},
|
||||
};
|
||||
return {active, handlers};
|
||||
}
|
||||
Reference in New Issue
Block a user