Files
NODEDC_MISSION_CORE/src/k1link/scene_profiles.py
T

147 lines
6.0 KiB
Python

"""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