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
This commit is contained in:
serversdownandClaude Opus 5.5 committed 2026-11-02 17:01:14 -05:00
1 parent 453d42e32a
commit 06fa56db09
4 files changed
+233 -3

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
"""DeviceAccess routes call-home by series (phase 4): a read, and an audited
change that is never retried, verified over a short config window (3 reads,
1 s apart), not the monitoring one."""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import micromate.protocol as mm_proto # noqa: E402
from device_access_fakes import FakeMiniMateClient, FakeMicromateClient, um12947_call_home # noqa: E402
from sfm.device_access.access import DeviceAccess # noqa: E402
from sfm.device_access.errors import DeviceError # noqa: E402
from sfm.device_access.models import UnitAddress # noqa: E402
ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None)
TCP3 = UnitAddress(host="10.0.0.6", tcp_port=12345, port=None, baud=None)
class Audit:
def __init__(self):
self.rows = {}
def begin(self, **f):
cid = f"c{len(self.rows) + 1}"
self.rows[cid] = dict(f, outcome="pending")
return cid
def finish(self, cid, **f):
self.rows[cid].update(f)
def access(*, s4=None, s3=None, sleeps=None):
return DeviceAccess(s4_client_factory=lambda a, **kw: s4, s3_client_factory=lambda a, **kw: s3,
start_reaper=False, audit=Audit(),
sleep=(sleeps.append if sleeps is not None else (lambda s: None)),
verify_timeout_s=60.0, verify_interval_s=5.0)
def test_call_home_state_dispatches_by_series():
assert access(s4=FakeMicromateClient()).call_home_state(ADDR, "UM20147").series == 4
assert access(s3=FakeMiniMateClient()).call_home_state(TCP3, "BE18193").series == 3
def test_set_call_home_dispatches_by_series():
s4 = FakeMicromateClient()
r = access(s4=s4).set_call_home(ADDR, "UM20147", enabled=False)
assert (r.series, r.outcome, r.verified) == (4, "sent", "ok") and len(s4.executed) == 1
s3 = FakeMiniMateClient()
r = access(s3=s3).set_call_home(TCP3, "BE18193", enabled=False)
assert (r.series, r.outcome, r.verified) == (3, "sent", "ok") and s3.writes == ["call_home"]
def test_the_verify_window_is_the_config_one_not_the_monitoring_one():
sleeps = []
s4 = FakeMicromateClient()
s4.protocol.execute = lambda plan: [type("Ack", (), {"sub": st.ack_sub, "data": bytes(11)})()
for st in plan.steps] # acked, but nothing changes
r = access(s4=s4, sleeps=sleeps).set_call_home(ADDR, "UM20147", enabled=False)
assert (r.outcome, r.verified) == ("failed", "mismatch")
assert sleeps == [1.0, 1.0, 1.0]
def test_set_call_home_on_a_dropped_held_line_is_not_retried():
fake = FakeMicromateClient(call_home=um12947_call_home(True))
da = access(s4=fake)
da.status(ADDR, "UM20147") # hold the line
fake.fail = [mm_proto.TimeoutError("peer gone")] # next call fails
with pytest.raises(DeviceError): # the failure, not a retry
da.set_call_home(ADDR, "UM20147", enabled=False)
assert fake.executed == []
def test_a_dry_run_needs_no_audit():
da = DeviceAccess(s4_client_factory=lambda a, **kw: FakeMicromateClient(), start_reaper=False,
audit=None, sleep=lambda s: None)
assert da.set_call_home(ADDR, "UM20147", enabled=False, dry_run=True).outcome == "dry_run"
+60
View File
@@ -435,3 +435,63 @@ def test_device_commands_normalises_the_serial(tmp_path, monkeypatch):
action="start monitoring", tier="change", request={}, caller="test")
monkeypatch.setattr(srv, "_get_db", lambda: db)
assert len(srv.db_device_commands(serial=" um20147 ", limit=100)["commands"]) == 1
# ── call-home by serial (phase 4) ─────────────────────────────────────────────
from device_access_fakes import um12947_call_home # noqa: E402
CH_STATE = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034, serial="UM20147")
def test_call_home_state_route(monkeypatch):
_s4(monkeypatch, FakeMicromateClient())
st = srv.device_call_home_state(**CH_STATE)
assert (st["series"], st["enabled"], st["dial_string"]) == (4, True, "RADIO RING")
def test_enable_route_returns_the_change_result(monkeypatch):
_s4(monkeypatch, FakeMicromateClient(call_home=um12947_call_home(False)))
resp = srv.device_call_home_enable(**CH)
assert resp.status_code == 200 and _body(resp)["action"] == "enable call-home"
def test_disable_route_returns_the_change_result(monkeypatch):
_s4(monkeypatch, FakeMicromateClient())
resp = srv.device_call_home_disable(**CH)
assert resp.status_code == 200 and _body(resp)["state_after"] == "disabled"
def _asgi(method, path, query=""):
import asyncio
msgs = []
async def receive():
return {"type": "http.request", "body": b"", "more_body": False}
async def send(m):
msgs.append(m)
scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": method,
"scheme": "http", "path": path, "raw_path": path.encode(), "root_path": "",
"query_string": query.encode(), "headers": [(b"host", b"sfm.local")],
"server": ("sfm.local", 80), "client": ("127.0.0.1", 1)}
asyncio.run(srv.app(scope, receive, send))
return next(m for m in msgs if m["type"] == "http.response.start")["status"]
@pytest.mark.parametrize("method,path", [("GET", "/device/call_home/state"),
("POST", "/device/call_home/enable"),
("POST", "/device/call_home/disable")])
def test_call_home_routes_need_a_serial(method, path):
assert _asgi(method, path, "host=10.0.0.5&tcp_port=9034") == 422
def test_call_home_routes_are_serial_aware():
assert {"/device/call_home/state", "/device/call_home/enable",
"/device/call_home/disable"} <= srv._SERIAL_AWARE_PATHS
def test_legacy_call_home_post_still_refuses_a_micromate_serial():
refusal = srv._device_guard("/device/call_home", {"serial": "UM20147"})
assert refusal is not None and refusal[0] == 501