diff --git a/sfm/server.py b/sfm/server.py index 54ec0ae..5f1a320 100644 --- a/sfm/server.py +++ b/sfm/server.py @@ -87,6 +87,7 @@ import dataclasses from sfm.device_access import DeviceAccess, DeviceError, UnitAddress from sfm.device_access.errors import BadRequest from sfm.device_access.series import normalise_serial +from sfm.audit import DbAudit logging.basicConfig( level=logging.INFO, @@ -359,7 +360,8 @@ def _run_with_retry(fn, *, is_tcp: bool): # legacy Series-3 path unchanged (spec 2026-10-20). # Constructing it does no I/O and starts no thread until a Series-4 session exists. -_device_access_instance: DeviceAccess = DeviceAccess() +# The audit sink is mandatory for live changes: without one they are refused. +_device_access_instance: DeviceAccess = DeviceAccess(audit=DbAudit(_get_db)) def _device_access() -> DeviceAccess: @@ -380,9 +382,22 @@ def _via_device_access(fn) -> dict: return dataclasses.asdict(result) if dataclasses.is_dataclass(result) else result +def _change_response(fn) -> JSONResponse: + """Run a start/stop; the ChangeResult is the body, its outcome picks the status. + + DeviceError mapping is _via_device_access's -- not repeated here. + """ + body = _via_device_access(fn) + status = 200 + if body["outcome"] == "failed": + status = 409 if body["verified"] == "mismatch" else 502 + return JSONResponse(status_code=status, content=body) + + _SERIAL_AWARE_PATHS = frozenset({ "/device/info", "/device/connect", "/device/monitor/status", "/device/settings", "/device/events", "/device/events/download", + "/device/monitor/start", "/device/monitor/stop", }) @@ -1838,15 +1853,32 @@ def device_rescue( @app.post("/device/monitor/start") def device_monitor_start( port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"), - baud: int = Query(38400, description="Serial baud rate"), + baud: Optional[int] = Query(None, description="Serial baud rate"), host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay"), tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"), -) -> dict: + serial: Optional[str] = Query(None, description=_SERIAL_DOC), + dry_run: bool = Query(False, description="Return the planned frames; send nothing"), + even_if_already: bool = Query(False, description="Send even if the unit is already in the target state"), + caller: Optional[str] = Query(None, description="Who is asking (recorded in the audit row)"), +): """ Command the device to start monitoring (recording triggered events). Sends SUB 0x96 and waits for ack SUB 0x69. + + With `serial`: the unit's identity is read first (a different unit is a 409, + nothing sent), then its state; `dry_run` returns the planned frames and sends + nothing; a live change is audited, verified by reading the state back, and + never retried. The response is the ChangeResult (409 if the unit never + reached the state, 502 if the ack was lost). + + Without `serial`: the legacy behaviour above, unchanged. """ + if serial: + return _change_response(lambda: _device_access().start_monitoring( + _unit_address(port, baud, host, tcp_port), serial, dry_run=dry_run, + even_if_already=even_if_already, caller=caller or "api")) + baud = 38400 if baud is None else baud conn_key = _live_cache.make_conn_key(host, tcp_port, port, baud) with _build_client(port=port, baud=baud, host=host, tcp_port=tcp_port) as client: try: @@ -1864,15 +1896,32 @@ def device_monitor_start( @app.post("/device/monitor/stop") def device_monitor_stop( port: Optional[str] = Query(None, description="Serial port (e.g. COM5)"), - baud: int = Query(38400, description="Serial baud rate"), + baud: Optional[int] = Query(None, description="Serial baud rate"), host: Optional[str] = Query(None, description="TCP host — modem IP or ACH relay"), tcp_port: int = Query(DEFAULT_TCP_PORT, description=f"TCP port (default {DEFAULT_TCP_PORT})"), -) -> dict: + serial: Optional[str] = Query(None, description=_SERIAL_DOC), + dry_run: bool = Query(False, description="Return the planned frames; send nothing"), + even_if_already: bool = Query(False, description="Send even if the unit is already in the target state"), + caller: Optional[str] = Query(None, description="Who is asking (recorded in the audit row)"), +): """ Command the device to stop monitoring. Sends SUB 0x97 and waits for ack SUB 0x68. + + With `serial`: the unit's identity is read first (a different unit is a 409, + nothing sent), then its state; `dry_run` returns the planned frames and sends + nothing; a live change is audited, verified by reading the state back, and + never retried. The response is the ChangeResult (409 if the unit never + reached the state, 502 if the ack was lost). + + Without `serial`: the legacy behaviour above, unchanged. """ + if serial: + return _change_response(lambda: _device_access().stop_monitoring( + _unit_address(port, baud, host, tcp_port), serial, dry_run=dry_run, + even_if_already=even_if_already, caller=caller or "api")) + baud = 38400 if baud is None else baud conn_key = _live_cache.make_conn_key(host, tcp_port, port, baud) with _build_client(port=port, baud=baud, host=host, tcp_port=tcp_port) as client: try: diff --git a/tests/test_server_device_access.py b/tests/test_server_device_access.py index 333ff6e..9f28a60 100644 --- a/tests/test_server_device_access.py +++ b/tests/test_server_device_access.py @@ -100,7 +100,7 @@ ADDR = UnitAddress(host="10.0.0.5", tcp_port=9034, port=None, baud=None) Q_TCP = {"host": "10.0.0.5", "tcp_port": "9034"} -@pytest.mark.parametrize("path", ["/device/events/erase", "/device/monitor/stop", "/device/config"]) +@pytest.mark.parametrize("path", ["/device/events/erase", "/device/config"]) def test_guard_refuses_a_um_serial_on_unsupported_routes_with_501(path): out = srv._device_guard(path, {"serial": "um20147", **Q_TCP}) assert out is not None and out[0] == 501 and path in out[1] @@ -113,6 +113,7 @@ def test_guard_lets_a_series3_serial_through_on_legacy_routes(): @pytest.mark.parametrize("path", ["/device/info", "/device/connect", "/device/monitor/status", "/device/settings", "/device/events", "/device/events/download", + "/device/monitor/start", "/device/monitor/stop", "/device/hangup"]) def test_guard_allows_um_serial_on_serial_aware_routes_and_hangup(path): assert srv._device_guard(path, {"serial": "UM20147", **Q_TCP}) is None @@ -255,3 +256,127 @@ def test_a_store_failure_is_500_and_names_what_was_downloaded(da, sdm, monkeypat srv.device_events_download(serial="UM20147", event_id=W_ID, **EV) assert ei.value.status_code == 500 assert "UM20147_20250531135901.IDFW" in ei.value.detail and "disk full" in ei.value.detail + + +# ── start / stop monitoring by serial ───────────────────────────────────────── + +import micromate.protocol as _mm_proto # noqa: E402 +from sfm.audit import DbAudit # noqa: E402 + +CH = dict(port=None, baud=None, host="10.0.0.5", tcp_port=9034, + serial="UM20147", dry_run=False, even_if_already=False, caller=None) + + +class _Rec: + 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 _s4(monkeypatch, fake, audit=None): + access = DeviceAccess(s4_client_factory=lambda a, **kw: fake, start_reaper=False, + audit=audit or _Rec(), sleep=lambda s: None, + verify_timeout_s=6.0, verify_interval_s=2.0) + monkeypatch.setattr(srv, "_device_access_instance", access) + return access + + +def _body(resp): + import json + return json.loads(resp.body) + + +def test_a_dry_run_is_200_with_the_frame(monkeypatch): + fake = FakeMicromateClient(run_states=[0x00]) + _s4(monkeypatch, fake) + resp = srv.device_monitor_start(**{**CH, "dry_run": True}) + assert resp.status_code == 200 + body = _body(resp) + assert body["outcome"] == "dry_run" and body["plan"]["steps"][0]["frame"].startswith("4102") + assert fake.executed == [] + + +def test_a_verified_live_start_is_200(monkeypatch): + fake = FakeMicromateClient(run_states=[0x00, 0x00, 0x02]) + _s4(monkeypatch, fake) + resp = srv.device_monitor_start(**CH) + assert resp.status_code == 200 and _body(resp)["verified"] == "ok" + + +def test_a_mismatch_is_409_and_keeps_states_seen(monkeypatch): + fake = FakeMicromateClient(run_states=[0x00]) + _s4(monkeypatch, fake) + resp = srv.device_monitor_start(**CH) + assert resp.status_code == 409 + body = _body(resp) + assert body["verified"] == "mismatch" and body["detail"]["states_seen"] + + +def test_a_lost_ack_with_a_good_read_back_is_502(monkeypatch): + fake = FakeMicromateClient(run_states=[0x00, 0x02], + execute_error=_mm_proto.TimeoutError("no ack")) + _s4(monkeypatch, fake) + resp = srv.device_monitor_start(**CH) + assert resp.status_code == 502 + assert _body(resp)["verified"] == "not_checked" or _body(resp)["outcome"] == "failed" + + +def test_stop_by_serial_works(monkeypatch): + fake = FakeMicromateClient(run_states=[0x02, 0x02, 0x00]) + _s4(monkeypatch, fake) + resp = srv.device_monitor_stop(**CH) + assert resp.status_code == 200 and _body(resp)["action"].startswith("stop") + + +@pytest.mark.parametrize("fn", ["device_monitor_start", "device_monitor_stop"]) +@pytest.mark.parametrize("run_state,exc,status", [(0x03, CallHomeInProgress, 503)]) +def test_a_device_error_maps_to_its_own_status(monkeypatch, fn, run_state, exc, status): + _s4(monkeypatch, FakeMicromateClient(run_states=[run_state])) + with pytest.raises(HTTPException) as e: + getattr(srv, fn)(**CH) + assert e.value.status_code == status + + +def test_a_wrong_unit_is_409(monkeypatch): + _s4(monkeypatch, FakeMicromateClient(serial_reported="UM12947")) + with pytest.raises(HTTPException) as e: + srv.device_monitor_start(**CH) + assert e.value.status_code == 409 + + +def test_a_live_change_through_the_real_wiring_records_an_audit_row(tmp_path, monkeypatch): + db = SeismoDb(tmp_path / "seismo.db") + fake = FakeMicromateClient(run_states=[0x00, 0x00, 0x02]) + _s4(monkeypatch, fake, audit=DbAudit(lambda: db)) + resp = srv.device_monitor_start(**CH) + assert resp.status_code == 200 + rows = db.query_device_commands() + assert len(rows) == 1 and rows[0]["outcome"] == "sent" + + +def test_the_module_instance_is_built_with_an_audit_sink(): + assert srv._device_access_instance._audit is not None + + +@pytest.mark.parametrize("fn", ["device_monitor_start", "device_monitor_stop"]) +def test_monitor_without_a_serial_runs_the_legacy_path_unchanged(monkeypatch, fn): + class Legacy(Exception): + pass + + def untouchable(): + raise AssertionError("DeviceAccess must not be used without a serial") + + def legacy_client(**kw): + assert kw["baud"] == 38400 # the default is restored on the legacy path + raise Legacy() + monkeypatch.setattr(srv, "_device_access", untouchable) + monkeypatch.setattr(srv, "_build_client", legacy_client) + with pytest.raises(Legacy): + getattr(srv, fn)(**{**CH, "serial": None})