feat(sfm): device_commands audit table -- one row per change attempt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
7ff527df07
commit
fb9b48f259
4 files changed
+160
No files matched your search
@@ -0,0 +1,16 @@
|
|||||||
|
"""The SDM side of the device audit: DeviceAccess calls this sink, which writes
|
||||||
|
SeismoDb.device_commands. Kept here so sfm.device_access never imports the DB."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Callable
|
||||||
|
|
||||||
|
|
||||||
|
class DbAudit:
|
||||||
|
def __init__(self, get_db: Callable[[], Any]) -> None:
|
||||||
|
self._get_db = get_db
|
||||||
|
|
||||||
|
def begin(self, **fields: Any) -> str:
|
||||||
|
return self._get_db().begin_device_command(**fields)
|
||||||
|
|
||||||
|
def finish(self, command_id: str, **fields: Any) -> None:
|
||||||
|
self._get_db().finish_device_command(command_id, **fields)
|
||||||
@@ -34,6 +34,7 @@ Usage
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import datetime
|
import datetime
|
||||||
|
import json
|
||||||
import logging
|
import logging
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import uuid
|
import uuid
|
||||||
@@ -126,6 +127,24 @@ CREATE TABLE IF NOT EXISTS monitor_log (
|
|||||||
CREATE INDEX IF NOT EXISTS idx_monitor_log_serial ON monitor_log(serial);
|
CREATE INDEX IF NOT EXISTS idx_monitor_log_serial ON monitor_log(serial);
|
||||||
CREATE INDEX IF NOT EXISTS idx_monitor_log_start ON monitor_log(start_time);
|
CREATE INDEX IF NOT EXISTS idx_monitor_log_start ON monitor_log(start_time);
|
||||||
CREATE INDEX IF NOT EXISTS idx_monitor_log_session ON monitor_log(session_id);
|
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)
|
||||||
|
finished_ts TEXT,
|
||||||
|
serial TEXT NOT NULL,
|
||||||
|
series INTEGER NOT NULL,
|
||||||
|
address TEXT NOT NULL,
|
||||||
|
action TEXT NOT NULL, -- e.g. "start monitoring"
|
||||||
|
tier TEXT NOT NULL, -- "change" | "destructive"
|
||||||
|
request TEXT, -- JSON: parameters + the planned frames (hex)
|
||||||
|
ack TEXT, -- JSON: ack summary
|
||||||
|
verified TEXT, -- "ok" | "mismatch" | "not_checked"
|
||||||
|
outcome TEXT NOT NULL, -- "pending" | "sent" | "skipped" | "failed"
|
||||||
|
error TEXT,
|
||||||
|
caller TEXT -- "webapp" | "terra-view" | "script" | ...
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_device_commands_serial ON device_commands(serial, ts);
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
@@ -372,6 +391,79 @@ class SeismoDb:
|
|||||||
).fetchall()
|
).fetchall()
|
||||||
return [dict(r) for r in rows]
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
# ── Device command audit ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def begin_device_command(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
serial: str,
|
||||||
|
series: int,
|
||||||
|
address: str,
|
||||||
|
action: str,
|
||||||
|
tier: str,
|
||||||
|
request: dict,
|
||||||
|
caller: str,
|
||||||
|
) -> str:
|
||||||
|
"""Write a ``pending`` audit row BEFORE anything is sent. Returns its id."""
|
||||||
|
cid = self._new_id()
|
||||||
|
ts = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||||
|
with self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO device_commands
|
||||||
|
(id, ts, serial, series, address, action, tier,
|
||||||
|
request, outcome, caller)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)
|
||||||
|
""",
|
||||||
|
(cid, ts, serial, series, address, action, tier,
|
||||||
|
json.dumps(request), caller),
|
||||||
|
)
|
||||||
|
return cid
|
||||||
|
|
||||||
|
def finish_device_command(
|
||||||
|
self,
|
||||||
|
command_id: str,
|
||||||
|
*,
|
||||||
|
outcome: str,
|
||||||
|
verified: Optional[str],
|
||||||
|
ack: Optional[dict],
|
||||||
|
error: Optional[str],
|
||||||
|
) -> None:
|
||||||
|
"""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(
|
||||||
|
"UPDATE device_commands SET finished_ts=?, outcome=?, verified=?, "
|
||||||
|
"ack=?, error=? WHERE id=?",
|
||||||
|
(ts, outcome, verified,
|
||||||
|
json.dumps(ack) if ack is not None else None,
|
||||||
|
error, command_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
def query_device_commands(
|
||||||
|
self,
|
||||||
|
serial: Optional[str] = None,
|
||||||
|
limit: int = 100,
|
||||||
|
) -> list[dict]:
|
||||||
|
"""Return audit rows, newest first, with request/ack parsed from JSON."""
|
||||||
|
with self._connect() as conn:
|
||||||
|
if serial:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM device_commands WHERE serial=? "
|
||||||
|
"ORDER BY ts DESC LIMIT ?", (serial, limit)).fetchall()
|
||||||
|
else:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM device_commands ORDER BY ts DESC LIMIT ?",
|
||||||
|
(limit,)).fetchall()
|
||||||
|
out = []
|
||||||
|
for r in rows:
|
||||||
|
d = dict(r)
|
||||||
|
for k in ("request", "ack"):
|
||||||
|
if d[k] is not None:
|
||||||
|
d[k] = json.loads(d[k])
|
||||||
|
out.append(d)
|
||||||
|
return out
|
||||||
|
|
||||||
# ── Events ────────────────────────────────────────────────────────────────
|
# ── Events ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def insert_events(
|
def insert_events(
|
||||||
|
|||||||
@@ -3080,6 +3080,17 @@ def db_sessions(
|
|||||||
return {"count": len(rows), "sessions": rows}
|
return {"count": len(rows), "sessions": rows}
|
||||||
|
|
||||||
|
|
||||||
|
@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"),
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
The audit trail of changes SFM attempted on units, newest first.
|
||||||
|
"""
|
||||||
|
return {"commands": _get_db().query_device_commands(serial, limit)}
|
||||||
|
|
||||||
|
|
||||||
# ── Entry point ────────────────────────────────────────────────────────────────
|
# ── Entry point ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""The device_commands audit table: one row per change attempt, pending -> result."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
|
from sfm.audit import DbAudit # noqa: E402
|
||||||
|
from sfm.database import SeismoDb # noqa: E402
|
||||||
|
|
||||||
|
ROW = dict(serial="UM20147", series=4, address="serial:/dev/ttyACM0",
|
||||||
|
action="start monitoring", tier="change",
|
||||||
|
request={"plan": {"steps": [{"sub": "0x96"}]}}, caller="test")
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_command_is_pending_until_finished(tmp_path):
|
||||||
|
db = SeismoDb(tmp_path / "s.db")
|
||||||
|
cid = db.begin_device_command(**ROW)
|
||||||
|
row = db.query_device_commands(serial="UM20147")[0]
|
||||||
|
assert (row["id"], row["outcome"], row["verified"]) == (cid, "pending", None)
|
||||||
|
assert row["request"]["plan"]["steps"][0]["sub"] == "0x96"
|
||||||
|
db.finish_device_command(cid, outcome="sent", verified="ok",
|
||||||
|
ack={"subs": ["0x69"]}, error=None)
|
||||||
|
row = db.query_device_commands(serial="UM20147")[0]
|
||||||
|
assert (row["outcome"], row["verified"], row["ack"]) == ("sent", "ok", {"subs": ["0x69"]})
|
||||||
|
assert row["finished_ts"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_table_survives_reopening(tmp_path):
|
||||||
|
SeismoDb(tmp_path / "s.db").begin_device_command(**ROW)
|
||||||
|
assert len(SeismoDb(tmp_path / "s.db").query_device_commands()) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_db_audit_is_a_thin_sink(tmp_path):
|
||||||
|
db = SeismoDb(tmp_path / "s.db")
|
||||||
|
audit = DbAudit(lambda: db)
|
||||||
|
cid = audit.begin(**ROW)
|
||||||
|
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")
|
||||||
Reference in new issue
Block a user