"""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)