Files
seismo-relay/sfm/device_access/access.py
T
serversdownandClaude Opus 5.5 06fa56db09 feat(sfm): call-home state and enable/disable by serial -- GET /device/call_home/state, POST /device/call_home/{enable,disable} (phase 4)
- DeviceAccess.call_home_state (a read) and set_call_home (change=True: never
  retried, audit required for a live change, dry run without one), routed by
  series like start/stop.  A config write is read back on its own window: up
  to 3 reads, 1 s apart, not the monitoring one.
- Routes, serial required (422 without), all three serial-aware: the state as
  a dict; enable / disable through _change_response, so their statuses are
  start/stop's and an unconfirmed change carries sent + audit_id.  The legacy
  GET / POST /device/call_home are unchanged (a Micromate serial is still
  refused there, 501).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 17:01:14 -05:00

265 lines
13 KiB
Python

"""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 ConnectFailed, DeviceError, NoAnswer, NotSupported, WrongUnit
from .events import parse_event_id
from .locks import UnitLocks
from .models import (CallHomeState, ChangeResult, DownloadedEvent, EventList, UnitAddress, UnitInfo,
UnitSettings, UnitStatus)
from .s3 import Series3Adapter, default_s3_client_factory
from .s4 import (
Series4Session, default_s4_client_factory, s4_call_home_state, s4_change_call_home, s4_change_monitoring,
s4_download_event, s4_identify, s4_list_events, s4_settings, s4_status,
)
from .series import normalise_serial, series_for_serial
log = logging.getLogger("sfm.device_access")
# A config write is read back at once, not after a sensor check: up to three
# reads, a second apart -- not the start/stop window.
_CALL_HOME_VERIFY_TIMEOUT_S = 3.0
_CALL_HOME_VERIFY_INTERVAL_S = 1.0
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,
audit: Any = None,
sleep: Callable[[float], None] = time.sleep,
verify_timeout_s: float = 60.0,
verify_interval_s: float = 2.0,
) -> None:
if verify_interval_s <= 0 or verify_timeout_s < verify_interval_s:
raise ValueError("verify_interval_s must be > 0 and verify_timeout_s >= verify_interval_s")
self._audit = audit
self._sleep = sleep
self._verify_timeout_s = verify_timeout_s
self._verify_interval_s = verify_interval_s
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, *, run_state: bool = False) -> UnitStatus:
"""`run_state` adds Series 4's raw SUB 0x49 code to `detail` (one more
round trip); Series 3 has no 0x49 and ignores it."""
return self._dispatch(address, serial, self._s3.status,
lambda client, s: s4_status(client, s, run_state=run_state))
def settings(self, address: UnitAddress, serial: str) -> UnitSettings:
return self._dispatch(address, serial, self._s3.settings, s4_settings)
def list_events(self, address: UnitAddress, serial: str) -> EventList:
return self._dispatch(address, serial, self._s3.list_events, s4_list_events)
def download_event(self, address: UnitAddress, serial: str, event_id: str) -> DownloadedEvent:
"""Read-only on the unit. Holds the unit for the whole download, so
other requests for it wait, then get 423."""
key, stamp = parse_event_id(event_id, serial) # BadRequest before any I/O
return self._dispatch(
address, serial,
lambda a, s: self._s3.download_event(a, s, key, stamp),
lambda c, s: s4_download_event(c, s, key, stamp))
def start_monitoring(self, address: UnitAddress, serial: str, *, dry_run: bool = False,
even_if_already: bool = False, caller: str = "api") -> ChangeResult:
return self._change_monitoring(address, serial, start=True, dry_run=dry_run,
even_if_already=even_if_already, caller=caller)
def stop_monitoring(self, address: UnitAddress, serial: str, *, dry_run: bool = False,
even_if_already: bool = False, caller: str = "api") -> ChangeResult:
return self._change_monitoring(address, serial, start=False, dry_run=dry_run,
even_if_already=even_if_already, caller=caller)
def _change_monitoring(self, address, serial, *, start, dry_run, even_if_already, caller):
serial = normalise_serial(serial)
series_for_serial(serial) # BadRequest (422) before the audit check
if not dry_run and self._audit is None:
raise NotSupported("no audit log is configured -- SFM refuses to change a unit "
"without one (nothing sent)")
kw = dict(start=start, dry_run=dry_run, even_if_already=even_if_already,
audit=self._audit, caller=caller, sleep=self._sleep,
verify_timeout_s=self._verify_timeout_s,
verify_interval_s=self._verify_interval_s)
return self._dispatch(
address, serial,
lambda a, s: self._s3.change_monitoring(a, s, **kw),
lambda c, s: s4_change_monitoring(c, s, address=address, **kw),
change=True)
def call_home_state(self, address: UnitAddress, serial: str) -> CallHomeState:
return self._dispatch(address, serial,
lambda a, s: self._s3.call_home_state(a, s),
lambda c, s: s4_call_home_state(c, s))
def set_call_home(self, address: UnitAddress, serial: str, *, enabled: bool,
dry_run: bool = False, even_if_already: bool = False,
caller: str = "api") -> ChangeResult:
"""Turn the unit's automatic call-home on or off (spec row 9): audited,
identity-checked, never retried, read back."""
serial = normalise_serial(serial)
series_for_serial(serial) # BadRequest (422) before the audit check
if not dry_run and self._audit is None:
raise NotSupported("no audit log is configured -- SFM refuses to change a unit "
"without one (nothing sent)")
kw = dict(enabled=enabled, dry_run=dry_run, even_if_already=even_if_already,
audit=self._audit, caller=caller, sleep=self._sleep,
verify_timeout_s=_CALL_HOME_VERIFY_TIMEOUT_S,
verify_interval_s=_CALL_HOME_VERIFY_INTERVAL_S)
return self._dispatch(
address, serial,
lambda a, s: self._s3.change_call_home(a, s, **kw),
lambda c, s: s4_change_call_home(c, s, address=address, **kw),
change=True)
def held_serial(self, address: UnitAddress) -> Optional[str]:
"""Serial of the OPEN held Series-4 line at this address, else None. No I/O."""
with self._sessions_guard:
session = self._sessions.get(address.key)
if session is not None and session.is_open:
return session.serial
return None
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], *, change: bool = False) -> 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:
with self._sessions_guard:
held = self._sessions.get(address.key)
if held is not None and held.is_open:
raise WrongUnit(
f"a Series-4 line to {held.serial} is held at {address.key}; "
"a Series-3 unit cannot be there -- POST /device/hangup first "
"if the modem has moved")
return s3_op(address, serial)
session = self._session_for(address, serial)
was_held = session.is_open
try:
return session.run(lambda client: s4_op(client, serial))
except DeviceError as exc:
self._forget_if_closed(address, session)
# A held line the peer dropped still reads open (the transport only
# learns at EOF), so the first request on it times out or fails.
# Call up fresh and retry ONCE. Safe only because every operation
# here is a read (identify, status, settings, list, download -- all
# idempotent). A change (`change=True`) is never retried, by
# construction: a write whose ack was lost must never be sent twice.
if was_held and not change and isinstance(exc, (NoAnswer, ConnectFailed)):
self._drop(address.key, session)
session.hang_up()
session = self._session_for(address, serial)
try:
return session.run(lambda client: s4_op(client, serial))
except DeviceError:
self._forget_if_closed(address, session)
raise
raise
def _forget_if_closed(self, address: UnitAddress, session: Series4Session) -> None:
if not session.is_open:
self._drop(address.key, session)
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:
if session.is_open:
raise WrongUnit(
f"a Series-4 line to {session.serial} is held at {address.key}; "
f"{serial} cannot be reached there -- POST /device/hangup first "
"if the modem has moved")
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")