feat(sfm): per-unit lock -- one connection per unit, 423 when busy
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
034529f498
commit
bb4b26835b
3 files changed
+97
No files matched your search
@@ -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
|
||||
@@ -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()
|
||||
@@ -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
|
||||
Reference in new issue
Block a user