# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """Reading the command history from the *other* process. The bot holds the database open and commits on every inbound message, so this opens its own read-only connection and closes it explicitly -- the pattern ``routes_suggestions.collect`` established, and for the same reason: a reader left dangling is a lock waiting to happen, and ``Store`` on a plain connection would apply its schema against a running bot. Every gatherer is wrapped the same way. A bot that has never run, a database older than these tables and a half-written file are all the same answer, and none of them is worth breaking the page over -- the page is most useful exactly when something is wrong. """ from __future__ import annotations import contextlib import sqlite3 from typing import TYPE_CHECKING, Any from signal_bot.analytics.scope import Scope, window if TYPE_CHECKING: from collections.abc import Callable, Iterator from pathlib import Path Gathered = dict[str, Any] GROUPS_SQL = """ SELECT group_id, COUNT(*) AS events, MIN(day) AS first_day, MAX(day) AS last_day FROM command_events GROUP BY group_id ORDER BY events DESC """ # The names shown beside a uuid on the page. Unlike the group chat, this is # a loopback page the maintainer is looking at, so everybody who has a name # gets one -- but a uuid still never appears without one beside it. NAMES_SQL = """ SELECT uuid, display_name FROM group_people WHERE (:group IS NULL OR group_id = :group) """ @contextlib.contextmanager def reading(path: Path) -> Iterator[sqlite3.Connection | None]: """A read-only connection, or None when there is nothing readable.""" if not path.is_file(): yield None return try: with contextlib.closing(sqlite3.connect(f"file:{path}?mode=ro", uri=True)) as conn: conn.row_factory = sqlite3.Row yield conn except sqlite3.Error: yield None def safely(path: Path, gather: Callable[[sqlite3.Connection], Gathered]) -> Gathered: """Run one gatherer, answering with the empty shape if anything is wrong.""" with reading(path) as conn: if conn is None: return {} try: return gather(conn) except sqlite3.Error: return {} def measure(conn: sqlite3.Connection, scope: Scope) -> Gathered: """The days covered and where the rows came from, on every response.""" measured = window(conn, scope) return { "first_day": measured.first_day, "last_day": measured.last_day, "days": measured.days, "events": measured.events, "enough_for_a_trend": measured.enough_for_a_trend, "sources": { "live": measured.live, "journald": measured.journald, "daily_uses": measured.daily, }, } def names_in(conn: sqlite3.Connection, scope: Scope) -> dict[str, str]: """Map each uuid to a display name, so no bare identifier is shown.""" return { str(row["uuid"]): str(row["display_name"]) for row in conn.execute(NAMES_SQL, scope.params()) } def groups(path: Path) -> Gathered: """Every group with a history, for the picker.""" def gather(conn: sqlite3.Connection) -> Gathered: return { "groups": [ { "id": str(row["group_id"]), "events": int(row["events"]), "first_day": str(row["first_day"]), "last_day": str(row["last_day"]), } for row in conn.execute(GROUPS_SQL) ] } return safely(path, gather) or {"groups": []} def empty(*lists: str) -> Gathered: """The shape every panel gets when there is nothing readable. Named keys with empty values rather than an error, so the page renders its "nothing yet" state instead of a stack trace -- and so the frontend needs no branch for a database that does not exist. """ return {"window": EMPTY_WINDOW, **{name: [] for name in lists}} EMPTY_WINDOW: Gathered = { "first_day": "", "last_day": "", "days": 0, "events": 0, "enough_for_a_trend": False, "sources": {"live": 0, "journald": 0, "daily_uses": 0}, }