"""Bounded, immutable planning-source cache contributed by device plugins.""" from __future__ import annotations import hashlib import json import os import shutil import threading from contextlib import contextmanager from uuid import uuid4 from k1link.sessions.recording import ( RecordingMaterializationCancelled, _stage_replay_prefix, _validate_source, _validate_source_state, _validated_artifact_digests, ) SCHEMA = "missioncore.planning-source/v1" class PlanningSources: def __init__(self, store, exporters, submap_extractors=None, scene_submap_extractors=None): self.store = store self.exporters = exporters self.submap_extractors = submap_extractors or {} self.scene_submap_extractors = scene_submap_extractors or {} self.root = store.data_dir / "planning-sources" self.root.mkdir(parents=True, exist_ok=True) self.lock = threading.Lock() self._scene_cache = None def get(self, session_id: str) -> dict: detail = self.store.get_session(session_id) exporter = self.exporters.get(detail.plugin_id) if not detail.summary.replayable or detail.summary.lab is not None or exporter is None: raise ValueError("В этой записи нет поддерживаемой пространственной зоны.") source = _validate_source(self.store.prepare_replay(session_id)) generation = hashlib.sha256( json.dumps([SCHEMA, session_id, source.identity], default=str).encode() ).hexdigest() with self.lock: path = self.root / (generation + ".json") if path.is_file() and path.stat().st_size < 32 * 1024 * 1024: try: doc = json.loads(path.read_text()) if doc["schema_version"] == SCHEMA and doc["generation"] == generation: return doc except (ValueError, KeyError): pass stage = None candidate = self.root / ("." + uuid4().hex + ".json") try: digests = _validated_artifact_digests(source) stage, primary, _ = _stage_replay_prefix(self.root, source) exporter(primary, candidate) if candidate.stat().st_size > 30 * 1024 * 1024: raise ValueError("Траектория превышает размер поддерживаемой зоны.") result = json.loads(candidate.read_text()) if source.identity != _validate_source_state( source ).identity or digests != _validated_artifact_digests(source): raise ValueError("Исходная запись изменилась во время подготовки.") doc = { **result, "schema_version": SCHEMA, "session_id": session_id, "label": detail.as_dict()["display_name"], "generation": generation, "units": "m", "frame_id": "session/" + session_id, "source_digests": digests, } candidate.write_text(json.dumps(doc, allow_nan=False)) os.replace(candidate, path) return doc finally: candidate.unlink(missing_ok=True) if stage is not None: shutil.rmtree(stage, ignore_errors=True) def bound(self, session_id: str, generation: str) -> dict: doc = self.get(session_id) if doc["generation"] != generation: raise ValueError("Исходная запись изменилась. Требуется повторный выбор зоны.") return doc def verify(self, session_id: str, generation: str) -> dict: doc = self.bound(session_id, generation) source = _validate_source(self.store.prepare_replay(session_id)) if _validated_artifact_digests(source) != doc["source_digests"]: raise ValueError("Контрольные суммы исходной записи изменились.") return doc def submap(self, session_id, generation, start, end, *, presentation=False): with self.prepared_submaps(session_id, generation, presentation=presentation) as extract: return extract(start, end) @contextmanager def prepared_submaps(self, session_id, generation, *, presentation=False, cancel_event=None): """One verified private snapshot for all tiles of one map build. Callers may assemble tiles inside this context, but must not publish the map until exit has revalidated the original source. Cancellation and failures discard staging without publishing a partial atlas. """ if cancel_event is not None and cancel_event.is_set(): raise InterruptedError("Reference preparation cancelled.") doc = self.verify(session_id, generation) detail = self.store.get_session(session_id) extractors = self.scene_submap_extractors if presentation else self.submap_extractors extractor = extractors.get(detail.plugin_id) if extractor is None: raise ValueError("Эта запись не поддерживает подготовку облака для совмещения.") source = _validate_source(self.store.prepare_replay(session_id)) stage = None try: stage, primary, _ = _stage_replay_prefix(self.root, source, cancel_event=cancel_event) def extract(start, end): if cancel_event is not None and cancel_event.is_set(): raise InterruptedError("Reference preparation cancelled.") points, evidence = extractor(primary, doc, start, end) return points, { **evidence, **{ k: doc[k] for k in ( "session_id", "generation", "label", "frame_id", "units", "source_digests", ) }, } yield extract if cancel_event is not None and cancel_event.is_set(): raise InterruptedError("Reference preparation cancelled.") if source.identity != _validate_source_state(source).identity: raise ValueError("Запись изменилась во время подготовки облака.") self.verify(session_id, generation) except RecordingMaterializationCancelled as exc: raise InterruptedError("Reference preparation cancelled.") from exc finally: if stage is not None: shutil.rmtree(stage, ignore_errors=True) def reference_map(self, session_id, generation, start, end, *, cancel_event=None): from .reference_map import build_reference_map return build_reference_map( self, session_id, generation, start, end, cancel_event=cancel_event ) def scene_reference_map(self, session_id, generation, start, end, *, cancel_event=None): from .reference_map import build_reference_map self.verify(session_id, generation) key = (session_id, generation, start, end) if self._scene_cache is not None and self._scene_cache[0] == key: return self._scene_cache[1] result = build_reference_map( self, session_id, generation, start, end, cancel_event=cancel_event, presentation=True ) self._scene_cache = (key, result) # One display atlas, not an unbounded route cache. return result