diff --git a/sfm/device_access/change.py b/sfm/device_access/change.py new file mode 100644 index 0000000..09c278d --- /dev/null +++ b/sfm/device_access/change.py @@ -0,0 +1,126 @@ +"""The series-independent core of a start/stop request. + +Identity -> state -> (dry run | skip | audit -> send once -> read back -> audit). +Each series supplies only its own pieces as callables: how to read the serial, +how to read the run-state name, how to send (returning the ack record), and how +to recognise a refusal or a ring. Nothing in here retries: `send` is called at +most once, and every path after `audit.begin` calls `audit.finish` exactly once. + +The state names `calling_home` and `unknown*` are Series-4 states; Series 3 +never produces them, so those branches are simply never taken there. +""" +from __future__ import annotations + +from typing import Any, Callable, Dict, Optional + +from .errors import AuditUnavailable, CallHomeInProgress, NotSupported, UnitStateUnknown, WrongUnit +from .models import ChangeResult, UnitAddress +from .series import normalise_serial + +CALL_HOME_MESSAGE = ("the unit started calling home; SFM hung up so the call can " + "reach THOR -- try again in a few minutes") + + +def _never(exc: BaseException) -> bool: + return False + + +def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_already: bool, + audit: Any, address: UnitAddress, caller: str, + sleep: Callable[[float], None], verify_timeout_s: float, verify_interval_s: float, + read_serial: Callable[[], str], + read_state: Callable[[], str], + describe_plan: Callable[[], Dict[str, Any]], + send: Callable[[], Dict[str, Any]], + is_refusal: Callable[[BaseException], bool] = _never, + is_ring: Callable[[BaseException], bool] = _never) -> ChangeResult: + action = "start monitoring" if start else "stop monitoring" + want = "monitoring" if start else "idle" + + reported = normalise_serial(read_serial()) + if reported != serial: + raise WrongUnit(f"asked for {serial} but {reported} answered at {address.key} -- " + "nothing sent") + before = read_state() + if before == "calling_home": + raise CallHomeInProgress(CALL_HOME_MESSAGE) + if before.startswith("unknown") and not dry_run: + raise UnitStateUnknown(f"the unit reports run state {before}, which has never " + "been measured -- nothing sent") + planned = dict(describe_plan(), sends_nothing=dry_run) + base = dict(serial=serial, series=series, action=action, plan=planned, state_before=before) + + if dry_run: + return ChangeResult(dry_run=True, sent=False, outcome="dry_run", + verified="not_checked", state_after=None, audit_id=None, **base) + if audit is None: + raise NotSupported("no audit log is configured -- SFM refuses to change a unit " + "without one (nothing sent)") + request = {"plan": planned, "even_if_already": even_if_already} + try: + cid = audit.begin(serial=serial, series=series, address=address.key, action=action, + tier="change", request=request, caller=caller) + except Exception as exc: # noqa: BLE001 + raise AuditUnavailable( + f"the audit log could not be written -- nothing sent: {exc}") from exc + if before == want and not even_if_already: + audit.finish(cid, outcome="skipped", verified="not_checked", ack=None, + error=f"already {want}") + return ChangeResult(dry_run=False, sent=False, outcome="skipped", + verified="not_checked", state_after=before, + audit_id=cid, detail={"reason": f"the unit is already {want}"}, **base) + + try: + ack = send() # the only send; nothing below can reach it again + except Exception as exc: # noqa: BLE001 -- recorded, never retried + if is_refusal(exc): # refused by the gate: nothing went out + audit.finish(cid, outcome="failed", verified="not_checked", ack=None, + error=f"refused before sending: {exc}") + raise + if is_ring(exc): + audit.finish(cid, outcome="failed", verified="not_checked", ack=None, + error=f"a call-home began in place of the ack: {exc}") + raise + try: + after: Optional[str] = read_state() + except Exception as follow: # noqa: BLE001 + if is_ring(follow): + audit.finish(cid, outcome="failed", verified="not_checked", ack=None, + error=f"no clean ack: {exc}; a call-home began: {follow}") + raise + after = None + if after == "calling_home": + audit.finish(cid, outcome="failed", verified="not_checked", ack=None, + error=f"no clean ack: {exc}; the unit is now calling home") + raise CallHomeInProgress(CALL_HOME_MESSAGE) from exc + audit.finish(cid, outcome="failed", verified="not_checked", ack=None, + error=f"no clean ack: {exc}") + if after is None: + raise # the link is suspect + return ChangeResult(dry_run=False, sent=True, outcome="failed", + verified="not_checked", state_after=after, audit_id=cid, + detail={"error": f"no clean ack: {exc}"}, **base) + + seen = [before] + polls = int(verify_timeout_s // verify_interval_s) + try: + for _ in range(polls): + sleep(verify_interval_s) + seen.append(read_state()) + if seen[-1] == want or seen[-1] == "calling_home": + break + except Exception as exc: # noqa: BLE001 -- the row must not stay pending + audit.finish(cid, outcome="sent", verified="not_checked", ack=ack, + error=f"sent and acknowledged; reading the state back failed: {exc}") + raise + if seen[-1] == "calling_home": + audit.finish(cid, outcome="sent", verified="not_checked", ack=ack, + error="sent and acknowledged; the unit then began calling home") + raise CallHomeInProgress(CALL_HOME_MESSAGE) + ok = seen[-1] == want + outcome, verified = ("sent", "ok") if ok else ("failed", "mismatch") + audit.finish(cid, outcome=outcome, verified=verified, ack=ack, + error=None if ok else f"unit reads {seen[-1]}, expected {want}") + return ChangeResult(dry_run=False, sent=True, outcome=outcome, verified=verified, + state_after=seen[-1], audit_id=cid, + detail={"states_seen": seen, "ack": ack}, **base) diff --git a/sfm/device_access/s3.py b/sfm/device_access/s3.py index 77de656..caf3826 100644 --- a/sfm/device_access/s3.py +++ b/sfm/device_access/s3.py @@ -9,11 +9,14 @@ from typing import Any, Callable, Optional from minimateplus import MiniMateClient from minimateplus.blastware_file import blastware_filename +from minimateplus.framing import build_bw_write_frame +from minimateplus.protocol import SUB_START_MONITORING, SUB_STOP_MONITORING from minimateplus.transport import TcpTransport from .errors import DeviceError, EventNotFound, MalformedReply, NoAnswer, NotSupported, StaleEvent, WrongUnit, translate +from .change import run_change from .events import iso_of, make_event_id, stamp_of -from .models import DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus +from .models import ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus log = logging.getLogger("sfm.device_access") @@ -85,10 +88,44 @@ class Series3Adapter: def __init__(self, client_factory: Callable[..., Any] = default_s3_client_factory) -> None: self._factory = client_factory - def change_monitoring(self, address: UnitAddress, serial: str, **kw: Any) -> Any: - raise NotSupported("Series 3 start/stop through DeviceAccess arrives in Task 5") + def change_monitoring(self, address: UnitAddress, serial: str, *, start: bool, dry_run: bool, + even_if_already: bool, audit: Any, caller: str, + sleep: Callable[[float], None], verify_timeout_s: float, + verify_interval_s: float) -> ChangeResult: + """Series-3 pieces for the shared core in change.py. One attempt, never + retried: `retry=False` stops _run's cold-boot second attempt, and the + core calls the write once.""" + sub = SUB_START_MONITORING if start else SUB_STOP_MONITORING + ack_sub = 0xFF - sub - def _run(self, address: UnitAddress, fn: Callable[[Any], Any], timeout: Optional[float] = None) -> Any: + def op(client: Any) -> ChangeResult: + def read_serial() -> str: + info = client.connect() # a fresh connection: connect() is the fresh 0x15 read + return info.serial or "" + + def describe_plan() -> dict: + what = "start monitoring" if start else "stop monitoring" + return {"action": what, "sends_nothing": True, "warnings": [], + "steps": [{"sub": f"0x{sub:02X}", "what": what, "offset": "0x0000", + "data_len": 0, "expect_ack": f"0x{ack_sub:02X}", + "frame": build_bw_write_frame(sub, b"").hex()}]} + + def send() -> dict: + # The client validates the ack SUB; it returns nothing else, so none is claimed. + (client.start_monitoring if start else client.stop_monitoring)() + return {"subs": [f"0x{ack_sub:02X}"]} + + return run_change( + serial=serial, series=3, start=start, dry_run=dry_run, + even_if_already=even_if_already, audit=audit, address=address, caller=caller, + sleep=sleep, verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s, + read_serial=read_serial, + read_state=lambda: "monitoring" if client.get_monitor_status().is_monitoring else "idle", + describe_plan=describe_plan, send=send) + return self._run(address, op, timeout=S3_EVENT_TIMEOUT, retry=False) + + def _run(self, address: UnitAddress, fn: Callable[[Any], Any], timeout: Optional[float] = None, + retry: bool = True) -> Any: def attempt() -> Any: client = self._factory(address) if timeout is None else self._factory(address, timeout=timeout) try: @@ -114,7 +151,7 @@ class Series3Adapter: # server._run_with_retry (any protocol error): retrying a # MalformedReply would also retry "no settings block", which a # reconnect cannot fix. - if not address.host: + if not retry or not address.host: raise log.info("Series 3 at %s: no clean answer, retrying once (unit may be cold)", address.key) return attempt() diff --git a/sfm/device_access/s4.py b/sfm/device_access/s4.py index 0534015..e5cf27c 100644 --- a/sfm/device_access/s4.py +++ b/sfm/device_access/s4.py @@ -20,6 +20,7 @@ from .errors import ( AuditUnavailable, CallHomeInProgress, DeviceError, EventNotFound, MalformedReply, NotSupported, StaleEvent, UnitStateUnknown, WrongUnit, translate, ) +from .change import CALL_HOME_MESSAGE, run_change from .events import iso_of, make_event_id, stamp_of from .models import ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus from .series import normalise_serial @@ -104,8 +105,7 @@ def _close(client: Any) -> None: log.debug("close failed", exc_info=True) -_RING_MESSAGE = ("the unit started calling home; SFM hung up so the call can " - "reach THOR -- try again in a few minutes") +_RING_MESSAGE = CALL_HOME_MESSAGE class Series4Session: @@ -325,104 +325,19 @@ def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool even_if_already: bool, audit: Any, address: UnitAddress, caller: str, sleep: Callable[[float], None], verify_timeout_s: float, verify_interval_s: float) -> ChangeResult: - """Identity -> state -> (dry run | skip | audit -> send -> read back -> audit).""" - action = "start monitoring" if start else "stop monitoring" - want = "monitoring" if start else "idle" - - reported = normalise_serial(client.serial(refresh=True)) - if reported != serial: - raise WrongUnit(f"asked for {serial} but {reported} answered at {address.key} -- " - "nothing sent") - before = client.read_run_state() - if before.name == "calling_home": - raise CallHomeInProgress(_RING_MESSAGE) - if before.name.startswith("unknown") and not dry_run: - raise UnitStateUnknown(f"the unit reports run state {before.name}, which has never " - "been measured -- nothing sent") + """Series-4 pieces for the shared core in change.py.""" plan = plan_start_monitoring() if start else plan_stop_monitoring() - planned = dict(plan.describe(), sends_nothing=dry_run) - base = dict(serial=serial, series=4, action=action, plan=planned, - state_before=before.name) - if dry_run: - return ChangeResult(dry_run=True, sent=False, outcome="dry_run", - verified="not_checked", state_after=None, audit_id=None, **base) - if audit is None: - raise NotSupported("no audit log is configured -- SFM refuses to change a unit " - "without one (nothing sent)") - request = {"plan": planned, "even_if_already": even_if_already} - try: - cid = audit.begin(serial=serial, series=4, address=address.key, action=action, - tier="change", request=request, caller=caller) - except Exception as exc: # noqa: BLE001 - raise AuditUnavailable( - f"the audit log could not be written -- nothing sent: {exc}") from exc - if before.name == want and not even_if_already: - audit.finish(cid, outcome="skipped", verified="not_checked", ack=None, - error=f"already {want}") - return ChangeResult(dry_run=False, sent=False, outcome="skipped", - verified="not_checked", state_after=before.name, - audit_id=cid, detail={"reason": f"the unit is already {want}"}, **base) - - try: + def send() -> dict: acks = client.protocol.execute(plan) - except OpcodeRefused as exc: # refused by the gate: nothing went out - audit.finish(cid, outcome="failed", verified="not_checked", ack=None, - error=f"refused before sending: {exc}") - raise - except RingDetected as exc: - audit.finish(cid, outcome="failed", verified="not_checked", ack=None, - error=f"a call-home began in place of the ack: {exc}") - raise # _exchange releases the line - except Exception as exc: # noqa: BLE001 -- recorded, never retried - try: - after = _try_run_state(client) - except RingDetected as ring: - audit.finish(cid, outcome="failed", verified="not_checked", ack=None, - error=f"no clean ack: {exc}; a call-home began: {ring}") - raise - if after == "calling_home": - audit.finish(cid, outcome="failed", verified="not_checked", ack=None, - error=f"no clean ack: {exc}; the unit is now calling home") - raise CallHomeInProgress(_RING_MESSAGE) from exc - audit.finish(cid, outcome="failed", verified="not_checked", ack=None, - error=f"no clean ack: {exc}") - if after is None: - raise # the line is suspect: let _exchange hang up - return ChangeResult(dry_run=False, sent=True, outcome="failed", - verified="not_checked", state_after=after, audit_id=cid, - detail={"error": f"no clean ack: {exc}"}, **base) + return {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]} - ack = {"subs": [f"0x{a.sub:02X}" for a in acks], "data": [bytes(a.data).hex() for a in acks]} - seen = [before.name] - polls = int(verify_timeout_s // verify_interval_s) - try: - for _ in range(polls): - sleep(verify_interval_s) - seen.append(client.read_run_state().name) - if seen[-1] == want or seen[-1] == "calling_home": - break - except Exception as exc: # noqa: BLE001 -- the row must not stay pending - audit.finish(cid, outcome="sent", verified="not_checked", ack=ack, - error=f"sent and acknowledged; reading the state back failed: {exc}") - raise - if seen[-1] == "calling_home": - audit.finish(cid, outcome="sent", verified="not_checked", ack=ack, - error="sent and acknowledged; the unit then began calling home") - raise CallHomeInProgress(_RING_MESSAGE) - ok = seen[-1] == want - outcome, verified = ("sent", "ok") if ok else ("failed", "mismatch") - audit.finish(cid, outcome=outcome, verified=verified, ack=ack, - error=None if ok else f"unit reads {seen[-1]}, expected {want}") - return ChangeResult(dry_run=False, sent=True, outcome=outcome, verified=verified, - state_after=seen[-1], audit_id=cid, - detail={"states_seen": seen, "ack": ack}, **base) - - -def _try_run_state(client: Any) -> Optional[str]: - try: - return client.read_run_state().name - except RingDetected: - raise - except Exception: # noqa: BLE001 - return None + return run_change( + serial=serial, series=4, start=start, dry_run=dry_run, even_if_already=even_if_already, + audit=audit, address=address, caller=caller, sleep=sleep, + verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s, + read_serial=lambda: client.serial(refresh=True), + read_state=lambda: client.read_run_state().name, + describe_plan=plan.describe, send=send, + is_refusal=lambda e: isinstance(e, OpcodeRefused), + is_ring=lambda e: isinstance(e, RingDetected)) diff --git a/tests/device_access_fakes.py b/tests/device_access_fakes.py index 4e9ff9a..02698ca 100644 --- a/tests/device_access_fakes.py +++ b/tests/device_access_fakes.py @@ -74,10 +74,14 @@ def default_s3_events(): class FakeMiniMateClient(_Base): - def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", events=None, **kw): + def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", events=None, + monitor_states=None, write_error=None, **kw): super().__init__(**kw) self.serial = serial self.monitoring = monitoring + self.monitor_states = list(monitor_states) if monitor_states else [monitoring] + self.write_error = write_error + self.writes: list = [] if compliance == "default": compliance = ComplianceConfig( recording_mode=0x01, sample_rate=1024, histogram_interval_sec=300, @@ -103,12 +107,25 @@ class FakeMiniMateClient(_Base): def get_monitor_status(self) -> MonitorStatus: self._step("get_monitor_status") + state = self.monitor_states.pop(0) if len(self.monitor_states) > 1 else self.monitor_states[0] return MonitorStatus( - is_monitoring=self.monitoring, battery_v=6.8, + is_monitoring=state, battery_v=6.8, memory_total=983026, memory_free=900000, ) + def _write(self, name): + self._step(name) + self.writes.append(name) + if self.write_error is not None: + raise self.write_error + + def start_monitoring(self) -> None: + self._write("start_monitoring") + + def stop_monitoring(self) -> None: + self._write("stop_monitoring") + def list_event_headers(self): self._step("list_event_headers") out = [] diff --git a/tests/test_device_access_change.py b/tests/test_device_access_change.py index 8d5ccd8..d2f82df 100644 --- a/tests/test_device_access_change.py +++ b/tests/test_device_access_change.py @@ -283,3 +283,134 @@ def test_a_malformed_serial_is_422_even_without_an_audit_sink(): from sfm.device_access.errors import BadRequest with pytest.raises(BadRequest): access(FakeMicromateClient(), audit=None).start_monitoring(ADDR, "XX123") + + +# ── Series 3 ────────────────────────────────────────────────────────────────── + +import minimateplus.protocol as mmp_proto # noqa: E402 +from device_access_fakes import FakeMiniMateClient # noqa: E402 + +TCP3 = UnitAddress(host="10.0.0.6", tcp_port=12345, port=None, baud=None) + + +def access3(fake, audit="default"): + seen = [] + + def factory(a, **kw): + seen.append(kw) + return fake + da = DeviceAccess(s3_client_factory=factory, start_reaper=False, + audit=Audit() if audit == "default" else audit, + sleep=lambda s: None, verify_timeout_s=6.0, verify_interval_s=2.0) + da.factory_calls = seen + return da + + +def test_series3_dry_run_returns_its_own_frame_and_sends_nothing(): + fake = FakeMiniMateClient(monitor_states=[False]) + r = access3(fake).start_monitoring(TCP3, "BE18193", dry_run=True) + assert (r.series, r.outcome, r.state_before) == (3, "dry_run", "idle") + assert r.plan["steps"][0]["sub"] == "0x96" and fake.writes == [] + assert r.plan["steps"][0]["expect_ack"] == "0x69" and r.plan["sends_nothing"] is True + + +def test_series3_start_is_verified_by_monitor_status(): + fake = FakeMiniMateClient(monitor_states=[False, False, True]) + da = access3(fake) + r = da.start_monitoring(TCP3, "BE18193") + assert (r.outcome, r.verified, r.state_after) == ("sent", "ok", "monitoring") + assert fake.writes == ["start_monitoring"] + assert da._audit.rows[r.audit_id]["ack"] == {"subs": ["0x69"]} + + +def test_series3_stop_acks_0x68(): + fake = FakeMiniMateClient(monitor_states=[True, False]) + da = access3(fake) + r = da.stop_monitoring(TCP3, "BE18193") + assert r.verified == "ok" and fake.writes == ["stop_monitoring"] + assert da._audit.rows[r.audit_id]["ack"] == {"subs": ["0x68"]} + + +def test_series3_wrong_unit_is_refused_before_writing(): + fake = FakeMiniMateClient(serial="BE11529") + with pytest.raises(WrongUnit): + access3(fake).stop_monitoring(TCP3, "BE18193") + assert fake.writes == [] + + +def test_series3_a_lost_ack_is_never_retried_even_over_tcp(): + fake = FakeMiniMateClient(monitor_states=[False, True], + write_error=mmp_proto.TimeoutError("no ack")) + da = access3(fake) + r = da.start_monitoring(TCP3, "BE18193") + assert fake.writes == ["start_monitoring"] # one send, no cold-boot retry + assert r.outcome == "failed" and r.state_after == "monitoring" + + +def test_series3_already_in_state_is_skipped(): + fake = FakeMiniMateClient(monitor_states=[True]) + da = access3(fake) + r = da.start_monitoring(TCP3, "BE18193") + assert (r.sent, r.outcome) == (False, "skipped") and fake.writes == [] + assert da._audit.rows[r.audit_id]["outcome"] == "skipped" + + +def test_series3_a_state_that_never_changes_is_a_mismatch(): + fake = FakeMiniMateClient(monitor_states=[False]) + da = access3(fake) + r = da.start_monitoring(TCP3, "BE18193") + assert (r.outcome, r.verified, r.state_after) == ("failed", "mismatch", "idle") + assert da._audit.rows[r.audit_id]["verified"] == "mismatch" + + +def test_series3_a_failing_read_back_is_audited_then_raised(): + fake = FakeMiniMateClient(monitor_states=[False]) + da = access3(fake) + real = fake.get_monitor_status + calls = [] + + def flaky(): + calls.append(1) + if len(calls) > 1: + raise mmp_proto.TimeoutError("quiet") + return real() + fake.get_monitor_status = flaky + with pytest.raises(NoAnswer): + da.start_monitoring(TCP3, "BE18193") + row = next(iter(da._audit.rows.values())) + assert (row["outcome"], row["verified"]) == ("sent", "not_checked") + assert "reading the state back failed" in row["error"] + assert fake.writes == ["start_monitoring"] + + +def test_series3_audit_begin_failing_sends_nothing(): + class Broken(Audit): + def begin(self, **f): + raise RuntimeError("disk full") + fake = FakeMiniMateClient(monitor_states=[False]) + with pytest.raises(AuditUnavailable): + access3(fake, audit=Broken()).start_monitoring(TCP3, "BE18193") + assert fake.writes == [] + + +def test_series3_lost_ack_with_unreadable_follow_up_raises_and_is_not_retried(): + fake = FakeMiniMateClient(monitor_states=[False], write_error=mmp_proto.TimeoutError("no ack")) + da = access3(fake) + real = fake.get_monitor_status + n = [] + + def second_fails(): + n.append(1) + if len(n) > 1: + raise mmp_proto.TimeoutError("still quiet") + return real() + fake.get_monitor_status = second_fails + with pytest.raises(NoAnswer): + da.start_monitoring(TCP3, "BE18193") + assert fake.writes == ["start_monitoring"] + assert len(da.factory_calls) == 1 # no second TCP attempt + row = next(iter(da._audit.rows.values())) + assert row["outcome"] == "failed" + +# The other Series-3 operations still retry once over TCP on a cold unit: +# tests/test_device_access_s3.py::test_a_cold_unit_over_tcp_gets_one_retry.