clipwright/clipwright/storage/channel_profiles.py
pedro-bento 71e0ebf7ea
All checks were successful
CI / unit (push) Successful in 49s
CI / backend-e2e (push) Successful in 1m26s
CI / dashboard-e2e (push) Successful in 2m30s
chore(channels): name the SQLite database clipwright.sqlite3
Make the file type explicit. CLIPWRIGHT_DB still overrides the path.
2026-10-06 12:13:25 +01:00

176 lines
5.5 KiB
Python

"""SQLite-backed channel profile store.
This is the runtime source of truth for channel profiles. It replaces the
committed ``channels/<slug>.json`` files: on the very first bootstrap (the
``seeded`` key is absent from ``meta``) any profile files that the file loader
still accepts are imported once, then the guard is set so later runs never
re-read the directory. Set ``CLIPWRIGHT_DB`` to move the database; otherwise it
lives at ``<repo>/clipwright.sqlite3``.
Threading: FastAPI sync endpoints run in a threadpool, so every public
operation is serialized by a module-level re-entrant lock. The pipeline runs in
a separate process and relies on SQLite's own locking (WAL + busy timeout).
"""
from __future__ import annotations
import json
import os
import sqlite3
import threading
from collections.abc import Mapping
from pathlib import Path
from clipwright.core.paths import REPO_ROOT
_LOCK = threading.RLock()
_SCHEMA = """
CREATE TABLE IF NOT EXISTS channel_profiles (
slug TEXT PRIMARY KEY,
name TEXT NOT NULL DEFAULT '',
data TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
"""
def db_path() -> Path:
"""Location of the profile database (``CLIPWRIGHT_DB`` overrides)."""
override = os.environ.get("CLIPWRIGHT_DB")
if override:
return Path(override)
return REPO_ROOT / "clipwright.sqlite3"
def _connect() -> sqlite3.Connection:
path = db_path()
path.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(path, timeout=15)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA busy_timeout=15000")
return conn
def _bootstrap(conn: sqlite3.Connection) -> None:
"""Create the schema if missing and run the one-time file import."""
conn.executescript(_SCHEMA)
_seed_if_needed(conn)
def _seed_if_needed(conn: sqlite3.Connection) -> None:
seeded = conn.execute("SELECT value FROM meta WHERE key = 'seeded'").fetchone()
if seeded is not None:
return
# Lazy import: profiles imports this module from inside its own functions,
# so a top-level import here would be circular.
from clipwright.pipeline import profiles
directory = profiles.CHANNELS_DIR
if directory.is_dir():
for path in sorted(directory.glob("*.json")):
slug = path.stem
try:
profile = profiles.load_profile(slug, channels_dir=directory)
except profiles.ProfileError:
continue
conn.execute(
"INSERT OR IGNORE INTO channel_profiles (slug, name, data) "
"VALUES (?, ?, ?)",
(slug, profile.name or slug, json.dumps(profile.to_dict(), ensure_ascii=False)),
)
conn.execute("INSERT OR REPLACE INTO meta (key, value) VALUES ('seeded', '1')")
def _row_to_dict(row: sqlite3.Row) -> dict:
data = json.loads(row["data"])
data["slug"] = row["slug"]
return data
def get_raw(slug: str) -> dict | None:
"""Return the stored profile dict (with ``slug`` injected) or ``None``."""
with _LOCK:
conn = _connect()
try:
_bootstrap(conn)
conn.commit()
row = conn.execute(
"SELECT slug, data FROM channel_profiles WHERE slug = ?", (slug,)
).fetchone()
return _row_to_dict(row) if row is not None else None
finally:
conn.close()
def list_raw() -> list[dict]:
"""Every stored profile as a parsed dict with ``slug`` injected."""
with _LOCK:
conn = _connect()
try:
_bootstrap(conn)
conn.commit()
rows = conn.execute(
"SELECT slug, data FROM channel_profiles ORDER BY slug"
).fetchall()
return [_row_to_dict(row) for row in rows]
finally:
conn.close()
def list_summaries() -> list[dict]:
"""``[{"slug", "name"}]`` for every profile, sorted by slug."""
with _LOCK:
conn = _connect()
try:
_bootstrap(conn)
conn.commit()
rows = conn.execute(
"SELECT slug, name FROM channel_profiles ORDER BY slug"
).fetchall()
return [{"slug": row["slug"], "name": row["name"] or row["slug"]} for row in rows]
finally:
conn.close()
def upsert(slug: str, name: str, data: Mapping) -> None:
"""Insert or replace a profile row (``updated_at`` is bumped on replace)."""
payload = json.dumps(dict(data), ensure_ascii=False)
with _LOCK:
conn = _connect()
try:
_bootstrap(conn)
conn.execute(
"""
INSERT INTO channel_profiles (slug, name, data)
VALUES (?, ?, ?)
ON CONFLICT(slug) DO UPDATE SET
name = excluded.name,
data = excluded.data,
updated_at = datetime('now')
""",
(slug, name, payload),
)
conn.commit()
finally:
conn.close()
def delete(slug: str) -> bool:
"""Delete a profile; ``True`` when a row was removed."""
with _LOCK:
conn = _connect()
try:
_bootstrap(conn)
cursor = conn.execute("DELETE FROM channel_profiles WHERE slug = ?", (slug,))
conn.commit()
return cursor.rowcount > 0
finally:
conn.close()