"""One connection per unit. A modem allows a single TCP session, so two requests must take turns instead of opening a second connection.""" from __future__ import annotations import threading from contextlib import contextmanager from typing import Dict, Iterator, Optional from .errors import UnitBusy class UnitLocks: def __init__(self, timeout: float = 20.0) -> None: self._timeout = timeout self._guard = threading.Lock() self._locks: Dict[str, threading.Lock] = {} def _lock_for(self, key: str) -> threading.Lock: with self._guard: return self._locks.setdefault(key, threading.Lock()) @contextmanager def hold(self, key: str, timeout: Optional[float] = None) -> Iterator[None]: lock = self._lock_for(key) wait = self._timeout if timeout is None else timeout if not lock.acquire(timeout=wait): raise UnitBusy(f"the unit at {key} is busy with another request; try again shortly") try: yield finally: lock.release() @contextmanager def try_hold(self, key: str) -> Iterator[bool]: lock = self._lock_for(key) got = lock.acquire(blocking=False) try: yield got finally: if got: lock.release()