58 lines
2.0 KiB
Python
58 lines
2.0 KiB
Python
"""The rest of a long list answer, for "áno, ukáž ďalších" (kept 24 hours).
|
|
|
|
A list answer shows its first items and asks whether to show more; the not yet
|
|
shown items are stored here under a random id that the signed conversation
|
|
token carries. Only rendered answer lines with their source links are stored
|
|
(the same text the user would see), never chat history. The file stays small:
|
|
expired pages are deleted on every write.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import secrets
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
|
|
LIFETIME = 24 * 3600
|
|
_lock = threading.Lock()
|
|
|
|
|
|
def _file() -> Path:
|
|
from tools.rag.common import DB_FILE
|
|
return DB_FILE.parent / "conversation_pages.sqlite"
|
|
|
|
|
|
def _connect() -> sqlite3.Connection:
|
|
connection = sqlite3.connect(_file(), timeout=10)
|
|
connection.execute("CREATE TABLE IF NOT EXISTS pages (id TEXT PRIMARY KEY, expires REAL, payload TEXT)")
|
|
return connection
|
|
|
|
|
|
def put(items: list[dict], meta: dict | None = None) -> str | None:
|
|
"""Store the remaining items; returns their id (None when storing is impossible)."""
|
|
if not items:
|
|
return None
|
|
page_id = secrets.token_urlsafe(12)
|
|
payload = json.dumps({"items": items, "meta": meta or {}}, ensure_ascii=False)
|
|
try:
|
|
with _lock, _connect() as connection:
|
|
connection.execute("DELETE FROM pages WHERE expires < ?", (time.time(),))
|
|
connection.execute("INSERT INTO pages VALUES (?, ?, ?)", (page_id, time.time() + LIFETIME, payload))
|
|
return page_id
|
|
except (sqlite3.Error, OSError):
|
|
return None
|
|
|
|
|
|
def get(page_id: str | None) -> dict | None:
|
|
if not isinstance(page_id, str) or not page_id:
|
|
return None
|
|
try:
|
|
with _lock, _connect() as connection:
|
|
row = connection.execute("SELECT payload FROM pages WHERE id = ? AND expires >= ?",
|
|
(page_id, time.time())).fetchone()
|
|
except (sqlite3.Error, OSError):
|
|
return None
|
|
return json.loads(row[0]) if row else None
|