diff --git a/sfm/device_access/__init__.py b/sfm/device_access/__init__.py index b5502ec..2093308 100644 --- a/sfm/device_access/__init__.py +++ b/sfm/device_access/__init__.py @@ -6,3 +6,4 @@ from .errors import ( from .models import UnitAddress, UnitInfo, UnitSettings, UnitStatus from .series import normalise_serial, series_for_serial from .locks import UnitLocks +from .access import DeviceAccess diff --git a/sfm/device_access/access.py b/sfm/device_access/access.py new file mode 100644 index 0000000..a7c95eb --- /dev/null +++ b/sfm/device_access/access.py @@ -0,0 +1,144 @@ +"""DeviceAccess -- the one door every device request passes through. + +The control surface does not care which series it is talking to; this does. +""" +from __future__ import annotations + +import logging +import threading +import time +from typing import Any, Callable, Dict, Optional + +from .errors import DeviceError +from .locks import UnitLocks +from .models import UnitAddress, UnitInfo, UnitSettings, UnitStatus +from .s3 import Series3Adapter, default_s3_client_factory +from .s4 import ( + Series4Session, default_s4_client_factory, s4_identify, s4_settings, s4_status, +) +from .series import normalise_serial, series_for_serial + +log = logging.getLogger("sfm.device_access") + + +class DeviceAccess: + def __init__( + self, *, + s3_client_factory: Callable[[UnitAddress], Any] = default_s3_client_factory, + s4_client_factory: Callable[[UnitAddress], Any] = default_s4_client_factory, + clock: Callable[[], float] = time.monotonic, + lock_timeout: float = 20.0, + keepalive_s: float = 60.0, + idle_hangup_s: float = 300.0, + reaper_interval_s: float = 5.0, + start_reaper: bool = True, + ) -> None: + self._locks = UnitLocks(lock_timeout) + self._s3 = Series3Adapter(s3_client_factory) + self._s4_factory = s4_client_factory + self._clock = clock + self._keepalive_s = keepalive_s + self._idle_hangup_s = idle_hangup_s + self._reaper_interval_s = reaper_interval_s + self._start_reaper = start_reaper + self._reaper: Optional[threading.Thread] = None + self._sessions: Dict[str, Series4Session] = {} + self._sessions_guard = threading.Lock() + + # ── public operations ───────────────────────────────────────────────────── + + def identify(self, address: UnitAddress, serial: str) -> UnitInfo: + return self._dispatch(address, serial, self._s3.identify, s4_identify) + + def status(self, address: UnitAddress, serial: str) -> UnitStatus: + return self._dispatch(address, serial, self._s3.status, s4_status) + + def settings(self, address: UnitAddress, serial: str) -> UnitSettings: + return self._dispatch(address, serial, self._s3.settings, s4_settings) + + def hang_up(self, address: UnitAddress) -> bool: + with self._locks.hold(address.key): + with self._sessions_guard: + session = self._sessions.pop(address.key, None) + if session is None: + return False + was_open = session.is_open + session.hang_up() + return was_open + + # ── dispatch ────────────────────────────────────────────────────────────── + + def _dispatch(self, address: UnitAddress, serial: str, + s3_op: Callable[[UnitAddress, str], Any], + s4_op: Callable[[Any, str], Any]) -> Any: + serial = normalise_serial(serial) + series = series_for_serial(serial) # raises BadRequest before any I/O + with self._locks.hold(address.key): + if series == 3: + return s3_op(address, serial) + session = self._session_for(address, serial) + try: + return session.run(lambda client: s4_op(client, serial)) + except DeviceError: + if not session.is_open: + with self._sessions_guard: + if self._sessions.get(address.key) is session: + del self._sessions[address.key] + raise + + def _session_for(self, address: UnitAddress, serial: str) -> Series4Session: + with self._sessions_guard: + session = self._sessions.get(address.key) + if session is not None and session.serial != serial: + session.hang_up() + session = None + if session is None: + session = Series4Session(address, serial, self._s4_factory, clock=self._clock) + self._sessions[address.key] = session + self._ensure_reaper() + return session + + # ── the reaper ──────────────────────────────────────────────────────────── + + def tick(self, now: Optional[float] = None) -> None: + """Per held line: hang up if idle, else keep alive, else listen for a ring.""" + now = self._clock() if now is None else now + with self._sessions_guard: + items = list(self._sessions.items()) + for key, session in items: + with self._locks.try_hold(key) as held: + if not held: + continue # mid-request: not idle + if not session.is_open: + self._drop(key, session) + continue + try: + if now - session.last_used >= self._idle_hangup_s: + session.hang_up() + self._drop(key, session) + elif now - session.last_traffic >= self._keepalive_s: + session.keepalive() + else: + session.listen() + except DeviceError as exc: + log.warning("held line %s closed: %s", key, exc) + self._drop(key, session) + + def _drop(self, key: str, session: Series4Session) -> None: + with self._sessions_guard: + if self._sessions.get(key) is session: + del self._sessions[key] + + def _ensure_reaper(self) -> None: + if not self._start_reaper or self._reaper is not None: + return + self._reaper = threading.Thread(target=self._reaper_loop, name="sfm-held-lines", daemon=True) + self._reaper.start() + + def _reaper_loop(self) -> None: + while True: + time.sleep(self._reaper_interval_s) + try: + self.tick() + except Exception: # noqa: BLE001 + log.exception("held-line reaper tick failed") diff --git a/tests/test_device_access.py b/tests/test_device_access.py new file mode 100644 index 0000000..c11e9dc --- /dev/null +++ b/tests/test_device_access.py @@ -0,0 +1,186 @@ +"""DeviceAccess: dispatch by serial, sessions, the lock, the reaper -- and the +contract that both series answer in the same shape.""" +from __future__ import annotations + +import dataclasses +import os +import sys +import threading + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from device_access_fakes import FakeMiniMateClient, FakeMicromateClient # noqa: E402 +from sfm.device_access.access import DeviceAccess # noqa: E402 +from sfm.device_access.errors import BadRequest, CallHomeInProgress, UnitBusy # noqa: E402 +from sfm.device_access.models import UnitAddress # noqa: E402 +from sfm.device_access.s4 import RingDetected # noqa: E402 + +ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None) + + +class Clock: + def __init__(self, t=1000.0): + self.t = t + + def __call__(self): + return self.t + + +def access(s3=(), s4=(), clock=None, lock_timeout=0.2): + s3q, s4q = list(s3), list(s4) + return DeviceAccess( + s3_client_factory=lambda a: s3q.pop(0), + s4_client_factory=lambda a: s4q.pop(0), + clock=clock or Clock(), lock_timeout=lock_timeout, start_reaper=False, + ) + + +def test_the_serial_prefix_picks_the_adapter(): + da = access(s3=[FakeMiniMateClient()], s4=[FakeMicromateClient()]) + assert da.identify(ADDR, "be18193").series == 3 + assert da.identify(ADDR, " um20147").series == 4 + + +def test_an_unknown_prefix_never_touches_a_unit(): + da = access() + with pytest.raises(BadRequest): + da.identify(ADDR, "XX123") + + +def test_a_micromate_stays_on_the_line_between_requests(): + fake = FakeMicromateClient() + da = access(s4=[fake]) + da.identify(ADDR, "UM20147") + da.status(ADDR, "UM20147") + da.settings(ADDR, "UM20147") + assert fake.opened == 1 # one call-up, three requests + assert fake.calls[0] == "connect" + + +def test_a_minimate_reconnects_per_request(): + a, b = FakeMiniMateClient(), FakeMiniMateClient() + da = access(s3=[a, b]) + da.status(ADDR, "BE18193") + da.status(ADDR, "BE18193") + assert a.closed == 1 and b.closed == 1 + + +def test_a_dropped_line_is_called_up_again_quietly(): + first, second = FakeMicromateClient(), FakeMicromateClient() + da = access(s4=[first, second]) + da.status(ADDR, "UM20147") + first._open = False # the modem dropped the idle line + st = da.status(ADDR, "UM20147") + assert st.series == 4 and second.opened == 1 + + +def test_a_different_serial_at_the_same_address_hangs_up_the_old_line(): + first, second = FakeMicromateClient(), FakeMicromateClient(serial="UM12947") + da = access(s4=[first, second]) + da.status(ADDR, "UM20147") + da.status(ADDR, "UM12947") + assert first.closed == 1 and second.opened == 1 + + +def test_a_busy_unit_answers_423_without_a_second_connection(): + fake = FakeMicromateClient() + da = access(s4=[fake], lock_timeout=0.2) + entered, release = threading.Event(), threading.Event() + + def slow_request(): + with da._locks.hold(ADDR.key): # simulate a request in flight + entered.set() + release.wait(2) + + t = threading.Thread(target=slow_request) + t.start() + entered.wait(2) + try: + with pytest.raises(UnitBusy): + da.status(ADDR, "UM20147") + assert fake.opened == 0 # no second connection was opened + finally: + release.set() + t.join() + + +def test_hang_up_closes_a_held_line(): + fake = FakeMicromateClient() + da = access(s4=[fake]) + da.status(ADDR, "UM20147") + assert da.hang_up(ADDR) is True + assert fake.closed == 1 + assert da.hang_up(ADDR) is False # nothing left to hang up + + +# ── the reaper ──────────────────────────────────────────────────────────────── + +def test_tick_listens_then_keeps_alive_then_hangs_up_when_idle(): + clock = Clock(1000.0) + fake = FakeMicromateClient() + da = access(s4=[fake], clock=clock) + da.status(ADDR, "UM20147") + fake.calls.clear() + + clock.t = 1030.0 + da.tick() # quiet: listen only + assert fake.calls == ["read_unsolicited"] + + clock.t = 1061.0 + da.tick() # 60 s since traffic: keep-alive + assert fake.calls[-1] == "poll" + + clock.t = 1301.0 + da.tick() # 300 s since last USE: hang up + assert fake.closed == 1 + assert da.hang_up(ADDR) is False + + +def test_tick_releases_the_line_on_a_ring_while_idle(): + clock = Clock(1000.0) + fake = FakeMicromateClient() + da = access(s4=[fake], clock=clock) + da.status(ADDR, "UM20147") + fake.fail = [RingDetected("RADIO RING")] + clock.t = 1010.0 + da.tick() + assert fake.closed == 1 + + +def test_tick_skips_a_unit_that_is_busy(): + clock = Clock(1000.0) + fake = FakeMicromateClient() + da = access(s4=[fake], clock=clock) + da.status(ADDR, "UM20147") + fake.calls.clear() + clock.t = 1400.0 + with da._locks.hold(ADDR.key): + da.tick() # must not block or hang up mid-request + assert fake.calls == [] and fake.closed == 0 + + +def test_a_ring_mid_request_is_a_clear_error(): + fake = FakeMicromateClient() + da = access(s4=[fake]) + da.status(ADDR, "UM20147") + fake.fail = [RingDetected("RADIO RING")] + with pytest.raises(CallHomeInProgress): + da.status(ADDR, "UM20147") + + +# ── the contract: both series answer in the same shape ──────────────────────── + +@pytest.mark.parametrize("op", ["identify", "status", "settings"]) +def test_both_series_return_the_same_model_with_the_same_fields(op): + da = access(s3=[FakeMiniMateClient()], s4=[FakeMicromateClient()]) + s3 = getattr(da, op)(ADDR, "BE18193") + s4 = getattr(da, op)(ADDR, "UM20147") + assert type(s3) is type(s4) + assert [f.name for f in dataclasses.fields(s3)] == [f.name for f in dataclasses.fields(s4)] + assert (s3.series, s4.series) == (3, 4) + for name in (f.name for f in dataclasses.fields(s3)): + a, b = getattr(s3, name), getattr(s4, name) + if a is not None and b is not None and name != "detail": + assert type(a) is type(b) or {type(a), type(b)} <= {int, float}, name