init commit
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
"""Хранилище позиций узлов (JSON-файл, запись атомарная)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
MAX_ENTRIES = 5000
|
||||
_KEY_RE = re.compile(r"^[0-9A-Za-z-]{8,64}$")
|
||||
|
||||
|
||||
def valid_key(key: str) -> bool:
|
||||
return bool(_KEY_RE.match(key))
|
||||
|
||||
|
||||
def clean_positions(raw) -> dict[str, dict[str, float]]:
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("positions должен быть объектом {id: {x, y}}")
|
||||
if len(raw) > MAX_ENTRIES:
|
||||
raise ValueError("слишком много узлов")
|
||||
out: dict[str, dict[str, float]] = {}
|
||||
for node_id, pos in raw.items():
|
||||
if not isinstance(node_id, str) or not 0 < len(node_id) <= 200:
|
||||
raise ValueError("некорректный id узла")
|
||||
if not isinstance(pos, dict):
|
||||
raise ValueError(f"позиция {node_id!r} должна быть объектом")
|
||||
coords = []
|
||||
for axis in ("x", "y"):
|
||||
v = pos.get(axis)
|
||||
if isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v):
|
||||
raise ValueError(f"{node_id!r}: {axis} должно быть конечным числом")
|
||||
coords.append(float(v))
|
||||
out[node_id] = {"x": coords[0], "y": coords[1]}
|
||||
return out
|
||||
|
||||
|
||||
class PositionStore:
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def _read(self) -> dict:
|
||||
try:
|
||||
return json.loads(self.path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except ValueError:
|
||||
log.warning("positions: файл %s повреждён, начинаю с пустого", self.path)
|
||||
return {}
|
||||
|
||||
def _write(self, data: dict) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, tmp = tempfile.mkstemp(dir=self.path.parent, prefix=".positions-")
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=1)
|
||||
os.replace(tmp, self.path)
|
||||
except BaseException:
|
||||
Path(tmp).unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
def get(self, key: str) -> dict:
|
||||
with self._lock:
|
||||
return self._read().get(key, {})
|
||||
|
||||
def put(self, key: str, positions: dict) -> None:
|
||||
with self._lock:
|
||||
data = self._read()
|
||||
data[key] = positions
|
||||
self._write(data)
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
with self._lock:
|
||||
data = self._read()
|
||||
if data.pop(key, None) is not None:
|
||||
self._write(data)
|
||||
Reference in New Issue
Block a user