From bb4b26835b9f45e4a0536b993ac37f4959f2649b Mon Sep 17 00:00:00 2001 From: serversdown Date: Wed, 21 Oct 2026 01:08:10 -0400 Subject: [PATCH] feat(sfm): per-unit lock -- one connection per unit, 423 when busy Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- sfm/device_access/__init__.py | 1 + sfm/device_access/locks.py | 41 ++++++++++++++++++++++++ tests/test_device_access_core.py | 55 ++++++++++++++++++++++++++++++++ 3 files changed, 97 insertions(+) create mode 100644 sfm/device_access/locks.py diff --git a/sfm/device_access/__init__.py b/sfm/device_access/__init__.py index cfc3535..b5502ec 100644 --- a/sfm/device_access/__init__.py +++ b/sfm/device_access/__init__.py @@ -5,3 +5,4 @@ from .errors import ( ) from .models import UnitAddress, UnitInfo, UnitSettings, UnitStatus from .series import normalise_serial, series_for_serial +from .locks import UnitLocks diff --git a/sfm/device_access/locks.py b/sfm/device_access/locks.py new file mode 100644 index 0000000..0e2b757 --- /dev/null +++ b/sfm/device_access/locks.py @@ -0,0 +1,41 @@ +"""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() diff --git a/tests/test_device_access_core.py b/tests/test_device_access_core.py index 6615d67..b96a015 100644 --- a/tests/test_device_access_core.py +++ b/tests/test_device_access_core.py @@ -81,3 +81,58 @@ def test_an_address_needs_a_host_or_a_port(): def test_the_lock_key_names_the_physical_link(): assert UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None).key == "tcp:10.0.0.5:9034" assert UnitAddress(host=None, tcp_port=None, port="/dev/ttyACM0", baud=115200).key == "serial:/dev/ttyACM0" + + +# ── per-unit lock ───────────────────────────────────────────────────────────── + +import threading # noqa: E402 + +from sfm.device_access.errors import UnitBusy # noqa: E402 +from sfm.device_access.locks import UnitLocks # noqa: E402 + + +def test_a_second_request_for_a_busy_unit_gets_unit_busy(): + locks = UnitLocks(timeout=0.2) + entered = threading.Event() + release = threading.Event() + + def holder(): + with locks.hold("tcp:10.0.0.5:9034"): + entered.set() + release.wait(2) + + t = threading.Thread(target=holder) + t.start() + entered.wait(2) + try: + with pytest.raises(UnitBusy, match="busy"): + with locks.hold("tcp:10.0.0.5:9034"): + pass + finally: + release.set() + t.join() + + +def test_different_units_do_not_block_each_other(): + locks = UnitLocks(timeout=0.2) + with locks.hold("tcp:10.0.0.5:9034"): + with locks.hold("tcp:10.0.0.6:9034"): + pass + + +def test_try_hold_never_waits(): + locks = UnitLocks(timeout=5) + with locks.hold("k"): + with locks.try_hold("k") as got: + assert got is False + with locks.try_hold("k") as got: + assert got is True + + +def test_the_lock_is_released_after_an_exception(): + locks = UnitLocks(timeout=0.2) + with pytest.raises(RuntimeError): + with locks.hold("k"): + raise RuntimeError("boom") + with locks.hold("k"): + pass