"""Durable removal intents: retain a connection until its real exposure is closed.""" from __future__ import annotations import copy import json import threading from pathlib import Path from persistence import atomic_write_json class PendingRemovals: def __init__(self, path: Path): self.path = Path(path) self.lock = threading.RLock() self.items = {} self.error = "" try: value = json.loads(self.path.read_text(encoding="utf-8")) if not isinstance(value, dict) or not all(isinstance(v, dict) for v in value.values()): raise ValueError("неверный формат") self.items = value except FileNotFoundError: pass except (OSError, ValueError) as exc: self.error = f"Не прочитаны ожидающие удаления: {exc}" def connections(self): with self.lock: return copy.deepcopy(self.items) def schedule(self, key: str, connection: dict): with self.lock: if self.error: raise ValueError(self.error) updated = {**self.items, key: dict(connection)} atomic_write_json(self.path, updated) self.items = updated def complete(self, key: str): with self.lock: updated = dict(self.items) updated.pop(key, None) atomic_write_json(self.path, updated) self.items = updated