Make simulation imports background tasks with Worker-owned sources and durable deletion
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
"""Worker-owned originals for legacy PLY worlds and simulation projects."""
|
||||
|
||||
import hashlib
|
||||
|
||||
from k1link.simulation.gaussian_pipeline_gateway import GaussianPipelineIntegrityError
|
||||
from k1link.simulation.source_retention import receipt_files
|
||||
|
||||
from .worlds import write_json
|
||||
|
||||
|
||||
def original_receipt(worlds, world_id):
|
||||
world = worlds.get(world_id)
|
||||
if world.get("storage", {}).get("kind") == "project":
|
||||
project = worlds.projects.projects.get(world["storage"]["project_id"])
|
||||
storage = project["source"].get("storage", {})
|
||||
else:
|
||||
storage = world.get("original_storage", {})
|
||||
receipt = storage.get("receipt")
|
||||
if not receipt:
|
||||
raise ValueError(
|
||||
"Исходник ещё не подтверждён в хранилище. Повторите после завершения импорта."
|
||||
)
|
||||
return world, storage, receipt
|
||||
|
||||
|
||||
def retain_legacy_original(worlds, world_id, provider, editor):
|
||||
"""A receipt and usable render result must survive before an exact source unlink."""
|
||||
with worlds.lock:
|
||||
world = worlds.get(world_id)
|
||||
cache = editor.get(editor.request(world_id)["key"])
|
||||
if cache["status"] != "ready":
|
||||
raise ValueError("Сначала дождитесь готового материала для просмотра.")
|
||||
for name in cache["files"]:
|
||||
path, expected = editor.asset(cache["key"], name)
|
||||
with path.open("rb") as stream:
|
||||
if hashlib.file_digest(stream, "sha256").hexdigest() != expected:
|
||||
raise GaussianPipelineIntegrityError("Render asset changed; original retained")
|
||||
source = worlds.directory(world_id) / "source.ply"
|
||||
storage = world.get("original_storage")
|
||||
if storage:
|
||||
if storage["provider_endpoint"] != provider.endpoint:
|
||||
raise GaussianPipelineIntegrityError("Original provider changed")
|
||||
receipt = provider.retained_source(storage["receipt"], verify=True)
|
||||
else:
|
||||
provider.require_source_retention()
|
||||
if source.is_symlink() or not source.is_file():
|
||||
raise GaussianPipelineIntegrityError("Local original missing")
|
||||
with source.open("rb") as stream:
|
||||
if hashlib.file_digest(stream, "sha256").hexdigest() != world["sha256"]:
|
||||
raise GaussianPipelineIntegrityError("Local original changed")
|
||||
bundle = provider.upload_source_bundle(
|
||||
source.parent, entrypoint="source.ply", source_format="ply"
|
||||
)
|
||||
receipt = provider.retain_source({"kind": "folder", "source": bundle.to_dict()})
|
||||
provider.retained_source(receipt, verify=True)
|
||||
if receipt_files(receipt) != {"source.ply": (world["byte_length"], world["sha256"])}:
|
||||
raise GaussianPipelineIntegrityError("Worker did not retain this exact PLY")
|
||||
world["original_storage"] = {
|
||||
"provider_endpoint": provider.endpoint,
|
||||
"receipt": receipt,
|
||||
"local_state": "retiring",
|
||||
}
|
||||
write_json(worlds.directory(world_id) / "world.json", world)
|
||||
removed = 0
|
||||
if source.exists():
|
||||
if source.is_symlink() or source.stat().st_size != world["byte_length"]:
|
||||
raise GaussianPipelineIntegrityError("Source changed before removal")
|
||||
with source.open("rb") as stream:
|
||||
if hashlib.file_digest(stream, "sha256").hexdigest() != world["sha256"]:
|
||||
raise GaussianPipelineIntegrityError("Source changed before removal")
|
||||
removed = source.stat().st_size
|
||||
source.unlink()
|
||||
world["original_storage"]["local_state"] = "remote"
|
||||
write_json(worlds.directory(world_id) / "world.json", world)
|
||||
return {"world_id": world_id, "removed_bytes": removed, "source_id": receipt["source_id"]}
|
||||
@@ -54,9 +54,9 @@ class ProjectWorlds:
|
||||
"schema_version": "missioncore.ai-polygon-world/v1",
|
||||
"world_id": project["project_id"].replace("sim-", "aiworld-", 1),
|
||||
"name": project["name"],
|
||||
"author": "",
|
||||
"license": "",
|
||||
"source_url": None,
|
||||
"author": project.get("attribution", {}).get("author", ""),
|
||||
"license": project.get("attribution", {}).get("license", ""),
|
||||
"source_url": project.get("attribution", {}).get("source_url"),
|
||||
"filename": "lod-meta.json",
|
||||
"byte_length": sum(a["byte_length"] for a in project["artifacts"]),
|
||||
"status": "available",
|
||||
|
||||
@@ -174,8 +174,8 @@ class GaussianPipelineGateway:
|
||||
source_format: str,
|
||||
additional_paths: list[str] | None = None,
|
||||
) -> GaussianSourceBundleUpload:
|
||||
if source_format not in {"lcc", "lcc2"}:
|
||||
raise GaussianPipelineIntegrityError("Gaussian source format must be lcc or lcc2")
|
||||
if source_format not in {"lcc", "lcc2", "ply"}:
|
||||
raise GaussianPipelineIntegrityError("Gaussian source format must be lcc, lcc2 or Gaussian ply")
|
||||
logical_entrypoint = _logical_path(entrypoint, "entrypoint")
|
||||
if not logical_entrypoint.lower().endswith(f".{source_format}"):
|
||||
raise GaussianPipelineIntegrityError(
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user