"""The series-independent core of a change request: start/stop monitoring, call-home on/off. A `ChangeKind` says what the change is called and which state read back means it took. Identity -> state -> (dry run | skip | audit -> pre-send drain -> 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), how to recognise a refusal or a ring, and optionally what to drain from the line just before sending. Nothing in here retries: `send` is called at most once, and every path after `audit.begin` calls `audit.finish` exactly once, through `finish` below. Once the send has started, a failure is never reported as if nothing went out: it is a `ChangeUnconfirmed` naming the audit row, carrying the status its cause would have had. The row's `sent` column says whether a frame went out (1), did not (0), or may have (NULL), and `states` keeps every state read. The state names `calling_home` and `unknown*` are Series-4 states, except `unknown(...)`, which Series 3 also produces for a flag byte never measured. Series 3 never produces `calling_home` or a ring, so those branches are simply never taken there. """ from __future__ import annotations from dataclasses import dataclass from typing import Any, Callable, Dict, List, NoReturn, Optional from .errors import ( AuditIncomplete, AuditUnavailable, CallHomeInProgress, ChangeUnconfirmed, NotSupported, UnitStateUnknown, WrongUnit, translate, ) 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") _HUNG_UP = "SFM hung up so the call can reach THOR" # The row's `sent` column. SENT_ACKNOWLEDGED, NOTHING_SENT, SENT_UNKNOWN = 1, 0, None def _never(exc: BaseException) -> bool: return False @dataclass(frozen=True) class ChangeKind: """What a change is called (the audit row's action, the messages' subject), the state `read_state` returns once it took, and the past tense for messages.""" action: str want: str became: str def monitoring_change(start: bool) -> ChangeKind: return (ChangeKind("start monitoring", "monitoring", "started") if start else ChangeKind("stop monitoring", "idle", "stopped")) def call_home_change(enabled: bool) -> ChangeKind: return (ChangeKind("enable call-home", "enabled", "enabled") if enabled else ChangeKind("disable call-home", "disabled", "disabled")) def settings_change() -> ChangeKind: """A settings change (phase 5): its "state" is a read-back verdict -- "as asked" (the unit holds what was written), "unchanged", or "differs".""" return ChangeKind("change settings", "as asked", "applied") def _take_snapshot(snapshot: Optional[Callable[[], Dict[str, Any]]]) -> Optional[Dict[str, Any]]: """The caller's record of what the unit holds after the change -- for the result and the audit row only. It never decides the outcome.""" if snapshot is None: return None try: return dict(snapshot()) except Exception as exc: # noqa: BLE001 -- a record, never a verdict return {"error": str(exc)} def run_change(*, kind: ChangeKind, serial: str, series: int, 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, pre_send: Optional[Callable[[], None]] = None, snapshot: Optional[Callable[[], Dict[str, Any]]] = None) -> ChangeResult: action, want, became = kind.action, kind.want, kind.became 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 def states(seen: List[str], after: Optional[str]) -> Dict[str, Any]: return {"before": before, "seen": list(seen), "after": after} def finish(unit: str, *, release_line: bool = False, **fields: Any) -> None: """The only way a row is finished. `unit` says what happened to the unit, so a finish that fails still says it. `release_line` says whether this path hangs up anyway, so a failed finish does not hold the line.""" try: audit.finish(cid, **fields) except Exception as exc: # noqa: BLE001 raise AuditIncomplete( f"{unit} -- but audit record {cid} could not be finished: {exc}", release_line=release_line) from exc def unconfirmed(unit: str, cause: BaseException, *, went_out: str, status: int, **fields: Any) -> NoReturn: """Finish the row, then say the change went out (or may have) and name it. `went_out` is "acknowledged" or "unknown"; the row's `sent` follows it.""" finish(unit, release_line=True, sent=SENT_ACKNOWLEDGED if went_out == "acknowledged" else SENT_UNKNOWN, **fields) raise ChangeUnconfirmed(f"{unit} -- audit record {cid}", audit_id=cid, sent=went_out, http_status=status) from cause def status_of(exc: BaseException) -> int: return translate(exc, connecting=False).http_status if before == want and not even_if_already: finish(f"nothing was sent ({serial} is already {want})", outcome="skipped", verified="not_checked", ack=None, error=f"already {want}", sent=NOTHING_SENT, states=states([before], None)) 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) if pre_send is not None: try: pre_send() # sends nothing: drains what is already waiting except Exception as exc: # noqa: BLE001 if is_ring(exc): finish("nothing was sent (a call-home began before sending)", release_line=True, outcome="failed", verified="not_checked", ack=None, error="a call-home began before sending -- nothing sent", sent=NOTHING_SENT, states=states([before], None)) raise CallHomeInProgress(CALL_HOME_MESSAGE) from exc finish(f"nothing was sent (the line failed before sending: {exc})", release_line=True, outcome="failed", verified="not_checked", ack=None, error=f"the line failed before sending -- nothing sent: {exc}", sent=NOTHING_SENT, states=states([before], None)) raise # the link is suspect 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 finish(f"nothing was sent (refused before sending: {exc})", release_line=True, outcome="failed", verified="not_checked", ack=None, error=f"refused before sending: {exc}", sent=NOTHING_SENT, states=states([before], None)) raise if is_ring(exc): unconfirmed(f"{action} was sent, but a call-home began in place of the " f"acknowledgement -- whether it {became} is unknown; {_HUNG_UP}", exc, went_out="unknown", status=CallHomeInProgress.http_status, outcome="failed", verified="not_checked", ack=None, error=f"a call-home began in place of the ack: {exc}", states=states([before], None)) try: after: Optional[str] = read_state() except Exception as follow: # noqa: BLE001 if is_ring(follow): unconfirmed(f"{action} was sent but the acknowledgement was lost ({exc}), and " f"the unit then began calling home -- whether it {became} is " f"unknown; {_HUNG_UP}", follow, went_out="unknown", status=CallHomeInProgress.http_status, outcome="failed", verified="not_checked", ack=None, error=f"no clean ack: {exc}; a call-home began: {follow}", states=states([before], None)) unconfirmed(f"{action} was sent but the acknowledgement was lost ({exc}), and " f"reading the state afterwards failed ({follow}) -- whether it " f"{became} is unknown", exc, went_out="unknown", status=status_of(exc), outcome="failed", verified="not_checked", ack=None, error=f"no clean ack: {exc}; the follow-up read failed: {follow}", states=states([before], None)) if after == "calling_home": unconfirmed(f"{action} was sent but the acknowledgement was lost ({exc}), and " f"the unit then began calling home -- whether it {became} is " f"unknown; {_HUNG_UP}", exc, went_out="unknown", status=CallHomeInProgress.http_status, outcome="failed", verified="not_checked", ack=None, error=f"no clean ack: {exc}; the unit is now calling home", states=states([before], after)) lost_detail: Dict[str, Any] = {"error": f"no clean ack: {exc}"} lost_states = states([before], after) snap = _take_snapshot(snapshot) # what the unit holds is what tells whether it landed if snap is not None: lost_detail["snapshot"] = lost_states["snapshot"] = snap finish(f"{action} was sent but the acknowledgement was lost ({exc}); the unit " f"now reads {after}", outcome="failed", verified="not_checked", ack=None, error=f"no clean ack: {exc}", sent=SENT_UNKNOWN, states=lost_states) return ChangeResult(dry_run=False, sent=True, outcome="failed", verified="not_checked", state_after=after, audit_id=cid, detail=lost_detail, **base) seen = [before] def last_poll() -> Optional[str]: return seen[-1] if len(seen) > 1 else None 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 if is_ring(exc): unconfirmed(f"{action} was sent and acknowledged, but the unit then began " f"calling home before its state could be read back -- whether it " f"{became} is unknown; {_HUNG_UP}", exc, went_out="acknowledged", status=CallHomeInProgress.http_status, outcome="sent", verified="not_checked", ack=ack, error=f"sent and acknowledged; a call-home began while reading the " f"state back: {exc}", states=states(seen, last_poll())) unconfirmed(f"{action} was sent and acknowledged, but reading the state back " f"failed: {exc}", exc, went_out="acknowledged", status=status_of(exc), outcome="sent", verified="not_checked", ack=ack, error=f"sent and acknowledged; reading the state back failed: {exc}", states=states(seen, last_poll())) if seen[-1] == "calling_home": cause = CallHomeInProgress(CALL_HOME_MESSAGE) unconfirmed(f"{action} was sent and acknowledged, but the unit then began calling " f"home -- whether it {became} is unknown; {_HUNG_UP}", cause, went_out="acknowledged", status=cause.http_status, outcome="sent", verified="not_checked", ack=ack, error="sent and acknowledged; the unit then began calling home", states=states(seen, last_poll())) ok = seen[-1] == want outcome, verified = ("sent", "ok") if ok else ("failed", "mismatch") error = None if ok else f"unit reads {seen[-1]}, expected {want}" detail: Dict[str, Any] = {"states_seen": seen, "ack": ack} if even_if_already and before == want: note = (f"the unit was already {want} before sending; the read-back cannot show " "that this send changed anything") detail["note"] = note if error is None: error = note row_states = states(seen, last_poll()) snap = _take_snapshot(snapshot) if snap is not None: detail["snapshot"] = row_states["snapshot"] = snap finish(f"{action} was sent and verified" if ok else f"{action} was sent and acknowledged, but the unit reads {seen[-1]}, not {want}", outcome=outcome, verified=verified, ack=ack, error=error, sent=SENT_ACKNOWLEDGED, states=row_states) return ChangeResult(dry_run=False, sent=True, outcome=outcome, verified=verified, state_after=seen[-1], audit_id=cid, detail=detail, **base)