Make simulation imports background tasks with Worker-owned sources and durable deletion

This commit is contained in:
DCCONSTRUCTIONS
2026-11-16 18:13:27 +03:00
parent 9871ae500f
commit 7c0dbd4e06
28 changed files with 1283 additions and 128 deletions
+19 -1
View File
@@ -49,6 +49,8 @@ def build_ai_polygon_router(
editor = EditorCache(data_dir, worlds)
routes = RoutePreparationStore(data_dir)
router = APIRouter(prefix="/api/v1/ai-polygon", tags=["ai-polygon"])
from k1link.web.simulation_originals_api import build_simulation_originals_router
router.include_router(build_simulation_originals_router(worlds))
adapters = Path(__file__).resolve().parents[3] / "simulation/ai-polygon"
from k1link.web.ai_profile_api import build_ai_profile_router
@@ -142,7 +144,7 @@ def build_ai_polygon_router(
@router.post("/worlds", status_code=201)
def create_world(body: WorldCreate):
return invoke(worlds.create, body)
raise HTTPException(410, "Импорт PLY перенесён в серверную обработку локаций. Обновите приложение.")
@router.get("/worlds/{world_id}")
def get_world(world_id: str):
@@ -187,6 +189,22 @@ def build_ai_polygon_router(
raise HTTPException(409, "Импорт не завершён.")
if row.get("storage", {}).get("kind") == "worker":
raise HTTPException(409, "Исходник локации хранится на Worker.")
if row.get("original_storage"):
from k1link.simulation.gaussian_pipeline_gateway import configured_gaussian_pipeline_gateway
provider = configured_gaussian_pipeline_gateway()
if provider is None:
raise HTTPException(503, "Сервер исходников недоступен.")
storage = row["original_storage"]
if provider.endpoint != storage["provider_endpoint"]:
provider.close()
raise HTTPException(503, "Хранилище исходника изменилось.")
def original_stream():
try:
yield from provider.stream_retained_file(storage["receipt"], "source.ply")
finally:
provider.close()
return StreamingResponse(original_stream(), media_type="application/octet-stream",
headers={"Content-Length": str(row["byte_length"]), "Cache-Control": "no-store"})
return FileResponse(
worlds.directory(world_id) / "source.ply",
media_type="application/octet-stream",
@@ -0,0 +1,97 @@
"""Explicit original downloads. No source staging or render fallback on Core."""
from pathlib import PurePosixPath
from urllib.parse import quote
from fastapi import APIRouter, HTTPException
from fastapi.responses import StreamingResponse
from k1link.simulation.ai_polygon.originals import original_receipt
from k1link.simulation.gaussian_pipeline_gateway import (
GaussianPipelineGatewayError,
configured_gaussian_pipeline_gateway,
)
from k1link.simulation.source_retention import receipt_files
def build_simulation_originals_router(
worlds, provider_factory=configured_gaussian_pipeline_gateway
):
router = APIRouter()
def resolve(world_id):
provider = provider_factory()
if provider is None:
raise HTTPException(503, "Сервер исходников недоступен. Обратитесь к администратору.")
try:
world, storage, receipt = original_receipt(worlds, world_id)
if storage["provider_endpoint"] != provider.endpoint:
raise ValueError("Хранилище исходника изменилось. Обратитесь к администратору.")
provider.retained_source(receipt)
return provider, world, receipt
except (ValueError, FileNotFoundError, GaussianPipelineGatewayError) as exc:
provider.close()
raise HTTPException(503, str(exc)) from exc
@router.get("/worlds/{world_id}/originals")
def originals(world_id: str):
provider, world, receipt = resolve(world_id)
try:
return {
"files": [
{
"name": world.get("filename", path)
if world.get("original_storage")
else path,
"byte_length": size,
"sha256": digest,
"url": (f"/api/v1/ai-polygon/worlds/{world_id}/original"
f"?path={quote(path, safe='')}"),
}
for path, (size, digest) in receipt_files(receipt).items()
]
}
finally:
provider.close()
@router.get("/worlds/{world_id}/original")
def original(world_id: str, path: str):
provider, world, receipt = resolve(world_id)
files = receipt_files(receipt)
if path not in files:
provider.close()
raise HTTPException(404, "Исходный файл не найден.")
iterator = provider.stream_retained_file(receipt, path)
try:
first = next(iterator)
except Exception as exc:
iterator.close()
provider.close()
raise HTTPException(
503, "Не удалось получить оригинал с сервера. Повторите попытку."
) from exc
def stream():
try:
yield first
yield from iterator
finally:
iterator.close()
provider.close()
name = (
world.get("filename", path)
if world.get("original_storage")
else PurePosixPath(path).name
)
return StreamingResponse(
stream(),
media_type="application/octet-stream",
headers={
"Content-Length": str(files[path][0]),
"Cache-Control": "no-store",
"Content-Disposition": "attachment; filename*=UTF-8''" + quote(name, safe=""),
},
)
return router
+17 -3
View File
@@ -28,6 +28,13 @@ class SimulationSourceFileCreate(BaseModel):
byte_length: int = Field(gt=0)
class SimulationSourceAttribution(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
author: str = Field(default="", max_length=500)
license: str = Field(default="", max_length=500)
source_url: str | None = Field(default=None, max_length=2048)
class SimulationProjectCreate(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
@@ -36,6 +43,7 @@ class SimulationProjectCreate(BaseModel):
scene_type: Literal["interior", "outdoor", "object"]
source_kind: Literal["archive", "folder"]
files: list[SimulationSourceFileCreate] = Field(min_length=1, max_length=10_000)
attribution: SimulationSourceAttribution | None = None
class SimulationProjectUpdate(BaseModel):
@@ -107,6 +115,7 @@ class SimulationProjectDocument(BaseModel):
scene_type: Literal["interior", "outdoor", "object"]
status: Literal["uploading", "queued", "processing", "importing", "ready", "failed"]
source: dict[str, Any]
attribution: dict[str, str | None] = Field(default_factory=dict, exclude=True)
provider: dict[str, Any]
artifacts: list[dict[str, Any]]
world_manifest: dict[str, Any] | None
@@ -153,6 +162,7 @@ def build_simulation_projects_router(
scene_type=request.scene_type,
source_kind=request.source_kind,
files=[item.model_dump() for item in request.files],
attribution=request.attribution.model_dump() if request.attribution else None,
)
except SimulationProjectError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -278,11 +288,15 @@ def build_simulation_projects_router(
except GaussianPipelineGatewayError as exc:
raise HTTPException(status_code=503, detail=str(exc)) from exc
@router.delete("/projects/{project_id}", status_code=204)
@router.get("/deletions")
def list_deletions():
return {"deletions": service.deletions.list()}
@router.delete("/projects/{project_id}", status_code=202)
def delete_project(project_id: str) -> Response:
try:
service.delete(project_id)
return Response(status_code=204, headers={"Cache-Control": "no-store"})
service.deletions.request(project_id)
return Response(status_code=202, headers={"Cache-Control": "no-store"})
except SimulationProjectNotFoundError as exc:
raise HTTPException(status_code=404, detail="Проект симуляции не найден.") from exc
except SimulationProjectConflictError as exc: