diff --git a/sfm/database.py b/sfm/database.py index dbc31f5..468c7e1 100644 --- a/sfm/database.py +++ b/sfm/database.py @@ -131,6 +131,7 @@ CREATE INDEX IF NOT EXISTS idx_monitor_log_session ON monitor_log(session_id); CREATE TABLE IF NOT EXISTS device_commands ( id TEXT PRIMARY KEY, ts TEXT NOT NULL, -- when the attempt began (UTC ISO) + -- ts/finished_ts: tz-aware UTC ISO (+00:00), unlike the naive UTC of older tables finished_ts TEXT, serial TEXT NOT NULL, series INTEGER NOT NULL, @@ -432,13 +433,20 @@ class SeismoDb: """Record the result of a command begun with begin_device_command().""" ts = datetime.datetime.now(datetime.timezone.utc).isoformat() with self._connect() as conn: - conn.execute( + cur = conn.execute( "UPDATE device_commands SET finished_ts=?, outcome=?, verified=?, " - "ack=?, error=? WHERE id=?", + "ack=?, error=? WHERE id=? AND outcome='pending'", (ts, outcome, verified, json.dumps(ack) if ack is not None else None, error, command_id), ) + if cur.rowcount == 0: + known = conn.execute( + "SELECT 1 FROM device_commands WHERE id=?", + (command_id,)).fetchone() + raise ValueError( + f"device command {command_id} " + + ("is already finished" if known else "is unknown")) def query_device_commands( self, diff --git a/sfm/server.py b/sfm/server.py index 0d7c3e4..54ec0ae 100644 --- a/sfm/server.py +++ b/sfm/server.py @@ -3083,7 +3083,7 @@ def db_sessions( @app.get("/db/device_commands") def db_device_commands( serial: Optional[str] = Query(None, description="Filter by unit serial"), - limit: int = Query(100, description="Max rows to return"), + limit: int = Query(100, ge=1, le=1000, description="Max rows to return"), ) -> dict: """ The audit trail of changes SFM attempted on units, newest first. diff --git a/tests/test_device_commands.py b/tests/test_device_commands.py index ac15255..3a9229c 100644 --- a/tests/test_device_commands.py +++ b/tests/test_device_commands.py @@ -39,3 +39,26 @@ def test_db_audit_is_a_thin_sink(tmp_path): audit.finish(cid, outcome="failed", verified="mismatch", ack=None, error="unit reads idle") row = db.query_device_commands()[0] assert (row["outcome"], row["verified"], row["error"]) == ("failed", "mismatch", "unit reads idle") + + +def test_finishing_an_unknown_id_raises_and_creates_nothing(tmp_path): + import pytest + db = SeismoDb(tmp_path / "s.db") + with pytest.raises(ValueError, match="no-such-id"): + db.finish_device_command("no-such-id", outcome="sent", verified="ok", + ack=None, error=None) + assert db.query_device_commands() == [] + + +def test_a_second_finish_raises_and_keeps_the_first_result(tmp_path): + import pytest + db = SeismoDb(tmp_path / "s.db") + cid = db.begin_device_command(**ROW) + db.finish_device_command(cid, outcome="failed", verified="mismatch", + ack={"subs": ["0x69"]}, error="unit reads idle") + with pytest.raises(ValueError, match=cid): + db.finish_device_command(cid, outcome="sent", verified="ok", + ack={"other": 1}, error=None) + row = db.query_device_commands()[0] + assert (row["outcome"], row["verified"], row["ack"], row["error"]) == \ + ("failed", "mismatch", {"subs": ["0x69"]}, "unit reads idle")