|
| 1 | +"""SQLite-backed audit log for executed actions. |
| 2 | +
|
| 3 | +``AuditLog(db_path)`` opens (or creates) a single-table SQLite database and |
| 4 | +appends one row per action execution. Rows carry the timestamp, action name, |
| 5 | +a JSON-encoded snapshot of the payload, the result / error repr, and the |
| 6 | +duration in milliseconds. |
| 7 | +
|
| 8 | +Writes use a short-lived connection per call (``check_same_thread=False`` |
| 9 | +semantics) so the log is safe to share between background worker threads |
| 10 | +and the scheduler. Readers call :meth:`AuditLog.recent` to pull the most |
| 11 | +recent N rows. |
| 12 | +
|
| 13 | +The module deliberately avoids buffering / background queues: every row is |
| 14 | +persisted synchronously with an ``INSERT`` inside a ``with connect(..)`` so |
| 15 | +a crash at most loses the currently-executing action. |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +import json |
| 21 | +import sqlite3 |
| 22 | +import threading |
| 23 | +import time |
| 24 | +from contextlib import closing |
| 25 | +from pathlib import Path |
| 26 | +from typing import Any |
| 27 | + |
| 28 | +from automation_file.exceptions import FileAutomationException |
| 29 | +from automation_file.logging_config import file_automation_logger |
| 30 | + |
| 31 | +_SCHEMA = """ |
| 32 | +CREATE TABLE IF NOT EXISTS audit ( |
| 33 | + id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 34 | + ts REAL NOT NULL, |
| 35 | + action TEXT NOT NULL, |
| 36 | + payload TEXT NOT NULL, |
| 37 | + result TEXT, |
| 38 | + error TEXT, |
| 39 | + duration_ms REAL NOT NULL |
| 40 | +); |
| 41 | +CREATE INDEX IF NOT EXISTS idx_audit_ts ON audit (ts DESC); |
| 42 | +""" |
| 43 | + |
| 44 | + |
| 45 | +class AuditException(FileAutomationException): |
| 46 | + """Raised when the audit log cannot be opened or written.""" |
| 47 | + |
| 48 | + |
| 49 | +class AuditLog: |
| 50 | + """Synchronous SQLite audit log.""" |
| 51 | + |
| 52 | + def __init__(self, db_path: str | Path) -> None: |
| 53 | + self._db_path = Path(db_path) |
| 54 | + self._lock = threading.Lock() |
| 55 | + try: |
| 56 | + self._db_path.parent.mkdir(parents=True, exist_ok=True) |
| 57 | + with closing(self._connect()) as conn: |
| 58 | + conn.executescript(_SCHEMA) |
| 59 | + conn.commit() |
| 60 | + except (OSError, sqlite3.DatabaseError) as err: |
| 61 | + raise AuditException(f"cannot open audit log {self._db_path}: {err}") from err |
| 62 | + |
| 63 | + def record( |
| 64 | + self, |
| 65 | + action: str, |
| 66 | + payload: Any, |
| 67 | + *, |
| 68 | + result: Any = None, |
| 69 | + error: BaseException | None = None, |
| 70 | + duration_ms: float = 0.0, |
| 71 | + ) -> None: |
| 72 | + """Append a single audit row. Never raises — failures are logged only.""" |
| 73 | + row = ( |
| 74 | + time.time(), |
| 75 | + action, |
| 76 | + _safe_json(payload), |
| 77 | + _safe_json(result) if result is not None else None, |
| 78 | + repr(error) if error is not None else None, |
| 79 | + float(duration_ms), |
| 80 | + ) |
| 81 | + try: |
| 82 | + with self._lock, closing(self._connect()) as conn: |
| 83 | + conn.execute( |
| 84 | + "INSERT INTO audit (ts, action, payload, result, error, duration_ms)" |
| 85 | + " VALUES (?, ?, ?, ?, ?, ?)", |
| 86 | + row, |
| 87 | + ) |
| 88 | + conn.commit() |
| 89 | + except sqlite3.DatabaseError as err: |
| 90 | + file_automation_logger.error("audit.record failed: %r", err) |
| 91 | + |
| 92 | + def recent(self, limit: int = 100) -> list[dict[str, Any]]: |
| 93 | + """Return the newest ``limit`` rows, newest first.""" |
| 94 | + if limit <= 0: |
| 95 | + return [] |
| 96 | + with closing(self._connect()) as conn: |
| 97 | + cursor = conn.execute( |
| 98 | + "SELECT id, ts, action, payload, result, error, duration_ms" |
| 99 | + " FROM audit ORDER BY ts DESC LIMIT ?", |
| 100 | + (limit,), |
| 101 | + ) |
| 102 | + rows = cursor.fetchall() |
| 103 | + return [ |
| 104 | + { |
| 105 | + "id": row[0], |
| 106 | + "ts": row[1], |
| 107 | + "action": row[2], |
| 108 | + "payload": json.loads(row[3]) if row[3] else None, |
| 109 | + "result": json.loads(row[4]) if row[4] else None, |
| 110 | + "error": row[5], |
| 111 | + "duration_ms": row[6], |
| 112 | + } |
| 113 | + for row in rows |
| 114 | + ] |
| 115 | + |
| 116 | + def count(self) -> int: |
| 117 | + with closing(self._connect()) as conn: |
| 118 | + cursor = conn.execute("SELECT COUNT(*) FROM audit") |
| 119 | + (total,) = cursor.fetchone() |
| 120 | + return int(total) |
| 121 | + |
| 122 | + def purge(self, older_than_seconds: float) -> int: |
| 123 | + """Delete rows older than ``older_than_seconds`` and return the row count.""" |
| 124 | + if older_than_seconds <= 0: |
| 125 | + raise AuditException("older_than_seconds must be positive") |
| 126 | + cutoff = time.time() - older_than_seconds |
| 127 | + with self._lock, closing(self._connect()) as conn: |
| 128 | + cursor = conn.execute("DELETE FROM audit WHERE ts < ?", (cutoff,)) |
| 129 | + conn.commit() |
| 130 | + return int(cursor.rowcount) |
| 131 | + |
| 132 | + def _connect(self) -> sqlite3.Connection: |
| 133 | + return sqlite3.connect(self._db_path, timeout=5.0) |
| 134 | + |
| 135 | + |
| 136 | +def _safe_json(value: Any) -> str: |
| 137 | + try: |
| 138 | + return json.dumps(value, default=repr, ensure_ascii=False) |
| 139 | + except (TypeError, ValueError): |
| 140 | + return json.dumps(repr(value), ensure_ascii=False) |
0 commit comments