"""Independent equipment identities, immutable profiles and assignment history. No vehicle node_id is used for identity, availability, or enrollment. Saving a policy never claims the hardware has applied it. Adapter owns vendor semantics. """ import json import secrets import sqlite3 import threading import time import uuid from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path from typing import Any, Protocol, cast Document = dict[str, Any] class EnrollmentAdapter(Protocol): def catalog(self) -> Document: ... def validate_policy(self, value: Document) -> Document: ... def inspect(self, evidence: Path) -> Document: ... def check_policy(self, candidate: Document, evidence: Path, policy: Document) -> None: ... def apply(self, instance: Document, evidence: Path) -> Document: ... class EquipmentError(ValueError): pass class EquipmentStore: @staticmethod def require_idle(row: Document) -> None: from .equipment_network import idle idle(row) def __init__(self, root: Path, adapters: dict[str, EnrollmentAdapter]) -> None: self.root = root / "independent-equipment" self.root.mkdir(mode=0o700, parents=True, exist_ok=True) if self.root.is_symlink() or self.root.stat().st_mode & 0o077: raise EquipmentError("Хранилище оборудования недоступно.") self.path = self.root / "registry.sqlite3" if self.path.is_symlink(): raise EquipmentError("Хранилище оборудования недоступно.") self.adapters = adapters self.read_lock = threading.Lock() with self.db() as db: db.executescript(""" CREATE TABLE IF NOT EXISTS profiles(id TEXT PRIMARY KEY, body TEXT NOT NULL); CREATE TABLE IF NOT EXISTS candidates(id TEXT PRIMARY KEY, expires REAL NOT NULL, body TEXT NOT NULL); CREATE TABLE IF NOT EXISTS instances(id TEXT PRIMARY KEY, identity_key TEXT UNIQUE NOT NULL, body TEXT NOT NULL); CREATE TABLE IF NOT EXISTS history(instance_id TEXT NOT NULL, revision INTEGER NOT NULL, body TEXT NOT NULL, PRIMARY KEY(instance_id, revision)); CREATE TABLE IF NOT EXISTS network_outbox( id TEXT PRIMARY KEY, instance TEXT NOT NULL, host TEXT NOT NULL, target TEXT NOT NULL, body TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, next_attempt REAL NOT NULL DEFAULT 0); """) from .equipment_command_journal import initialize initialize(db) self.path.chmod(0o600) @contextmanager def db(self) -> Iterator[sqlite3.Connection]: db = sqlite3.connect(self.path, timeout=5) try: db.execute("PRAGMA synchronous=FULL") with db: yield db finally: db.close() def adapter(self, model: str) -> EnrollmentAdapter: if model not in self.adapters: raise EquipmentError("Модель не поддерживается.") return self.adapters[model] def catalog(self) -> Document: return {"models": [a.catalog() for a in self.adapters.values()]} def public(self, row: Document) -> Document: public = {k: v for k, v in row.items() if k not in ("identity_key", "evidence_id")} details = getattr(self.adapters.get(row.get("model_id")), "observation_details", None) if details and row.get("evidence_id"): # Add newly supported observations from the immutable enrollment # snapshot without requiring USB reconnection or altering policy. public["observed"] = { **row.get("observed", {}), **details(self.root / "evidence" / row["evidence_id"]), } return public def profiles(self) -> list[Document]: with self.db() as db: return [ json.loads(r[0]) for r in db.execute("SELECT body FROM profiles ORDER BY rowid DESC") ] def save_profile(self, name: str, model: str, settings: Document) -> Document: settings = self.adapter(model).validate_policy(settings) name = name.strip() if not name or len(name) > 80: raise EquipmentError("Укажите название профиля до 80 символов.") row: Document = { "id": uuid.uuid4().hex, "name": name, "model_id": model, "settings": settings, "created_at": time.time(), } with self.db() as db: db.execute("INSERT INTO profiles VALUES(?,?)", (row["id"], json.dumps(row))) return row def inspect(self, model: str) -> Document: adapter = self.adapter(model) if not self.read_lock.acquire(blocking=False): raise EquipmentError("Чтение USB уже выполняется. Дождитесь результата.") try: row = adapter.inspect(self.root / "evidence") row.update(id=secrets.token_urlsafe(32), expires_at=time.time() + 600) with self.db() as db: db.execute("DELETE FROM candidates WHERE expires < ?", (time.time(),)) db.execute( "INSERT INTO candidates VALUES(?,?,?)", (row["id"], row["expires_at"], json.dumps(row)), ) return self.public(row) finally: self.read_lock.release() @staticmethod def _find(db: sqlite3.Connection, table: str, identifier: str) -> Document: # Table names are internal constants, never request data. row = db.execute(f"SELECT body FROM {table} WHERE id=?", (identifier,)).fetchone() if row is None: raise EquipmentError("Запись не найдена. Обновите список.") return cast(Document, json.loads(row[0])) def listing(self, vehicle: str | None = None) -> list[Document]: with self.db() as db: rows = [ json.loads(r[0]) for r in db.execute("SELECT body FROM instances ORDER BY rowid") ] return [self.public(r) for r in rows if vehicle is None or r["vehicle_id"] == vehicle] def add( self, candidate_id: str, name: str, vehicle_id: str, profile_id: str | None = None ) -> Document: name = name.strip() if not name or len(name) > 80: raise EquipmentError("Укажите название устройства до 80 символов.") with self.db() as db: db.execute("BEGIN IMMEDIATE") candidate = self._find(db, "candidates", candidate_id) if candidate["expires_at"] <= time.time(): raise EquipmentError("Проверка USB устарела. Прочитайте трекер повторно.") settings = candidate["settings"] if profile_id: profile = self._find(db, "profiles", profile_id) if profile["model_id"] != candidate["model_id"]: raise EquipmentError("Профиль предназначен для другой модели.") settings = profile["settings"] self.adapter(candidate["model_id"]).check_policy( candidate, self.root / "evidence", settings ) row = { **candidate, "id": uuid.uuid4().hex, "name": name, "vehicle_id": vehicle_id, "revision": 1, "settings": settings, "profile_id": profile_id, "policy_state": "saved", "updated_at": time.time(), } row.pop("expires_at") try: db.execute( "INSERT INTO instances VALUES(?,?,?)", (row["id"], row["identity_key"], json.dumps(row)), ) except sqlite3.IntegrityError: raise EquipmentError( "Этот трекер уже добавлен. Измените аппарат в его настройках." ) from None db.execute("DELETE FROM candidates WHERE id=?", (candidate_id,)) return self.public(row) def update( self, identifier: str, revision: int, name: str, vehicle_id: str, settings: Document ) -> Document: with self.db() as db: db.execute("BEGIN IMMEDIATE") old = self._find(db, "instances", identifier) self.require_idle(old) if old["revision"] != revision: raise EquipmentError("Настройки изменились в другом окне. Откройте их заново.") name = name.strip() if not name or len(name) > 80: raise EquipmentError("Укажите название устройства до 80 символов.") settings = self.adapter(old["model_id"]).validate_policy(settings) self.adapter(old["model_id"]).check_policy(old, self.root / "evidence", settings) row = { **old, "name": name, "vehicle_id": vehicle_id, "settings": settings, "revision": revision + 1, "updated_at": time.time(), } if settings != old["settings"]: row.update(policy_state="saved", profile_id=None) db.execute( "INSERT INTO history VALUES(?,?,?)", (old["id"], old["revision"], json.dumps(old)) ) db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier)) return self.public(row) def refresh_observation(self, identifier: str, revision: int) -> Document: with self.db() as db: before = self._find(db, "instances", identifier) self.require_idle(before) if before["revision"] != revision: raise EquipmentError("Настройки изменились. Откройте устройство заново.") candidate = self.inspect(before["model_id"]) with self.db() as db: db.execute("BEGIN IMMEDIATE") snapshot = self._find(db, "candidates", candidate["id"]) old = self._find(db, "instances", identifier) self.require_idle(old) if old["revision"] != revision: raise EquipmentError("Настройки изменились во время чтения. Повторите проверку.") if snapshot["identity_key"] != old["identity_key"]: raise EquipmentError("Подключён другой трекер. Существующая запись не изменена.") row = { **old, "observed": snapshot["observed"], "evidence_id": snapshot["evidence_id"], "revision": revision + 1, "updated_at": time.time(), } # Fresh USB observation supersedes the endpoint projection. row.pop("network_server1", None) if snapshot["observed"].get("configuration") != old["observed"].get("configuration"): row["policy_state"] = "saved" db.execute("INSERT INTO history VALUES(?,?,?)", (identifier, revision, json.dumps(old))) db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier)) db.execute("DELETE FROM candidates WHERE id=?", (candidate["id"],)) return self.public(row) def apply(self, identifier: str, revision: int) -> Document: if not self.read_lock.acquire(blocking=False): raise EquipmentError("USB занят. Дождитесь завершения текущего действия.") try: # Keep assignment/policy stable for the entire bounded USB operation. with self.db() as db: db.execute("BEGIN IMMEDIATE") old = self._find(db, "instances", identifier) self.require_idle(old) if old["revision"] != revision: raise EquipmentError("Настройки изменились. Откройте устройство заново.") adapter = self.adapter(old["model_id"]) adapter.check_policy(old, self.root / "evidence", old["settings"]) result = adapter.apply(old, self.root / "evidence") row = {**old, **result, "revision": revision + 1, "updated_at": time.time()} if "observed" in result: row.pop("network_server1", None) db.execute( "INSERT INTO history VALUES(?,?,?)", (identifier, revision, json.dumps(old)) ) db.execute("UPDATE instances SET body=? WHERE id=?", (json.dumps(row), identifier)) return self.public(row) finally: self.read_lock.release()