from __future__ import annotations import sqlite3 import threading from contextlib import closing from datetime import datetime from pathlib import Path from typing import Any FINAL_FIELDS = ("status", "finished_at", "duration_ms", "target_time", "summary_rows", "detail", "exit_code") STATUS_GROUPS = { "processed": ("processed", "history_repaired"), "idle": ("waiting", "skipped"), "problem": ("failed", "timeout", "interrupted", "cancelled"), } def now_text() -> str: return datetime.now().strftime("%Y-%m-%d %H:%M:%S") class RunStore: def __init__(self, path: Path) -> None: self.path = path self.path.parent.mkdir(parents=True, exist_ok=True) self._lock = threading.Lock() with self._connect() as connection: connection.executescript( """ PRAGMA journal_mode=WAL; CREATE TABLE IF NOT EXISTS runs ( id INTEGER PRIMARY KEY AUTOINCREMENT, trigger TEXT NOT NULL, dry_run INTEGER NOT NULL DEFAULT 0, status TEXT NOT NULL, started_at TEXT NOT NULL, finished_at TEXT, duration_ms INTEGER, target_time TEXT NOT NULL DEFAULT '', summary_rows INTEGER, detail TEXT NOT NULL DEFAULT '', exit_code INTEGER ); CREATE INDEX IF NOT EXISTS runs_status ON runs(status, id); """ ) def create(self, trigger: str, dry_run: bool) -> int: with self._lock, self._connect() as connection: cursor = connection.execute( "INSERT INTO runs(trigger, dry_run, status, started_at) VALUES (?, ?, 'running', ?)", (trigger, int(dry_run), now_text()), ) return int(cursor.lastrowid) def finish(self, run_id: int, **values: Any) -> None: columns = [name for name in FINAL_FIELDS if name in values] assignments = ", ".join(f"{name} = ?" for name in columns) with self._lock, self._connect() as connection: connection.execute( f"UPDATE runs SET {assignments} WHERE id = ?", (*[values[name] for name in columns], run_id), ) def get(self, run_id: int) -> dict[str, Any] | None: with self._connect() as connection: row = connection.execute("SELECT * FROM runs WHERE id = ?", (run_id,)).fetchone() return dict(row) if row else None def page(self, page: int = 1, page_size: int = 20, status: str = "") -> tuple[list[dict[str, Any]], int]: where, params = self._status_filter(status) offset = max(0, page - 1) * page_size with self._connect() as connection: total = connection.execute(f"SELECT COUNT(*) FROM runs {where}", params).fetchone()[0] rows = connection.execute( f"SELECT * FROM runs {where} ORDER BY id DESC LIMIT ? OFFSET ?", (*params, page_size, offset), ).fetchall() return [dict(row) for row in rows], int(total) def latest_finished(self) -> dict[str, Any] | None: with self._connect() as connection: row = connection.execute("SELECT * FROM runs WHERE status <> 'running' ORDER BY id DESC LIMIT 1").fetchone() return dict(row) if row else None def latest_written(self) -> dict[str, Any] | None: with self._connect() as connection: row = connection.execute( "SELECT * FROM runs WHERE status = 'processed' AND dry_run = 0 ORDER BY id DESC LIMIT 1" ).fetchone() return dict(row) if row else None def counts_since(self, started_at: str) -> dict[str, int]: with self._connect() as connection: rows = connection.execute( "SELECT status, COUNT(*) FROM runs WHERE started_at >= ? AND dry_run = 0 GROUP BY status", (started_at,), ).fetchall() return {str(status): int(count) for status, count in rows} def mark_interrupted(self) -> int: with self._lock, self._connect() as connection: cursor = connection.execute( "UPDATE runs SET status = 'interrupted', finished_at = ? WHERE status = 'running'", (now_text(),), ) return cursor.rowcount def prune(self, keep: int) -> list[int]: with self._lock, self._connect() as connection: rows = connection.execute( "SELECT id FROM runs WHERE status <> 'running' ORDER BY id DESC LIMIT -1 OFFSET ?", (keep,), ).fetchall() removed = [int(row[0]) for row in rows] connection.executemany("DELETE FROM runs WHERE id = ?", [(run_id,) for run_id in removed]) return removed @staticmethod def _status_filter(status: str) -> tuple[str, tuple[object, ...]]: statuses = STATUS_GROUPS.get(status, (status,) if status else ()) if not statuses: return "", () return f"WHERE status IN ({', '.join('?' for _ in statuses)})", statuses def _connect(self) -> Any: connection = sqlite3.connect(self.path, timeout=30) connection.row_factory = sqlite3.Row return _Transaction(connection) class _Transaction: def __init__(self, connection: sqlite3.Connection) -> None: self.connection = connection def __enter__(self) -> sqlite3.Connection: return self.connection def __exit__(self, exc_type: object, *_: object) -> None: with closing(self.connection): if exc_type is None: self.connection.commit() else: self.connection.rollback()