fix(scene): persist editor and battery profiles in Core

This commit is contained in:
DCCONSTRUCTIONS
2026-11-10 01:08:00 +03:00
parent 7595bea07c
commit cd34b6ce1a
18 changed files with 581 additions and 91 deletions
+146
View File
@@ -0,0 +1,146 @@
"""Durable operator scene documents. Never part of telemetry/cache retention."""
from __future__ import annotations
import fcntl
import hashlib
import json
import os
from contextlib import contextmanager
from datetime import UTC, datetime
from pathlib import Path
from threading import RLock
from typing import Any
MAX_BYTES = 32_000_000
KINDS = {
"battery": "missioncore.battery-scene/v1",
"rover": "missioncore.rover-scene/v1",
"battery-ui": "missioncore.battery-ui/v1",
"battery-view": "missioncore.battery-view/v1",
"environments": "missioncore.environment-library/v1",
}
_lock = RLock()
class ProfileConflict(ValueError):
pass
def validate_document(kind: str, document: Any) -> None:
if kind not in KINDS or not isinstance(document, dict) or document.get("schema") != KINDS[kind]:
raise ValueError("Неверный тип профиля.")
if kind in ("battery", "rover"):
if not all(
isinstance(document.get(k), dict) for k in ("materials", "postFx", "assignments")
):
raise ValueError("Неполный документ сцены.")
if not isinstance(document.get("model"), str) or len(document["materials"]) > 256:
raise ValueError("Неверная модель или библиотека материалов.")
elif kind == "battery-ui":
if not all(isinstance(document.get(k), dict) for k in ("markings", "panels")):
raise ValueError("Неполный профиль оформления батареи.")
elif kind == "battery-view":
height = document.get("height")
if type(height) not in (int, float) or not 360 <= height <= 2160:
raise ValueError("Неверная высота окна.")
else:
profiles = document.get("profiles")
if not isinstance(profiles, list) or len(profiles) > 64:
raise ValueError("Неверная библиотека окружений.")
ids = []
for profile in profiles:
if (
not isinstance(profile, dict)
or profile.get("schema") != "missioncore.environment-profile/v1"
):
raise ValueError("Неверный профиль окружения.")
pid = profile.get("id")
if not isinstance(pid, str) or not pid.startswith("env/") or pid in ids:
raise ValueError("Повторяющийся или неверный профиль окружения.")
ids.append(pid)
class SceneProfileStore:
def __init__(self, root: Path):
self.root = root
def path(self, kind: str, owner: str) -> Path:
if kind not in KINDS or not owner or len(owner) > 512 or any(ord(c) < 32 for c in owner):
raise ValueError("Неверный идентификатор профиля.")
return self.root / kind / hashlib.sha256(owner.encode()).hexdigest() / "meta.json"
def read(self, kind: str, owner: str) -> dict:
path = self.path(kind, owner)
if not path.exists():
return {"revision": 0, "document": None}
value = json.loads(path.read_text())
if (
value.get("schema") != "missioncore.scene-profile-meta/v1"
or value.get("kind") != kind
or value.get("ownerId") != owner
or type(value.get("revision")) is not int
or value["revision"] < 1
):
raise ValueError("Повреждён файл профиля. Исходный файл сохранён.")
validate_document(kind, value.get("document"))
return value
@contextmanager
def locked(self):
with _lock:
self.root.mkdir(parents=True, exist_ok=True)
with (self.root / ".write.lock").open("a") as stream:
fcntl.flock(stream, fcntl.LOCK_EX)
try:
yield
finally:
fcntl.flock(stream, fcntl.LOCK_UN)
@staticmethod
def atomic(path: Path, data: bytes) -> None:
temporary = path.with_name(path.name + ".tmp")
try:
with temporary.open("wb") as stream:
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
descriptor = os.open(path.parent, os.O_RDONLY)
try:
os.fsync(descriptor)
finally:
os.close(descriptor)
finally:
temporary.unlink(missing_ok=True)
def save(self, kind: str, owner: str, document: dict, expected_revision: int) -> dict:
validate_document(kind, document)
if type(expected_revision) is not int or expected_revision < 0:
raise ValueError("Неверная ревизия профиля.")
path = self.path(kind, owner)
with self.locked():
current = self.read(kind, owner)
if current["revision"] != expected_revision:
raise ProfileConflict(
"Профиль изменён в другом окне. Откройте сцену заново; "
"изменения можно экспортировать."
)
if current["document"] == document:
return current
value = {
"schema": "missioncore.scene-profile-meta/v1",
"kind": kind,
"ownerId": owner,
"revision": expected_revision + 1,
"updatedAt": datetime.now(UTC).isoformat(),
"document": document,
}
data = json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2).encode()
if len(data) > MAX_BYTES:
raise ValueError("Профиль превышает 32 МБ.")
path.parent.mkdir(parents=True, exist_ok=True)
if path.exists():
self.atomic(path.with_name("meta.previous.json"), path.read_bytes())
self.atomic(path, data)
return value
+2
View File
@@ -235,6 +235,7 @@ from k1link.web.runtime_readiness import (
BackgroundReconcilerReadiness,
build_runtime_readiness,
)
from k1link.web.scene_profiles_api import build_scene_profiles_router
from k1link.web.session_api import build_session_router
from k1link.web.session_overview_api import build_session_overview_router
from k1link.sessions.overview import SessionOverviewService
@@ -2010,6 +2011,7 @@ app.include_router(
service=simulation_project_service,
)
)
app.include_router(build_scene_profiles_router(lambda: session_store.data_dir / "scene-profiles"))
frontend_dist = REPOSITORY_ROOT / "apps" / "control-station" / "dist"
try:
app.include_router(build_ai_polygon_router(session_store.data_dir, OBSERVATORY_RECORDED_JOB_QUEUE))
+60
View File
@@ -0,0 +1,60 @@
"""Scene persistence on the canonical operator Core, not in browser storage."""
import json
from collections.abc import Callable
from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from k1link.scene_profiles import MAX_BYTES, ProfileConflict, SceneProfileStore
from .fleet_api import local_operator
def build_scene_profiles_router(root_provider: Callable[[], Path]) -> APIRouter:
router = APIRouter(
prefix="/api/v1/scene-profiles",
tags=["scene-profiles"],
dependencies=[Depends(local_operator)],
)
@router.get("/{kind}")
def read(kind: str, response: Response, owner: str = Query(min_length=1, max_length=512)):
response.headers["Cache-Control"] = "no-store"
try:
return SceneProfileStore(root_provider()).read(kind, owner)
except (OSError, ValueError) as error:
raise HTTPException(
500, "Не удалось прочитать файл профиля. Сохранённые настройки не изменены."
) from error
@router.put("/{kind}")
async def save(
kind: str,
request: Request,
response: Response,
owner: str = Query(min_length=1, max_length=512),
):
response.headers["Cache-Control"] = "no-store"
data = bytearray()
async for chunk in request.stream():
data.extend(chunk)
if len(data) > MAX_BYTES:
raise HTTPException(413, "Профиль превышает 32 МБ.")
try:
body = json.loads(data)
if not isinstance(body, dict) or set(body) != {"document", "expected_revision"}:
raise ValueError("Неверный запрос сохранения.")
return SceneProfileStore(root_provider()).save(
kind, owner, body["document"], body["expected_revision"]
)
except ProfileConflict as error:
raise HTTPException(409, str(error)) from error
except (ValueError, TypeError, KeyError) as error:
raise HTTPException(422, str(error)) from error
except OSError as error:
raise HTTPException(
500, "Не удалось записать профиль. Предыдущая версия сохранена."
) from error
return router