45 lines
1.8 KiB
Python
45 lines
1.8 KiB
Python
"""Brain-owned durable replay storage; never shared with Sense or Bell."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sqlite3
|
|
import threading
|
|
from contextlib import closing
|
|
from pathlib import Path
|
|
|
|
|
|
class SQLiteReplayStore:
|
|
def __init__(self, path: str | Path) -> None:
|
|
self._path = str(path)
|
|
self._lock = threading.Lock()
|
|
with closing(self._connect()) as connection:
|
|
connection.execute("PRAGMA journal_mode=WAL")
|
|
connection.execute(
|
|
"CREATE TABLE IF NOT EXISTS machine_replay (principal TEXT NOT NULL, token_id TEXT NOT NULL, expires_at INTEGER NOT NULL, PRIMARY KEY(principal, token_id))"
|
|
)
|
|
|
|
def _connect(self) -> sqlite3.Connection:
|
|
connection = sqlite3.connect(self._path, timeout=5, isolation_level=None)
|
|
connection.execute("PRAGMA busy_timeout=5000")
|
|
return connection
|
|
|
|
def consume(self, principal: str, token_id: str, expires_at: int, now: int) -> bool:
|
|
if not principal or not token_id or expires_at <= now:
|
|
return False
|
|
with self._lock, closing(self._connect()) as connection:
|
|
try:
|
|
connection.execute("BEGIN IMMEDIATE")
|
|
connection.execute("DELETE FROM machine_replay WHERE expires_at <= ?", (now,))
|
|
connection.execute(
|
|
"INSERT INTO machine_replay(principal, token_id, expires_at) VALUES (?, ?, ?)",
|
|
(principal, token_id, expires_at),
|
|
)
|
|
connection.execute("COMMIT")
|
|
return True
|
|
except sqlite3.IntegrityError:
|
|
connection.execute("ROLLBACK")
|
|
return False
|
|
except Exception:
|
|
connection.execute("ROLLBACK")
|
|
return False
|