Files
cwshed-clone/app/belki/history.py
T

120 lines
5.6 KiB
Python

"""Durable calculation history for PostgreSQL, with a local SQLite fallback."""
from __future__ import annotations
import json
import os
import sqlite3
from pathlib import Path
from typing import Any
class CalculationStore:
"""Persist successful calculations without coupling the domain to a database."""
def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None:
self.database_url = database_url or ""
self.sqlite_path = Path(sqlite_path) if sqlite_path else None
fetch_limit = 5000
if self.database_url.startswith(("postgres://", "postgresql://")):
import psycopg
self._psycopg = psycopg
self._ensure_postgres_schema()
else:
self.sqlite_path = self.sqlite_path or Path("data/belki.sqlite3")
self.sqlite_path.parent.mkdir(parents=True, exist_ok=True)
self._ensure_sqlite_schema()
@classmethod
def from_environment(cls) -> "CalculationStore":
return cls(
database_url=os.getenv("BELKI_DATABASE_URL"),
sqlite_path=os.getenv("BELKI_HISTORY_DB", "data/belki.sqlite3"),
)
def _ensure_sqlite_schema(self) -> None:
with sqlite3.connect(self.sqlite_path) as connection:
connection.execute(
"""CREATE TABLE IF NOT EXISTS calculations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
actor_id INTEGER,
source TEXT NOT NULL,
mode TEXT NOT NULL,
input_json TEXT NOT NULL,
result_json TEXT,
message TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
)"""
)
def _ensure_postgres_schema(self) -> None:
with self._psycopg.connect(self.database_url) as connection:
connection.execute(
"""CREATE TABLE IF NOT EXISTS belki_calculations (
id BIGSERIAL PRIMARY KEY,
actor_id BIGINT,
source TEXT NOT NULL,
mode TEXT NOT NULL,
input_json JSONB NOT NULL,
result_json JSONB,
message TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)"""
)
def save(self, *, actor_id: int | None, source: str, payload: dict[str, Any], response: dict[str, Any]) -> int:
mode = str(payload.get("mode", response.get("mode", "unknown")))
message = str(response["message"])
result = response.get("result")
if self.database_url.startswith(("postgres://", "postgresql://")):
from psycopg.types.json import Jsonb
with self._psycopg.connect(self.database_url) as connection:
row = connection.execute(
"""INSERT INTO belki_calculations
(actor_id, source, mode, input_json, result_json, message)
VALUES (%s, %s, %s, %s, %s, %s) RETURNING id""",
(actor_id, source, mode, Jsonb(payload), Jsonb(result) if result is not None else None, message),
).fetchone()
return int(row[0])
with sqlite3.connect(self.sqlite_path) as connection:
cursor = connection.execute(
"""INSERT INTO calculations
(actor_id, source, mode, input_json, result_json, message)
VALUES (?, ?, ?, ?, ?, ?)""",
(actor_id, source, mode, json.dumps(payload, ensure_ascii=False),
json.dumps(result, ensure_ascii=False) if result is not None else None, message),
)
return int(cursor.lastrowid)
def list_calculations(self, *, sort_by: str = "kitten_id", descending: bool = True,
limit: int = 100) -> list[dict[str, Any]]:
"""Return admin rows with safe, application-level sorting by kitten identity."""
limit = max(1, min(int(limit), 500))
fetch_limit = 5000
if self.database_url.startswith(("postgres://", "postgresql://")):
with self._psycopg.connect(self.database_url) as connection:
rows = connection.execute(
"""SELECT id, actor_id, source, mode, input_json, result_json, message, created_at
FROM belki_calculations ORDER BY created_at DESC LIMIT %s""", (fetch_limit,)
).fetchall()
else:
with sqlite3.connect(self.sqlite_path) as connection:
rows = connection.execute(
"""SELECT id, actor_id, source, mode, input_json, result_json, message, created_at
FROM calculations ORDER BY created_at DESC LIMIT ?""", (fetch_limit,)
).fetchall()
records = []
for row in rows:
input_data = row[4] if isinstance(row[4], dict) else json.loads(row[4])
result_data = row[5] if isinstance(row[5], dict) or row[5] is None else json.loads(row[5])
records.append({
"id": row[0], "actor_id": row[1], "source": row[2], "mode": row[3],
"input": input_data, "result": result_data, "message": row[6],
"created_at": row[7].isoformat() if hasattr(row[7], "isoformat") else row[7],
})
if sort_by not in {"kitten_id", "kitten_name"}:
sort_by = "kitten_id"
records.sort(key=lambda item: (item["input"].get(sort_by) is None, item["input"].get(sort_by, "")),
reverse=descending)
return records[:limit]